feat(开通口径): 供应商登录不再自动开分公司 —— 改为「超管先建分公司 + 绑定主系统供应商」
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

开发者裁决:「子系统需要超级管理员先去创建分公司,分公司的电话号码对应得上主系统时才能进行一个绑定
主系统的供应商账号,然后供应商才能使用这个供应商系统;而不是主系统存在就直接登录、创建分公司
——因为我们这个子系统还可能给**非主系统的供应商**使用。」三项子决定:完全关闭登录即开通 / 手填供应商编码
登录时比对 / 存量回填绑定。

改前问题(真库实测):5 家分公司**全部**由登录惰性开通(含当天新开的 SUP41472132);
`branches` 无任何主系统字段,"绑定"只靠"编码恰好相同"猜;登录只验密码不验归属 ⇒ 换绑即张冠李戴。

改动:
① 迁移 20261026:`branches.main_supplier_code`(可空)+ 部分唯一索引;**存量回填只认证据**
   (该分公司有 `profiles.account_source='main_supplier'` 账号)⇒ 5 家 SUP* 回填为自身编码,平台 BR001/BR002 不绑
② 登录(`/token` 与 `/unified-login` 两条入口):本地没有该手机号 ⇒ **403 supplier_not_provisioned**,
   不再建任何数据;有账号 ⇒ 回主系统验密码 **+ `checkMainSupplierBinding()` 比对**
   (未绑定 ⇒ `branch_not_bound`;不一致 ⇒ `supplier_binding_mismatch`)
③ 超管建分公司:新增可选「主系统供应商编码」——填了 ⇒ 账号 `account_source='main_supplier'`(密码随机不可用、
   **不下发初始密码**、`must_change_password=false`)、`branch_code` 默认取该编码;不填 ⇒ 本地供应商(现状)
④ 编辑分公司可改绑定(空串 = 解绑);一个主系统供应商只能绑一家(建/改都拦,409 `main_supplier_already_bound`)
⑤ `ensureMainSupplierBranchAndAdmin` 停用(无调用方;文件头写明原因,保留供将来超管驱动的批量开通)
⑥ 界面:`BranchManagement` 表单加「主系统供应商编码(选填,如 SUP38887897)」(中/英/印尼)

工程纪律:新增 SQL 全部落在 service(`mainSystemSupplierAuth.loadMainSupplierAccountForLogin`、
`branchAccountService.findBranchCreateConflict`)—— 路由层裸 SQL 棘轮 `routeLayerBoundary.test.ts` 两次踩红后按规矩下移;
冲突检查**顺序即优先级**(绑定冲突先判,否则重复提交只会得到泛泛的 already_exists,实测踩到)。

真库 E2E(跑完已彻底清理,剩回原 7 家):
V1 未开通手机号登录 ⇒ 403 supplier_not_provisioned 且分公司数 7→7(**没有自动开通**)
V2 存量 5 家绑定已回填;V3 建+绑定 201(绑定落档 + 无初始密码)
V4 同一供应商重复绑定 ⇒ 409 main_supplier_already_bound
V5 不填绑定 ⇒ 201 本地供应商(无绑定 + local + 下发初始密码)

