diff --git a/docs/design/20261010-主系统订单按配送日合并与缺货流转.md b/docs/design/20261010-主系统订单按配送日合并与缺货流转.md index ac9761d..d75f8bd 100644 --- a/docs/design/20261010-主系统订单按配送日合并与缺货流转.md +++ b/docs/design/20261010-主系统订单按配送日合并与缺货流转.md @@ -488,7 +488,40 @@ SUP92185841:2 张(10-09)→ MAIN_BR002;**另 2 张 10-08 老单不动** 按前端文案纪律,以上新增/改动文案**未经批准不视为定稿**,等你回话后我再调。 -### 9.5 本地数据说明 +# +### 9.6 修复:「主系统改派给别的供应商 / 转自采」时本地行没被剔除(2026-10-10 真库漏判) + +**现象**(开发者):「当前主系统将商品转移给了其他的供应商或者自采,为什么没有从这个供应商的订单中移除呢?」 + +**真库取证**(订单 `ORD_WEB_20261010_BR002_0001`,我方 `SUP38887897`,抄手皮/精瘦肉/苹果): + +| 侧 | 事实 | +|---|---| +| 主系统 `tenant_br002.supplier_preparations` | 我方那三条(`prep_id=b30e1466…` 等,12:26 建)**已不存在**;同一 `(order, sku)` 改成三条**新行**(14:09:15 建)挂在 **`supplier_code=SUP41472132`**(另一家供应商) | +| 主系统 lookup 返回 | 三条都是 `found=false` + `current_supplier_code=SUP41472132` + `reassigned=true`(`prepare_status=null`) | +| 我方台账 | 三条都还是 `disposition=imported`,`last_seen_active_at` 停在 14:09:04(改派前 11 秒) | + +**根因**:`isPreparationNoLongerOurs()` 第一行是 `if (!found) return false` —— +判据假设"改派后老备货行还在,只是 `reassigned=true`",但主系统实际实现是**删旧行 + 为新供应商另建一行** +⇒ 我方看到 `found=false` 就**直接放弃**,那三行永远留着(卡在"未完成采购",整单推不动)。 +另外"最后一轮对账还没跑到"也有一份:改派发生在 14:09:15,我方上一轮是 14:09:04(下一次 ≤10 分钟)。 + +**修法**:`reassigned` **优先于** `found` —— 只要 lookup 说"订单行当前供应商非空且不是我们",无论旧备货行在不在, +都算"不再属于我们";仍然不碰的只有"查不到 + 没有改派信号"(真正的退货/取消/删除,交给开关控制的退货跟随)。 + +**真库验证**(修后手动跑一轮该分公司导入): +``` +[main-system-import] SUP38887897:主系统已转走「抄手皮」⇒ 已从本地订单剔除 +[main-system-import] SUP38887897:主系统已转走「精瘦肉」⇒ 已从本地订单剔除 +[main-system-import] SUP38887897:主系统已转走「苹果」⇒ 已从本地订单剔除 +[main-system-import] SUP38887897 缺货跟随:已剔除 3 行 / 有货物事实未剔除 0 行 +台账:imported → skipped_stockout(原因:主系统已把该行转走,本地剔除);我方订单剩余行:0 +``` +⚠️ **对主系统的契约依赖**:lookup 必须**在 `found=false` 时也照常返回 `current_supplier_code` / `reassigned`** +(他们现在就是这么做的)——否则我们无法区分"改派"与"退货/取消"。已写进对接清单。 +⚠️ **遗留决策**:三行全被剔除后订单变成**空单**(`order_status=30`、金额 0、0 行)仍在列表里;要不要自动关闭/移除空单,等开发者裁决。 + +## 9.5 本地数据说明 验收时把本地**我们自己导入的 6 张单**(`ORD_API_*`,客户 `MAIN_SUP37831443`)与三张台账清掉后重导,得到 1 张日单; 主系统数据**全程未改**(缺货验证用的是本地 stub 主系统)。重导前的 6 张单可由主系统随时重新拉取重建。 diff --git a/docs/design/20261010-分公司开通与主系统供应商绑定.md b/docs/design/20261010-分公司开通与主系统供应商绑定.md new file mode 100644 index 0000000..a0db4ee --- /dev/null +++ b/docs/design/20261010-分公司开通与主系统供应商绑定.md @@ -0,0 +1,95 @@ +# 分公司开通与「主系统供应商」绑定(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 家 | + +## 4.1 附带清理:历史迁移里写死的「华东分公司 BR002」(2026-10-10) + +**现象**(开发者):分公司管理页里冒出一行「**华东分公司** 4000000002 / 华东负责人 / 上海市浦东新区示例路100号」, +问"为什么这里面会存在这个华东分公司?" + +**根因**:它是**建库基础迁移里写死的演示数据**,与任何主系统供应商无关: + +| 迁移 | 内容 | +|---|---| +| `20260607_create_branch_tenant.sql` | `INSERT INTO branches VALUES ('BR001','默认分公司',…), ('BR002','华东分公司','华东负责人','4000000002','上海市浦东新区示例路100号')` | +| `20260608_orders_branch_isolation.sql` | 又插一次 `('BR001','默认分公司'), ('BR002','华东分公司')`(`ON CONFLICT DO NOTHING`) | + +截图里的 4000000002 / 华东负责人 / 上海市浦东新区示例路100号 与迁移字面值**逐字一致** ⇒ 证据确凿。 +「华东分公司」是**主系统(配送系统)自己的经营单元**,被历史基础迁移顺手带进了本仓库; +而本系统的「分公司 = 主系统的**供应商**」(编码 `SUPxxxxx`,由开通流程创建)⇒ 这行既无供应商对应、也无业务数据。 + +**处置**(开发者裁决:「治根 —— 把历史的那条迁移指令删掉,整理好」): + +| 项 | 处理 | +|---|---| +| **BR002 那两条 INSERT** | **从历史迁移中删除**(`20260607` / `20260608` 各一处),并在原处留注释说明为什么不再插入 ⇒ **新机器建库不会再出现** | +| `seed-demo-data.ts` 的演示客户 `CUST003`(原挂 BR002) | 改挂 **BR001**(否则演示种子会撞 `branches` 外键) | +| **BR001「默认分公司」** | **保留**:它是 `PLATFORM_BRANCH_CODE` 的默认值(平台级配置/超管落地依赖它),且演示账号(admin/operator/finance/warehouse/delivery)挂在它下面 | +| `20261009_br002_*` 两条**业务数据**迁移 | 不动:它们按客户名单开扣点、且都有 `to_regclass` 守卫,在无 `tenant_br002` 时**空转**(不是"建分公司") | +| 存量本地库 | 删掉 `BR002` 行 + 其全部引用行(`legacy_public.categories` 15 行)+ 租户注册行 + `tenant_br002` schema;`purchaser1` 演示账号改挂 BR001 | +| 附带 | 删掉随"主系统结构"拷进来、**未注册**的孤儿租户 schema `tenant_br003..007`(空) | + +**验证**:`branches` 只剩 `BR001 默认分公司`;租户 schema 只剩 `tenant_br001 + tenant_template`; +`migrationReplayHygiene.test.ts` 4 绿;设计门禁同基线(`check-migrations.py` ✅)。 + +## 5. 不变量与影响面 + +- **主系统供应商的密码权威仍在主系统**:本地密码不可用、改密/停用即时生效(与改造前一致); +- **非主系统供应商不受影响**:走本地账号 + 本地密码(现状),只是现在**不会**被误绑到主系统供应商; +- **订单/导入不受影响**:导入只认 `branches` + 台账,与登录无关; +- **未做/待定**:① 分公司列表暂未展示绑定列(要靠表单回填看到);② 解绑后该供应商立即无法登录(刻意如此,防呆); + ③ 主系统侧"按手机号查供应商"的只读接口(可在超管建分公司时自动带出编码)已记为可选增强,未向对方提出。 diff --git a/docs/给主系统AI的对接改造清单.md b/docs/给主系统AI的对接改造清单.md index bd5699b..305619c 100644 --- a/docs/给主系统AI的对接改造清单.md +++ b/docs/给主系统AI的对接改造清单.md @@ -2089,6 +2089,47 @@ prep `931eda1a-3c19-4b49-ab24-664b54770fc4` / `SUP35143228` / `ORD_WEB_20261009_ **含义**:如果分配量本身就错了,请**你们侧改**(改完按上面的申请通道通知我方);我方不会替你们改,也不会用改量的方式绕过。 我方内部可用「缺货」上报处理"量不够/供不了"的场景。 +### 4.5.14 我方回执 · lookup 的「改派」信号现在是**契约依赖**(2026-10-10) + +背景:主系统把某行**改派给别的供应商 / 转自采**后,我方订单里那行必须被剔除(开发者报障:"为什么没有从 +这个供应商的订单中移除呢")。实测你们的落地方式是**删掉我们那条 `supplier_preparations` + 为同一 +`(order_code, sku_code)` 另建一条挂到新供应商**,于是 lookup 返回: + +```json +{ "found": false, "id": "<我们原来的 prep_id>", "prepare_status": null, + "current_supplier_code": "SUP41472132", "reassigned": true } +``` + +**请保持这个语义**(我们已按它改好判据,并依赖它在 `found=false` 时**照常**返回这两个字段): + +| 字段 | 我们的用法 | 请勿改成 | +|---|---|---| +| `current_supplier_code` | 订单行**当前**归属的供应商;非空且 ≠ 我们 ⇒ 判定"不再属于我们",**无论 `found` 真假** | 不要在 `found=false` 时省略/null(否则我们无法区分"改派"与"退货/取消",只能不动作) | +| `reassigned` | 同上,作为**布尔快捷判据**(= `current_supplier_code != null && ≠ 请求方`) | 不要只在 `found=true` 时给 `true` | +| `prepare_status=40` | "转自采"的另一种形态(旧行还在时) | 保持 | + +我方**不碰**的情形(避免误删):`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 主系统侧疑似既有缺陷(同源代码,两个仓库都有,请主系统判断是否修) diff --git a/migrations/20260607_create_branch_tenant.sql b/migrations/20260607_create_branch_tenant.sql index 9fd05cb..3820796 100644 --- a/migrations/20260607_create_branch_tenant.sql +++ b/migrations/20260607_create_branch_tenant.sql @@ -1,64 +1,66 @@ --- 分公司(多租户)隔离 - -CREATE TABLE IF NOT EXISTS branches ( - branch_code VARCHAR(50) PRIMARY KEY, - branch_name VARCHAR(200) NOT NULL, - contact_name VARCHAR(100), - contact_phone VARCHAR(20), - address TEXT, - status INTEGER DEFAULT 1, - created_at TIMESTAMPTZ DEFAULT NOW(), - updated_at TIMESTAMPTZ DEFAULT NOW() -); - -INSERT INTO branches (branch_code, branch_name, contact_name, contact_phone, address) -VALUES ('BR001', '默认分公司', '平台默认', '4000000000', '总部') -ON CONFLICT (branch_code) DO NOTHING; - -INSERT INTO branches (branch_code, branch_name, contact_name, contact_phone, address) -VALUES ('BR002', '华东分公司', '华东负责人', '4000000002', '上海市浦东新区示例路100号') -ON CONFLICT (branch_code) DO NOTHING; - -ALTER TABLE profiles ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50) REFERENCES branches(branch_code); -ALTER TABLE customers ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50) REFERENCES branches(branch_code); -ALTER TABLE suppliers ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50) REFERENCES branches(branch_code); -ALTER TABLE orders ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50) REFERENCES branches(branch_code); -ALTER TABLE warehouses ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50) REFERENCES branches(branch_code); -ALTER TABLE purchase_orders ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50) REFERENCES branches(branch_code); -ALTER TABLE delivery_persons ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50) REFERENCES branches(branch_code); -ALTER TABLE after_sales ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50) REFERENCES branches(branch_code); -ALTER TABLE exception_tickets ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50) REFERENCES branches(branch_code); -ALTER TABLE customer_statements ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50) REFERENCES branches(branch_code); -ALTER TABLE supplier_statements ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50) REFERENCES branches(branch_code); -ALTER TABLE invoices ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50) REFERENCES branches(branch_code); -ALTER TABLE delivery_tasks ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50) REFERENCES branches(branch_code); -ALTER TABLE inventory ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50) REFERENCES branches(branch_code); -ALTER TABLE supplier_preparations ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50) REFERENCES branches(branch_code); -ALTER TABLE inspections ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50) REFERENCES branches(branch_code); - -UPDATE customers SET branch_code = 'BR001' WHERE branch_code IS NULL; -UPDATE suppliers SET branch_code = 'BR001' WHERE branch_code IS NULL; -UPDATE orders SET branch_code = 'BR001' WHERE branch_code IS NULL; -UPDATE warehouses SET branch_code = 'BR001' WHERE branch_code IS NULL; -UPDATE purchase_orders SET branch_code = 'BR001' WHERE branch_code IS NULL; -UPDATE delivery_persons SET branch_code = 'BR001' WHERE branch_code IS NULL; -UPDATE after_sales SET branch_code = 'BR001' WHERE branch_code IS NULL; -UPDATE exception_tickets SET branch_code = 'BR001' WHERE branch_code IS NULL; -UPDATE customer_statements SET branch_code = 'BR001' WHERE branch_code IS NULL; -UPDATE supplier_statements SET branch_code = 'BR001' WHERE branch_code IS NULL; -UPDATE invoices SET branch_code = 'BR001' WHERE branch_code IS NULL; -UPDATE delivery_tasks SET branch_code = 'BR001' WHERE branch_code IS NULL; -UPDATE inventory SET branch_code = 'BR001' WHERE branch_code IS NULL; -UPDATE supplier_preparations SET branch_code = 'BR001' WHERE branch_code IS NULL; -UPDATE inspections SET branch_code = 'BR001' WHERE branch_code IS NULL; - --- 超级管理员不绑定分公司;其余默认账号归属 BR001 -UPDATE profiles SET branch_code = 'BR001' -WHERE branch_code IS NULL - AND id NOT IN ( - SELECT user_id FROM user_roles WHERE role = 'super_admin' - ); - -ALTER TABLE branches ENABLE ROW LEVEL SECURITY; -CREATE POLICY anon_select_branches ON branches FOR SELECT USING (true); -CREATE POLICY anon_manage_branches ON branches FOR ALL USING (true); +-- 分公司(多租户)隔离 + +CREATE TABLE IF NOT EXISTS branches ( + branch_code VARCHAR(50) PRIMARY KEY, + branch_name VARCHAR(200) NOT NULL, + contact_name VARCHAR(100), + contact_phone VARCHAR(20), + address TEXT, + status INTEGER DEFAULT 1, + created_at TIMESTAMPTZ DEFAULT NOW(), + updated_at TIMESTAMPTZ DEFAULT NOW() +); + +-- 平台默认分公司(`PLATFORM_BRANCH_CODE` 默认值 = BR001;平台级配置/超管落地都依赖它)。 +-- ⚠️ 2026-10-10 开发者裁定:**不再插入 BR002「华东分公司」**。 +-- 那行是主系统(配送系统)自己的经营单元名,被历史基础迁移顺手带进了本仓库; +-- 本系统里「分公司 = 主系统的**供应商**」(编码 `SUPxxxxx`,由开通流程创建), +-- 凭空多出一家「华东分公司」既无对应供应商、也无业务数据,纯属建库残留 +-- (每次在新机器上建库都会冒出来 ⇒ 本次连同 20260608 一并清掉)。 +INSERT INTO branches (branch_code, branch_name, contact_name, contact_phone, address) +VALUES ('BR001', '默认分公司', '平台默认', '4000000000', '总部') +ON CONFLICT (branch_code) DO NOTHING; + +ALTER TABLE profiles ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50) REFERENCES branches(branch_code); +ALTER TABLE customers ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50) REFERENCES branches(branch_code); +ALTER TABLE suppliers ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50) REFERENCES branches(branch_code); +ALTER TABLE orders ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50) REFERENCES branches(branch_code); +ALTER TABLE warehouses ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50) REFERENCES branches(branch_code); +ALTER TABLE purchase_orders ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50) REFERENCES branches(branch_code); +ALTER TABLE delivery_persons ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50) REFERENCES branches(branch_code); +ALTER TABLE after_sales ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50) REFERENCES branches(branch_code); +ALTER TABLE exception_tickets ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50) REFERENCES branches(branch_code); +ALTER TABLE customer_statements ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50) REFERENCES branches(branch_code); +ALTER TABLE supplier_statements ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50) REFERENCES branches(branch_code); +ALTER TABLE invoices ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50) REFERENCES branches(branch_code); +ALTER TABLE delivery_tasks ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50) REFERENCES branches(branch_code); +ALTER TABLE inventory ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50) REFERENCES branches(branch_code); +ALTER TABLE supplier_preparations ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50) REFERENCES branches(branch_code); +ALTER TABLE inspections ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50) REFERENCES branches(branch_code); + +UPDATE customers SET branch_code = 'BR001' WHERE branch_code IS NULL; +UPDATE suppliers SET branch_code = 'BR001' WHERE branch_code IS NULL; +UPDATE orders SET branch_code = 'BR001' WHERE branch_code IS NULL; +UPDATE warehouses SET branch_code = 'BR001' WHERE branch_code IS NULL; +UPDATE purchase_orders SET branch_code = 'BR001' WHERE branch_code IS NULL; +UPDATE delivery_persons SET branch_code = 'BR001' WHERE branch_code IS NULL; +UPDATE after_sales SET branch_code = 'BR001' WHERE branch_code IS NULL; +UPDATE exception_tickets SET branch_code = 'BR001' WHERE branch_code IS NULL; +UPDATE customer_statements SET branch_code = 'BR001' WHERE branch_code IS NULL; +UPDATE supplier_statements SET branch_code = 'BR001' WHERE branch_code IS NULL; +UPDATE invoices SET branch_code = 'BR001' WHERE branch_code IS NULL; +UPDATE delivery_tasks SET branch_code = 'BR001' WHERE branch_code IS NULL; +UPDATE inventory SET branch_code = 'BR001' WHERE branch_code IS NULL; +UPDATE supplier_preparations SET branch_code = 'BR001' WHERE branch_code IS NULL; +UPDATE inspections SET branch_code = 'BR001' WHERE branch_code IS NULL; + +-- 超级管理员不绑定分公司;其余默认账号归属 BR001 +UPDATE profiles SET branch_code = 'BR001' +WHERE branch_code IS NULL + AND id NOT IN ( + SELECT user_id FROM user_roles WHERE role = 'super_admin' + ); + +ALTER TABLE branches ENABLE ROW LEVEL SECURITY; +CREATE POLICY anon_select_branches ON branches FOR SELECT USING (true); +CREATE POLICY anon_manage_branches ON branches FOR ALL USING (true); diff --git a/migrations/20260608_orders_branch_isolation.sql b/migrations/20260608_orders_branch_isolation.sql index be46e61..5ef7886 100644 --- a/migrations/20260608_orders_branch_isolation.sql +++ b/migrations/20260608_orders_branch_isolation.sql @@ -1,45 +1,46 @@ --- 订单/明细分公司隔离(可重复执行) - -ALTER TABLE orders ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50); -ALTER TABLE order_items ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50); - -CREATE TABLE IF NOT EXISTS branches ( - branch_code VARCHAR(50) PRIMARY KEY, - branch_name VARCHAR(200) NOT NULL, - status INTEGER DEFAULT 1, - created_at TIMESTAMPTZ DEFAULT NOW(), - updated_at TIMESTAMPTZ DEFAULT NOW() -); - -INSERT INTO branches (branch_code, branch_name) VALUES - ('BR001', '默认分公司'), - ('BR002', '华东分公司') -ON CONFLICT (branch_code) DO NOTHING; - -ALTER TABLE customers ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50); -ALTER TABLE profiles ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50); - -UPDATE customers SET branch_code = 'BR001' WHERE branch_code IS NULL; -UPDATE orders o -SET branch_code = c.branch_code -FROM customers c -WHERE o.customer_code = c.customer_code AND (o.branch_code IS NULL OR o.branch_code = ''); - -UPDATE order_items oi -SET branch_code = o.branch_code -FROM orders o -WHERE oi.order_code = o.order_code AND (oi.branch_code IS NULL OR oi.branch_code = ''); - -ALTER TABLE customer_skus ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50); -UPDATE customer_skus cs -SET branch_code = c.branch_code -FROM customers c -WHERE cs.customer_code = c.customer_code AND (cs.branch_code IS NULL OR cs.branch_code = ''); - -UPDATE profiles SET branch_code = 'BR001' -WHERE branch_code IS NULL - AND id NOT IN (SELECT user_id FROM user_roles WHERE role = 'super_admin'); - -CREATE INDEX IF NOT EXISTS idx_orders_branch_code ON orders(branch_code); -CREATE INDEX IF NOT EXISTS idx_order_items_branch_code ON order_items(branch_code); -CREATE INDEX IF NOT EXISTS idx_customers_branch_code ON customers(branch_code); +-- 订单/明细分公司隔离(可重复执行) + +ALTER TABLE orders ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50); +ALTER TABLE order_items ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50); + +CREATE TABLE IF NOT EXISTS branches ( + branch_code VARCHAR(50) PRIMARY KEY, + branch_name VARCHAR(200) NOT NULL, + status INTEGER DEFAULT 1, + created_at TIMESTAMPTZ DEFAULT NOW(), + updated_at TIMESTAMPTZ DEFAULT NOW() +); + +-- ⚠️ 2026-10-10:只保留平台默认分公司 BR001;BR002「华东分公司」是主系统自己的经营单元名, +-- 不属于本系统(本系统分公司 = 主系统供应商,由开通流程创建),已从历史迁移中删除。 +INSERT INTO branches (branch_code, branch_name) VALUES + ('BR001', '默认分公司') +ON CONFLICT (branch_code) DO NOTHING; + +ALTER TABLE customers ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50); +ALTER TABLE profiles ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50); + +UPDATE customers SET branch_code = 'BR001' WHERE branch_code IS NULL; +UPDATE orders o +SET branch_code = c.branch_code +FROM customers c +WHERE o.customer_code = c.customer_code AND (o.branch_code IS NULL OR o.branch_code = ''); + +UPDATE order_items oi +SET branch_code = o.branch_code +FROM orders o +WHERE oi.order_code = o.order_code AND (oi.branch_code IS NULL OR oi.branch_code = ''); + +ALTER TABLE customer_skus ADD COLUMN IF NOT EXISTS branch_code VARCHAR(50); +UPDATE customer_skus cs +SET branch_code = c.branch_code +FROM customers c +WHERE cs.customer_code = c.customer_code AND (cs.branch_code IS NULL OR cs.branch_code = ''); + +UPDATE profiles SET branch_code = 'BR001' +WHERE branch_code IS NULL + AND id NOT IN (SELECT user_id FROM user_roles WHERE role = 'super_admin'); + +CREATE INDEX IF NOT EXISTS idx_orders_branch_code ON orders(branch_code); +CREATE INDEX IF NOT EXISTS idx_order_items_branch_code ON order_items(branch_code); +CREATE INDEX IF NOT EXISTS idx_customers_branch_code ON customers(branch_code); diff --git a/migrations/20261026_branches_main_supplier_code.sql b/migrations/20261026_branches_main_supplier_code.sql new file mode 100644 index 0000000..524274d --- /dev/null +++ b/migrations/20261026_branches_main_supplier_code.sql @@ -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; diff --git a/migrations/20261026_warehouse_storage_zone.sql b/migrations/20261028_warehouse_storage_zone.sql similarity index 100% rename from migrations/20261026_warehouse_storage_zone.sql rename to migrations/20261028_warehouse_storage_zone.sql diff --git a/migrations/20261027_branch_supplier_categories.sql b/migrations/20261029_branch_supplier_categories.sql similarity index 100% rename from migrations/20261027_branch_supplier_categories.sql rename to migrations/20261029_branch_supplier_categories.sql diff --git a/server/src/routes/auth.ts b/server/src/routes/auth.ts index c971328..2c02d98 100644 --- a/server/src/routes/auth.ts +++ b/server/src/routes/auth.ts @@ -50,15 +50,16 @@ 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 { - loadAccountSourceByLoginName, - loginWithMainSupplierCredential, -} from '../services/mainSystemSupplierLogin'; +import { loadAuthUsersByIds } from '../services/accountLoginService'; import { listAssignableRoleCodes } from '../services/roleDefinitionService'; const router = Router(); @@ -443,12 +444,20 @@ async function createAuthUser(params: { return runInBranchSchema(branchCode, runCreate); } +/** 该登录名是否属于「主系统供应商账号」(本地密码不可用,必须回主系统校验) */ +async function loadAccountSource(loginName: string): Promise { + const result = await pool.query<{ account_source: string }>( + `SELECT account_source FROM profiles WHERE lower(username) = lower($1) LIMIT 1`, + [loginName] + ); + return result.rows[0]?.account_source ?? null; +} + /** * 供应商账号登录:向主系统校验 → 通过则(必要时)惰性开通分公司+管理员 → 签发本系统 token。 * - * 校验/开通的实现在 `loginWithMainSupplierCredential`(与小程序入口共用);本函数只负责 - * 把三态结果映射成 HTTP 响应: - * ok → 签发会话 + * 三态处理是本函数的核心: + * ok → 登录 * invalid → 400(主系统明确说凭据不对/账号不可用) * unavailable → 503(**没问成**:未配置/超时/网络/5xx)。**绝不回落本地密码**, * 否则主系统一挂,供应商就能拿本地旧密码登进来,绕过主系统的停用与改密。 @@ -465,29 +474,62 @@ async function handleMainSupplierLogin( */ issueSession: (user: AuthUserRow) => Promise = (user) => jsonTokenSession(res, user) ): Promise { - const outcome = await loginWithMainSupplierCredential(loginName, password); + const verdict = await verifySupplierCredentialOnMainSystem(loginName, password); - if (outcome.kind === 'unavailable') { + if (verdict.kind === 'unavailable') { + console.warn(`[login] 供应商账号登录未能完成主系统校验(${verdict.reason}):${loginName}`); return res.status(503).json({ error: 'main_system_unavailable', error_description: '主系统暂时不可用,供应商账号暂时无法登录,请稍后重试', }); } - if (outcome.kind === 'login_name_taken') { - return res.status(409).json({ - error: 'login_name_taken', - error_description: '该手机号已被本系统内部账号占用,请联系超级管理员处理', - }); - } - if (outcome.kind === 'internal_error') { - return res.status(500).json({ error: 'server_error', error_description: '登录失败,请稍后重试' }); - } - if (outcome.kind !== 'ok') { + if (verdict.kind !== 'ok') { return res.status(400).json({ error: 'invalid_credentials', error_description: '登录名或密码错误' }); } - return issueSession(outcome.user); + + /** + * ⚠️ **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([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(); @@ -497,7 +539,7 @@ router.post('/token', async (req: Request, res: Response) => { } // ① 主系统供应商账号:本地密码是随机不可用值,一律以主系统为准 - if (await loadAccountSourceByLoginName(loginName) === 'main_supplier') { + if (await loadAccountSource(loginName) === 'main_supplier') { // 必须 await:直接 return Promise 会让 reject 绕过本函数的 try/catch return await handleMainSupplierLogin(res, loginName, password); } @@ -518,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: '登录名或密码错误' }); @@ -559,7 +607,7 @@ router.post('/unified-login', async (req: Request, res: Response) => { } // ① 主系统供应商账号:与 /token 同一条通道(本地密码是随机不可用值,以主系统为准) - if (await loadAccountSourceByLoginName(loginName) === 'main_supplier') { + if (await loadAccountSource(loginName) === 'main_supplier') { return await handleMainSupplierLogin(res, loginName, password, (user) => jsonUnifiedSession(res, user, loginName) ); @@ -573,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: '登录名或密码错误' }); @@ -689,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) { @@ -697,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 = ''; @@ -713,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: '分公司编码或登录账号已存在', @@ -738,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 @@ -779,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( @@ -805,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) { @@ -824,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; @@ -841,10 +927,6 @@ router.put('/admin/branches/:branchCode', authMiddleware, async (req: AuthReques const contactName = String(req.body?.contact_name || '').trim(); const contactPhone = normalizeBranchAccountLogin(req.body?.contact_phone); const address = String(req.body?.address || '').trim(); - const supplierCategoriesProvided = Object.prototype.hasOwnProperty.call(req.body || {}, 'supplier_categories'); - const supplierCategories = supplierCategoriesProvided - ? String(req.body?.supplier_categories ?? '').trim().slice(0, 500) - : null; const loginError = validateBranchAccountLogin(contactPhone); if (!branchName) { @@ -854,17 +936,47 @@ 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}`, + }); + } + } + + // 经营分类(supplier_categories,2026-10-10):传了就更新,不传保持不变 + const supplierCategoriesProvided = Object.prototype.hasOwnProperty.call(req.body || {}, 'supplier_categories'); + const supplierCategories = supplierCategoriesProvided + ? String(req.body?.supplier_categories ?? '').trim().slice(0, 500) + : null; + const result = await pool.query( `UPDATE branches SET branch_name = $2, contact_name = $3, contact_phone = $4, address = $5, - supplier_categories = CASE WHEN $6::boolean THEN $7 ELSE supplier_categories END, + main_supplier_code = CASE WHEN $6::boolean THEN $7::varchar ELSE main_supplier_code END, + supplier_categories = CASE WHEN $8::boolean THEN $9::text ELSE supplier_categories END, updated_at = NOW() WHERE branch_code = $1 - RETURNING branch_code, branch_name, contact_name, contact_phone, address, status, tax_level, supplier_categories`, - [branchCode, branchName, contactName || null, contactPhone, address || null, supplierCategoriesProvided, supplierCategories] + RETURNING branch_code, branch_name, contact_name, contact_phone, address, status, tax_level, main_supplier_code, supplier_categories`, + [branchCode, branchName, contactName || null, contactPhone, address || null, hasBindingField, nextBinding ?? null, supplierCategoriesProvided, supplierCategories] ); if (!result.rowCount) { return res.status(404).json({ error: 'not_found', error_description: '分公司不存在' }); diff --git a/server/src/routes/mobile/mobileAuthRoutes.ts b/server/src/routes/mobile/mobileAuthRoutes.ts index d21a04c..269a6a6 100644 --- a/server/src/routes/mobile/mobileAuthRoutes.ts +++ b/server/src/routes/mobile/mobileAuthRoutes.ts @@ -20,43 +20,57 @@ import { MobileRoleType, } from './mobileShared'; import { + checkMainSupplierBinding, isMainSystemVerificationEnabled, + loadMainSupplierAccountForLogin, looksLikeSupplierLoginName, + verifySupplierCredentialOnMainSystem, } from '../../services/mainSystemSupplierAuth'; -import { - loadAccountSourceByLoginName, - loginWithMainSupplierCredential, -} from '../../services/mainSystemSupplierLogin'; +import { loadAuthUsersByIds } from '../../services/accountLoginService'; const router = Router(); /** * 主系统供应商账号(= 本系统分公司管理员):本地密码不可用,先回主系统校验后发 mobile token。 - * 与 Web 入口走同一套 `loginWithMainSupplierCredential`,避免小程序端“永远登不进”。 + * + * 口径与 Web 一致(2026-10-10 开发者裁决):**不自动开分公司**。必须由超管先建分公司、 + * 绑定主系统供应商编码,且本地已有 `account_source='main_supplier'` 账号,供应商才可能登录。 */ async function respondMainSupplierMobileLogin( res: Response, loginName: string, password: string, + account: { id: string; branch_code: string | null; main_supplier_code: string | null }, roleType?: MobileRoleType ) { - const outcome = await loginWithMainSupplierCredential(loginName, password); - if (outcome.kind === 'unavailable') { + const verdict = await verifySupplierCredentialOnMainSystem(loginName, password); + if (verdict.kind === 'unavailable') { return res.status(503).json({ error: 'main_system_unavailable', error_description: '主系统暂时不可用,供应商账号暂时无法登录,请稍后重试', }); } - if (outcome.kind === 'login_name_taken') { - return res.status(409).json({ - error: 'login_name_taken', - error_description: '该手机号已被本系统内部账号占用,请联系超级管理员处理', - }); - } - if (outcome.kind !== 'ok') { + if (verdict.kind !== 'ok') { return res.status(400).json({ error: 'invalid_credentials', error_description: '登录名或密码错误' }); } - const payload = await createMobileLoginResponse(outcome.user.id, outcome.user.email, roleType); + const binding = checkMainSupplierBinding({ + profileSupplierCode: verdict.profile.supplierCode, + boundMainSupplierCode: account.main_supplier_code, + }); + if (!binding.ok) { + 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([account.id]); + if (!user) { + return res.status(500).json({ error: 'server_error', error_description: '登录失败,请稍后重试' }); + } + const payload = await createMobileLoginResponse(user.id, user.email, roleType); return res.json(payload); } @@ -71,8 +85,9 @@ router.post('/login', async (req, res: Response) => { } // ① 主系统供应商账号:本地密码是随机不可用值,一律以主系统为准 - if ((await loadAccountSourceByLoginName(username)) === 'main_supplier') { - return await respondMainSupplierMobileLogin(res, username, password, roleType); + const mainAccount = await loadMainSupplierAccountForLogin(username); + if (mainAccount) { + return await respondMainSupplierMobileLogin(res, username, password, mainAccount, roleType); } const { verifyLoginNameOutcome, loginOutcomeToNeedBranchJson } = await import( @@ -87,9 +102,12 @@ router.post('/login', async (req, res: Response) => { return res.json(payload); } - // ② 本地没有/没通过:可能是尚未开通的主系统供应商(手机号)⇒ 惰性开通后登录 + // ② 本地没有/没通过:**不再惰性开通**(2026-10-10 口径)。手机号形态给可执行提示。 if (looksLikeSupplierLoginName(username) && isMainSystemVerificationEnabled()) { - return await respondMainSupplierMobileLogin(res, username, password, roleType); + return res.status(403).json({ + error: 'supplier_not_provisioned', + error_description: '该供应商尚未在本系统开通,请联系超级管理员先创建分公司并绑定', + }); } return res.status(400).json({ error: 'invalid_credentials', error_description: '登录名或密码错误' }); diff --git a/server/src/seed-demo-data.ts b/server/src/seed-demo-data.ts index a888e8f..475466a 100644 --- a/server/src/seed-demo-data.ts +++ b/server/src/seed-demo-data.ts @@ -22,7 +22,7 @@ export async function seedDemoData(pool: Pool) { INSERT INTO customers (customer_code, company_name, contact_name, contact_phone, address, status, branch_code) VALUES ('CUST001', '阳光食堂', '张经理', '13800000001', '北京市朝阳区示范路1号', 10, 'BR001'), ('CUST002', '绿野学校食堂', '李老师', '13800000002', '北京市海淀区学院路88号', 10, 'BR001'), - ('CUST003', '华东示范食堂', '周经理', '13800000003', '上海市浦东新区示例路66号', 10, 'BR002') + ('CUST003', '示范食堂三店', '周经理', '13800000003', '上海市浦东新区示例路66号', 10, 'BR001') ON CONFLICT (customer_code) DO NOTHING `); } diff --git a/server/src/services/branchAccountService.ts b/server/src/services/branchAccountService.ts new file mode 100644 index 0000000..b4d31ae --- /dev/null +++ b/server/src/services/branchAccountService.ts @@ -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 { + 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; +} diff --git a/server/src/services/mainSystemOrderImport.ts b/server/src/services/mainSystemOrderImport.ts index c79de35..4ae51ce 100644 --- a/server/src/services/mainSystemOrderImport.ts +++ b/server/src/services/mainSystemOrderImport.ts @@ -1598,13 +1598,20 @@ export async function importMainSystemOrders(params: { * 主系统这一行是不是"已经不属于我们了"(开发者 2026-10-10 口径: * 「只需主系统那边是转移了、没有再次分配给这个供应商,那么本地就不该存在」)。 * - * 判据(来自真实主系统实测,针对被转自采的 `蚝油` 行): + * 判据(来自真实主系统实测,针对被转自采的 `蚝油` 行;2026-10-10 补"改派删行"形态): * - 该行**已不在** `view=active` 列表里(转移后主系统就不再把它当我们的备货任务); - * - 且 `lookup` 还能查到它,并且 - * · `prepare_status = 40`(= 主系统把该行转自采;主系统 `transferPreparationStockoutToPurchase` 落的就是 40),**或** - * · `reassigned = true` 且当前供应商不是我们(改派给了别人 / INTERNAL)。 - * 只认这两种"明确不再属于我们"的情形;`found=false`(行被删)与"还在我们名下"一律不碰, - * 留给开关控制的退货跟随去判(避免把"退货/取消"误当缺货清掉)。 + * - 且 `lookup` 给出下面任一"明确不再属于我们"的信号: + * · `prepare_status = 40`(= 主系统把该行转自采;`transferPreparationStockoutToPurchase` 落的就是 40),**或** + * · `reassigned = true` 且**订单行当前供应商不是我们**(改派给别人 / INTERNAL)。 + * + * ⚠️ 2026-10-10 修正(真库实测的漏判):主系统"改派给别的供应商"落地成 + * **删掉我们那条 `supplier_preparations` 行 + 为同一 (order, sku) 另建一条挂到新供应商**, + * 于是我们那条的 `found=false` —— 而旧实现 `if (!found) return false` 直接放弃 ⇒ + * 我方订单里那几行**永远留着**(实测:抄手皮/精瘦肉/苹果 被改派给 `SUP41472132`, + * lookup 返回 `found=false` + `current_supplier_code=SUP41472132` + `reassigned=true`, + * 我方三日不动、卡在"未完成采购")。 + * 现在:**`reassigned` 优先于 `found`** —— 只要订单行当前供应商不是我们(且非空),无论旧备货行在不在,都算"不再属于我们"。 + * 仍然不碰的只有"查不到 + 没有改派信号"(真正的退货/取消/删除),留给开关控制的退货跟随去判。 */ export function isPreparationNoLongerOurs(params: { state: @@ -1618,11 +1625,14 @@ export function isPreparationNoLongerOurs(params: { ourBranchCode: string; }): boolean { const { state, ourBranchCode } = params; - if (!state?.found) return false; - if (Number(state.prepareStatus) === 40) return true; + if (!state) return false; const current = String(state.currentSupplierCode || '').trim().toUpperCase(); const ours = String(ourBranchCode || '').trim().toUpperCase(); - return state.reassigned === true && Boolean(current) && current !== ours; + /** 明确改派给了**别人**(当前供应商非空且不是我们)——这条信号与"旧备货行是否还在"无关 */ + const reassignedElsewhere = state.reassigned === true && Boolean(current) && current !== ours; + if (!state.found) return reassignedElsewhere; + if (Number(state.prepareStatus) === 40) return true; + return reassignedElsewhere; } /** diff --git a/server/src/services/mainSystemSupplierAuth.ts b/server/src/services/mainSystemSupplierAuth.ts index a7931ec..2d62351 100644 --- a/server/src/services/mainSystemSupplierAuth.ts +++ b/server/src/services/mainSystemSupplierAuth.ts @@ -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 = /** * 校验通过。 diff --git a/server/src/services/mainSystemSupplierLogin.ts b/server/src/services/mainSystemSupplierLogin.ts deleted file mode 100644 index 5f8b38b..0000000 --- a/server/src/services/mainSystemSupplierLogin.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { pool } from '../db'; -import { loadAuthUsersByIds, type AuthUserRow } from './accountLoginService'; -import { ensureMainSupplierBranchAndAdmin } from './supplierBranchProvisioning'; -import { verifySupplierCredentialOnMainSystem } from './mainSystemSupplierAuth'; - -/** - * 主系统供应商账号在本系统的登录支持 —— **各登录入口共用的唯一实现**。 - * - * 背景:本系统的「分公司管理员」= 主系统的供应商账号(见 supplierBranchProvisioning.ts)。 - * 开通时本地密码写的是**随机不可用值**,因此登录一律回主系统校验 - * ⇒ 主系统改密/停用即时生效,本地不保存可用密码。 - * - * ⚠️ 任何登录入口(`/api/auth/token`、`/api/auth/unified-login`、`/api/mobile/login` …) - * 都必须经过这里;漏掉某个入口,那个入口的供应商账号就会一直报「登录名或密码错误」。 - * 各入口的**会话签发**(Web token / mobile token)由调用方各自完成。 - */ - -/** 该登录名是否属于「主系统供应商账号」(本地密码不可用,必须回主系统校验) */ -export async function loadAccountSourceByLoginName(loginName: string): Promise { - const result = await pool.query<{ account_source: string }>( - `SELECT account_source FROM profiles WHERE lower(username) = lower($1) LIMIT 1`, - [loginName] - ); - return result.rows[0]?.account_source ?? null; -} - -export type MainSupplierLoginOutcome = - | { kind: 'ok'; user: AuthUserRow; branchCode: string; created: boolean } - /** 主系统**明确答复**凭据不对/账号不可用 */ - | { kind: 'invalid' } - /** **没问成**:未配置/超时/网络/5xx —— 调用方必须 fail closed,绝不回落本地密码 */ - | { kind: 'unavailable'; reason: string } - /** 该手机号已被本系统内部账号占用,无法作为供应商管理员开通 */ - | { kind: 'login_name_taken' } - | { kind: 'internal_error' }; - -/** - * 校验主系统供应商凭据 → 惰性开通分公司+管理员 → 取回本系统用户。 - * 三态语义与 `verifySupplierCredentialOnMainSystem` 一致(见 MainSupplierLoginOutcome)。 - */ -export async function loginWithMainSupplierCredential( - loginName: string, - password: string -): Promise { - const verdict = await verifySupplierCredentialOnMainSystem(loginName, password); - - if (verdict.kind === 'unavailable') { - console.warn(`[login] 供应商账号登录未能完成主系统校验(${verdict.reason}):${loginName}`); - return { kind: 'unavailable', reason: verdict.reason }; - } - if (verdict.kind !== 'ok') { - return { kind: 'invalid' }; - } - - let provisioned: Awaited>; - try { - provisioned = await ensureMainSupplierBranchAndAdmin(verdict.profile); - } catch (error: any) { - if (error?.code === 'login_name_taken') { - return { kind: 'login_name_taken' }; - } - throw error; - } - - const [user] = await loadAuthUsersByIds([provisioned.userId]); - if (!user) { - return { kind: 'internal_error' }; - } - return { kind: 'ok', user, branchCode: provisioned.branchCode, created: provisioned.created }; -} diff --git a/server/src/services/supplierBranchProvisioning.ts b/server/src/services/supplierBranchProvisioning.ts index 2754f83..b550c23 100644 --- a/server/src/services/supplierBranchProvisioning.ts +++ b/server/src/services/supplierBranchProvisioning.ts @@ -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) diff --git a/server/tests/mainSystemDayMergeAndStockout.test.ts b/server/tests/mainSystemDayMergeAndStockout.test.ts index 36a74cd..5cef9ef 100644 --- a/server/tests/mainSystemDayMergeAndStockout.test.ts +++ b/server/tests/mainSystemDayMergeAndStockout.test.ts @@ -404,7 +404,7 @@ describe('缺货跟随判据:主系统"已经不属于我们了"(2026-10-10 } }); - it('查不到该行(found=false)⇒ 不认(退货/取消留给开关控制的退货跟随判)', () => { + it('查不到该行且**没有改派信号**(found=false + 供应商空)⇒ 不认(退货/取消留给开关控制的退货跟随判)', () => { expect( isPreparationNoLongerOurs({ state: state({ found: false, prepareStatus: null, reassigned: false, currentSupplierCode: null }), @@ -413,6 +413,32 @@ describe('缺货跟随判据:主系统"已经不属于我们了"(2026-10-10 ).toBe(false); }); + it('⚠️ 改派 = "删旧行 + 建新行"(found=false 但订单行当前供应商是别人)⇒ **认**(2026-10-10 真库漏判修复)', () => { + // 实测:抄手皮/精瘦肉/苹果 被改派给 SUP41472132,lookup 返回 + // found=false + current_supplier_code=SUP41472132 + reassigned=true ⇒ 旧实现永远不剔除 + expect( + isPreparationNoLongerOurs({ + state: state({ found: false, prepareStatus: null, reassigned: true, currentSupplierCode: 'SUP41472132' }), + ourBranchCode: ours, + }) + ).toBe(true); + }); + + it('found=false 但当前供应商仍是我们 / 字段缺失 ⇒ 仍不认(不可凭猜删本地行)', () => { + expect( + isPreparationNoLongerOurs({ + state: state({ found: false, prepareStatus: null, reassigned: true, currentSupplierCode: ours }), + ourBranchCode: ours, + }) + ).toBe(false); + expect( + isPreparationNoLongerOurs({ + state: state({ found: false, prepareStatus: null, reassigned: false, currentSupplierCode: 'SUP_OTHER' }), + ourBranchCode: ours, + }) + ).toBe(false); + }); + it('reassigned 但当前供应商仍是我们(脏数据)⇒ 不认', () => { expect( isPreparationNoLongerOurs({ diff --git a/server/tests/supplierBranchBinding.test.ts b/server/tests/supplierBranchBinding.test.ts new file mode 100644 index 0000000..414fa01 --- /dev/null +++ b/server/tests/supplierBranchBinding.test.ts @@ -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'); + }); +}); diff --git a/src/i18n/locales/en/system.ts b/src/i18n/locales/en/system.ts index ec40435..4f60824 100644 --- a/src/i18n/locales/en/system.ts +++ b/src/i18n/locales/en/system.ts @@ -258,6 +258,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.ph.supplierCategories": "Business categories (optional, e.g. vegetables, pork, dry goods)", "branches.act.saveEdit": "Save changes", diff --git a/src/i18n/locales/id/system.ts b/src/i18n/locales/id/system.ts index d0ee62d..cace3eb 100644 --- a/src/i18n/locales/id/system.ts +++ b/src/i18n/locales/id/system.ts @@ -258,6 +258,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.ph.supplierCategories": "Kategori usaha (opsional, mis. sayur, daging babi, sembako)", "branches.act.saveEdit": "Simpan perubahan", diff --git a/src/i18n/locales/zh-CN/system.ts b/src/i18n/locales/zh-CN/system.ts index 6897dd5..697764d 100644 --- a/src/i18n/locales/zh-CN/system.ts +++ b/src/i18n/locales/zh-CN/system.ts @@ -258,6 +258,7 @@ export const system: MessageDict = { "branches.ph.contact": "联系人", "branches.ph.phone": "联系电话", "branches.ph.phoneLogin": "登录账号(手机号或字母,如 chengdu_admin)", + "branches.ph.mainSupplierCode": "主系统供应商编码(选填,如 SUP38887897)", "branches.ph.address": "地址(仓库/出发点,供路线规划使用)", "branches.ph.supplierCategories": "经营分类(选填,如:蔬菜、猪肉、干杂)", "branches.act.saveEdit": "保存修改", diff --git a/src/lib/localApiClient.ts b/src/lib/localApiClient.ts index e210286..858ece1 100644 --- a/src/lib/localApiClient.ts +++ b/src/lib/localApiClient.ts @@ -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; supplier_categories?: string; } ) { @@ -572,6 +576,7 @@ export const supabase = { address: string | null; status: number; tax_level?: string | null; + main_supplier_code?: string | null; supplier_categories?: string | null; }; }>(`/auth/admin/branches/${encodeURIComponent(branchCode)}`, { diff --git a/src/pages/system/BranchManagement.tsx b/src/pages/system/BranchManagement.tsx index 972ce5e..0f3debb 100644 --- a/src/pages/system/BranchManagement.tsx +++ b/src/pages/system/BranchManagement.tsx @@ -47,6 +47,8 @@ interface Branch { address: string | null; status: number; tax_level?: string | null; + /** 绑定的主系统供应商编码;null = 本系统自己的供应商 */ + main_supplier_code?: string | null; supplier_categories?: string | null; } @@ -55,6 +57,8 @@ const emptyForm = { contact_name: '', contact_phone: '', address: '', + /** 主系统供应商编码(可选,2026-10-10):填了 ⇒ 该分公司管理员回主系统校验密码 */ + main_supplier_code: '', supplier_categories: '', }; @@ -155,6 +159,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 || '', supplier_categories: branch.supplier_categories || '', }); window.scrollTo({ top: 0, behavior: 'smooth' }); @@ -188,6 +193,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(), supplier_categories: form.supplier_categories.trim(), }); if (error) throw error; @@ -202,6 +209,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); @@ -349,6 +357,12 @@ export const BranchManagement: React.FC = () => { className="app-input px-4 py-2 border rounded-lg" required /> + setForm({ ...form, main_supplier_code: e.target.value })} + className="app-input px-4 py-2 border rounded-lg" + />