refactor(登录): 删除已停用的回主系统验密码+比对绑定值死代码
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s

loadMainSupplierAccountForLogin / checkMainSupplierBinding / verifySupplierCredentialOnMainSystem 调用方为 0,连同惰性开通服务 supplierBranchProvisioning、端点 supplierLogin、配置 supplierLoginPath 一并删除;mainSystemSupplierAuth 仅留 looksLikeSupplierLoginName / isMainSystemVerificationEnabled 两个只读辅助(供登录页未开通提示,不发请求、不比对绑定值)。更新契约测试与设计文档 §4 第 9 条、环境变量手册。
This commit is contained in:
雨天
2026-10-13 10:52:30 +08:00
parent 17957fe120
commit d2dc891259
9 changed files with 29 additions and 370 deletions
@@ -132,7 +132,7 @@ resolveOurBranchByBinding({ envelopeBranchCode, rowBranchCode, supplierCode, sub
| 6 | 合并键 | `mainSystemOrderImport.ts`(`bucketGroupsByDeliveryDate` / `claimDayOrder`) | 配送日合并键加 `main_branch_code`(§5.1) |
| 7 | 调度 | `mainSystemOrderImport.ts`(`listMainSupplierBranchCodes` / 定时对账) | "要拉哪些分公司"改成**有生效绑定的分公司**(不再看 `account_source`);归属断言改为"落在本分公司生效绑定的 supplier_code 集合内" |
| 8 | 登录 | `server/src/routes/auth.ts`、`server/src/routes/mobile/mobileAuthRoutes.ts` | **两条入口都**删掉「回主系统验密码 + 绑定比对」分支 ⇒ 本地密码登录(含小程序) |
| 9 | 登录 | `server/src/services/mainSystemSupplierAuth.ts` | `checkMainSupplierBinding()` / `loadMainSupplierAccountForLogin()` / `verifySupplierCredentialOnMainSystem()` **保留但登录链路零调用**(纯函数仍有单测;将来批量开通/校验可复用) |
| 9 | 登录 | `server/src/services/mainSystemSupplierAuth.ts` | ~~`checkMainSupplierBinding()` / `loadMainSupplierAccountForLogin()` / `verifySupplierCredentialOnMainSystem()` **保留但登录链路零调用**~~ **2026-10-13 开发者要求「清理无用代码」⇒ 三函数已删除**,连同惰性开通服务 `supplierBranchProvisioning.ts`、端点 `supplierLogin` 与配置 `supplierLoginPath`;文件仅存 `looksLikeSupplierLoginName` / `isMainSystemVerificationEnabled` 两个只读辅助(供登录页「未开通」提示,不发请求、不比对绑定值) |
| 10 | 超管建/改 | `server/src/routes/auth.ts` | 建分公司时**总是**生成 `access_code` + 下发本地管理员初始密码(`must_change_password: true`、`account_source='local'`);`main_supplier_code` 降级为**手工通配绑定**登记;新增只读 `GET /auth/admin/branches/:code/bindings` |
| 11 | 绑定同步 | `server/src/services/branchAccessCode.ts` | **首选**:入站用载荷里的 `subsystem_code`(P0-2 ①)、出站按码拉取(②)⇒ 镜像只在需要时由 `binding.changed` 回调或回读维护(P0-2 退路) |
| 12 | 界面 | `src/pages/system/BranchManagement.tsx`、`src/lib/localApiClient.ts` | 「接入编码」列 + 复制 + 「已绑定的主系统供应商」弹层(含空态);三语文案 |
@@ -439,7 +439,6 @@ docker compose -f docker-compose.prod.yml --env-file .env.production up -d --bui
| `MAIN_SYSTEM_PRICE_QTY_REQUEST_PATH` | 可选 | `/api/supplier/preparations/price-qty-request` | 改价/改量申请提交路径 |
| `MAIN_SYSTEM_ACTUAL_QTY_DECISION_PATH` | 可选 | `/api/supplier/preparations/actual-qty-decision` | 实收/单位申请的**决策回传**路径(我方审核结论发给主系统) |
| `MAIN_SYSTEM_PRICE_QTY_LIST_PATH` | 可选 | `/api/supplier/preparations/price-qty-requests` | 申请列表**只读回读**路径(Q6 对账兜底,`?kind=actual_qty` 取实收链) |
| `MAIN_SYSTEM_SUPPLIER_LOGIN_PATH` | 可选 | `/api/supplier/login` | 供应商账号校验路径 |
| `MAIN_SYSTEM_TIMEOUT_MS` | 可选 | 5000 | 调用主系统超时(毫秒) |
| `MAIN_SYSTEM_RETURN_FOLLOW` | 可选 | 关(`=1` 开) | 第三方订单退货跟随 |
| `MAIN_SYSTEM_REPORT_ENABLED` | 可选 | 关(`=true` 开) | 批次报告推送到主系统(第九批);关 = 不采集不推送、零出站 |
-1
View File
@@ -75,7 +75,6 @@ export const config = {
mainSystem: {
baseUrl: (process.env.MAIN_SYSTEM_BASE_URL || '').replace(/\/+$/, ''),
timeoutMs: Number(process.env.MAIN_SYSTEM_TIMEOUT_MS || 5000),
supplierLoginPath: process.env.MAIN_SYSTEM_SUPPLIER_LOGIN_PATH || '/api/supplier/login',
},
// 主系统「进销存对接密钥」:本系统以外部 ERP 身份拉取分配给某供应商(= 我们的分公司)的备货任务。
// 见主系统 docs/供应商开放API接入.md §2/§7:oauth 换 token → GET /supplier/preparations。
-6
View File
@@ -28,7 +28,6 @@ export const MAIN_SYSTEM_DEFAULT_PATHS = {
* 用途:webhook 漏推 / 结果事件没到达时,我方对账用它关闭"已失效/已无对应行"的待审行。
*/
priceQtyRequestsList: '/api/supplier/preparations/price-qty-requests',
supplierLogin: '/api/supplier/login',
/**
* 第九批「批次报告同步」(我方推、主系统收;契约 §2.12.9):
* ① 传文件:multipart 字段名 `file`,`?path=<对象名>`;回 `{path, signedUrl}`(**用回执的 path 登记**)
@@ -67,11 +66,6 @@ export function isMainSystemIntegrationEnabled(): boolean {
return Boolean(mainSystemBaseUrl() && clientId && clientSecret);
}
/** 供应商账号登录校验是否可用(只需要域名) */
export function isMainSystemLoginEnabled(): boolean {
return Boolean(mainSystemBaseUrl());
}
export function mainSystemWebhookSecret(): string {
return String(config.mainSystemIntegration.webhookSecret || '');
}
@@ -32,8 +32,6 @@ function pathOverride(endpoint: MainSystemEndpoint): string | undefined {
return process.env.MAIN_SYSTEM_ACTUAL_QTY_DECISION_PATH;
case 'priceQtyRequestsList':
return process.env.MAIN_SYSTEM_PRICE_QTY_LIST_PATH;
case 'supplierLogin':
return config.mainSystem.supplierLoginPath;
case 'qualityReportUpload':
return process.env.MAIN_SYSTEM_REPORT_UPLOAD_PATH;
case 'qualityReportRegister':
-1
View File
@@ -13,7 +13,6 @@ export {
MAIN_SYSTEM_FETCH_TIMEOUT_MS,
MAIN_SYSTEM_OAUTH_TIMEOUT_MS,
isMainSystemIntegrationEnabled,
isMainSystemLoginEnabled,
isPriceQtyRequestEnabled,
mainSystemBaseUrl,
mainSystemCredentials,
+14 -162
View File
@@ -1,178 +1,30 @@
import { config } from '../config';
import { pool } from '../db';
/**
* 向主系统(AI 生鲜配送)校验「供应商账号」的凭据,并取回供应商档案。
* 登录相关的**残留只读辅助**(2026-10-13 清理后仅剩这两个)。
*
* 背景(见 .cursor/rules/01-second-dev-supplier.mdc「两层供应商语义」):
* 本系统的「分公司」= 主系统的「供应商」;本系统的「供应商」= 厂商(与主系统无关)。
* 本系统的分公司管理员账号就是主系统的供应商账号(登录名 = 手机号),
* 密码权威在主系统 —— 因此登录时必须回主系统校验,本地不保存可用密码。
* 背景:这里曾经实现「手机号形态的登录名 ⇒ **回主系统验密码** ⇒ 比对
* `branches.main_supplier_code` 绑定值 ⇒ 不一致就拒绝」这套登录通道
* (`loadMainSupplierAccountForLogin` / `checkMainSupplierBinding` / `verifySupplierCredentialOnMainSystem`
* + `supplierBranchProvisioning` 惰性开通)。2026-10-27 起登录已与主系统**彻底解耦**
* (一律我方本地账号 + 本地密码;手机号只是本地账号字段),那些函数**调用方为 0**;
* 2026-10-13 开发者要求**清理无用代码**,已全部删除(含端点/配置/惰性开通服务)。
*
* 实现说明:本期直接复用主系统**已有的** `POST /api/supplier/login`
* (实测返回体含 profile.supplier.supplier_code / company_name,正好是开通分公司所需字段),
* 这样**无需改动主系统**即可先跑通登录链路。
* 生产化建议:主系统另加一个带签名 + IP 白名单 + 限流的服务间端点,
* 不要把无限流的对客登录接口长期当作服务间校验通道(已记入规则文档待办)。
* 现在只剩下面两个辅助,**不发起任何网络请求、不比对绑定值**,只服务于登录页
* 「本地没有该登录名 ⇒ 403 未开通」那一句提示(见 `routes/auth.ts` / `routes/mobile/mobileAuthRoutes.ts`)。
*
* 设计:docs/design/20261027-分公司接入编码与主系统供应商绑定.md(§4 第 9 条已改为"已删除")。
*/
/** 中国大陆手机号:本系统的分公司管理员登录名就是手机号 */
/** 中国大陆手机号:本系统的分公司管理员登录名形如手机号 */
const MAINLAND_PHONE_RE = /^1[3-9]\d{9}$/;
export type MainSupplierProfile = {
/** 主系统供应商编码,用作本系统的分公司编码(如 SUP37831443) */
supplierCode: string;
/** 主系统供应商名称,用作分公司名称 */
companyName: string;
/** 联系人(主系统账号的 full_name) */
contactName: string;
/** 登录手机号 */
phone: string;
/** 主系统侧的分公司与名称(仅留痕/排障用,不参与本系统建模) */
mainBranchCode: string | null;
mainBranchName: string | null;
};
/**
* **分公司 ↔ 主系统供应商绑定**的判定(2026-10-10 开发者裁决,纯函数便于单测)。
*
* 口径:超管建分公司时**显式**填入该分公司绑定的主系统供应商编码(`branches.main_supplier_code`);
* 供应商登录时先回主系统校验凭据,再**比对**主系统返回的 `supplier_code` 与本分公司的绑定值:
* · 一致 ⇒ 放行;
* · 不一致 ⇒ 拒绝(防"同一个手机号在主系统换了归属/改了公司,我方还让他进原来那家分公司");
* · 分公司**没有绑定**(NULL)⇒ 拒绝(说明这家不是主系统供应商,或超管漏填)。
*
* 为什么必须比对而不是只验密码:手机号是登录名,但**归属**才是身份;
* 主系统侧换绑后,我方 branch_code 是写死的,只验密码会张冠李戴。
*/
/**
* 按登录名取「主系统供应商账号」及其分公司的**绑定值**(登录用;SQL 在 service,路由层不得内嵌 SQL)。
* 只认 `account_source='main_supplier'`:本地账号不走主系统通道。
*/
export async function loadMainSupplierAccountForLogin(loginName: string): Promise<{
id: string;
branch_code: string | null;
main_supplier_code: string | null;
} | null> {
const result = await pool.query<{ id: string; branch_code: string | null; main_supplier_code: string | null }>(
`SELECT p.id, p.branch_code, b.main_supplier_code
FROM public.profiles p
LEFT JOIN public.branches b ON b.branch_code = p.branch_code
WHERE lower(p.username) = lower($1) AND p.account_source = 'main_supplier'
LIMIT 1`,
[loginName]
);
return result.rows[0] ?? null;
}
export function checkMainSupplierBinding(params: {
/** 主系统校验通过后返回的供应商编码 */
profileSupplierCode: string | null | undefined;
/** 我方分公司绑定的主系统供应商编码(branches.main_supplier_code) */
boundMainSupplierCode: string | null | undefined;
}): { ok: true; supplierCode: string } | { ok: false; reason: 'not_bound' | 'mismatch'; supplierCode: string; bound: string | null } {
const supplierCode = String(params.profileSupplierCode || '').trim().toUpperCase();
const bound = String(params.boundMainSupplierCode || '').trim().toUpperCase() || null;
if (!bound) return { ok: false, reason: 'not_bound', supplierCode, bound: null };
if (!supplierCode || supplierCode !== bound) {
return { ok: false, reason: 'mismatch', supplierCode, bound };
}
return { ok: true, supplierCode };
}
export type MainSupplierVerifyOutcome =
/**
* 校验通过。
* ok = 凭据正确
* invalid = 主系统**明确答复**凭据不对/账号不可用(密码错、已停用、需选分公司)
* unavailable = **没问成**(未配置、超时、网络错、5xx)—— 调用方必须 fail closed
*/
| { kind: 'ok'; profile: MainSupplierProfile }
| { kind: 'invalid'; reason: string }
| { kind: 'unavailable'; reason: string };
/** 登录名是否像中国大陆手机号(仅用于"未开通"提示;**不能**据此认定对方是主系统供应商) */
export function looksLikeSupplierLoginName(loginName: string): boolean {
return MAINLAND_PHONE_RE.test(String(loginName || '').trim());
}
/** 主系统是否配置过(仅用于是否给"未开通"提示;不发起任何调用) */
export function isMainSystemVerificationEnabled(): boolean {
return Boolean(config.mainSystem.baseUrl);
}
export async function verifySupplierCredentialOnMainSystem(
username: string,
password: string
): Promise<MainSupplierVerifyOutcome> {
const { baseUrl, timeoutMs, supplierLoginPath } = config.mainSystem;
if (!baseUrl) {
return { kind: 'unavailable', reason: 'main_system_not_configured' };
}
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
try {
const response = await fetch(`${baseUrl}${supplierLoginPath}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
// ⚠️ 绝不记录 password;此处只发往主系统
body: JSON.stringify({ username, password }),
signal: controller.signal,
});
const raw = await response.text();
let payload: any = null;
try {
payload = raw ? JSON.parse(raw) : null;
} catch {
payload = null;
}
// ⚠️ 只有「主系统**明确拒绝了这个凭据**」才叫 invalid;其余非 2xx 一律算 unavailable(没问成)。
//
// 实测(2026-10-08 核对主系统 index.ts:110-114):主系统对 /api/supplier/login 挂了
// loginIpLimiter 80 次/10 分钟/**IP** + loginLimiter 30 次/10 分钟/账号。
// 我们是从本系统这一台机器**服务间**调用 ⇒ 所有供应商共用同一个 IP 配额,
// 超过就会拿到 429。若把 429 当成"凭据错",供应商会看到"密码错误"而百思不得其解,
// 还会把"主系统限流"误判成"密码被改"。必须归到 unavailable(→ 503)。
const CREDENTIAL_REJECTION_STATUS = new Set([400, 401, 403]);
if (!response.ok && !CREDENTIAL_REJECTION_STATUS.has(response.status)) {
console.warn(`[main-auth] 主系统校验返回 ${response.status}(非凭据拒绝),按不可用处理`);
return { kind: 'unavailable', reason: `main_http_${response.status}` };
}
if (!response.ok) {
return { kind: 'invalid', reason: String(payload?.error || `main_http_${response.status}`) };
}
// 主系统要求先选分公司(一个账号挂多个供应商):本期不支持,按登录失败处理并留痕
if (payload?.need_branch) {
console.warn(`[main-auth] 账号命中多个分公司(need_branch),本期不支持:${username}`);
return { kind: 'invalid', reason: 'need_branch' };
}
const supplier = payload?.profile?.supplier;
const supplierCode = String(supplier?.supplier_code || '').trim();
if (!supplierCode) {
console.warn(`[main-auth] 主系统返回缺少 supplier_code:${username}`);
return { kind: 'invalid', reason: 'supplier_code_missing' };
}
return {
kind: 'ok',
profile: {
supplierCode,
companyName: String(supplier?.company_name || '').trim() || supplierCode,
contactName: String(payload?.profile?.full_name || '').trim(),
phone: String(payload?.profile?.phone || username).trim(),
mainBranchCode: payload?.profile?.branch_code ?? null,
mainBranchName: payload?.profile?.branch_name ?? null,
},
};
} catch (error: any) {
const aborted = error?.name === 'AbortError';
console.warn(`[main-auth] 主系统校验未完成(${aborted ? 'timeout' : 'network_error'}):${error?.message || error}`);
return { kind: 'unavailable', reason: aborted ? 'timeout' : 'network_error' };
} finally {
clearTimeout(timer);
}
}
@@ -1,157 +0,0 @@
import { randomUUID } from 'crypto';
import type { PoolClient } from 'pg';
import { pool } from '../db';
import { ensureTenantSchemaCloned, applyTenantSearchPath } from './tenantSchemaService';
import { hashPassword } from '../utils/password';
import type { MainSupplierProfile } from './mainSystemSupplierAuth';
/**
* 惰性开通:主系统供应商 → 本系统「分公司 + 分公司管理员」。
*
* ## ⚠️ 2026-10-10 起**已停用**(开发者裁决):登录不再触达本服务
*
* 原设计:某个手机号在本系统查不到账号、但通过了主系统供应商凭据校验 ⇒ 在这里惰性开通。
* 问题:本系统还要给**非主系统的供应商**使用,自助开通让超管失去"先建分公司"的控制点,
* 而且"绑定哪个主系统供应商"没有落档(详见 `docs/design/20261010-分公司开通与主系统供应商绑定.md`)。
*
* 现在:**超管先建分公司并绑定主系统供应商编码(`branches.main_supplier_code`)**,供应商才能登录;
* 未开通的供应商登录一律拒绝(`supplier_not_provisioned`)。本文件**没有任何调用方**,
* 保留仅为将来"超管驱动的批量开通存量供应商"复用其中的建租户/配置逻辑(届时务必在超管鉴权后调用)。
*
* 触发时机:某个手机号在本系统**查不到账号**,但通过了主系统的供应商凭据校验。
* 一次事务内完成(与 `POST /api/auth/admin/branches` 的开通步骤一致):
* 1. branches (branch_code = 主系统 supplier_code)
* 2. 租户 schema (ensureTenantSchemaCloned,分公司级数据隔离靠它)
* 3. system_configs 分公司级初始化
* 4. auth.users (登录名 = 手机号,密码写**随机不可用**值)
* 5. profiles (account_source='main_supplier',绑定分公司)
* 6. user_roles (role='admin')
*
* 幂等:以**手机号**为准——已存在且来源为 main_supplier 直接复用;
* 若该手机号已被本系统内部账号占用,则拒绝(绝不抢占内部账号)。
* 密码:本地写入随机哈希(本地永远校验不过),登录一律回主系统校验 ⇒ 主系统改密/停用即时生效。
*/
/** 与 admin/branches 保持一致的分公司级默认配置 */
const BRANCH_LLM_CONFIG_JSON =
'{"enabled": false, "provider": "ark", "apiKeys": "", "model": "doubao-seed-2-0-lite-260428", "imageModel": "doubao-seedream-4-0-250828", "imageSize": "512x512", "baseUrl": "https://ark.cn-beijing.volces.com/api/v3"}';
export type SupplierBranchProvisionResult = {
userId: string;
branchCode: string;
/** 本次是否新建(false = 复用既有开通结果) */
created: boolean;
};
function err(code: string, message: string) {
return Object.assign(new Error(message), { code });
}
export async function ensureMainSupplierBranchAndAdmin(
profile: MainSupplierProfile
): Promise<SupplierBranchProvisionResult> {
const branchCode = String(profile.supplierCode || '').trim().toUpperCase();
const username = String(profile.phone || '').trim();
if (!branchCode || !username) {
throw err('invalid_supplier_profile', '主系统返回的供应商档案不完整(缺 supplier_code 或手机号)');
}
// ① 幂等:手机号已开通 ⇒ 直接复用
const existingAccount = await pool.query<{ id: string; branch_code: string | null; account_source: string }>(
`SELECT id, branch_code, account_source FROM profiles WHERE lower(username) = lower($1) LIMIT 1`,
[username]
);
if (existingAccount.rowCount) {
const row = existingAccount.rows[0];
if (row.account_source !== 'main_supplier') {
throw err('login_name_taken', '该手机号已被本系统内部账号占用,无法作为供应商管理员开通');
}
return { userId: row.id, branchCode: row.branch_code || branchCode, created: false };
}
const userId = randomUUID();
const email = `${username}@meoo.local`;
const fullName = profile.contactName || `${profile.companyName}管理员`;
// 本地密码:随机值,本地校验永远不通过(登录一律回主系统)
const passwordHash = await hashPassword(randomUUID() + randomUUID());
const client: PoolClient = await pool.connect();
try {
await client.query('BEGIN');
// ② 分公司主档:已存在(可能是超管手工建的同码分公司)则复用,不覆盖其资料
const branchExists = await client.query('SELECT 1 FROM branches WHERE branch_code = $1', [branchCode]);
if (!branchExists.rowCount) {
await client.query(
`INSERT INTO branches (branch_code, branch_name, contact_name, contact_phone, address, status)
VALUES ($1, $2, $3, $4, $5, 1)`,
[branchCode, profile.companyName, profile.contactName || null, username, null]
);
} else {
console.warn(`[supplier-provision] 分公司 ${branchCode} 已存在,复用之(不覆盖既有资料)`);
}
// ③ 租户 schema(幂等)+ 分公司级配置
const schemaName = await ensureTenantSchemaCloned(branchCode, 'active', client);
await applyTenantSearchPath(client, schemaName);
await client.query(
`INSERT INTO system_configs (config_key, config_value, config_group, description, branch_code)
VALUES ('branch_llm_config', $1::jsonb, 'ai', '分公司大模型配置', $2)
ON CONFLICT ((COALESCE(branch_code, '__GLOBAL__')), config_key) DO NOTHING`,
[BRANCH_LLM_CONFIG_JSON, branchCode]
);
// ④ 账号与角色都落在 public
await client.query(`SELECT set_config('search_path', 'public', true)`);
const emailTaken = await client.query('SELECT 1 FROM auth.users WHERE lower(email) = lower($1)', [email]);
if (emailTaken.rowCount) {
throw err('login_name_taken', '该手机号对应的登录账号已存在');
}
await client.query(
`INSERT INTO auth.users (
instance_id, id, aud, role, email, encrypted_password, email_confirmed_at,
raw_app_meta_data, raw_user_meta_data
) VALUES (
'00000000-0000-0000-0000-000000000000', $1, 'authenticated', 'authenticated', $2,
$3, NOW(),
'{"provider":"email","providers":["email"]}'::jsonb, $4::jsonb
)`,
[userId, email, passwordHash, JSON.stringify({ username, full_name: fullName })]
);
// must_change_password = false:密码本来就是主系统那套,不要求再改一次
//
// ⚠️ 必须用 ON CONFLICT:auth.users 上有 AFTER INSERT 触发器 on_auth_user_created →
// handle_new_user(),它会**先插一行 profiles**(id/username/full_name/avatar_url)。
// 直接 INSERT 会撞 profiles_pkey(实测 23505)。这里改为 upsert,
// 无论触发器在不在都能把分公司、来源、状态补齐。
await client.query(
`INSERT INTO profiles (id, username, full_name, phone, branch_code, status, must_change_password, account_source)
VALUES ($1, $2, $3, $4, $5, 1, false, 'main_supplier')
ON CONFLICT (id) DO UPDATE SET
username = EXCLUDED.username,
full_name = EXCLUDED.full_name,
phone = EXCLUDED.phone,
branch_code = EXCLUDED.branch_code,
status = EXCLUDED.status,
must_change_password = EXCLUDED.must_change_password,
account_source = EXCLUDED.account_source`,
[userId, username, fullName, username, branchCode]
);
await client.query(`INSERT INTO user_roles (user_id, role) VALUES ($1, 'admin')`, [userId]);
await client.query('COMMIT');
console.log(
`[supplier-provision] 已开通分公司 ${branchCode}(${profile.companyName})管理员 ${username}`
);
return { userId, branchCode, created: true };
} catch (error) {
await client.query('ROLLBACK').catch(() => undefined);
throw error;
} finally {
client.release();
}
}
+14 -39
View File
@@ -1,6 +1,5 @@
import { describe, expect, it } from 'vitest';
import { readFileSync } from 'node:fs';
import { checkMainSupplierBinding } from '../src/services/mainSystemSupplierAuth';
import { existsSync, readFileSync } from 'node:fs';
/**
* 分公司 ↔ 主系统供应商的**开通与绑定**(2026-10-10 立,**2026-10-27 口径变更**)。
@@ -8,8 +7,9 @@ import { checkMainSupplierBinding } from '../src/services/mainSystemSupplierAuth
* 2026-10-10 口径:超管先建分公司 + 绑定主系统供应商编码,**登录回主系统校验密码并比对绑定值**。
* 2026-10-27 口径(开发者裁决,本文件已按新口径重写):
* ① **登录与主系统彻底解耦** —— 一律**我方本地账号 + 本地密码**(Web 与小程序同口径),
* 与手机号无关;`verifySupplierCredentialOnMainSystem` / `loadMainSupplierAccountForLogin` /
* `checkMainSupplierBinding` 三个函数**保留**(纯函数仍有单测)但**登录链路不再调用**;
* 与手机号无关;2026-10-13 开发者要求**清理无用代码** ⇒
* `verifySupplierCredentialOnMainSystem` / `loadMainSupplierAccountForLogin` / `checkMainSupplierBinding`
* 三个函数**已删除**(连同端点/配置 + 惰性开通服务 `supplierBranchProvisioning`);
* ② 绑定的载体改为**我方接入编码**(`branches.access_code`)+ 镜像表 `main_supplier_bindings`,
* 主系统在其 `(分公司 × 供应商)` 授权行上绑定该编码;货按编码流转,**未被绑定就收不到**;
* ③ 超管建分公司**总是**下发本地初始密码(首登改密)并生成接入编码;填了主系统供应商编码 ⇒
@@ -22,37 +22,6 @@ const supplierAuthSrc = readFileSync(new URL('../src/services/mainSystemSupplier
const branchAccountSrc = readFileSync(new URL('../src/services/branchAccountService.ts', import.meta.url), 'utf8');
const bindingSrc = readFileSync(new URL('../src/services/branchAccessCode.ts', import.meta.url), 'utf8');
describe('绑定判定(纯函数)', () => {
it('绑定一致 ⇒ 放行', () => {
expect(
checkMainSupplierBinding({ profileSupplierCode: 'sup38887897', boundMainSupplierCode: 'SUP38887897' })
).toEqual({ ok: true, supplierCode: 'SUP38887897' });
});
it('主系统换了归属(编码不一致)⇒ 拒绝 mismatch(防张冠李戴)', () => {
const r = checkMainSupplierBinding({
profileSupplierCode: 'SUP41472132',
boundMainSupplierCode: 'SUP38887897',
});
expect(r.ok).toBe(false);
if (!r.ok) expect(r.reason).toBe('mismatch');
});
it('分公司没绑定主系统供应商(NULL)⇒ 拒绝 not_bound(这是本系统自己的供应商)', () => {
for (const bound of [null, undefined, '', ' ']) {
const r = checkMainSupplierBinding({ profileSupplierCode: 'SUP38887897', boundMainSupplierCode: bound });
expect(r.ok, `bound=${String(bound)}`).toBe(false);
if (!r.ok) expect(r.reason).toBe('not_bound');
}
});
it('主系统没给编码 ⇒ 拒绝(不能凭"密码对了"就当成那家供应商)', () => {
const r = checkMainSupplierBinding({ profileSupplierCode: null, boundMainSupplierCode: 'SUP38887897' });
expect(r.ok).toBe(false);
if (!r.ok) expect(r.reason).toBe('mismatch');
});
});
describe('登录链路:本地账号,且不再回主系统校验(2026-10-27 口径)', () => {
const mobileAuthSrc = readFileSync(
new URL('../src/routes/mobile/mobileAuthRoutes.ts', import.meta.url),
@@ -65,16 +34,22 @@ describe('登录链路:本地账号,且不再回主系统校验(2026-10-27
expect(mobileAuthSrc).not.toContain('ensureMainSupplierBranchAndAdmin');
});
it('⛔ Web 与小程序都不再回主系统验密码(三个函数只保留、不接登录)', () => {
it('⛔ Web 与小程序都不再回主系统验密码;三函数与惰性开通**已删除**(2026-10-13 清理)', () => {
for (const [name, src] of [['auth.ts', authSrc], ['mobileAuthRoutes.ts', mobileAuthSrc]] as const) {
expect(src, name).not.toContain('verifySupplierCredentialOnMainSystem(');
expect(src, name).not.toContain('loadMainSupplierAccountForLogin(');
expect(src, name).not.toContain('checkMainSupplierBinding(');
expect(src, name).not.toContain('main_system_unavailable');
}
// 保留的纯函数仍在(供将来批量开通/校验复用),但调用方为 0
expect(supplierAuthSrc).toContain('export function checkMainSupplierBinding');
expect(supplierAuthSrc).toContain('export async function verifySupplierCredentialOnMainSystem');
// 2026-10-13:无调用方的死代码已删除(源码里不应再有这三个函数的**定义**;惰性开通服务文件也不存在)
expect(supplierAuthSrc).not.toContain('export function checkMainSupplierBinding');
expect(supplierAuthSrc).not.toContain('export async function verifySupplierCredentialOnMainSystem');
expect(supplierAuthSrc).not.toContain('export async function loadMainSupplierAccountForLogin');
expect(supplierAuthSrc).not.toContain('supplierLoginPath');
expect(
existsSync(new URL('../src/services/supplierBranchProvisioning.ts', import.meta.url)),
'supplierBranchProvisioning.ts 应已删除'
).toBe(false);
});
it('两个登录入口的"本地没有该登录名"分支 ⇒ 403 未开通,而不是替他开通', () => {