From fed8a2f0c71854d9c63251fde5050614d15df0cb Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Tue, 13 Oct 2026 14:15:32 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E8=B7=A8=E7=B3=BB=E7=BB=9F):=20=E6=8E=A5?= =?UTF-8?q?=E6=94=B6=E4=B8=BB=E7=B3=BB=E7=BB=9F=E5=8D=95=E4=BD=8D=E5=8F=98?= =?UTF-8?q?=E6=9B=B4=E4=BA=8B=E5=AE=9E=E4=BA=8B=E4=BB=B6=20preparations.un?= =?UTF-8?q?it=5Fchanged?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 主系统回执(对接清单 §4.5.24):他们管理端改备货行单位时,若价格没变就不发 price_changed ⇒ 我方镜像里的单位一直是旧的(他们 §10.4 / 本仓 §11.4-3 登记的同源 反向缺口)。他们已新增专用事实事件(提交 3608614d,开关 SUPPLIER_UNIT_CHANGED_PUSH_ENABLED 默认关,等我们接收端就绪),只推事实、不给我方造待审,请我们加接收端。 - mainSystemUnitChangedInbox.ts:applyUnitChangedFact —— 按 (branch_code, prep_id) 在 main_system_order_import_items 找到我方订单行,**只写 order_items.unit = final_unit** (价/量/状态/退货标记不动,不建任何待审);我方已是该单位 ⇒ ignored(幂等,他们那边 也有回声抑制);留一条操作日志 main_system_unit_changed_applied - mainSystemIntegration.ts:新增 preparations.unit_changed 分支,**就地 return** (不得落到末尾的「建单导入」兜底 —— 他们明确提醒:将来若被塞 data[] 会误建单) - 字段兼容:preparation_id/prep_id 都认;final_unit 优先、unit 作别名;before_unit 可缺; before_value/after_value 恒 null(无任何价格分支会碰它) - 安全:缺 prep_id/缺 final_unit/非 uuid/行对不上 ⇒ ignored + 原因,不猜不建行 验证: - server/tests/unitChangedInbox.test.ts(9 例:落值/幂等/大小写空白/缺字段/行对不上/落点顺序源码钉) - 真库 E2E(按他们 §二 载荷自签打进我方 dev API):applied ⇒ 我方单位 斤→件 且价/量未动; 同一条重投 ⇒ ignored(幂等跳过);坏签名 ⇒ 401;缺 final_unit ⇒ ignored;收尾还原 - 服务端 tsc 0 错;全量 26 failed / 376 passed 与基线持平(差异仅对方 WIP 的 pickingZoneOrder) - 设计文 §11.9(含"延迟重投"已知边界);对接清单 §4.5.24 五(我方回执,请他们开开关) --- docs/design/20261011-跨系统改价改量审核.md | 52 +++++ docs/给主系统AI的对接改造清单.md | 45 ++++ server/src/routes/mainSystemIntegration.ts | 22 ++ .../services/mainSystemUnitChangedInbox.ts | 161 +++++++++++++ server/tests/unitChangedInbox.test.ts | 215 ++++++++++++++++++ 5 files changed, 495 insertions(+) create mode 100644 server/src/services/mainSystemUnitChangedInbox.ts create mode 100644 server/tests/unitChangedInbox.test.ts diff --git a/docs/design/20261011-跨系统改价改量审核.md b/docs/design/20261011-跨系统改价改量审核.md index 1d894ff..df08a8a 100644 --- a/docs/design/20261011-跨系统改价改量审核.md +++ b/docs/design/20261011-跨系统改价改量审核.md @@ -654,3 +654,55 @@ reason「单位变更补报(改量审核已落定):旧单位 → 新单位 | U9 | 仍有 `pending` ⇒ 不补发(保持 `waiting`);`pending` 清掉后由清扫补上 | 用例 ⑧ | | U10 | 幂等:同一意图重复触发只上报一次(确定性 `client_request_id`) | 用例 ⑨ | | U11 | 单位已改回 `before_unit` ⇒ 标 `noop`,不发 HTTP | 用例 ⑩ | + +## 11.9 主系统改单位也告知我方:新事件 `preparations.unit_changed` 的**接收端**(2026-10-13 追加) + +**背景**:§11.4-3 / 他们 §10.4 登记的同源**反向**缺口 —— 他们管理端改备货行单位时,若价格没变就不发 +`price_changed` ⇒ 我方镜像里的单位一直是旧的。他们开发者已拍板(D1=A 新增**专用事实事件**、D2=**只推事实、不给我方造待审**), +提交 `3608614d` + 设计文 `docs/design/20261013-prep-unit-change-outbound.md`,开关 +`SUPPLIER_UNIT_CHANGED_PUSH_ENABLED` **默认关**(等我们接收端就绪后开启)。回执见对接清单 §4.5.24。 + +### 11.9.1 事件契约(他们 §二) + +单对象推(**刻意不带 `data[]`**),信封与既有事件一致(`X-Event` / `X-Signature: sha256=…` / `X-Client-Id` / +`X-Request-Id` + 体内 `subsystem_code`)。关键字段: + +| 字段 | 说明 | +|---|---| +| `preparation_id` / `prep_id` | 主系统备货行 id(两个名字同值,都认) | +| `before_unit` / `final_unit` | **权威**旧值/新值 | +| `unit` | = `final_unit`(我方文档的字段名别名) | +| `before_value` / `after_value` | **恒 `null`** —— 这条**不是**改价,禁止走价格分支 | +| `client_request_id` | `uc___`(**稳定幂等键**:同一事实重试不变,单位再变才换键) | +| `source` / `operator` / `operator_role` / `changed_at` | 留痕用;`source` 区分是他们哪个入口改的 | + +### 11.9.2 我方落地(接收端) + +| 步 | 动作 | 落点 | +|---|---|---| +| ① 定位我方行 | `public.main_system_order_import_items (branch_code, prep_id)` → `our_order_code` / `our_order_item_id` | `mainSystemUnitChangedInbox.ts` | +| ② 幂等 | 读我方当前 `unit`;**已等于 `final_unit`** ⇒ `ignored`(不写库、不留痕)—— 他们"回声抑制"之外的第二道兜底 | 同上 | +| ③ 落值 | **只写** `order_items.unit = final_unit`(走 `runWithTenantDataAccess`,RLS 正确);**不动价/量/状态**,不写任何待审 | 同上 | +| ④ 留痕 | 操作日志 `main_system_unit_changed_applied`(旧值/新值/来源/幂等键/操作人) | 同上 | +| ⑤ 就地 return | webhook 里**必须 return**,不得落到末尾的「建单导入」兜底 | `mainSystemIntegration.ts` | + +**纪律(四条)**: + +1. **不回推**:他们只报事实,我方无需回报(也没有这条反向通道)。 +2. **不建待审**:他们改的是**他们自己的备货行**,我方跟着镜像即可 —— 与 `preparations.price_changed` + "可审"不同(那条会给操作员一个"跟不跟"的决定点)。 +3. **不改价/量**:`before_value`/`after_value` 恒 null 是刻意的;把它当改价会把单位变更变成价格待审(他们 §一已论证过)。 +4. **不猜不造行**:行对不上(未对照/已删/`our_order_item_id` 为空)⇒ `ignored` + 原因,**不新建任何行**。 + +**已知边界(如实登记)**:幂等按"我方当前单位是否已等于 `final_unit`"判定 ⇒ 若**他们的事件被延迟重投**、且其间 +我方自己又把单位改成了别的值,那条旧事件会把我方单位写回旧值。他们的投递是**立即 2 次重试**、不做持久重放, +窗口极小;真要收口需要一张事实表(记 `client_request_id` + `changed_at`)——**本轮不做**,等出现实际案例再评估。 + +### 11.9.3 验收 + +| # | 项 | 结果 | +|---|---|---| +| U12 | 收到事件 ⇒ 我方该行 `unit` 写成 `final_unit`,价/量/状态/退货标记不动 | 用例 ① + 真库 E2E | +| U13 | 幂等:我方已是该单位 ⇒ `ignored`,不重复写、不刷日志 | 用例 ② | +| U14 | 落点安全:`preparations.unit_changed` 走完就 return,**不落到「建单导入」兜底** | 用例 ③(行为钉)+ ④(源码钉) | +| U15 | 缺 `prep_id` / 缺 `final_unit` / 行对不上 ⇒ `ignored` + 原因,不建行 | 用例 ⑤ | diff --git a/docs/给主系统AI的对接改造清单.md b/docs/给主系统AI的对接改造清单.md index 4c0a3b0..6fba7a2 100644 --- a/docs/给主系统AI的对接改造清单.md +++ b/docs/给主系统AI的对接改造清单.md @@ -3811,6 +3811,7 @@ prep `931eda1a-3c19-4b49-ab24-664b54770fc4` / `SUP35143228` / `ORD_WEB_20261009_ 加一个 `preparations.unit_changed` 的 handler:**按 `prep_id` 找到你们那行,把单位写成 `final_unit`(幂等)**。 - **不需要**回推给我方(我们只报事实); - **不需要**建待审(除非你们自己希望"人工决定跟不跟"——那是你们的业务面,我方不做要求); +- ⚠️ handler 里请**就地 return**,**不要落到你们 webhook 末尾的「建单导入」兜底**(本事件不带 `data[]`,当前落到兜底只会 `200 ignored`,但将来若有人给它加了行数据就会误建单); - 你们想留痕的话,照 `price_changed` 的事实表加一行即可(键建议用 `client_request_id`)。 **现在的兼容性**:你们的未知事件兜底在建单之前会先判 `rows.length === 0` ⇒ 收到本事件就是 @@ -3842,3 +3843,47 @@ prep `931eda1a-3c19-4b49-ab24-664b54770fc4` / `SUP35143228` / `ORD_WEB_20261009_ `supplierPreparationStatusService.ts`(**两个写单位入口**都在 COMMIT 之后发:写价服务 + 状态服务)、 `supplierPriceQtyRequestService.ts` / `prepAmendRequestService.ts` / `supplierBusinessRoutes.ts`(来源接线)、 `config.ts` + `.env.example`(开关登记);钉子 `server/tests/prepUnitChangedEvent.test.ts`(16 例)。 + +#### 五、我方回执(供应商系统 AI 填,2026-10-13):**接收端已实现,可以开开关** + +> 你们 §三 要的那一件事做完了。**实现提交**:本仓「接收主系统单位变更事实事件 `preparations.unit_changed`」(即本文所在提交); +> 设计文 `docs/design/20261011-跨系统改价改量审核.md` **§11.9**。 + +**落点**:`server/src/services/mainSystemUnitChangedInbox.ts`(处理器)+ `server/src/routes/mainSystemIntegration.ts` +(`preparations.unit_changed` 分支,**就地 return**)。行为逐条对齐你们 §二/§三: + +| 你们的要求 | 我方实现 | +|---|---| +| 按 `prep_id` 找到我方那行 | `public.main_system_order_import_items (branch_code, prep_id)` → 我方订单行(**不按 sku/名称猜**) | +| 把单位写成 `final_unit`(幂等) | 只 `UPDATE order_items SET unit = final_unit`;我方当前单位**已等于**它 ⇒ `ignored`(不写库、不留痕) | +| **不需要**回推 | 不回推(我们也没有这条反向通道) | +| **不需要**建待审 | 不建待审、不写任何申请台账 | +| 不要落到「建单导入」兜底 | 分支内 `return res.json(...)`;用例里有**源码钉**(分支必须在 `event !== 'preparations.allocated'` 与 `importMainSystemGroups(...)` 之前) | +| 想留痕就加一行 | 留一条操作日志 `main_system_unit_changed_applied`(旧值/新值/来源/`client_request_id`/operator) | + +**字段兼容**:`preparation_id`/`prep_id` 都认;`final_unit` 优先、`unit` 作别名;`before_unit` 可缺(只做留痕); +`before_value`/`after_value` 恒 null ⇒ 我们**没有任何价格分支**会碰它(与你们 §一 的论证一致)。 + +**我方验证(真库 × 真验签 × 真处理器,按你们 §二 的载荷逐字段自签打进我方 dev API)**: + +| # | 场景 | 结果 | +|---|---|---| +| ① | 真事件(斤 → 件) | `200 {status:"applied"}`;我方该行 `unit=件`,**价/量/退货标记分毫未动** | +| ② | **同一条重投** | `200 {status:"ignored", reason:"我方单位已是 件(幂等跳过)"}`,库不再变 | +| ③ | 坏签名 | `401 invalid_signature`(验签是真在跑,不是摆设) | +| ④ | 缺 `final_unit` | `200 {status:"ignored", reason:"缺少 final_unit"}` —— 不猜、不建行 | +| ⑤ | 收尾还原 | 我方单位回 `斤` 并照常上报(你们行本来就是 `斤` ⇒ `no_change ⇒ applied`),两侧一致 | + +另有 **9 条单测**钉住落值/幂等/大小写空白不敏感/缺字段/行对不上/落点顺序:`server/tests/unitChangedInbox.test.ts`。 + +**请你们做的**:把 `SUPPLIER_UNIT_CHANGED_PUSH_ENABLED` 打开(你们 §四 已实测投递到我们进程 `200`,我们这边 +现在会真正落值而不是 `ignored`)。开关打开后你们再改一次单位,我们看日志确认即可 —— 我们这边的日志行是 +`[main-system-webhook] <分公司> preparations.unit_changed:applied — 单位 X → Y`。 + +**如实登记一条边界**(设计文 §11.9.2):我方幂等按"当前单位是否已等于 `final_unit`"判定 ⇒ 若贵方某条事件被 +**延迟重投**、且其间我方自己又把单位改成了别的值,那条旧事件会把我方单位写回旧值。贵方投递是**立即 2 次重试**、 +不做持久重放 ⇒ 窗口极小。要彻底收口得加一张事实表(记 `client_request_id` + `changed_at` 判新旧), +**本轮不做**;若你们希望做,按清单提一条我们再评估。 + +**另**:本轮我方也已把「跳过 ≠ 排队」收口(见 §2.15 —— 跳过时留意图、改量落定后定向补发), +与这条接收端**互不冲突**:你们改单位 ⇒ 我们镜像;我们改单位 ⇒ 载体送达你们;双方都不回声。 diff --git a/server/src/routes/mainSystemIntegration.ts b/server/src/routes/mainSystemIntegration.ts index baba6e6..dae34f1 100644 --- a/server/src/routes/mainSystemIntegration.ts +++ b/server/src/routes/mainSystemIntegration.ts @@ -33,6 +33,8 @@ import { recordActualQtyRequest, recordPriceChangedFact, } from '../services/mainSystemActualQtyInbox'; +// 备货行「单位」变更事实(2026-10-13,主系统 `preparations.unit_changed` 的接收端;设计文 §11.9) +import { applyUnitChangedFact } from '../services/mainSystemUnitChangedInbox'; import type { MainPreparationRow } from '../services/mainSystemPreparations'; /** @@ -433,6 +435,26 @@ router.post('/main-system/webhook', async (req: Request, res: Response) => { return res.json({ ok: true, ...recorded }); } + /* ── 备货行「单位」变更事实(2026-10-13 新增接收端,主系统提交 3608614d)──────── + * `preparations.unit_changed`:**他们**管理端改备货行单位时推给我们(专用事实事件,因为既有的 + * `price_changed` 触发门是"价格真的变了",同价事件的接收端也会丢弃 ⇒ 只改单位时静默)。 + * 我方动作:按 `prep_id` 找到我方订单行,**只写 `unit = final_unit`(幂等)** —— + * 不回推、不建待审、不动价/量(`before_value`/`after_value` 恒 null,禁止当改价处理)。 + * ⚠️ 必须**就地 return**:本事件不带 `data[]`,若落到底部的「建单导入」兜底,将来被塞行数据就会误建单。 + * 设计文 docs/design/20261011-跨系统改价改量审核.md §11.9。 + */ + if (event === 'preparations.unit_changed') { + if (!branchCode) { + return res.json({ ok: true, ignored: true, reason: resolved.ok ? 'not_bound' : resolved.reason }); + } + const applied = await applyUnitChangedFact({ branchCode, payload }); + console.log( + `[main-system-webhook] ${branchCode} ${event}:${applied.status}` + + `${applied.reason ? ` — ${applied.reason}` : ''}` + ); + return res.json({ ok: true, ...applied }); + } + if (!branchCode) { /** * 定不到我方分公司(未绑定 / 已解绑 / 编码不认识 / 供应商编码缺失)⇒ 200 收下但忽略。 diff --git a/server/src/services/mainSystemUnitChangedInbox.ts b/server/src/services/mainSystemUnitChangedInbox.ts new file mode 100644 index 0000000..19b144e --- /dev/null +++ b/server/src/services/mainSystemUnitChangedInbox.ts @@ -0,0 +1,161 @@ +import { pool } from '../db'; +import { runWithTenantDataAccess } from './tenantSchemaService'; + +/** + * 主系统改**备货行单位** → 通知我方(事件 `preparations.unit_changed`,2026-10-13)。 + * + * 为什么需要:主系统管理端改单位时,若**价格没变**就不发 `preparations.price_changed` + * ⇒ 我方镜像里的单位一直是旧的(他们的 §10.4 / 本仓设计文 §11.4-3 登记的同源反向缺口)。 + * 他们开发者已拍板:新增**专用事实事件**(`3608614d`,开关 `SUPPLIER_UNIT_CHANGED_PUSH_ENABLED` 默认关), + * **只推事实、不给我方造待审**。本模块是接收端。 + * + * 我方落地(设计文 §11.9): + * ① 按 `(branch_code, prep_id)` 在 `main_system_order_import_items` 找到我方订单行; + * ② **幂等**:我方当前单位已等于 `final_unit` ⇒ `ignored`(他们那边也有"回声抑制",这是第二道兜底); + * ③ **只写** `order_items.unit` —— 不动价/量/状态,**不建任何待审**; + * ④ 留一条操作日志(旧值/新值/来源/幂等键)。 + * + * 纪律:不回推(他们只报事实);行对不上就 `ignored` + 原因,**不猜、不建行**。 + */ + +export type UnitChangedOutcome = { + status: 'applied' | 'ignored'; + reason: string; + /** 落地的我方订单行 id(幂等跳过/找不到行时为 null) */ + rowId: string | null; + /** 实际落地的单位(排障/日志用) */ + unit?: string | null; +}; + +function text(value: unknown): string | null { + if (value === null || value === undefined) return null; + const s = String(value).trim(); + return s || null; +} + +const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +/** 事件载荷 → 业务字段(两个字段名都认:`preparation_id`/`prep_id`、`final_unit`/`unit`) */ +export function mapUnitChangedPayload(payload: any) { + const prepId = text(payload?.preparation_id) ?? text(payload?.prep_id); + const finalUnit = text(payload?.final_unit) ?? text(payload?.unit); + return { + prepId, + beforeUnit: text(payload?.before_unit), + finalUnit, + unitAlias: text(payload?.unit), + skuCode: text(payload?.sku_code), + orderCode: text(payload?.order_code), + source: text(payload?.source), + operator: text(payload?.operator), + operatorRole: text(payload?.operator_role), + changedAt: text(payload?.changed_at), + clientRequestId: text(payload?.client_request_id), + }; +} + +/** 单位比较:首尾空白与大小写不敏感(与他们 `isUnitActuallyChanged` 同口径) */ +function sameUnit(a: string | null, b: string | null): boolean { + return String(a ?? '').trim().toLowerCase() === String(b ?? '').trim().toLowerCase(); +} + +/** + * 应用一条 `preparations.unit_changed`(幂等)。 + * + * 业务失败不抛错:返回 `ignored` + 原因,调用方(webhook)照旧 200 收下 —— 重推解决不了前置问题。 + */ +export async function applyUnitChangedFact(params: { + branchCode: string; + payload: any; +}): Promise { + const branchCode = String(params.branchCode || '').trim(); + if (!branchCode) return { status: 'ignored', reason: '缺少分公司', rowId: null }; + const mapped = mapUnitChangedPayload(params.payload); + if (!mapped.prepId) return { status: 'ignored', reason: '缺少 preparation_id', rowId: null }; + if (!mapped.finalUnit) return { status: 'ignored', reason: '缺少 final_unit', rowId: null }; + if (!UUID_RE.test(mapped.prepId)) { + // 不拿非 uuid 去撞 `prep_id = $2::uuid`(那会抛 22P02 并打 500) + return { status: 'ignored', reason: `preparation_id 不是 uuid:${mapped.prepId}`, rowId: null }; + } + + // ① 定位我方订单行(行级对照台账是唯一权威,不按 sku/名称猜) + const link = await pool.query<{ our_order_code: string | null; our_order_item_id: string | null }>( + `SELECT our_order_code, our_order_item_id::text AS our_order_item_id + FROM public.main_system_order_import_items + WHERE branch_code = $1 AND prep_id = $2::uuid + LIMIT 1`, + [branchCode, mapped.prepId] + ); + const row = link.rows[0]; + if (!row?.our_order_item_id || !row.our_order_code) { + return { status: 'ignored', reason: '我方没有该备货行的对照行(未对照上/已删除)', rowId: null }; + } + + // ② 读我方当前单位(tenant 隔离:必须走 runWithTenantDataAccess) + const current = await runWithTenantDataAccess(branchCode, (client) => + client.query<{ unit: string | null }>( + `SELECT unit FROM order_items WHERE order_code = $1 AND id = $2::uuid LIMIT 1`, + [row.our_order_code, row.our_order_item_id] + ) + ); + const currentRow = current.rows[0]; + if (!currentRow) { + return { status: 'ignored', reason: '我方订单行已不存在', rowId: null }; + } + if (sameUnit(currentRow.unit, mapped.finalUnit)) { + return { + status: 'ignored', + reason: `我方单位已是 ${mapped.finalUnit}(幂等跳过)`, + rowId: null, + unit: mapped.finalUnit, + }; + } + + // ③ 只写 unit;价/量/状态/退货标记一律不动(`order_items` 无 updated_at 列) + const updated = await runWithTenantDataAccess(branchCode, (client) => + client.query<{ id: string }>( + `UPDATE order_items SET unit = $3 + WHERE order_code = $1 AND id = $2::uuid + RETURNING id::text AS id`, + [row.our_order_code, row.our_order_item_id, mapped.finalUnit] + ) + ); + const rowId = updated.rows[0]?.id ?? null; + + // ④ 留痕(失败不阻断:日志属辅助面) + try { + const { writeAuditLog } = await import('./auditService'); + await writeAuditLog({ + operatorId: null, + operatorRole: mapped.operatorRole || 'main_system', + operationType: 'main_system_unit_changed_applied', + targetTable: 'order_items', + targetId: rowId ?? undefined, + branchCode, + actionCategory: 'order', + ipAddress: null, + oldValue: { unit: currentRow.unit ?? null }, + newValue: { + unit: mapped.finalUnit, + before_unit: mapped.beforeUnit, + prep_id: mapped.prepId, + our_order_code: row.our_order_code, + main_order_code: mapped.orderCode, + sku_code: mapped.skuCode, + source: mapped.source, + operator: mapped.operator, + changed_at: mapped.changedAt, + client_request_id: mapped.clientRequestId, + }, + }); + } catch (error: unknown) { + console.error('[unit-changed] 写操作日志失败:', (error as Error)?.message || error); + } + + return { + status: 'applied', + reason: `单位 ${currentRow.unit ?? '—'} → ${mapped.finalUnit}(主系统管理端改动,我方镜像)`, + rowId, + unit: mapped.finalUnit, + }; +} diff --git a/server/tests/unitChangedInbox.test.ts b/server/tests/unitChangedInbox.test.ts new file mode 100644 index 0000000..ff679e2 --- /dev/null +++ b/server/tests/unitChangedInbox.test.ts @@ -0,0 +1,215 @@ +import { describe, expect, it, vi, beforeEach } from 'vitest'; +import { readFileSync } from 'node:fs'; +import path from 'node:path'; + +/** + * 主系统改**备货行单位** → 通知我方(事件 `preparations.unit_changed`,2026-10-13)。 + * + * 反向缺口:他们管理端改单位时若价格没变就不发 `price_changed` ⇒ 我方镜像里的单位一直是旧的。 + * 他们已新增专用事实事件(提交 `3608614d`,开关默认关,等我们接收端就绪)。 + * + * 本文件钉住接收端的四条不变量: + * ① 落值:按 `prep_id` 找到我方行,**只写 `unit = final_unit`**(价/量/状态不动); + * ② 幂等:我方已是该单位 ⇒ `ignored`,不重复写、不刷日志; + * ③ 安全:缺 `prep_id`/缺 `final_unit`/非 uuid/行对不上 ⇒ `ignored` + 原因,**不猜不建行**; + * ④ 落点:webhook 里**就地 return**,不落到末尾的「建单导入」兜底(他们 §三 明确提醒)。 + */ + +const query = vi.hoisted(() => vi.fn()); +const withTenantData = vi.hoisted(() => vi.fn()); +const audit = vi.hoisted(() => vi.fn()); + +vi.mock('../src/db', () => ({ + pool: { query: (...args: unknown[]) => query(...args), connect: vi.fn() }, + getRawPoolQuery: () => query, +})); +vi.mock('../src/services/tenantSchemaService', () => ({ + runWithTenantDataAccess: (...args: unknown[]) => withTenantData(...args), +})); +vi.mock('../src/services/auditService', () => ({ + writeAuditLog: (...args: unknown[]) => audit(...args), +})); + +import { + applyUnitChangedFact, + mapUnitChangedPayload, +} from '../src/services/mainSystemUnitChangedInbox'; + +const BRANCH = 'BR002'; +const PREP = 'c66d867e-3a98-4d5e-b15a-a46321fa5403'; +const ORDER = 'ORD_API_20261012_BR002_0001'; +const ITEM = '3e65a38f-ad78-4010-b370-4142650308fd'; + +function payload(overrides: Record = {}) { + return { + event: 'preparations.unit_changed', + branch_code: BRANCH, + supplier_code: 'SUP37831443', + subsystem_code: 'SCF69N8ZQEVQ', + order_code: 'ORD_WEB_20261012_BR002_0004', + preparation_id: PREP, + prep_id: PREP, + sku_code: 'SKU78659863567', + before_unit: '斤', + final_unit: '件', + unit: '件', + before_value: null, + after_value: null, + client_request_id: `uc_${PREP}_斤_件`, + source: 'admin_prep_edit', + operator: 'u-1', + operator_role: 'admin', + changed_at: '2026-10-13T06:03:54.000Z', + ...overrides, + }; +} + +/** 组装 pool / tenant 两侧的桩:link 命中 + 我方当前单位 unitNow */ +function stub(params: { unitNow: string | null; link?: { our_order_code: string | null; our_order_item_id: string | null } | null }) { + const link = params.link === undefined ? { our_order_code: ORDER, our_order_item_id: ITEM } : params.link; + query.mockImplementation(async (sql: string) => { + if (String(sql).includes('FROM public.main_system_order_import_items')) { + return link ? { rowCount: 1, rows: [link] } : { rowCount: 0, rows: [] }; + } + if (String(sql).startsWith('UPDATE public.main_system_price_qty_unit_deferred')) return { rowCount: 1, rows: [] }; + return { rowCount: 0, rows: [] }; + }); + const updates: unknown[][] = []; + withTenantData.mockImplementation(async (_branch: string, fn: (client: unknown) => unknown) => + fn({ + query: async (sql: string, values?: unknown[]) => { + if (String(sql).startsWith('UPDATE order_items')) { + updates.push(values || []); + return { rowCount: 1, rows: [{ id: ITEM }] }; + } + if (String(sql).includes('FROM order_items')) { + return params.unitNow === null + ? { rowCount: 0, rows: [] } + : { rowCount: 1, rows: [{ unit: params.unitNow }] }; + } + return { rowCount: 0, rows: [] }; + }, + }) + ); + return { updates }; +} + +beforeEach(() => { + query.mockReset(); + withTenantData.mockReset(); + audit.mockReset(); + audit.mockResolvedValue(undefined); +}); + +describe('主系统改单位 ⇒ 我方接收端(preparations.unit_changed)', () => { + it('① 落值:只写 unit = final_unit,价/量/状态不碰,并留一条操作日志', async () => { + const { updates } = stub({ unitNow: '斤' }); + const out = await applyUnitChangedFact({ branchCode: BRANCH, payload: payload() }); + expect(out.status).toBe('applied'); + expect(out.rowId).toBe(ITEM); + expect(out.unit).toBe('件'); + expect(updates, '恰好写一次').toHaveLength(1); + expect(updates[0], '参数 = [order_code, item_id, 新单位]').toEqual([ORDER, ITEM, '件']); + // 操作日志 + expect(audit).toHaveBeenCalledTimes(1); + const logged = audit.mock.calls[0][0] as any; + expect(logged.operationType).toBe('main_system_unit_changed_applied'); + expect(logged.branchCode).toBe(BRANCH); + expect(logged.oldValue).toEqual({ unit: '斤' }); + expect(logged.newValue.unit).toBe('件'); + expect(logged.newValue.client_request_id).toBe(`uc_${PREP}_斤_件`); + expect(logged.newValue.source).toBe('admin_prep_edit'); + }); + + it('①b 落值 SQL 只动 unit(源码钉:不得顺手改价/量)', () => { + const src = readFileSync(path.join(__dirname, '../src/services/mainSystemUnitChangedInbox.ts'), 'utf8'); + expect(src).toContain('UPDATE order_items SET unit = $3'); + expect(src).not.toMatch(/SET unit = \$3[^`]*?(price|quantity)/); + }); + + it('② 幂等:我方已是该单位 ⇒ ignored(不写、不留痕)', async () => { + const { updates } = stub({ unitNow: '件' }); + const out = await applyUnitChangedFact({ branchCode: BRANCH, payload: payload() }); + expect(out.status).toBe('ignored'); + expect(String(out.reason)).toContain('幂等跳过'); + expect(updates).toHaveLength(0); + expect(audit).not.toHaveBeenCalled(); + }); + + it('②b 幂等比较对大小写/空白不敏感(他们那边同口径)', async () => { + const { updates } = stub({ unitNow: ' 件 ' }); + const out = await applyUnitChangedFact({ branchCode: BRANCH, payload: payload({ final_unit: '件' }) }); + expect(out.status).toBe('ignored'); + expect(updates).toHaveLength(0); + }); + + it('③ 载荷:两个字段名都认(prep_id / unit 别名),before/after value 恒 null 不进结果', () => { + const mapped = mapUnitChangedPayload( + payload({ preparation_id: null, final_unit: null, unit: '箱', sku_code: 'SKU1' }) + ); + expect(mapped.prepId).toBe(PREP); + expect(mapped.finalUnit).toBe('箱'); + expect(mapped.beforeUnit).toBe('斤'); + // 只有单位语义,没有任何"价"字段被采纳 + expect(Object.keys(mapped)).not.toContain('price'); + }); + + it('③b 他们没给 before_unit 也能落值(before 只是留痕字段,不参与判定)', async () => { + const { updates } = stub({ unitNow: '斤' }); + const out = await applyUnitChangedFact({ + branchCode: BRANCH, + payload: payload({ before_unit: null, client_request_id: `uc_${PREP}__件` }), + }); + expect(out.status).toBe('applied'); + expect(updates).toHaveLength(1); + }); + + it('④ 安全:缺 prep_id / 缺 final_unit / 非 uuid / 行对不上 ⇒ ignored + 原因,不发写', async () => { + const cases: Array<[Record, string]> = [ + [{ preparation_id: null, prep_id: null }, '缺少 preparation_id'], + [{ final_unit: null, unit: null }, '缺少 final_unit'], + [{ preparation_id: 'not-a-uuid', prep_id: 'not-a-uuid' }, '不是 uuid'], + ]; + for (const [override, expected] of cases) { + query.mockReset(); + withTenantData.mockReset(); + const out = await applyUnitChangedFact({ branchCode: BRANCH, payload: payload(override) }); + expect(out.status).toBe('ignored'); + expect(String(out.reason)).toContain(expected); + expect(withTenantData, '前置校验不通过时不该读租户库').not.toHaveBeenCalled(); + } + + // 行对不上(对照台账没有该 prep / 缺我们的行 id):不猜、不建行 + const { updates } = stub({ unitNow: '斤', link: null }); + const missing = await applyUnitChangedFact({ branchCode: BRANCH, payload: payload() }); + expect(missing.status).toBe('ignored'); + expect(String(missing.reason)).toContain('没有该备货行的对照行'); + expect(updates).toHaveLength(0); + + const { updates: updates2 } = stub({ unitNow: '斤', link: { our_order_code: ORDER, our_order_item_id: null } }); + const noItem = await applyUnitChangedFact({ branchCode: BRANCH, payload: payload() }); + expect(noItem.status).toBe('ignored'); + expect(updates2).toHaveLength(0); + }); + + it('④b 我方订单行已不存在 ⇒ ignored(不是 applied)', async () => { + const { updates } = stub({ unitNow: null }); + const out = await applyUnitChangedFact({ branchCode: BRANCH, payload: payload() }); + expect(out.status).toBe('ignored'); + expect(String(out.reason)).toContain('已不存在'); + expect(updates).toHaveLength(0); + }); + + it('⑤ 落点:webhook 里就地 return,不落到「建单导入」兜底(源码钉)', () => { + const route = readFileSync(path.join(__dirname, '../src/routes/mainSystemIntegration.ts'), 'utf8'); + const branchAt = route.indexOf("event === 'preparations.unit_changed'"); + const fallbackAt = route.indexOf("if (event !== 'preparations.allocated')"); + const importAt = route.indexOf('importMainSystemGroups({'); + expect(branchAt, '必须存在 unit_changed 分支').toBeGreaterThan(-1); + expect(branchAt, 'unit_changed 分支必须在未知事件兜底之前').toBeLessThan(fallbackAt); + expect(branchAt, 'unit_changed 分支必须在建单导入之前').toBeLessThan(importAt); + // 分支内 return(就地收口) + const branchBody = route.slice(branchAt, fallbackAt); + expect(branchBody).toContain('return res.json({ ok: true, ...applied })'); + }); +});