feat(跨系统): 单位变更改为「登记待审」—— 主系统改单位我方可见、由人决定跟不跟
主系统 2026-10-13 §4.5.25 请求(原话「自己只能改自己 —— 与改价完全同款,我方不替你们落库」):
我们原来的 `applyUnitChangedFact` 是"收到即直接 UPDATE 我方镜像行",
等于他们一改单位就把我们的数据改了,与改价那条(事实 + 待审)不一致,而且**我们界面看不到任何申请**。
改后(默认):
- `mainSystemUnitChangedInbox.applyUnitChangedFact` ⇒ **登记待审**:
写 `public.main_system_actual_qty_requests`(field='unit'、node='unit_changed'、
before_unit/unit、client_request_id、operator、applied_at=changed_at、fact_registered=true、
payload.local_only=true),**不再写 order_items**;
- **只留最新**:同 (branch, prep) 的旧 pending 单位行先转 superseded;
- **幂等**:同一 request_id / client_request_id 重投 ⇒ 唯一键冲突 ⇒ ignored(不建第二行);
- 审核通过 ⇒ 复用既有 `applyActualQtySyncValue`(它本来就支持 field='unit':写
order_items.unit + 验收/核货单位 + 审计);驳回 ⇒ 不写、只留痕;
- **不回传**(local_only;他们只报事实,不需要回执);
- 回退开关 `UNIT_CHANGED_AUTO_APPLY=1` = 旧的"收到即改"(仅线上异常回退),已按闸门登记
server/.env.example + 部署手册。
无需迁移:`main_system_actual_qty_requests` 建表起就允许 field IN ('qty','unit','price') 且有
before_unit/unit 列(20261022);审核页 `PriceQtyRequestsPage` 也早已支持 field='unit' 的
"旧单位 → 新单位"渲染 —— 缺的只是接收端登记这一步。
验证:
- `server/tests/unitChangedInbox.test.ts` 重写为 8 例(默认待审 / 字段齐全且不写 order_items /
只留最新先 UPDATE 后 INSERT / 幂等 / 校验四连 / 回退开关两条 / 落点源码钉);
- 真库端到端(自签 webhook × 真审核接口):返回 pending 且我方单位不动 ⇒ **审核页接口
scope=pending 能列到**("单位 斤 → 件")⇒ 通过 ⇒ 单位落 件 + 台账 approved + 留痕 ⇒
反向再走一遍并审核 ⇒ 还原、无遗留 pending;复跑同一事件 ⇒ ignored;
- 双端 tsc 0 错;全量 26 failed / 2666 passed 与基线持平(唯一差异仍是对方 WIP 的 pickingZoneOrder);
门禁 8 通过 / 1 既定红 / 1 未执行。
文档:设计文 §11.9 加口径翻转提示 + 新增 §11.11(改后行为表 / 验收 U16–U24 / 与 §11.8、§11.10 的关系);
对接清单新增「八、我方回执」(告诉对方可以这样验:他们改一次单位 ⇒ 我们多一条待审)。
This commit is contained in:
@@ -657,6 +657,9 @@ reason「单位变更补报(改量审核已落定):旧单位 → 新单位
|
||||
|
||||
## 11.9 主系统改单位也告知我方:新事件 `preparations.unit_changed` 的**接收端**(2026-10-13 追加)
|
||||
|
||||
> ⚠️ **口径已于 2026-10-13 晚翻转**(主系统 §4.5.25 请求):接收端**不再「收到即改镜像」**,
|
||||
> 而是**登记待审**、由我方人工决定跟不跟 —— 见下面的 **§11.11**。本节其余内容(事件契约、落点纪律)不变。
|
||||
|
||||
**背景**:§11.4-3 / 他们 §10.4 登记的同源**反向**缺口 —— 他们管理端改备货行单位时,若价格没变就不发
|
||||
`price_changed` ⇒ 我方镜像里的单位一直是旧的。他们开发者已拍板(D1=A 新增**专用事实事件**、D2=**只推事实、不给我方造待审**),
|
||||
提交 `3608614d` + 设计文 `docs/design/20261013-prep-unit-change-outbound.md`,开关
|
||||
@@ -682,7 +685,7 @@ reason「单位变更补报(改量审核已落定):旧单位 → 新单位
|
||||
|---|---|---|
|
||||
| ① 定位我方行 | `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 正确);**不动价/量/状态**,不写任何待审 | 同上 |
|
||||
| ③ 落值 | ⚠️ 默认**不落值**:登记一条 `field='unit'` 的**待审行**(§11.11);审核通过时才**只写** `order_items.unit = final_unit`(走 `runWithTenantDataAccess`,RLS 正确),**不动价/量/状态** | 同上 |
|
||||
| ④ 留痕 | 操作日志 `main_system_unit_changed_applied`(旧值/新值/来源/幂等键/操作人) | 同上 |
|
||||
| ⑤ 就地 return | webhook 里**必须 return**,不得落到末尾的「建单导入」兜底 | `mainSystemIntegration.ts` |
|
||||
|
||||
@@ -754,3 +757,52 @@ reason「单位变更补报(改量审核已落定):旧单位 → 新单位
|
||||
(疑似其复现流程清理掉了)⇒ 回执 `not_found 申请不存在或不属于本供应商`,我方台账**保持 pending 不变**;
|
||||
3. ⇒ 该行属"对方侧已无此申请"的**幽灵待审**,按既有 Q6 对账口径在宽限期后被自动关闭(`failed`),
|
||||
无需人工干预;若他们希望我们立刻清掉,让他们回一句即可(或重新推一条同 request_id 的结果事件)。
|
||||
|
||||
|
||||
## 11.11 口径翻转:单位变更改为「登记待审」(2026-10-13 晚,主系统 §4.5.25 请求)
|
||||
|
||||
**他们的口径(原话)**:「**自己只能改自己** —— 与改价完全同款,我方不替你们落库。」
|
||||
他们指出:我们原来的 `applyUnitChangedFact` 是「收到即直接 UPDATE 我方镜像」,
|
||||
等于**他们一改单位就把我们的数据改了**,与改价那条(事实 + 待审)不一致;
|
||||
请我们照 `recordPriceChangedFact` 对 `price_changed` 的做法:**登记成一条待审**,由我们的人决定跟不跟。
|
||||
(契约不变:事件名/字段都不变,他们**不需要改代码**。)
|
||||
|
||||
### 11.11.1 改后行为
|
||||
|
||||
| 步 | 动作 |
|
||||
|---|---|
|
||||
| ① 收到 `preparations.unit_changed` | 按 `(branch_code, prep_id)` 找到我方订单行;**不再写 `order_items`** |
|
||||
| ② 登记待审 | 写 `public.main_system_actual_qty_requests`:`field='unit'`、`node='unit_changed'`、`before_unit`/`unit`、`client_request_id`、`operator`、`applied_at=changed_at`、`fact_registered=true`、`payload.local_only=true` |
|
||||
| ③ 只留最新 | 同 `(branch, prep)` 的旧 **pending 单位行**转 `superseded`(与成本价事实同款纪律) |
|
||||
| ④ 幂等 | `request_id`(他们信封 id)或 `client_request_id`(`uc_<prep>_<before>_<after>`)重投 ⇒ 唯一键冲突 ⇒ `ignored`(重复投递),不新增第二行 |
|
||||
| ⑤ 审核(我方人工) | **通过** ⇒ 写 `order_items.unit`(+ 验收/核货单位、审计留痕);**驳回** ⇒ 不写、只留痕 |
|
||||
| ⑥ 回执 | **不回传**(`local_only=true`;他们只报事实,不需要回执);若他们将来想要「跟了/没跟」的回执,需新增事件,另行商定 |
|
||||
| 回退开关 | `UNIT_CHANGED_AUTO_APPLY=1` ⇒ 回到 2026-10-13 之前的「收到即改镜像、不建待审」(仅线上异常回退) |
|
||||
|
||||
**表结构不用迁移**:`main_system_actual_qty_requests` 从建表起就允许 `field IN ('qty','unit','price')`
|
||||
且已有 `before_unit`/`unit` 列(迁移 20261022);审核页 `PriceQtyRequestsPage` 也早已支持 `field='unit'` 的
|
||||
「旧单位 → 新单位」渲染 —— 缺的只是**接收端登记**这一步。
|
||||
|
||||
### 11.11.2 验收
|
||||
|
||||
| # | 项 | 结果 |
|
||||
|---|---|---|
|
||||
| U16 | 收到事件 ⇒ 接口返回 `status='pending'`,**我方单位不变** | 用例 ① + 真库 E2E |
|
||||
| U17 | 待审行字段齐全(before_unit/unit/幂等键/`local_only`),且**不写 order_items** | 用例 ① |
|
||||
| U18 | 只留最新:旧 pending 单位行先转 `superseded`(先 UPDATE 后 INSERT) | 用例 ② |
|
||||
| U19 | 幂等:同一事实重投 ⇒ `ignored`(唯一键冲突),不新增第二行 | 用例 ③ + 真库复跑实测 |
|
||||
| U20 | 安全:缺 prep_id / 缺 final_unit / 非 uuid / 行对不上 ⇒ 不建行 | 用例 ④ |
|
||||
| U21 | 回退开关 `UNIT_CHANGED_AUTO_APPLY=1` ⇒ 旧的「收到即改」(含旧幂等语义) | 用例 ⑤ |
|
||||
| U22 | **审核页可见**:`listActualQtyInbox({scope:'pending'})` 能列到该行,内容「单位 斤 → 件」 | 真库 E2E |
|
||||
| U23 | 审核通过 ⇒ 我方单位变为 `final_unit`、台账 `approved`、留痕 `payload.apply` | 真库 E2E |
|
||||
| U24 | 反向再走一遍并审核 ⇒ 数据还原、无遗留 pending | 真库 E2E |
|
||||
|
||||
用例:`server/tests/unitChangedInbox.test.ts`(8 例,已按新口径重写)。
|
||||
真库端到端(自签 webhook × 真审核接口):待审可见 → 通过 → 单位落值 → 反向还原,全绿。
|
||||
|
||||
### 11.11.3 与其它机制的关系
|
||||
|
||||
- **§11.8 定向补发**:不受影响(那是「我方改单位被待审改量挡住」的补发;本节的「待审」是**他们的变更**进我们的审核队列);
|
||||
- **§11.10.3 的「单位变更会占一条 pending」**:那条说的是**我方送出去的载体**在他们侧待审;
|
||||
本节新说的是**他们改单位**在我们侧待审 —— 两条链路各自独立,互不阻塞;
|
||||
- **不会引发回声**:我们审核通过后写的是**我们自己的** `order_items.unit`,**不回传**给他们。
|
||||
|
||||
@@ -448,6 +448,7 @@ docker compose -f docker-compose.prod.yml --env-file .env.production up -d --bui
|
||||
| `MAIN_SYSTEM_IMPORT_CONCURRENCY` | 可选 | 4 | 分公司导入并发(上限 10);500 家绑码时并发 4 可把瞬时峰值压到个位数 QPS |
|
||||
| `MAIN_SYSTEM_IMPORT_SPREAD_SEC` | 可选 | 120 | 拉货**错峰窗口**(秒):把各分公司的开始时刻在窗口内均匀铺开,避免整轮一起打主系统;`0` = 关闭错峰(尽快跑完)。窗口再被「家数 × 400 ms」封顶 ⇒ 2–3 家只等几百毫秒 |
|
||||
| `STOCK_COVER_REQUIRE_OUTSOURCED` | 可选 | 1(开) | 库存抵扣口径:开 = 只结转账外持有余额(`inventory_holding`,防同一批货计两次成本);`0` = 回退旧行为(只看物理自由库存),仅用于线上异常回退 |
|
||||
| `UNIT_CHANGED_AUTO_APPLY` | 可选 | 0(要审) | 主系统推 `preparations.unit_changed` 时的口径:不设/非 `1` = **登记待审**(审核页可见,人工决定跟不跟,通过才写我方单位);`1` = 回退旧行为(收到即改镜像、不建待审),仅用于线上异常回退 |
|
||||
| `MAIN_SYSTEM_BINDING_SYNC_URL` | 可选 | 空(不启用) | 「接入编码绑定」的**回读**端点(主系统只读接口全 URL);空则只依赖 `binding.changed` 回调与超管手工登记 —— 见 `docs/design/20261027-分公司接入编码与主系统供应商绑定.md` §8 P0-2 |
|
||||
|
||||
#### 租户 / 数据库 / 存储(PG_*、TENANT_*、S3_*、STORAGE_*)
|
||||
|
||||
@@ -4003,3 +4003,30 @@ prep `931eda1a-3c19-4b49-ab24-664b54770fc4` / `SUP35143228` / `ORD_WEB_20261009_
|
||||
(`[main-system-webhook] BR002 preparations.unit_changed:applied — 单位 X → Y(主系统管理端改动,我方镜像)`);
|
||||
- 你们修的那个"审核通过数量类申请会把旧数量当采购价"的缺陷,我们这边**没有对应写路径**
|
||||
(我们只在审核通过时回传结论,不写你们的采购价),无需我们改。
|
||||
|
||||
#### 八、我方回执(供应商系统 AI 填,2026-10-13 深夜):**§4.5.25 已实现 —— 单位变更在我们这边也是"待审"了**
|
||||
|
||||
> 你们 §4.5.25 的要求(「不要再自动 UPDATE 你们的镜像行…照 `recordPriceChangedFact` 登记成一条待审」)
|
||||
> **已落地**。契约不变、你们不用改任何代码。
|
||||
|
||||
**改后行为**(`server/src/services/mainSystemUnitChangedInbox.ts`):
|
||||
|
||||
| 步 | 动作 |
|
||||
|---|---|
|
||||
| 收到 `preparations.unit_changed` | 按 `(branch_code, prep_id)` 找到我方订单行;**不再写我方单位** |
|
||||
| 登记待审 | 写 `main_system_actual_qty_requests`:`field='unit'`、`node='unit_changed'`、`before_unit`/`unit`、`client_request_id`、`operator`、`applied_at=changed_at`、`fact_registered=true`、`payload.local_only=true` |
|
||||
| 只留最新 | 同一行旧的 **pending 单位行**转 `superseded`(与成本价事实同款纪律) |
|
||||
| 幂等 | 你们同一 `request_id` 或同一 `client_request_id` 重投 ⇒ 命中唯一键 ⇒ `ignored`(重复投递),不建第二行 |
|
||||
| 我方人工审核 | **通过** ⇒ 写 `order_items.unit`(含验收/核货单位,带审计留痕);**驳回** ⇒ 不写、只留痕 |
|
||||
| 回执 | **不回传**(`local_only`)。如果你们希望知道"我们跟了没跟",需要新增一条事件,你们提一条我们再评估 |
|
||||
| 回退开关 | `UNIT_CHANGED_AUTO_APPLY=1` = 回到旧行为(收到即改),仅线上异常回退用 |
|
||||
|
||||
**真机验证(自签 webhook × 真审核接口 × 真库)**:
|
||||
事件打进我们 API ⇒ 返回 `200 {status:"pending"}`、**我方单位保持 斤 不动** ⇒
|
||||
审核页接口 `scope=pending` **能列到这条**(内容「单位 斤 → 件」)⇒ 审核通过 ⇒ 我方单位变 `件`、台账 `approved` + 留痕
|
||||
⇒ 反向再走一遍(件 → 斤)并审核 ⇒ 还原,**无遗留 pending**。复跑同一条事件 ⇒ `ignored`(幂等)✅。
|
||||
用例 `server/tests/unitChangedInbox.test.ts` 8 例(默认待审 / 只留最新 / 幂等 / 校验 / 回退开关 / 落点源码钉)。
|
||||
|
||||
**你们那边现在可以这样验**:在备货表或订单明细改一次单位(改成另一个值)⇒ 你们应看到
|
||||
`preparations.unit_changed` 投递 `success/200`;我们这边会**多出一条待审**(审核页可见),
|
||||
我们审核通过后我方订单行/备货镜像才跟着变。**我们不再"收到就改"**,与你们的「自己只能改自己」对齐。
|
||||
|
||||
@@ -21,6 +21,10 @@ MAIN_SYSTEM_IMPORT_CONCURRENCY=4
|
||||
# 规模改造:拉货**错峰窗口**(秒)——把各分公司开始时刻在窗口内均匀铺开,避免整轮一起打主系统;
|
||||
# 默认 120,0=关闭(尽快跑完);窗口再被「家数 × 400 ms」封顶 ⇒ 2–3 家只等几百毫秒
|
||||
MAIN_SYSTEM_IMPORT_SPREAD_SEC=120
|
||||
# 单位变更待审口径(2026-10-13,主系统 §4.5.25):默认(不设或非 1)= 收到 unit_changed 后**登记待审**,
|
||||
# 我方人工决定跟不跟;置 1 = 回退旧行为(收到即改镜像、不建待审),仅用于线上异常回退
|
||||
UNIT_CHANGED_AUTO_APPLY=0
|
||||
|
||||
# 库存抵扣口径(2026-10-13):默认开 = 只允许结转账外持有余额(防同一批货计两次成本);
|
||||
# 置 0 = 回退旧行为(只看物理自由库存),仅用于线上异常回退
|
||||
STOCK_COVER_REQUIRE_OUTSOURCED=1
|
||||
|
||||
@@ -6,25 +6,26 @@ import { runWithTenantDataAccess } from './tenantSchemaService';
|
||||
*
|
||||
* 为什么需要:主系统管理端改单位时,若**价格没变**就不发 `preparations.price_changed`
|
||||
* ⇒ 我方镜像里的单位一直是旧的(他们的 §10.4 / 本仓设计文 §11.4-3 登记的同源反向缺口)。
|
||||
* 他们开发者已拍板:新增**专用事实事件**(`3608614d`,开关 `SUPPLIER_UNIT_CHANGED_PUSH_ENABLED` 默认关),
|
||||
* **只推事实、不给我方造待审**。本模块是接收端。
|
||||
* 他们开发者已拍板:新增**专用事实事件**(`3608614d`,开关 `SUPPLIER_UNIT_CHANGED_PUSH_ENABLED`)。
|
||||
*
|
||||
* 我方落地(设计文 §11.9):
|
||||
* ① 按 `(branch_code, prep_id)` 在 `main_system_order_import_items` 找到我方订单行;
|
||||
* ② **幂等**:我方当前单位已等于 `final_unit` ⇒ `ignored`(他们那边也有"回声抑制",这是第二道兜底);
|
||||
* ③ **只写** `order_items.unit` —— 不动价/量/状态,**不建任何待审**;
|
||||
* ④ 留一条操作日志(旧值/新值/来源/幂等键)。
|
||||
* ⚠️ **口径翻转(2026-10-13 晚,他们 §4.5.25 请求)**:原来是"收到即改我方镜像行",
|
||||
* 那等于"他们一改就把我们的数据改了",与"**自己只能改自己**"(改价那条早已是"事实 + 待审")冲突
|
||||
* ⇒ 现在默认**登记待审**:写一条 `main_system_actual_qty_requests`(`field='unit'`,`node='unit_changed'`),
|
||||
* 审核页看得到、由我方的人决定跟不跟;**通过时才写** `order_items.unit`(见 `decideActualQtyRequest`)。
|
||||
* `UNIT_CHANGED_AUTO_APPLY=1` 可整体回退旧行为(收到即改、不建待审)。
|
||||
*
|
||||
* 纪律:不回推(他们只报事实);行对不上就 `ignored` + 原因,**不猜、不建行**。
|
||||
*/
|
||||
|
||||
export type UnitChangedOutcome = {
|
||||
status: 'applied' | 'ignored';
|
||||
status: 'applied' | 'ignored' | 'pending';
|
||||
reason: string;
|
||||
/** 落地的我方订单行 id(幂等跳过/找不到行时为 null) */
|
||||
rowId: string | null;
|
||||
/** 实际落地的单位(排障/日志用) */
|
||||
unit?: string | null;
|
||||
/** 登记待审时:待审行 id(审核页据此操作) */
|
||||
requestRowId?: string | null;
|
||||
};
|
||||
|
||||
function text(value: unknown): string | null {
|
||||
@@ -51,6 +52,9 @@ export function mapUnitChangedPayload(payload: any) {
|
||||
operatorRole: text(payload?.operator_role),
|
||||
changedAt: text(payload?.changed_at),
|
||||
clientRequestId: text(payload?.client_request_id),
|
||||
/** 他们信封里的投递 id(事件唯一)—— 用作待审台账的 `request_id`(库里 NOT NULL + 唯一) */
|
||||
requestId: text(payload?.request_id),
|
||||
reason: text(payload?.reason),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -60,7 +64,107 @@ function sameUnit(a: string | null, b: string | null): boolean {
|
||||
}
|
||||
|
||||
/**
|
||||
* 应用一条 `preparations.unit_changed`(幂等)。
|
||||
* 单位变更是否**需要人工审核**(2026-10-13 口径翻转,主系统 §4.5.25 请求)。
|
||||
*
|
||||
* 默认**要审**:他们改单位推 `preparations.unit_changed` 过来,我方**不再直接改镜像行**,
|
||||
* 而是登记一条待审(`main_system_actual_qty_requests`,`field='unit'`)⇒ 审核页看得到、由人决定跟不跟;
|
||||
* 通过时才写 `order_items.unit`。理由与改价同款:**自己只能改自己**。
|
||||
*
|
||||
* `UNIT_CHANGED_AUTO_APPLY=1` 可**整体回退**到 2026-10-13 之前的行为(收到即改镜像、不建待审)。
|
||||
*/
|
||||
export function isUnitChangedReviewRequired(): boolean {
|
||||
return String(process.env.UNIT_CHANGED_AUTO_APPLY ?? '').trim() !== '1';
|
||||
}
|
||||
|
||||
/**
|
||||
* 把一条单位变更**登记成待审**(`main_system_actual_qty_requests`,`field='unit'`)。
|
||||
*
|
||||
* 纪律(与成本价事实 `recordPriceChangedFact` 同款):
|
||||
* · **同一行只留最新一条待审**:同 `(branch, prep)` 的旧 pending 单位行转 `superseded`;
|
||||
* · **幂等**:`request_id`(他们信封 id)或 `client_request_id`(`uc_<prep>_<before>_<after>`)重复投递
|
||||
* ⇒ 命中唯一键 ⇒ `ignored`(重复投递),不新增第二行;
|
||||
* · 事实来源:他们那边**已经改了**(`changed_at` 落 `applied_at`),所以我们只决定"跟不跟";
|
||||
* · `payload.local_only=true` ⇒ 审核通过时**不回传**给他们(他们只报事实,不需要回执)。
|
||||
*/
|
||||
async function registerUnitChangedPending(params: {
|
||||
branchCode: string;
|
||||
mapped: ReturnType<typeof mapUnitChangedPayload>;
|
||||
ourOrderCode: string;
|
||||
}): Promise<UnitChangedOutcome> {
|
||||
const { branchCode, mapped, ourOrderCode } = params;
|
||||
const prepId = String(mapped.prepId);
|
||||
const requestId = mapped.requestId || `unit:${mapped.clientRequestId || `${prepId}:${mapped.beforeUnit}->${mapped.finalUnit}`}`;
|
||||
|
||||
// 同一行只留最新:旧的待审单位行转 superseded(可追溯,审核页"已失效"档能看到)
|
||||
await pool.query(
|
||||
`UPDATE public.main_system_actual_qty_requests
|
||||
SET status = 'superseded', updated_at = NOW(),
|
||||
decision_reason = COALESCE(decision_reason, '被更新的单位变更取代(只留最新一条待审)')
|
||||
WHERE branch_code = $1 AND prep_id = $2::uuid AND field = 'unit' AND status = 'pending'`,
|
||||
[branchCode, prepId]
|
||||
);
|
||||
|
||||
try {
|
||||
const inserted = await pool.query<{ id: string }>(
|
||||
`INSERT INTO public.main_system_actual_qty_requests
|
||||
(branch_code, request_id, prep_id, order_code, our_order_code, sku_code, node, field,
|
||||
before_value, proposed_value, before_unit, unit, operator, reason, client_request_id,
|
||||
status, fact_registered, payload, applied_at)
|
||||
VALUES ($1,$2,$3::uuid,$4,$5,$6,'unit_changed','unit',
|
||||
NULL, NULL, $7, $8, $9, $10, $11,
|
||||
'pending', true, $12::jsonb, $13::timestamptz)
|
||||
RETURNING id::text AS id`,
|
||||
[
|
||||
branchCode,
|
||||
requestId,
|
||||
prepId,
|
||||
mapped.orderCode,
|
||||
ourOrderCode,
|
||||
mapped.skuCode,
|
||||
mapped.beforeUnit,
|
||||
mapped.finalUnit,
|
||||
mapped.operator,
|
||||
mapped.reason,
|
||||
mapped.clientRequestId,
|
||||
JSON.stringify({
|
||||
event: 'preparations.unit_changed',
|
||||
source: 'main_system_unit_changed',
|
||||
source_label: mapped.source,
|
||||
operator_role: mapped.operatorRole,
|
||||
changed_at: mapped.changedAt,
|
||||
// 他们只报事实:审核结论**不回传**(`decideActualQtyRequest` 按 local_only 处理)
|
||||
local_only: true,
|
||||
}),
|
||||
mapped.changedAt,
|
||||
]
|
||||
);
|
||||
const id = inserted.rows[0]?.id ?? null;
|
||||
return {
|
||||
status: 'pending',
|
||||
reason: `已登记待审:单位 ${mapped.beforeUnit || '—'} → ${mapped.finalUnit}(由我方审核决定是否跟)`,
|
||||
rowId: null,
|
||||
unit: mapped.finalUnit,
|
||||
requestRowId: id,
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
// 唯一键冲突 = 同一事实重投(幂等)
|
||||
if (String((error as { code?: string })?.code) === '23505') {
|
||||
return {
|
||||
status: 'ignored',
|
||||
reason: '该单位变更已在待审台账里(重复投递,幂等跳过)',
|
||||
rowId: null,
|
||||
unit: mapped.finalUnit,
|
||||
};
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理一条 `preparations.unit_changed`(幂等)。
|
||||
*
|
||||
* · 默认(`isUnitChangedReviewRequired()`):**登记待审**,返回 `{status:'pending'}`;
|
||||
* · 回退开关打开时:直接改镜像行(旧行为,返回 `applied/ignored`)。
|
||||
*
|
||||
* 业务失败不抛错:返回 `ignored` + 原因,调用方(webhook)照旧 200 收下 —— 重推解决不了前置问题。
|
||||
*/
|
||||
@@ -91,7 +195,16 @@ export async function applyUnitChangedFact(params: {
|
||||
return { status: 'ignored', reason: '我方没有该备货行的对照行(未对照上/已删除)', rowId: null };
|
||||
}
|
||||
|
||||
// ② 读我方当前单位(tenant 隔离:必须走 runWithTenantDataAccess)
|
||||
/**
|
||||
* ② **登记待审**(默认口径):写一条 `field='unit'` 的待审行,由人决定跟不跟。
|
||||
* 同 `(branch, prep)` 的旧 pending 单位行转 `superseded`(只留最新一条待审,与成本价事实同款纪律)。
|
||||
* 幂等:他们同一 `request_id` / 同一 `client_request_id` 重投 ⇒ 命中唯一键 ⇒ `ignored`(重复投递)。
|
||||
*/
|
||||
if (isUnitChangedReviewRequired()) {
|
||||
return registerUnitChangedPending({ branchCode, mapped, ourOrderCode: row.our_order_code });
|
||||
}
|
||||
|
||||
// ③ 回退路径:读我方当前单位(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`,
|
||||
@@ -111,7 +224,7 @@ export async function applyUnitChangedFact(params: {
|
||||
};
|
||||
}
|
||||
|
||||
// ③ 只写 unit;价/量/状态/退货标记一律不动(`order_items` 无 updated_at 列)
|
||||
// ④ 只写 unit;价/量/状态/退货标记一律不动(`order_items` 无 updated_at 列)
|
||||
const updated = await runWithTenantDataAccess(branchCode, (client) =>
|
||||
client.query<{ id: string }>(
|
||||
`UPDATE order_items SET unit = $3
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
@@ -6,13 +6,21 @@ import path from 'node:path';
|
||||
* 主系统改**备货行单位** → 通知我方(事件 `preparations.unit_changed`,2026-10-13)。
|
||||
*
|
||||
* 反向缺口:他们管理端改单位时若价格没变就不发 `price_changed` ⇒ 我方镜像里的单位一直是旧的。
|
||||
* 他们已新增专用事实事件(提交 `3608614d`,开关默认关,等我们接收端就绪)。
|
||||
* 他们新增了专用事实事件(提交 `3608614d`)。
|
||||
*
|
||||
* 本文件钉住接收端的四条不变量:
|
||||
* ① 落值:按 `prep_id` 找到我方行,**只写 `unit = final_unit`**(价/量/状态不动);
|
||||
* ② 幂等:我方已是该单位 ⇒ `ignored`,不重复写、不刷日志;
|
||||
* ③ 安全:缺 `prep_id`/缺 `final_unit`/非 uuid/行对不上 ⇒ `ignored` + 原因,**不猜不建行**;
|
||||
* ④ 落点:webhook 里**就地 return**,不落到末尾的「建单导入」兜底(他们 §三 明确提醒)。
|
||||
* ⚠️ **口径翻转(2026-10-13 晚,他们 §4.5.25 请求)**:原来是"收到即改我方镜像行",
|
||||
* 等于"他们一改就把我们的数据改了",与"自己只能改自己"(改价早已是"事实 + 待审")冲突
|
||||
* ⇒ 现在默认**登记待审**(`main_system_actual_qty_requests`,`field='unit'`),
|
||||
* 审核页看得到、由人决定跟不跟;通过时才写 `order_items.unit`。
|
||||
* `UNIT_CHANGED_AUTO_APPLY=1` 可整体回退旧行为。
|
||||
*
|
||||
* 本文件钉住:
|
||||
* ① 默认:登记一条**待审**行(含 before_unit/unit/client_request_id/local_only),**不写** order_items;
|
||||
* ② 只留最新:同 prep 的旧 pending 单位行转 superseded;
|
||||
* ③ 幂等:同一事实重投(唯一键冲突)⇒ ignored,不新增第二行;
|
||||
* ④ 安全:缺 prep_id / 缺 final_unit / 非 uuid / 行对不上 ⇒ ignored + 原因,不建行;
|
||||
* ⑤ 回退开关:`UNIT_CHANGED_AUTO_APPLY=1` ⇒ 回到"收到即改"(旧用例语义);
|
||||
* ⑥ 落点:webhook 里**就地 return**,不落到「建单导入」兜底。
|
||||
*/
|
||||
|
||||
const query = vi.hoisted(() => vi.fn());
|
||||
@@ -32,6 +40,7 @@ vi.mock('../src/services/auditService', () => ({
|
||||
|
||||
import {
|
||||
applyUnitChangedFact,
|
||||
isUnitChangedReviewRequired,
|
||||
mapUnitChangedPayload,
|
||||
} from '../src/services/mainSystemUnitChangedInbox';
|
||||
|
||||
@@ -43,6 +52,7 @@ const ITEM = '3e65a38f-ad78-4010-b370-4142650308fd';
|
||||
function payload(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
event: 'preparations.unit_changed',
|
||||
request_id: 'evt-unit-1',
|
||||
branch_code: BRANCH,
|
||||
supplier_code: 'SUP37831443',
|
||||
subsystem_code: 'SCF69N8ZQEVQ',
|
||||
@@ -64,14 +74,30 @@ function payload(overrides: Record<string, unknown> = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
/** 组装 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')) {
|
||||
/** pool 侧桩:link 命中 + 待审登记(INSERT/UPDATE)记录 */
|
||||
function stub(params: {
|
||||
link?: { our_order_code: string | null; our_order_item_id: string | null } | null;
|
||||
insertFails?: boolean;
|
||||
currentUnit?: string | null;
|
||||
}) {
|
||||
const link =
|
||||
params.link === undefined ? { our_order_code: ORDER, our_order_item_id: ITEM } : params.link;
|
||||
const calls: Array<{ sql: string; params?: unknown[] }> = [];
|
||||
query.mockImplementation(async (sql: string, values?: unknown[]) => {
|
||||
const text = String(sql);
|
||||
calls.push({ sql: text, params: values });
|
||||
if (text.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: [] };
|
||||
if (text.startsWith('UPDATE public.main_system_actual_qty_requests')) {
|
||||
return { rowCount: 1, rows: [] };
|
||||
}
|
||||
if (text.startsWith('INSERT INTO public.main_system_actual_qty_requests')) {
|
||||
if (params.insertFails) {
|
||||
throw Object.assign(new Error('duplicate key'), { code: '23505' });
|
||||
}
|
||||
return { rowCount: 1, rows: [{ id: 'pending-row-1' }] };
|
||||
}
|
||||
return { rowCount: 0, rows: [] };
|
||||
});
|
||||
const updates: unknown[][] = [];
|
||||
@@ -83,15 +109,13 @@ function stub(params: { unitNow: string | null; link?: { our_order_code: string
|
||||
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: 1, rows: [{ unit: params.currentUnit ?? '斤' }] };
|
||||
}
|
||||
return { rowCount: 0, rows: [] };
|
||||
},
|
||||
})
|
||||
);
|
||||
return { updates };
|
||||
return { calls, updates };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -99,108 +123,119 @@ beforeEach(() => {
|
||||
withTenantData.mockReset();
|
||||
audit.mockReset();
|
||||
audit.mockResolvedValue(undefined);
|
||||
delete process.env.UNIT_CHANGED_AUTO_APPLY;
|
||||
});
|
||||
|
||||
describe('主系统改单位 ⇒ 我方接收端(preparations.unit_changed)', () => {
|
||||
it('① 落值:只写 unit = final_unit,价/量/状态不碰,并留一条操作日志', async () => {
|
||||
const { updates } = stub({ unitNow: '斤' });
|
||||
afterEach(() => {
|
||||
delete process.env.UNIT_CHANGED_AUTO_APPLY;
|
||||
});
|
||||
|
||||
describe('单位变更接收端:默认**登记待审**(2026-10-13 口径翻转)', () => {
|
||||
it('① 登记一条待审行:带 before_unit/unit/幂等键 + local_only,且**不写** order_items', async () => {
|
||||
const { calls, updates } = stub({});
|
||||
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');
|
||||
expect(out.status).toBe('pending');
|
||||
expect(out.requestRowId).toBe('pending-row-1');
|
||||
expect(String(out.reason)).toContain('已登记待审');
|
||||
expect(updates, '待审阶段不得改我方单位').toHaveLength(0);
|
||||
|
||||
const insert = calls.find((c) => c.sql.startsWith('INSERT INTO public.main_system_actual_qty_requests'));
|
||||
expect(insert, '必须写入待审台账').toBeTruthy();
|
||||
// 列里写死的部分(node/field/status/fact_registered)走 SQL 文本断言,参数按下标断言
|
||||
expect(insert?.sql).toContain("'unit_changed','unit'");
|
||||
expect(insert?.sql).toContain("'pending', true");
|
||||
const v = insert?.params as unknown[];
|
||||
expect(v[1], 'request_id').toBe('evt-unit-1');
|
||||
expect(v[2], 'prep_id').toBe(PREP);
|
||||
expect(v[6], 'before_unit').toBe('斤');
|
||||
expect(v[7], 'unit=新单位').toBe('件');
|
||||
expect(v[10], 'client_request_id 幂等键').toBe(`uc_${PREP}_斤_件`);
|
||||
expect(String(v[11]), 'local_only(审核结论不回传)').toContain('"local_only":true');
|
||||
});
|
||||
|
||||
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('② 只留最新:同 prep 的旧 pending 单位行先转 superseded', async () => {
|
||||
const { calls } = stub({});
|
||||
await applyUnitChangedFact({ branchCode: BRANCH, payload: payload() });
|
||||
const supersede = calls.find((c) => c.sql.startsWith('UPDATE public.main_system_actual_qty_requests'));
|
||||
expect(supersede, '必须先清理旧待审').toBeTruthy();
|
||||
expect(supersede?.sql).toContain("status = 'superseded'");
|
||||
expect(supersede?.sql).toContain("field = 'unit'");
|
||||
// 顺序:先 supersede 再 INSERT
|
||||
const idxUpdate = calls.findIndex((c) => c.sql.startsWith('UPDATE public.main_system_actual_qty_requests'));
|
||||
const idxInsert = calls.findIndex((c) => c.sql.startsWith('INSERT INTO public.main_system_actual_qty_requests'));
|
||||
expect(idxUpdate).toBeLessThan(idxInsert);
|
||||
});
|
||||
|
||||
it('② 幂等:我方已是该单位 ⇒ ignored(不写、不留痕)', async () => {
|
||||
const { updates } = stub({ unitNow: '件' });
|
||||
it('③ 幂等:同一事实重投(唯一键冲突)⇒ ignored,不新增第二行', async () => {
|
||||
const { calls } = stub({ insertFails: true });
|
||||
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();
|
||||
expect(calls.filter((c) => c.sql.startsWith('INSERT INTO'))).toHaveLength(1);
|
||||
});
|
||||
|
||||
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, unknown>, string]> = [
|
||||
it('④ 安全:缺 prep_id / 缺 final_unit / 非 uuid / 行对不上 ⇒ 不建行', async () => {
|
||||
for (const [override, expected] of [
|
||||
[{ 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) {
|
||||
] as Array<[Record<string, unknown>, string]>) {
|
||||
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();
|
||||
expect(query).not.toHaveBeenCalled();
|
||||
}
|
||||
|
||||
// 行对不上(对照台账没有该 prep / 缺我们的行 id):不猜、不建行
|
||||
const { updates } = stub({ unitNow: '斤', link: null });
|
||||
const { calls } = stub({ link: null });
|
||||
const missing = await applyUnitChangedFact({ branchCode: BRANCH, payload: payload() });
|
||||
expect(missing.status).toBe('ignored');
|
||||
expect(String(missing.reason)).toContain('没有该备货行的对照行');
|
||||
expect(updates).toHaveLength(0);
|
||||
expect(calls.some((c) => c.sql.startsWith('INSERT INTO'))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
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);
|
||||
describe('回退开关:UNIT_CHANGED_AUTO_APPLY=1 ⇒ 旧的"收到即改"', () => {
|
||||
it('① 开关打开:直接写 order_items.unit,不建待审', async () => {
|
||||
process.env.UNIT_CHANGED_AUTO_APPLY = '1';
|
||||
expect(isUnitChangedReviewRequired()).toBe(false);
|
||||
const { calls, updates } = stub({});
|
||||
const out = await applyUnitChangedFact({ branchCode: BRANCH, payload: payload() });
|
||||
expect(out.status).toBe('applied');
|
||||
expect(updates).toHaveLength(1);
|
||||
expect(updates[0]).toEqual([ORDER, ITEM, '件']);
|
||||
expect(calls.some((c) => c.sql.startsWith('INSERT INTO public.main_system_actual_qty_requests'))).toBe(false);
|
||||
// 审计日志仍在
|
||||
expect(audit).toHaveBeenCalledTimes(1);
|
||||
expect((audit.mock.calls[0][0] as { operationType: string }).operationType).toBe(
|
||||
'main_system_unit_changed_applied'
|
||||
);
|
||||
});
|
||||
|
||||
it('④b 我方订单行已不存在 ⇒ ignored(不是 applied)', async () => {
|
||||
const { updates } = stub({ unitNow: null });
|
||||
it('② 开关打开时,我方已是该单位 ⇒ ignored(旧幂等语义保留)', async () => {
|
||||
process.env.UNIT_CHANGED_AUTO_APPLY = '1';
|
||||
const { updates } = stub({ currentUnit: '件' });
|
||||
const out = await applyUnitChangedFact({ branchCode: BRANCH, payload: payload() });
|
||||
expect(out.status).toBe('ignored');
|
||||
expect(String(out.reason)).toContain('已不存在');
|
||||
expect(String(out.reason)).toContain('幂等跳过');
|
||||
expect(updates).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
it('⑤ 落点:webhook 里就地 return,不落到「建单导入」兜底(源码钉)', () => {
|
||||
describe('载荷映射与落点', () => {
|
||||
it('两个字段名都认(prep_id / unit 别名),并带出 request_id / reason', () => {
|
||||
const mapped = mapUnitChangedPayload(
|
||||
payload({ preparation_id: null, final_unit: null, unit: '箱', reason: '复称' })
|
||||
);
|
||||
expect(mapped.prepId).toBe(PREP);
|
||||
expect(mapped.finalUnit).toBe('箱');
|
||||
expect(mapped.beforeUnit).toBe('斤');
|
||||
expect(mapped.requestId).toBe('evt-unit-1');
|
||||
expect(mapped.reason).toBe('复称');
|
||||
expect(Object.keys(mapped)).not.toContain('price');
|
||||
});
|
||||
|
||||
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')");
|
||||
@@ -208,8 +243,6 @@ describe('主系统改单位 ⇒ 我方接收端(preparations.unit_changed)'
|
||||
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 })');
|
||||
expect(route.slice(branchAt, fallbackAt)).toContain('return res.json({ ok: true, ...applied })');
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user