测试:新增 `server/tests/supplierBranchBinding.test.ts`(11 条)+
`docs/design/20261010-分公司开通与主系统供应商绑定.md`(口径/落地/验收/不变量);
对接清单 §4.5.15(告知对方:新供应商须我方超管先建并绑定后才能登录,并可选地请他们加"按手机号查供应商"只读接口)。
服务端全量失败集与基线**逐文件一致(24,零新增)**;前端 142 文件 / 707 用例全绿;门禁同基线。
This commit is contained in:
Ubuntu
2026-10-10 14:43:01 +08:00
parent e7840dc622
commit 13f8e72a36
13 changed files with 509 additions and 47 deletions
@@ -0,0 +1,65 @@
# 分公司开通与「主系统供应商」绑定(2026-10-10 定稿)
> 开发者当轮指令(原话要点):
> 「我们的子系统(供应商系统)需要**超级管理员先去创建分公司**,分公司的**电话号码对应得上主系统**时
> 才能进行一个**绑定主系统的供应商账号**,然后供应商才能使用这个供应商系统;
> **而不是主系统存在就直接登录、创建分公司** —— 因为我们这个子系统还可能给**非主系统的供应商**使用,
> 存在这种情况的。」
## 1. 改前的问题(实测)
本系统的「分公司」有两种来源,但此前**分不清、也没档案**:
| 来源 | 触发 | 结果 |
|---|---|---|
| **登录惰性开通**(原设计) | 手机号在本系统查不到,但**主系统供应商凭据校验通过** | `ensureMainSupplierBranchAndAdmin()` 一个事务内建 分公司 + 租户 schema + 管理员;`branch_code = 主系统 supplier_code` |
| 超管建分公司 | `POST /api/auth/admin/branches` | 建分公司 + 租户 + **本地账号**(初始密码由手机号派生);**不校验主系统、无绑定步骤** |
由此三个问题:
1. **超管失去控制点**:任何在主系统有账号的供应商都能自助开通(真库实测:5 家分公司全部是登录自动开通的,
含 2026-10-10 当天新开的 `SUP41472132 水产荣县乐德镇光海水产养殖场`);
2. **绑定无档**:`branches` 表**没有**任何主系统字段,"绑定哪个主系统供应商"只能靠"编码恰好相同"猜;
也无法表达"这家**不是**主系统供应商";
3. **张冠李戴**:登录只验密码、不验归属 —— 主系统侧换绑/换公司后,我方 `branch_code` 是写死的,没人拦。
## 2. 定稿口径
| # | 规则 |
|---|---|
| ① | **登录不再惰性开通**:本地没有该手机号的账号 ⇒ `403 supplier_not_provisioned`(提示联系超管);不建任何数据 |
| ② | **超管先建分公司**,并**显式绑定**主系统供应商编码(`branches.main_supplier_code`,可空) |
| ③ | **绑定 = 该分公司的身份**:填了 ⇒ 这家分公司就是主系统那家供应商(管理员登录**回主系统校验密码**,本地密码随机不可用);不填 ⇒ **本系统自己的供应商**(本地账号 + 初始密码,供非主系统供应商使用) |
| ④ | **登录双校验**:主系统凭据通过 **且** 返回的 `supplier_code` == 该分公司绑定值;未绑定 / 不一致一律拒绝(`branch_not_bound` / `supplier_binding_mismatch`) |
| ⑤ | **一个主系统供应商只能绑一家分公司**(唯一索引 + 建/改都拦) |
| ⑥ | 存量(已由登录自动开通的)**回填绑定 = 自身编码**,行为不变但从此落档 |
## 3. 落地
| 层 | 改动 |
|---|---|
| 迁移 | `migrations/20261026_branches_main_supplier_code.sql`:加 `main_supplier_code VARCHAR(64)`、部分唯一索引 `uq_branches_main_supplier_code`;**回填只认证据**(该分公司存在 `profiles.account_source='main_supplier'` 的账号),不靠编码前缀猜 |
| 判定 | `mainSystemSupplierAuth.checkMainSupplierBinding()`(**纯函数**,便于单测):`not_bound` / `mismatch` / `ok` |
| 登录 | `routes/auth.ts`:`/token` 与 `/unified-login` 两条入口的"本地没有该手机号"分支 ⇒ 403;`handleMainSupplierLogin` 改为"必须已有账号 + 绑定比对",不再调用开通服务 |
| 开通服务 | `supplierBranchProvisioning.ensureMainSupplierBranchAndAdmin()` **已停用**(无调用方),文件头写明原因;保留仅供将来"超管驱动的批量开通"复用建租户/配置逻辑 |
| 超管建/改分公司 | `POST /auth/admin/branches` 接受 `main_supplier_code`(可选):填了 ⇒ 账号 `account_source='main_supplier'`、密码随机不可用、**不下发初始密码**、`branch_code` 默认取该编码;`PUT` 支持改绑定(空串 = 解绑,等于把这家改成"本系统自己的供应商") |
| 界面 | `BranchManagement` 表单新增「主系统供应商编码(选填,如 SUP38887897)」一个输入框(中/英/印尼),提交时带上 |
## 4. 验收(真库实测,跑完已清理)
| # | 场景 | 结果 |
|---|---|---|
| V1 | 未开通的手机号登录 | **403 `supplier_not_provisioned`**,且分公司数 7 → 7(**没有自动开通**) |
| V2 | 存量回填 | 5 家 `SUP*` 全部 `main_supplier_code = branch_code`;平台 `BR001/BR002` 无绑定 |
| V3 | 超管建 + 绑定 | 201;落档 `main_supplier_code=SUP99999999`、`account_source='main_supplier'`、`default_password: null`、`must_change_password: false` |
| V4 | 同一供应商重复绑定 | **409 `main_supplier_already_bound`**("已绑定分公司 SUP99999999") |
| V5 | 不填绑定 | 201;`main_supplier_code=NULL`、`account_source='local'`、**下发初始密码**(本地供应商) |
| V6 | 清理 | 测试分公司/租户 schema/账号全部删除,剩回原 7 家 |
## 5. 不变量与影响面
- **主系统供应商的密码权威仍在主系统**:本地密码不可用、改密/停用即时生效(与改造前一致);
- **非主系统供应商不受影响**:走本地账号 + 本地密码(现状),只是现在**不会**被误绑到主系统供应商;
- **订单/导入不受影响**:导入只认 `branches` + 台账,与登录无关;
- **未做/待定**:① 分公司列表暂未展示绑定列(要靠表单回填看到);② 解绑后该供应商立即无法登录(刻意如此,防呆);
③ 主系统侧"按手机号查供应商"的只读接口(可在超管建分公司时自动带出编码)已记为可选增强,未向对方提出。
@@ -2111,6 +2111,25 @@ prep `931eda1a-3c19-4b49-ab24-664b54770fc4` / `SUP35143228` / `ORD_WEB_20261009_
我方**不碰**的情形(避免误删):`found=false` 且没有改派信号(当前供应商为空或仍是我们)⇒ 视为退货/取消/删除,
交给开关控制的退货跟随判定。若你们希望"退货/取消"也由我们主动剔除,需要另给一个显式信号(§3.1 的 P0-1 仍未做)。
### 4.5.15 我方内部口径变更 · 供应商账号改为「**超管先建分公司 + 绑定**」才能登录(2026-10-10)
(**不需要你们改代码**,但你们客服/联调会遇到,先说一声。)
| 项 | 以前 | 现在 |
|---|---|---|
| 供应商首次登录(手机号 + 主系统密码) | 我方查不到账号 ⇒ **自动建分公司 + 租户 + 管理员**(`branch_code = 你们的 supplier_code`) | **不再自动开通**:返回 `403 supplier_not_provisioned`,提示联系我方超级管理员 |
| 开通方式 | 供应商自助 | **我方超级管理员先建分公司**,并在建分公司时填「主系统供应商编码」(= 你们的 `supplier_code`)完成**绑定**;绑定后才允许登录 |
| 登录校验 | 只回你们那边验密码 | 回你们那边验密码 **+ 比对**返回的 `supplier_code` 是否等于分公司绑定值(不一致 ⇒ `supplier_binding_mismatch`,防换绑张冠李戴) |
| 一个供应商两家分公司 | 可能出现 | 不允许(绑定唯一) |
**为什么改**:我方这套系统**还要给非主系统的供应商使用**,自助开通让超管失去控制点、绑定也无档可查。
所以:主系统供应商 = **绑定**的分公司(管理员密码仍以你们为准);我方自己的供应商 = 不填绑定(本地账号密码)。
**对你们的影响**:新供应商在你们那边建档后,**必须等我方超管建好并绑定分公司**,该供应商才能登录我方系统;
在那之前他登录我方会看到「请联系超级管理员开通」。若你们希望这个过程再自动化一点,
可以给我们一个只读接口「**按手机号查供应商**」(返回 `supplier_code` + 公司名 + 联系人),
超管建分公司时就能自动带出编码并当场校验 —— 这条**可选**,你们有档期再说。
## 5. 附录
### 5.1 主系统侧疑似既有缺陷(同源代码,两个仓库都有,请主系统判断是否修)
@@ -0,0 +1,33 @@
-- 分公司 ↔ 主系统供应商:**显式绑定**(2026-10-10 开发者裁决)
--
-- 背景(原设计的问题):本系统的分公司有两种来源,但此前**无法区分、也没有档案**:
-- ① 主系统供应商(登录时惰性开通,branch_code = 主系统 supplier_code);
-- ② 本系统自己的供应商(超管建分公司,本地账号 + 本地密码)。
-- 绑定关系此前是**隐式**的(编码恰好相同 + 手机号相同 + profiles.account_source='main_supplier'),
-- 事后答不出"这家分公司绑的是哪个主系统供应商",也无法表达"这家**不是**主系统供应商"。
--
-- 现在的口径(开发者):**超管先建分公司并绑定主系统供应商编码,供应商才能登录**;
-- 登录即自动开分公司的口子**关闭**;本系统自己的供应商不填绑定(main_supplier_code IS NULL)。
--
-- 幂等:IF NOT EXISTS;回填只认"有 main_supplier 账号"这一**证据**(不靠编码前缀猜)。
ALTER TABLE public.branches
ADD COLUMN IF NOT EXISTS main_supplier_code VARCHAR(64);
COMMENT ON COLUMN public.branches.main_supplier_code IS
'绑定的主系统供应商编码(= 主系统的 supplier_code);NULL = 本系统自己的供应商(本地账号密码)。登录时回主系统校验并比对本列,不一致拒绝登录';
-- 回填存量(开发者裁决:已由登录自动开通的分公司,回填绑定 = 自身编码)
UPDATE public.branches b
SET main_supplier_code = b.branch_code
WHERE b.main_supplier_code IS NULL
AND EXISTS (
SELECT 1 FROM public.profiles p
WHERE p.branch_code = b.branch_code
AND p.account_source = 'main_supplier'
);
-- 一个主系统供应商只能绑一家分公司(防两家分公司抢同一供应商)
CREATE UNIQUE INDEX IF NOT EXISTS uq_branches_main_supplier_code
ON public.branches (main_supplier_code)
WHERE main_supplier_code IS NOT NULL;
+138 -45
View File
@@ -50,13 +50,15 @@ import {
applyTenantSearchPath,
invalidateTenantSchemaResolveCache,
} from '../services/tenantSchemaService';
import { findBranchCreateConflict } from '../services/branchAccountService';
import { runInBranchSchema, invalidateActiveTenantBranchesCache } from '../services/tenantSchemaFallback';
import {
checkMainSupplierBinding,
isMainSystemVerificationEnabled,
loadMainSupplierAccountForLogin,
looksLikeSupplierLoginName,
verifySupplierCredentialOnMainSystem,
} from '../services/mainSystemSupplierAuth';
import { ensureMainSupplierBranchAndAdmin } from '../services/supplierBranchProvisioning';
import { loadAuthUsersByIds } from '../services/accountLoginService';
import { listAssignableRoleCodes } from '../services/roleDefinitionService';
@@ -485,26 +487,49 @@ async function handleMainSupplierLogin(
return res.status(400).json({ error: 'invalid_credentials', error_description: '登录名或密码错误' });
}
let provisioned: Awaited<ReturnType<typeof ensureMainSupplierBranchAndAdmin>>;
try {
provisioned = await ensureMainSupplierBranchAndAdmin(verdict.profile);
} catch (error: any) {
if (error?.code === 'login_name_taken') {
return res.status(409).json({
error: 'login_name_taken',
error_description: '该手机号已被本系统内部账号占用,请联系超级管理员处理',
});
}
throw error;
/**
* ⚠️ **2026-10-10 口径(开发者裁决):关闭"登录即自动开分公司"**。
*
* 原设计:主系统凭据校验通过 ⇒ 惰性建分公司 + 租户 + 管理员。
* 问题:本系统还要给**非主系统的供应商**使用,自助开通让超管失去"先建分公司"的控制点。
* 现在:**分公司必须由超级管理员先建好、并绑定主系统供应商编码**,供应商才可能登录:
* ① 本地必须已有该手机号的账号(`profiles.account_source='main_supplier'`,且所属分公司已绑定);
* ② 主系统凭据通过后,**比对**主系统返回的 `supplier_code` 与分公司绑定值(`checkMainSupplierBinding`),
* 不一致/未绑定 ⇒ 拒绝(防换绑张冠李戴)。
*/
const account = await loadMainSupplierAccountForLogin(loginName);
if (!account) {
return res.status(403).json({
error: 'supplier_not_provisioned',
error_description: '该供应商尚未在本系统开通,请联系超级管理员先创建分公司并绑定',
});
}
const binding = checkMainSupplierBinding({
profileSupplierCode: verdict.profile.supplierCode,
boundMainSupplierCode: account.main_supplier_code,
});
if (!binding.ok) {
console.warn(
`[login] 供应商绑定校验未通过(${binding.reason}):${loginName} 主系统=${binding.supplierCode || '—'} 绑定=${binding.bound || '—'}`
);
return res.status(403).json({
error: binding.reason === 'not_bound' ? 'branch_not_bound' : 'supplier_binding_mismatch',
error_description:
binding.reason === 'not_bound'
? '该分公司尚未绑定主系统供应商,请联系超级管理员'
: '该账号所属供应商与分公司绑定的供应商不一致,请联系超级管理员核对',
});
}
const [user] = await loadAuthUsersByIds([provisioned.userId]);
const [user] = await loadAuthUsersByIds([account.id]);
if (!user) {
return res.status(500).json({ error: 'server_error', error_description: '登录失败,请稍后重试' });
}
return issueSession(user);
}
/** 取"主系统供应商账号 + 绑定值":SQL 在 `mainSystemSupplierAuth`(路由层不得内嵌 SQL) */
router.post('/token', async (req: Request, res: Response) => {
try {
const loginName = String(req.body?.username || req.body?.login_name || req.body?.email || '').trim();
@@ -535,10 +560,16 @@ router.post('/token', async (req: Request, res: Response) => {
return jsonTokenSession(res, outcome.user);
}
// ② 本地没有/没通过:可能是尚未开通的主系统供应商(手机号)⇒ 惰性开通后登录
/**
* ② 本地没有/没通过:**不再惰性开通**(2026-10-10 口径)。
* 手机号形态 ⇒ 说明这可能是主系统供应商,但分公司/账号必须由超级管理员先建好并绑定;
* 这里给一句可执行的提示,而不是替他开通。
*/
if (looksLikeSupplierLoginName(loginName) && isMainSystemVerificationEnabled()) {
// 同上:必须 await
return await handleMainSupplierLogin(res, loginName, password);
return res.status(403).json({
error: 'supplier_not_provisioned',
error_description: '该供应商尚未在本系统开通,请联系超级管理员先创建分公司并绑定',
});
}
return res.status(400).json({ error: 'invalid_credentials', error_description: '登录名或密码错误' });
@@ -590,11 +621,12 @@ router.post('/unified-login', async (req: Request, res: Response) => {
return jsonUnifiedSession(res, outcome.user, loginName);
}
// ② 本地没通过:可能是尚未开通的主系统供应商(手机号)⇒ 惰性开通后登录
// ② 本地没通过:**不再惰性开通**(2026-10-10 口径)——分公司/账号由超管先建好并绑定
if (looksLikeSupplierLoginName(loginName) && isMainSystemVerificationEnabled()) {
return await handleMainSupplierLogin(res, loginName, password, (user) =>
jsonUnifiedSession(res, user, loginName)
);
return res.status(403).json({
error: 'supplier_not_provisioned',
error_description: '该供应商尚未在本系统开通,请联系超级管理员先创建分公司并绑定',
});
}
return res.status(400).json({ error: 'invalid_credentials', error_description: '登录名或密码错误' });
@@ -706,6 +738,13 @@ router.post('/admin/branches', authMiddleware, async (req: AuthRequest, res: Res
const contactName = String(req.body?.contact_name || '').trim();
const contactPhone = normalizeBranchAccountLogin(req.body?.contact_phone);
const address = String(req.body?.address || '').trim();
/**
* **主系统供应商编码**(2026-10-10 口径,可选):
* 填了 ⇒ 这家分公司 = 主系统的那家供应商(管理员登录回主系统校验密码;本地密码随机不可用);
* 不填 ⇒ 本系统自己的供应商(本地账号 + 初始密码)。
* 见 docs/design/20261010-分公司开通与主系统供应商绑定.md
*/
const mainSupplierCodeRaw = String(req.body?.main_supplier_code || '').trim().toUpperCase();
const loginError = validateBranchAccountLogin(contactPhone);
if (!branchName) {
@@ -714,14 +753,25 @@ router.post('/admin/branches', authMiddleware, async (req: AuthRequest, res: Res
if (loginError) {
return res.status(400).json({ error: 'invalid_login', error_description: loginError });
}
if (mainSupplierCodeRaw && !/^[A-Z0-9_-]{2,30}$/.test(mainSupplierCodeRaw)) {
return res.status(400).json({
error: 'invalid_main_supplier_code',
error_description: '主系统供应商编码只能包含字母、数字、下划线和横线',
});
}
const username = contactPhone;
const email = `${username}@meoo.local`;
const fullName = contactName || `${branchName}管理员`;
const userId = randomUUID();
const profilePhone = isPhoneBranchLogin(contactPhone) ? contactPhone : null;
const initialPassword = initialPasswordForBranchLogin(contactPhone);
const passwordHash = await hashPassword(initialPassword);
/**
* 主系统供应商账号:本地密码写**随机不可用**值(登录一律回主系统校验),也不下发初始密码;
* 本地供应商:保持现状(初始密码由手机号派生,首次登录强制改密)。
*/
const isMainSupplier = Boolean(mainSupplierCodeRaw);
const initialPassword = isMainSupplier ? null : initialPasswordForBranchLogin(contactPhone);
const passwordHash = await hashPassword(initialPassword ?? randomUUID() + randomUUID());
const client = await pool.connect();
let branchCode = '';
@@ -730,24 +780,32 @@ router.post('/admin/branches', authMiddleware, async (req: AuthRequest, res: Res
branchCode = String(req.body?.branch_code || '').trim().toUpperCase();
if (!branchCode) {
branchCode = await generateNextBranchCode(client);
// 主系统供应商:编码默认就是主系统供应商编码(沿用既有约定);本地供应商:自动生成
branchCode = mainSupplierCodeRaw || (await generateNextBranchCode(client));
}
if (!/^[A-Z0-9_-]{2,30}$/.test(branchCode)) {
await client.query('ROLLBACK');
return res.status(400).json({ error: 'invalid_branch_code', error_description: '分公司编码只能包含字母、数字、下划线和横线' });
}
const existing = await client.query(
`SELECT 1 FROM branches WHERE branch_code = $1
UNION ALL
SELECT 1 FROM profiles WHERE lower(username) = lower($2)
UNION ALL
SELECT 1 FROM auth.users WHERE lower(email) = lower($3)
LIMIT 1`,
[branchCode, username, email]
);
if (existing.rowCount) {
/**
* 冲突检查(SQL 在 `branchAccountService`,路由层有裸 SQL 棘轮):
* 编码/登录名/邮箱占用,以及**该主系统供应商是否已被别家绑定**。
*/
const conflict = await findBranchCreateConflict({
branchCode,
username,
email,
mainSupplierCode: mainSupplierCodeRaw || null,
});
if (conflict) {
await client.query('ROLLBACK');
if (conflict.kind === 'main_supplier') {
return res.status(409).json({
error: 'main_supplier_already_bound',
error_description: `主系统供应商 ${mainSupplierCodeRaw} 已绑定分公司 ${conflict.branchCode}`,
});
}
return res.status(400).json({
error: 'already_exists',
error_description: '分公司编码或登录账号已存在',
@@ -755,9 +813,9 @@ router.post('/admin/branches', authMiddleware, async (req: AuthRequest, res: Res
}
await client.query(
`INSERT INTO branches (branch_code, branch_name, contact_name, contact_phone, address, status)
VALUES ($1, $2, $3, $4, $5, 1)`,
[branchCode, branchName, contactName || null, contactPhone, address || null]
`INSERT INTO branches (branch_code, branch_name, contact_name, contact_phone, address, status, main_supplier_code)
VALUES ($1, $2, $3, $4, $5, 1, $6)`,
[branchCode, branchName, contactName || null, contactPhone, address || null, mainSupplierCodeRaw || null]
);
// 新分公司:立即 active,业务表走独立 schema
@@ -796,16 +854,17 @@ router.post('/admin/branches', authMiddleware, async (req: AuthRequest, res: Res
// 原来这里是裸 INSERT,必然撞 profiles_pkey(23505),再被外层 catch 的
// /duplicate key value/ 误报成 "already_exists" —— 表现为"超管建分公司永远失败"。
await client.query(
`INSERT INTO profiles (id, username, full_name, phone, branch_code, status, must_change_password)
VALUES ($1, $2, $3, $4, $5, 1, true)
`INSERT INTO profiles (id, username, full_name, phone, branch_code, status, must_change_password, account_source)
VALUES ($1, $2, $3, $4, $5, 1, $6, $7)
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`,
[userId, username, fullName, profilePhone, branchCode]
must_change_password = EXCLUDED.must_change_password,
account_source = EXCLUDED.account_source`,
[userId, username, fullName, profilePhone, branchCode, !isMainSupplier, isMainSupplier ? 'main_supplier' : 'local']
);
await client.query(
@@ -822,11 +881,16 @@ router.post('/admin/branches', authMiddleware, async (req: AuthRequest, res: Res
}
return res.status(201).json({
branch: { branch_code: branchCode, branch_name: branchName },
branch: {
branch_code: branchCode,
branch_name: branchName,
main_supplier_code: mainSupplierCodeRaw || null,
},
account: {
username,
// 主系统供应商:本地密码不可用(登录回主系统校验)⇒ 不下发初始密码
default_password: initialPassword,
must_change_password: true,
must_change_password: !isMainSupplier,
},
});
} catch (error: any) {
@@ -841,7 +905,12 @@ router.post('/admin/branches', authMiddleware, async (req: AuthRequest, res: Res
}
});
/** 更新分公司资料(名称/联系人/电话/地址);不改 branch_code,不改登录账号 */
/**
* 更新分公司资料(名称/联系人/电话/地址/主系统供应商绑定);不改 branch_code,不改登录账号。
*
* `main_supplier_code` 语义(2026-10-10):传了就更新绑定(`null`/空串 = 解绑 ⇒ 变成"本系统自己的供应商",
* 该分公司的供应商账号将**无法再登录**,因为登录要求绑定一致)。故意开放给超管用于纠错。
*/
router.put('/admin/branches/:branchCode', authMiddleware, async (req: AuthRequest, res: Response) => {
try {
if (!(await requireAdmin(req, res))) return;
@@ -867,16 +936,40 @@ router.put('/admin/branches/:branchCode', authMiddleware, async (req: AuthReques
return res.status(400).json({ error: 'invalid_login', error_description: loginError });
}
const hasBindingField = req.body?.main_supplier_code !== undefined;
const nextBinding = hasBindingField
? String(req.body?.main_supplier_code || '').trim().toUpperCase() || null
: undefined;
if (nextBinding && !/^[A-Z0-9_-]{2,30}$/.test(nextBinding)) {
return res.status(400).json({
error: 'invalid_main_supplier_code',
error_description: '主系统供应商编码只能包含字母、数字、下划线和横线',
});
}
if (nextBinding) {
const bound = await pool.query(
`SELECT branch_code FROM branches WHERE main_supplier_code = $1 AND branch_code <> $2 LIMIT 1`,
[nextBinding, branchCode]
);
if (bound.rowCount) {
return res.status(409).json({
error: 'main_supplier_already_bound',
error_description: `主系统供应商 ${nextBinding} 已绑定分公司 ${bound.rows[0].branch_code}`,
});
}
}
const result = await pool.query(
`UPDATE branches
SET branch_name = $2,
contact_name = $3,
contact_phone = $4,
address = $5,
main_supplier_code = CASE WHEN $6::boolean THEN $7::varchar ELSE main_supplier_code END,
updated_at = NOW()
WHERE branch_code = $1
RETURNING branch_code, branch_name, contact_name, contact_phone, address, status, tax_level`,
[branchCode, branchName, contactName || null, contactPhone, address || null]
RETURNING branch_code, branch_name, contact_name, contact_phone, address, status, tax_level, main_supplier_code`,
[branchCode, branchName, contactName || null, contactPhone, address || null, hasBindingField, nextBinding ?? null]
);
if (!result.rowCount) {
return res.status(404).json({ error: 'not_found', error_description: '分公司不存在' });
@@ -0,0 +1,56 @@
import { pool } from '../db';
/**
* 分公司账号开通相关的**只读判定**(SQL 放 service:路由层有裸 SQL 棘轮
* `tests/routeLayerBoundary.test.ts`,新增 SQL 必须落在 services/)。
*/
export type BranchCreateConflict =
| { kind: 'branch_code' }
| { kind: 'username' }
| { kind: 'email' }
/** 该主系统供应商已被**另一家**分公司绑定 */
| { kind: 'main_supplier'; branchCode: string };
/**
* 建分公司前的冲突检查(一次问全,路由层只调这一个函数):
* ① 分公司编码已存在;② 登录名(手机号)已被占用;③ 邮箱已被占用;
* ④ **主系统供应商已被别家绑定**(`main_supplier_code` 唯一,2026-10-10 绑定口径)。
* 传了 `mainSupplierCode` 时④才参与判定。
*/
export async function findBranchCreateConflict(input: {
branchCode: string;
username: string;
email: string;
mainSupplierCode?: string | null;
}): Promise<BranchCreateConflict | null> {
const mainCode = String(input.mainSupplierCode || '').trim().toUpperCase() || null;
/**
* ⚠️ **顺序即优先级**:先判"该主系统供应商已被别家绑定"。
* 因为绑定主系统供应商时 `branch_code` 默认取该编码 ⇒ 重试/重复提交会**同时**命中两条冲突,
* 这时给"已绑定分公司 X"更有用(原来用 UNION + LIMIT 1,顺序由实现决定 ⇒ 实测给出的是
* 泛泛的 `already_exists`,指向不了真正原因)。
*/
if (mainCode) {
const bound = await pool.query<{ branch_code: string }>(
`SELECT branch_code FROM public.branches WHERE main_supplier_code = $1 LIMIT 1`,
[mainCode]
);
if (bound.rowCount) {
return { kind: 'main_supplier', branchCode: String(bound.rows[0].branch_code) };
}
}
const result = await pool.query<{ kind: string }>(
`SELECT 'branch_code' AS kind FROM public.branches WHERE branch_code = $1
UNION ALL
SELECT 'username' AS kind FROM public.profiles WHERE lower(username) = lower($2)
UNION ALL
SELECT 'email' AS kind FROM auth.users WHERE lower(email) = lower($3)
LIMIT 1`,
[input.branchCode, input.username, input.email]
);
const kind = result.rows[0]?.kind;
return kind ? ({ kind: kind as 'branch_code' | 'username' | 'email' }) : null;
}
@@ -1,4 +1,5 @@
import { config } from '../config';
import { pool } from '../db';
/**
* 向主系统(AI 生鲜配送)校验「供应商账号」的凭据,并取回供应商档案。
@@ -32,6 +33,53 @@ export type MainSupplierProfile = {
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 =
/**
* 校验通过。
@@ -8,6 +8,16 @@ 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)
+116
View File
@@ -0,0 +1,116 @@
import { describe, expect, it } from 'vitest';
import { readFileSync } from 'node:fs';
import { checkMainSupplierBinding } from '../src/services/mainSystemSupplierAuth';
/**
* 分公司 ↔ 主系统供应商的**显式绑定**(开发者 2026-10-10 裁决):
* 「需要超级管理员先去创建分公司,分公司的电话号码对应得上主系统时才能进行一个绑定主系统的供应商账号,
* 然后供应商才能使用这个供应商系统;而不是主系统存在就直接登录创建分公司
* —— 因为我们这个子系统还可能给非主系统的供应商使用。」
*
* 三条铁律:
* ① **登录不再惰性开通**(分公司/账号一律超管先建);
* ② 登录必须**比对**主系统返回的 supplier_code 与 `branches.main_supplier_code`;
* ③ 没绑定(NULL)= 本系统自己的供应商 ⇒ 该账号不允许走主系统通道登录。
*/
const authSrc = readFileSync(new URL('../src/routes/auth.ts', import.meta.url), 'utf8');
const supplierAuthSrc = readFileSync(new URL('../src/services/mainSystemSupplierAuth.ts', import.meta.url), 'utf8');
const branchAccountSrc = readFileSync(new URL('../src/services/branchAccountService.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('登录链路:不再惰性开通', () => {
it('登录里不再调用 ensureMainSupplierBranchAndAdmin(该服务已停用)', () => {
expect(authSrc).not.toContain('ensureMainSupplierBranchAndAdmin');
expect(authSrc).not.toContain('supplierBranchProvisioning');
});
it('两个登录入口的"本地没有该手机号"分支 ⇒ 403 未开通,而不是替他开通', () => {
const hits = authSrc.match(/error: 'supplier_not_provisioned'/g) ?? [];
expect(hits.length, '两个入口(/token 与 /unified-login)都要有').toBeGreaterThanOrEqual(2);
});
it('主系统校验通过后必须做绑定比对(不一致/未绑定各有独立错误码)', () => {
expect(authSrc).toContain('checkMainSupplierBinding({');
expect(authSrc).toContain("error: binding.reason === 'not_bound' ? 'branch_not_bound' : 'supplier_binding_mismatch'");
// 本地账号必须存在且来源是主系统供应商(SQL 在 service:路由层有裸 SQL 棘轮)
expect(authSrc).toContain('loadMainSupplierAccountForLogin(loginName)');
expect(supplierAuthSrc).toContain("p.account_source = 'main_supplier'");
expect(supplierAuthSrc).toContain('b.main_supplier_code');
});
it('建分公司的冲突检查也在 service(编码/登录名/邮箱占用 + 主系统供应商已被别家绑定)', () => {
expect(authSrc).toContain('findBranchCreateConflict({');
expect(branchAccountSrc).toContain('WHERE main_supplier_code = $1 LIMIT 1');
// 顺序即优先级:绑定冲突要先判(重复提交时同时命中两条,给"已绑定分公司 X"才有用)
expect(branchAccountSrc.indexOf('main_supplier_code = $1')).toBeLessThan(
branchAccountSrc.indexOf("SELECT 'branch_code' AS kind")
);
});
});
describe('超管建分公司:绑定落档', () => {
it('建分公司接受 main_supplier_code:写进 branches,编码默认取它,账号来源改 main_supplier', () => {
expect(authSrc).toContain('const mainSupplierCodeRaw = String(req.body?.main_supplier_code');
expect(authSrc).toContain('branchCode = mainSupplierCodeRaw || (await generateNextBranchCode(client))');
expect(authSrc).toContain('INSERT INTO branches (branch_code, branch_name, contact_name, contact_phone, address, status, main_supplier_code)');
expect(authSrc).toContain("isMainSupplier ? 'main_supplier' : 'local'");
// 主系统供应商账号:本地密码不可用、不下发初始密码
expect(authSrc).toContain('const initialPassword = isMainSupplier ? null : initialPasswordForBranchLogin(contactPhone)');
expect(authSrc).toContain('must_change_password: !isMainSupplier');
});
it('一个主系统供应商只能绑一家分公司(建与改都拦)', () => {
const hits = authSrc.match(/error: 'main_supplier_already_bound'/g) ?? [];
expect(hits.length).toBeGreaterThanOrEqual(2);
// 建的检查走 service;改的检查在 UPDATE 里带 CASE(同一 SQL 语句)
expect(branchAccountSrc).toContain("kind: 'main_supplier', branchCode");
});
it('编辑分公司可改绑定(空串 = 解绑)', () => {
expect(authSrc).toContain('const hasBindingField = req.body?.main_supplier_code !== undefined;');
expect(authSrc).toContain('main_supplier_code = CASE WHEN $6::boolean THEN $7::varchar ELSE main_supplier_code END');
});
});
describe('迁移:绑定列 + 存量回填', () => {
const migration = readFileSync(
new URL('../../migrations/20261026_branches_main_supplier_code.sql', import.meta.url),
'utf8'
);
it('加列、唯一索引、且回填只认"有 main_supplier 账号"这一证据', () => {
expect(migration).toMatch(/ADD COLUMN IF NOT EXISTS main_supplier_code VARCHAR\(64\)/);
expect(migration).toMatch(/CREATE UNIQUE INDEX IF NOT EXISTS uq_branches_main_supplier_code/);
expect(migration).toContain("p.account_source = 'main_supplier'");
expect(migration).toContain('SET main_supplier_code = b.branch_code');
});
});
+1
View File
@@ -257,6 +257,7 @@ export const system: MessageDict = {
"branches.ph.contact": "Contact",
"branches.ph.phone": "Phone",
"branches.ph.phoneLogin": "Login (phone or letters, e.g. chengdu_admin)",
"branches.ph.mainSupplierCode": "Main-system supplier code (optional, e.g. SUP38887897)",
"branches.ph.address": "Address (warehouse / depot for routing)",
"branches.act.saveEdit": "Save changes",
"branches.act.create": "Create branch",
+1
View File
@@ -257,6 +257,7 @@ export const system: MessageDict = {
"branches.ph.contact": "Kontak",
"branches.ph.phone": "Telepon",
"branches.ph.phoneLogin": "Login (telepon atau huruf, mis. chengdu_admin)",
"branches.ph.mainSupplierCode": "Kode pemasok sistem utama (opsional)",
"branches.ph.address": "Alamat (gudang / depo untuk rute)",
"branches.act.saveEdit": "Simpan perubahan",
"branches.act.create": "Buat cabang",
+1
View File
@@ -257,6 +257,7 @@ export const system: MessageDict = {
"branches.ph.contact": "联系人",
"branches.ph.phone": "联系电话",
"branches.ph.phoneLogin": "登录账号(手机号或字母,如 chengdu_admin)",
"branches.ph.mainSupplierCode": "主系统供应商编码(选填,如 SUP38887897)",
"branches.ph.address": "地址(仓库/出发点,供路线规划使用)",
"branches.act.saveEdit": "保存修改",
"branches.act.create": "创建分公司",
+7 -2
View File
@@ -534,11 +534,13 @@ export const supabase = {
contact_name?: string;
contact_phone: string;
address?: string;
/** 绑定的主系统供应商编码(可选);填了 ⇒ 该分公司管理员回主系统校验密码 */
main_supplier_code?: string | null;
}) {
try {
const result = await apiFetch<{
branch: { branch_code: string; branch_name: string };
account: { username: string; default_password: string; must_change_password: boolean };
branch: { branch_code: string; branch_name: string; main_supplier_code?: string | null };
account: { username: string; default_password: string | null; must_change_password: boolean };
}>('/auth/admin/branches', {
method: 'POST',
body: JSON.stringify(payload),
@@ -559,6 +561,8 @@ export const supabase = {
contact_name?: string;
contact_phone: string;
address?: string;
/** 传了就更新绑定(`null` = 解绑);不传 = 保持原绑定 */
main_supplier_code?: string | null;
}
) {
try {
@@ -571,6 +575,7 @@ export const supabase = {
address: string | null;
status: number;
tax_level?: string | null;
main_supplier_code?: string | null;
};
}>(`/auth/admin/branches/${encodeURIComponent(branchCode)}`, {
method: 'PUT',
+14
View File
@@ -44,6 +44,8 @@ interface Branch {
address: string | null;
status: number;
tax_level?: string | null;
/** 绑定的主系统供应商编码;null = 本系统自己的供应商 */
main_supplier_code?: string | null;
}
const emptyForm = {
@@ -51,6 +53,8 @@ const emptyForm = {
contact_name: '',
contact_phone: '',
address: '',
/** 主系统供应商编码(可选,2026-10-10):填了 ⇒ 该分公司管理员回主系统校验密码 */
main_supplier_code: '',
};
const DEFAULT_BRANCH_PASSWORD = '12345678';
@@ -111,6 +115,7 @@ export const BranchManagement: React.FC = () => {
contact_name: branch.contact_name || '',
contact_phone: branch.contact_phone || '',
address: branch.address || '',
main_supplier_code: branch.main_supplier_code || '',
});
window.scrollTo({ top: 0, behavior: 'smooth' });
};
@@ -143,6 +148,8 @@ export const BranchManagement: React.FC = () => {
contact_name: form.contact_name.trim() || undefined,
contact_phone: contactPhone,
address: form.address.trim() || undefined,
// 传了就更新绑定(空串 = 解绑);不传 = 保持原绑定
main_supplier_code: form.main_supplier_code.trim().toUpperCase(),
});
if (error) throw error;
cancelEdit();
@@ -156,6 +163,7 @@ export const BranchManagement: React.FC = () => {
contact_name: form.contact_name.trim() || undefined,
contact_phone: contactPhone,
address: form.address.trim() || undefined,
main_supplier_code: form.main_supplier_code.trim().toUpperCase() || null,
});
if (error) throw error;
setForm(emptyForm);
@@ -303,6 +311,12 @@ export const BranchManagement: React.FC = () => {
className="app-input px-4 py-2 border rounded-lg"
required
/>
<input
placeholder={t('system.branches.ph.mainSupplierCode')}
value={form.main_supplier_code}
onChange={(e) => setForm({ ...form, main_supplier_code: e.target.value })}
className="app-input px-4 py-2 border rounded-lg"
/>
<input
placeholder={t('system.branches.ph.address')}
value={form.address}