From 277b575fc90c3fb726a925c357f3ad9c28b7b1bf Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Sat, 10 Oct 2026 10:26:04 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E8=B7=A8=E7=B3=BB=E7=BB=9F):=20=E4=BB=B7?= =?UTF-8?q?=E6=A0=BC/=E6=94=B9=E9=87=8F=E9=93=BE=E7=BF=BB=E8=BD=AC?= =?UTF-8?q?=E4=B8=BA=E3=80=8C=E5=85=88=E6=94=B9=E5=90=8E=E9=80=9A=E7=9F=A5?= =?UTF-8?q?=E3=80=8D+=20=E6=88=90=E6=9C=AC=E4=BB=B7=E3=80=8C=E5=85=88?= =?UTF-8?q?=E6=94=B9=E5=90=8E=E5=AE=A1=E3=80=8D=E6=8E=A5=E6=94=B6=E7=AB=AF?= =?UTF-8?q?=20+=20=E7=89=88=E6=9C=AC=E6=A0=A1=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 开发者口径(2026-10-12):「改了就是改了……相当于就是自己只能改自己的」;主系统 `3e90deb9`(第七批)同步把**成本价**翻转为"先改后通知",并交付乐观并发校验。 一、我方改我方的(销售价 / 数量)⇒ 先改后通知 · `isPriceQtyLocalFirst()` 总开关(默认 true;置 false 整体回退旧"先审后改",旧实现与旧测试全部保留) · 守卫放行 + `notifyMainSystemPriceQtyChanges()`(异步、逐条、失败只日志不阻塞) · 接线:订单明细保存(**COMMIT 之后**、try/finally 之外、不 await)、自采列表改销售价(分支内无 return/throw) · 主系统结论**不再覆盖我方值**:只记台账 + 留痕(`local_first.divergence`),不一致不提醒 · **界面分流取消**:原先"涨价/加量"会把用户编辑值**回填成原值**("改不动"的真身),现改为原样交保存链路 · 修掉实测缺陷:通知是 COMMIT 之后发的,回表读到的是**新值** ⇒ 判 no_change **根本不通知** (真库复现:8.30→9.10 主系统完全收不到)⇒ 新增 `beforePrice/beforeQty` 入参,由调用方给改动前的值 二、对方改它的(成本价)⇒ 先改后审(我方审核决定跟不跟) · `post_complete_price` 归入**事实登记**(FACT_NODES 4→5):驳回文案不再谎称"双方均不改值" · 审核同意 = **我方销售价跟随落值**:写 price/locked_price/price_locked_at/amount + 重建结算投影; 已结算/已结案(≥90) 仍只留痕。此前 `field='price'` 是**静默无操作**(真库 4 条 approved 我方价格没动) · 结算投影同步统一包进 `runWithTenantDbContext`(裸调用会 `relation "orders" does not exist` 静默失败) · `preparations.price_changed` **接收端**(此前一律 200 ignored):有待审 ⇒ 刷成最新值; 无待审 ⇒ 补一条本地待审事实行(`local_only=true`,结论不回传对方) · **同一商品同一字段只留一条待审**:新申请到达 ⇒ 旧 pending 转 `superseded` (`superseded_by` / `refresh_history` 可回溯),插入 / 原地刷新 / Q6 对账三条路径都收敛 三、乐观并发校验(主系统第七批 §12.3 / 我方 §4.5.6-A) · 迁移 `20261025_…`:`request_version` + `request_updated_at` · 事件与 Q6 都落版本;审核回执带 `decided_basis_version` · 409 `stale_request_version` ⇒ **不写任何值**,Q6 单行刷新 + 提示"请重新确认"(suspended 走 error toast) · 审核页在「对方生效时间」后显示版本徽标 `v3`(纯数字,不新增文案) 验证:服务端全量失败文件与基线**逐文件一致(24,零新增)**;新增/改动用例 `mainSystemPriceQtyRequest`(46) / `salePriceDiversion`(4) / `actualQtyInbox`(13) / `actualQtyFactSync`(12) / `PriceQtyRequestsPage.render`(6) / 前端 `orderManagement*`(84) 全绿;前后端 tsc exit 0; 真库 E2E(通知真的送达、成本价跟随落值 8.30→3.50 / amount→28.00、版本 v7→v8 刷新、同商品待审恒为 1 条) 跑完均已还原;设计门禁 8 通过 / 1 未通过(check-ai-cost 基线红)/ 1 未执行(无 psql)。 文档:清单 §4.5.8(+四)、设计文档 `20261011-跨系统改价改量审核.md` §10、 `20261011-实收数量与单位的事后同步.md` §11。 --- .../20261011-实收数量与单位的事后同步.md | 42 +- docs/design/20261011-跨系统改价改量审核.md | 81 +- docs/manual/02-环境要求与安装部署.md | 1 + docs/给主系统AI的对接改造清单.md | 331 +++++- ...ain_system_actual_qty_status_withdrawn.sql | 22 + ...main_system_actual_qty_request_version.sql | 25 + server/.env.example | 2 + .../modules/workflow/routes/orderRoutes.ts | 38 +- server/src/routes/mainSystemIntegration.ts | 47 +- .../services/mainSystem/api/preparations.ts | 126 +- server/src/services/mainSystem/config.ts | 5 + server/src/services/mainSystem/endpoints.ts | 2 + .../src/services/mainSystemActualQtyApply.ts | 58 +- .../src/services/mainSystemActualQtyInbox.ts | 1047 ++++++++++++++++- server/src/services/mainSystemOrderImport.ts | 37 + .../src/services/mainSystemPriceQtyRequest.ts | 418 ++++++- .../src/services/orderManageItemsService.ts | 37 +- .../purchaseLinkedSalePriceService.ts | 50 +- server/src/utils/deterministicUuid.ts | 19 + .../actualQtyDecidedAndReconcile.test.ts | 172 +++ server/tests/actualQtyFactSync.test.ts | 35 + server/tests/actualQtyInbox.test.ts | 111 +- .../tests/mainSystemPriceQtyRequest.test.ts | 354 +++++- server/tests/salePriceDiversion.test.ts | 41 +- src/i18n/locales/en/orders.ts | 10 + src/i18n/locales/id/orders.ts | 10 + src/i18n/locales/zh-CN/orders.ts | 10 + .../PriceQtyRequestsPage.render.test.tsx | 116 +- src/pages/orders/PriceQtyRequestsPage.tsx | 278 ++++- .../orderManagement/OrderManagementPage.tsx | 117 +- ...rManagementPage.priceQtyLocalFirst.test.ts | 41 + src/utils/workflowApi.ts | 56 +- 32 files changed, 3443 insertions(+), 296 deletions(-) create mode 100644 migrations/20261024_main_system_actual_qty_status_withdrawn.sql create mode 100644 migrations/20261025_main_system_actual_qty_request_version.sql create mode 100644 server/src/utils/deterministicUuid.ts create mode 100644 server/tests/actualQtyDecidedAndReconcile.test.ts create mode 100644 src/pages/orders/orderManagement/orderManagementPage.priceQtyLocalFirst.test.ts diff --git a/docs/design/20261011-实收数量与单位的事后同步.md b/docs/design/20261011-实收数量与单位的事后同步.md index 3217af7..19a8f80 100644 --- a/docs/design/20261011-实收数量与单位的事后同步.md +++ b/docs/design/20261011-实收数量与单位的事后同步.md @@ -14,7 +14,10 @@ ⇒ 本机制的"审核"**不是改值闸门**,而是**同步 + 留痕**:对方的实际值先落定,我方只决定"我这条记录要不要跟着改"。 **适用范围**:**实收数量 + 单位**。 -**单价不在此链**:子系统销售价 ↔ 主系统成本价 **只要存在变动就发申请**(走 `20261011-跨系统改价改量审核.md` 那条"先审后改"的通道)。 +**单价与本链同口径(2026-10-12 起)**:子系统的**销售价 / 数量**是我方字段 ⇒ **先改后通知**:本地立即生效、 +随后异步通知主系统,对方结论**不回改我方值**("自己只能改自己的",见 +[`20261011-跨系统改价改量审核.md`](20261011-跨系统改价改量审核.md) **§10**)。 +**反向**:主系统的**成本价**(= 它的字段,含 `post_complete_price`)由它先生效再通知,我方只登记事实、不回写它。 ## 2. 与我方既有实现的差异(2026-10-11 实测代码) @@ -110,4 +113,41 @@ **回归**:`PriceQtyRequestsPage.render.test.tsx`(动作文案/生效时间列/历史区)、`src/i18n`(三语键一致)。 +## 11. 实施记录(2026-10-12 第 3 批:成本价也走"先改后审" + 版本校验 + 事实事件接收端) + +主系统第七批 `3e90deb9`(其设计文档 §12)把**成本价**从 ≥90"先审后改"翻转为"**先改后通知**", +本批把我方接收端补齐。开发者同时给了三条口径: +> 「**驳回 = 我方自己不改而已**,而不是还得去改主系统的成本价;主系统任何状态都能发出没有问题, +> 只需要**确保为最新的**就行;**不要出现一个商品两条需要处理的申请**,应该是保留最新的,旧的作为历史记录可回溯。」 +> 「主系统发出的修改,我们这边**肯定要展示**呀,**要我方审核**的呀。」 + +### 11.1 改动清单 + +| # | 项 | 落地 | +|---|---|---| +| 1 | `post_complete_price` 归入**事实登记** | `FACT_NODES` 由 4 项加到 5 项(原先注释写"成本价先审后改、不在其列",与对方第七批相反;不改会让**驳回**文案谎称"双方均不改值") | +| 2 | **同意 = 我方销售价跟随落值**(不再是静默无操作) | `mainSystemActualQtyApply.ts` 新增 `field='price'` 分支:写 `price / locked_price / price_locked_at / amount`(与自采列表改销售价同一口径)+ **重建客户/供应商结算投影**;已结算/已结案仍走 `skipped_settled` 只留痕。真库实测:8.30 → 3.50 ⇒ `amount 66.40 → 28.00` ✓ | +| 3 | **乐观并发校验接线** | 迁移 `20261025_main_system_actual_qty_request_version.sql`(`request_version` + `request_updated_at`);事件与 Q6 都落库;审核回执带 `decided_basis_version`;对方 409 `stale_request_version` ⇒ **我方不写任何值**,自动用 Q6 单行刷新 + 提示"该申请已被主系统更新为最新值,已刷新,请重新确认"(`suspended` 走 **error** toast,不再报成功) | +| 4 | `preparations.price_changed` **接收端** | 此前一律 `{ok:true, ignored:true}`(对方以为"我们没收到")。现在:有待审 ⇒ **刷成最新值 + 留痕**;无待审 ⇒ 补一条**本地待审事实行**(`payload.local_only=true`,结论不回传对方——它已改完);幂等键 = 对方 `client_request_id` 派生的**确定性 UUID**(纯函数 `src/utils/deterministicUuid.ts`) | +| 5 | **同一商品同一字段只留一条待审** | `supersedeOlderPending()`:新申请/事实到达时,同 `(prep_id, field)` 的旧 `pending` 自动转 `superseded`(进"已处理"历史;`payload.superseded_by` = 被谁取代,`refresh_history` = 每次刷新的新旧值)。插入、原地刷新、Q6 对账三条路径都收敛 | +| 6 | 审核页展示 | 待审表「对方生效时间」列后加**版本徽标** `v3`(纯数字,不新增文案);成本价申请本就在该页可审可驳回(节点/字段/原值→建议值/对方生效时间/我方落值结果齐全) | + +### 11.2 实测(真库,跑完均已还原/清理) + +| 场景 | 结果 | +|---|---| +| `price_changed` 事实(该商品无待审) | `recorded` ⇒ 待审行 `local_only=true`、`proposed=4` ✓ | +| 同商品再来一笔更新的(3.5) | `refreshed` ⇒ 原行刷成 `3.5`(**不新建第二条**)✓ | +| 同意(本地事实行) | `我方销售价 8.3 → 3.5、金额 → 28`;订单行 `price=3.50 / amount=28.00`;**无回执外呼** ✓ | +| 签名 webhook:带 `request_version=7` 的新申请 | 落库 `request_version=7`、原因文案"事实登记(对方已先改自己的实际值;驳回不回滚)" ✓ | +| 同 `request_id` 原地刷新到 `v8` + 2.5 | `refreshed` ⇒ `request_version=8` ✓;同商品同字段待审条数 **= 1** ✓ | + +**又踩到并修掉的坑(第 2 条是**存量**缺陷)**: +1. 通知链的 `before` 值取错 ——「先改后通知」是**写完库 COMMIT 之后**才通知,`submitPriceQtyRequest` 回表读到的是**新值** + ⇒ 判 `no_change` **根本不通知**(真库复现:改价 8.30→9.10 对方完全收不到)。修法:新增 `beforePrice/beforeQty` 入参, + 由调用方给"改动前的值"(`notifyMainSystemPriceQtyChanges` 传 `change.from`),并加回归用例钉住。 +2. `syncStatementsForOrderSafe(orderCode, null)` 直接调用会**静默失败**(它内部用裸连接查 `orders`/结算表, + 无 ALS 上下文时报 `relation "orders" does not exist` 且只打日志)⇒ 结算投影停在旧值。已在**价、量两条分支**上 + 统一包进 `runWithTenantDbContext(branchCode, …)`。 + **至此第 1、2 批全部落地**;剩余仅"主系统按 §2.9 发 `node=inbound` + `applied_at`"(已在《给主系统 AI 的对接改造清单》§2.9 提出,等对方回执)。 diff --git a/docs/design/20261011-跨系统改价改量审核.md b/docs/design/20261011-跨系统改价改量审核.md index 84281ac..9a99283 100644 --- a/docs/design/20261011-跨系统改价改量审核.md +++ b/docs/design/20261011-跨系统改价改量审核.md @@ -1,5 +1,15 @@ # 跨系统改价 / 改量:请求—审核—回传(2026-10-11) +> ## ⚠️ 口径已于 2026-10-12 翻转:**先改后通知**(本文 §1–§8 的"先审后改"仅存历史) +> +> 开发者 2026-10-12 定稿:**「自己只能改自己的」**—— +> **我方销售价 / 我方数量:本地**立即生效**(参与全部财务口径),随后**异步通知**主系统跟着变; +> 主系统的同意/驳回**都不回改我方值**,不一致只留痕、不提醒。** +> 因此本文下面凡出现"**要审核 / 先审后改 / 以主系统最终值为准 / 按回传值落地**"的表述, +> 一律以 **§10**(含新的判定表与实现要点)为准;§1 判定表仍用于**主系统侧**决定它自己要不要审。 +> 旧口径的实现**未删除**(`isPriceQtyLocalFirst()` 置 `false` 即整体回退,用于线上异常回退), +> 其测试也全部保留在 `tests/mainSystemPriceQtyRequest.test.ts`(默认跑旧口径,新口径在同文件末尾单独钉住)。 + > 开发者当轮定稿口径(原话要点): > 「子系统改销售价 **都应该要审核**;两个例外:① 分配过来时主系统成本价为 0(= 子系统销售价为 0),他补价 **无需审核**; > ② **改低**(低于原价)无需审核 —— 主系统与子系统**分别留下详细日志**就行。」 @@ -23,7 +33,8 @@ > 开发者 2026-10-11 定稿:「原数据为 0 就无需审核,两边系统留下日志就行」——价与量**同一口径**。 - 免审不等于不告知:**免审改动也要上报主系统**(保证两边一致),并且**两边各留详细日志**; -- 审核中管理员可把值改成中间值 ⇒ **一切以主系统最终值为准**,子系统按回传值落地; +- ~~审核中管理员可把值改成中间值 ⇒ **一切以主系统最终值为准**,子系统按回传值落地~~ + ⚠️ **2026-10-12 翻转**:主系统最终值**不再覆盖我方值**,只记台账 + 留痕(差异记 `divergence`)——见 §10; - 语义定位:子系统侧 = **客户(主系统)提出改销售价/数量的建议**;主系统侧 = 供应商改价/改量的**新**流程。 ## 2. 为什么不复用主系统现有的 `POST /preparations/amend-price` @@ -295,13 +306,16 @@ server/src/services/mainSystem/ ## 8.1.1 与改价并列的「实收数量」口径(2026-10-11 定稿,**与改价规则不同**) +> ⚠️ 本节的**销售价**一行已被 2026-10-12 口径翻转(**先改后通知**,见 §10); +> **实收数量**的三条硬约束(两边独立、只留痕、不改对方)**继续有效**。 + 开发者原话要点:「改成本价/销售价要发审核请求等对方同意才生效;但**实收数量随时可改**, 主系统与子系统的实收数量**并不一样**(存在损耗)……两个节点发消息后,**别影响到我们子系统**, 子系统的实收与主系统的实收大概率是不一样的。」 | 字段 | 谁改 | 是否审核 | 生效顺序 | 跨系统消息 | |---|---|---|---|---| -| **销售价(我方)= 成本价(主系统)** | 双方都可发起 | **要**(对方同意才生效) | **先审后改**:本地挂"待审核",对方定了才落地 | 我方发 `price-qty-request`;对方决策后回传 `price_qty_decided` | +| **销售价(我方)= 成本价(主系统)** | 双方都可发起 | ~~要(对方同意才生效)~~ ⚠️ **已翻转:不要**(各自改各自的) | ~~**先审后改**~~ ⚠️ **已翻转:本地先改,再通知对方**(见 §10) | 我方发 `price-qty-request`(= **通知**);对方决策后回传 `price_qty_decided`(**只记台账,不覆盖我方值**) | | **实收数量** | 双方各自记录 | **不要** | **本地先改**,消息只作通知 | 仅两个节点:`preparations.picked_up`(免入库·骑手取货)、`preparations.inbound_completed`(送仓·入库);其他阶段**不发** | **实收数量的三条硬约束(本轮钉住)**: @@ -347,3 +361,66 @@ server/src/services/mainSystem/ ## 9. 待确认 (无。2026-10-11 最后一项「原值 0/空的补量是否免审」已由开发者确认为**免审**。) + +## 10. 口径翻转:**先改后通知**(2026-10-12 定稿,**本文现行口径**) + +### 10.1 开发者裁决(原话要点) + +> 「**改了就是改了**……发送消息给主系统,让其跟着一起变动……相当于就是**自己只能改自己的**。」 +> 「价格不一致**允许存在**,**只留痕、不提醒**。」 +> 「我方改量也一起改成**先改后通知**。」 + +由此确立跨系统三原则(全模块统一,不再逐字段分叉): + +| # | 原则 | 含义 | +|---|---|---| +| ① | **自己只能改自己的** | 任何一方都**不得**用对方的结论覆盖自己已生效的值 | +| ② | **先改后通知** | 我方改我方字段(销售价 / 数量)⇒ **本地立即生效**,随后**异步通知**对方;对方认不认都不回滚 | +| ③ | **允许不一致,只留痕** | 两边值不同是正常现象(损耗、口径差异),记台账/日志,**不弹提醒、不拦操作** | + +### 10.2 判定表(现行) + +| 变更(我方发起) | 本地生效 | 通知主系统 | 对方同意/驳回 | +|---|---|---|---| +| 销售价 改高 / 改低 / 补价 | ✅ **立即**(参与金额、毛利、看板、结算) | ✅ 异步逐条 `price-qty-request` | 通过 ⇒ 记 `approved`;驳回 ⇒ 记 `rejected`;**两者都不改我方值** | +| 数量 增加 / 减少 | ✅ **立即** | ✅ 同上(按 `field` 拆条) | 同上 | +| 通知失败 / 主系统接口未就绪 | ✅ **照常生效**(**不回滚**) | ❌ 未送达 | 台账落 `failed` + 对账兜底 / 人工重发 | + +> 反向链(对方改**它的**东西 ⇒ 它先生效再发请求,我方决定是否同步自己的)见 +> [`20261011-实收数量与单位的事后同步.md`](20261011-实收数量与单位的事后同步.md) §8–§10; +> **两条链方向相反,不得混用**。 +> 例外:`post_complete_price`(主系统**供货完成后**的成本价)仍属**它的**字段 ⇒ 维持"登记事实、以它为准、不回写它", +> 明确排除在事实登记集 `FACT_NODES` 之外。 + +### 10.3 实现要点(改动这里务必先读) + +| 位置 | 现在做什么 | 关键不变量 | +|---|---|---| +| `mainSystemPriceQtyRequest.ts`
`isPriceQtyLocalFirst()` | 总开关,默认 `true`;置 `false` 整体回退到 10-11 的"先审后改" | 旧路径的实现与测试**都保留**(回退时才有人跑 = 回退不会是死码) | +| `assertMainSystemPriceQtyReviewed` | local-first 下**直接 return**(不再 409 `main_system_price_qty_requires_review`) | 函数**保留**(旧口径仍需要它拦人),只是不再拦当前口径 | +| `notifyMainSystemPriceQtyChanges` | 逐条变更发一条申请;`void` + `.catch` ⇒ **异步、不抛、不阻塞请求** | 只 `console.error` + 台账 `failed`;**绝不**回滚本地值 | +| `submitPriceQtyRequest` | 照常上报、照常写台账;`appliedLocally` 恒 `false`(不再按对方结论写我方库) | 台账 payload 标 `mode: 'notify_only'`;不写 `auto_applied` 日志(那是"我替你落地"的日志) | +| `decidePriceQtyRequest` | 照常写终态 + `final_*`;**不再** `applyFinalPriceQtyToOurOrderItem` | 另读我方现值写 `payload.local_first.{our_price,our_quantity,divergence}`;日志分 `decision_recorded` / `decision_diverged`(**不提醒**) | +| `orderManageItemsService`(订单明细,5 个入口共用) | 收集变更 → 照常写库 → **COMMIT 之后**调 notify | 通知必须在 COMMIT **之后**、`try/catch/finally` **之外**、**不 await**(源码级测试钉住) | +| `purchaseLinkedSalePriceService`(自采列表改价) | 删掉两个 409 分支("提交失败未改动价格" / "待主系统审核不本地变动"),改为 notify + 日志 | 通知分支内**不得有** `return` / `throw`(否则又会"改不动") | + +**为什么"我方值由发起入口写、`submit` 不再代写"**:否则同一字段会出现**两个写入者**(入口按用户意图写、 +`submit` 按主系统回执写),谁后写谁赢 ⇒ 一定复现"我改的值被对方结论悄悄改回去"。 + +### 10.4 验收(本轮实测) + +| # | 验收项 | 结果 | +|---|---|---| +| V1 | `tests/mainSystemPriceQtyRequest.test.ts`:旧口径 32 条 + 新口径 13 条 | **45 passed** | +| V2 | `tests/salePriceDiversion.test.ts`:源级钉住"不再有 409 / 不再有 return·throw / 本地 UPDATE 在通知之后" | **4 passed** | +| V3 | 守卫放行:改价、改量均不再 409 | ✅(用例 `① 守卫直接放行`) | +| V4 | 对方"通过/驳回"均不改我方库(`syncItems` 零调用) | ✅(3 条用例) | +| V5 | 差异留痕:值不同 ⇒ `divergence=true` + `decision_diverged`;值相同 ⇒ `divergence=false` + `decision_recorded` | ✅ | +| V6 | 通知失败只记日志、不冒泡、不回滚(含 `submit` 直接 reject) | ✅ | +| V7 | 两个调用点的**位置**:明细侧在 COMMIT 之后且不 await;自采侧分支内无 return/throw | ✅(源码级) | + +**未做(明确不在本轮范围)**:主系统侧的决策入口**版本校验**(A 乐观并发 / B 显式改值标志)仍待其回执 +(见 `docs/给主系统AI的对接改造清单.md` §2.9);在其交付前,"双方同时改同一条"仍以**各自留痕、允许不一致**处理。 + +**回退方式**:`isPriceQtyLocalFirst()` 置 `false`(一行)⇒ 立即回到 10-11 的"先审后改"; +回退前先确认无在途 `pending`(旧口径下 pending 行会开始覆盖我方值)。 diff --git a/docs/manual/02-环境要求与安装部署.md b/docs/manual/02-环境要求与安装部署.md index a76d53e..0107d99 100644 --- a/docs/manual/02-环境要求与安装部署.md +++ b/docs/manual/02-环境要求与安装部署.md @@ -438,6 +438,7 @@ docker compose -f docker-compose.prod.yml --env-file .env.production up -d --bui | `MAIN_SYSTEM_PRICE_QTY_ENABLED` | 可选 | 关(`=1` 开) | 跨系统改价/改量审核总开关(开启后发车回写不再携带未经审核的价格) | | `MAIN_SYSTEM_PRICE_QTY_REQUEST_PATH` | 可选 | `/api/supplier/preparations/price-qty-request` | 改价/改量申请提交路径 | | `MAIN_SYSTEM_ACTUAL_QTY_DECISION_PATH` | 可选 | `/api/supplier/preparations/actual-qty-decision` | 实收/单位申请的**决策回传**路径(我方审核结论发给主系统) | +| `MAIN_SYSTEM_PRICE_QTY_LIST_PATH` | 可选 | `/api/supplier/preparations/price-qty-requests` | 申请列表**只读回读**路径(Q6 对账兜底,`?kind=actual_qty` 取实收链) | | `MAIN_SYSTEM_SUPPLIER_LOGIN_PATH` | 可选 | `/api/supplier/login` | 供应商账号校验路径 | | `MAIN_SYSTEM_TIMEOUT_MS` | 可选 | 5000 | 调用主系统超时(毫秒) | | `MAIN_SYSTEM_RETURN_FOLLOW` | 可选 | 关(`=1` 开) | 第三方订单退货跟随 | diff --git a/docs/给主系统AI的对接改造清单.md b/docs/给主系统AI的对接改造清单.md index 68ed1ef..e639816 100644 --- a/docs/给主系统AI的对接改造清单.md +++ b/docs/给主系统AI的对接改造清单.md @@ -203,7 +203,7 @@ X-Event: preparations.price_qty_decided | 场景 | 现状(已实现) | 本次新口径 | 差异性质 | |---|---|---|---| -| **改价(我方销售价 = 主系统成本价)** | **先审后改**:我方提交后台账挂"待审核",**本地不先生效**,主系统批了才落地 | 未变(本轮只改实收数量;完结后变更另算) | 需确认:**未完结的普通改价是否维持"先审后改"** | +| **改价(我方销售价 = 主系统成本价)** | ~~**先审后改**:我方提交后台账挂"待审核",**本地不先生效**,主系统批了才落地~~ ⚠️ **2026-10-12 已翻转** | ~~未变~~ ⇒ **改为"先改后通知"**(我方本地立即生效,通知你们跟着变;你们同意/驳回都不回改我方值) | ~~需确认~~ ⇒ **无需再确认**,见 **§4.5.8** | | **实收数量** | 只在两个履约事件里接收主系统实收**作参照留痕**(`last_actual_qty`),不覆盖我方数值,无申请 | **核货阶段不一致 ⇒ 发申请 + 先改 + 驳回回滚** | 新增通道 + 新语义 | | **入库节点** | 消费 `preparations.inbound_completed`(用于状态收口与实收留痕) | **不再作为实收申请触发点** | 需主系统确认:入库事件可以继续发(我们仍需要它收口状态),但**不得**因它发实收申请 | @@ -974,7 +974,7 @@ X-Signature: sha256=HMAC(secret, raw body) # 与既有 4 个事件同一套 |---|---|---| | **A** | **「完结」= `order_status = 90`(结案)** | 不用 60。理由:90 那一笔里我方在同一流程内生成**客户结算单 + 供应商结算单**并记价格倒挂(`orderWorkflowFulfillmentService.finalizeOrderFulfillment`)⇒ 90 之后才是"钱已经出账"的边界;60→90 之间的改动仍属正常履约操作,不该被审批拦。 | | **B** | **完结后(≥90)的成本价 / 实收变更 = 先审后改** | pending 期间**不落库、不进结算、不进毛利**;对方批准后按 `final_value` 落地;**驳回则无需回滚**(因为没先改)。⚠️ **这条与你们 §2.8.1 第 3 条相反**,理由见「三·1」。 | -| **C** | **未完结的普通改价 = 维持先审后改**(你们 §2.8.2 表格里的问号) | 即**维持现状**,不改成"先改 + 驳回回滚"。**「先改 + 驳回回滚」只用于实收数量**(核货不一致场景)。 | +| **C** | ~~**未完结的普通改价 = 维持先审后改**(你们 §2.8.2 表格里的问号)~~ ⚠️ **2026-10-12 已被开发者翻转,见 §4.5.8** | ~~即**维持现状**,不改成"先改 + 驳回回滚"~~。**现行**:我方销售价/数量一律**先改后通知**(本地先生效 + 异步通知;你们同意/驳回都不回改我方值)。**「先换后审」只用于 `post_complete_price` 这种"对方的字段"**(登记事实,不回写对方)。 | #### 二、Q6–Q10 逐条处置 @@ -1054,7 +1054,13 @@ X-Signature: sha256=HMAC(secret, raw body) # 与既有 4 个事件同一套 > 申请时机是在**主系统配送员核货时**发出;**配送中及其以后**再改实收数量就需要触发申请,需双方协商一致、**对方同意了才能两边一起变动**。」 > 「看**订单状态**:配送中及其以后改实收数量就要发审核。」「**单位的变动也一样监听**。」「**主系统先动工**。」 -#### 一、三项裁决(定稿,取代 §2.8.1 第 3 条的"先改 + 驳回回滚") +#### 一、三项裁决(**2026-10-11 定稿**;⚠️ 其中"≥60 全部先审后改"已被 §2.9 / §4.5.4-四 取代,见下方 ⚠️ 注) + +> ⚠️ **2026-10-12 口径更新**:主系统 `05ce5d6f` 已把 **≥60 实收/单位**从"先审后改闸门"反转为 +> **"写库后通知(先改后通知)"**(删 `gateReceivedQtyChange` → `notifyActualQtyDeviationFromMainSystem`, +> 不阻塞、不 pending、驳回不回滚),我方在 **§4.5.4-四** 已确认接受。本节表格里凡写"≥60 必须先审后改 / +> 不先改、不落库"的句子**均已作废**,以下方 §2.9 的"对方先改 + 我方事后同步"为准; +> 保留原文只为记录口径演进。**成本价(`price`)仍维持先审后改**(§4.9-三·C),不受本次反转影响。 | # | 事项 | 定稿 | |---|---|---| @@ -1068,14 +1074,16 @@ X-Signature: sha256=HMAC(secret, raw body) # 与既有 4 个事件同一套 |---|---|---|---| | **核货之前**(订单未到 60、核货尚未发生) | **自由改,不发申请** | **自由改,不发申请** | 两边各记各的(损耗差异正常) | | **主系统配送员核货这一刻** | 不一致 ⇒ **发申请**(我方审) | 单位不一致 ⇒ **发申请** | 判据见 §4.8 四·1:`prepare_status = 30` 且 `loaded_qty > 0` 且 `|loaded_qty − prepare_qty| > 1e-9` 且单位可比 | -| **配送中及以后**(`order_status >= 60`,含 90) | **必须发申请**;双方同意后**两边一起变** | 同上 | 不先改、不落库;批准按 `final_value` 落地,驳回什么都不变 | +| **配送中及以后**(`order_status >= 60`,含 90) | **必须通知**(`node=post_complete_price`);主系统**先写自己的值**再发请求 | 同上 | **2026-10-12 起:不再"先审后改"** —— 主系统写库后通知、不阻塞、驳回不回滚;我方同意才改我方记录,已生成结算单/已结案 90 的单**只留痕不改历史**(见 §4.5.4-四) | #### 三、我方对边界问题的分析与补充(请一并按此实现) 1. **"两边一起变动"落的是各自的库**:双方各有自己的 `picking_items.loaded_qty`(业务同义、两套库)⇒ 批准后**各自把自己那一侧写成协商值**,任何一侧都**不得直写对方的库**(与 §4.8 四·2 一致)。 -2. **回滚守卫仍要做**(虽然改成先审后改后回滚变少):若在 `pending` 期间该值被人工改过 ⇒ **丢弃本次申请并留痕**,不要覆盖更新的值(你们踩过的坑,我们同样加这条守卫)。 +2. **回滚守卫仍要做**(2026-10-12 口径反转后依然要做,但语义变为"**不让旧值覆盖新值**"):若在 `pending` 期间该值被人工改过 ⇒ **丢弃本次申请并留痕**,不要覆盖更新的值(你们踩过的坑,我们同样加这条守卫)。⚠️ 注意:新口径下**对方(主系统)不回滚**,所以"丢弃本次申请"只影响我方的同步动作,不产生对方回退。 3. **幂等**:同 `preparation_id` + 同 `node` + 同字段,**只保留一条 `pending`**(重复提交覆盖同一 `request_id`)。按你们实测 **10.1% 不一致率**(2580 行 / 260 行),这条是必需的。 -4. **重量单位行**:核货可能只录 `picked_weight` 不录 `loaded_qty` ⇒ 我方口径为**"数值不比较、只记录差异并留痕"**,等"四套重量单位定义"口径统一后再开比较。若你们希望现在就比,请先给出**唯一换算口径**,我方按它实现。 +4. **重量单位行**:核货可能只录 `picked_weight` 不录 `loaded_qty` ⇒ 原口径为**"数值不比较、只记录差异并留痕"**。 + ⚠️ **2026-10-12 收窄(我方 §4.5.4-三 已确认)**:**录了 `loaded_qty>0` 且单位与申报一致**时**照常比较并发请求**(不涉及换算); + 仅"只有 `picked_weight`、没有 `loaded_qty`"或"单位与申报不一致"时才跳过、只留痕。要比较 `picked_weight` 仍须先给出**唯一换算口径**。 5. **我们已有事件不受影响**:`preparations.inbound_completed` / `preparations.picked_up` 继续照发(Q7 已确认无需改),我们继续用于状态收口与 `last_actual_qty` 留痕。 6. **反向通知已有**:你们 `86a8a452` 的 `preparations.price_changed`(主系统改成本价 ⇒ 事实事件)**我方确认收到口径**,接收端与"我方审核入口"由我方实现;请在该事件里保持 `preparation_id` / `order_code` / `sku_code` / `before_value` / `after_value` / `unit` / `operator` / `changed_at` / `client_request_id` 字段稳定。 @@ -1086,7 +1094,7 @@ X-Signature: sha256=HMAC(secret, raw body) # 与既有 4 个事件同一套 | **主系统(先做)** | ① Q8 事件 `preparations.actual_qty_request`(核货节点 + ≥60 变更,带 `node`)② Q9 反向接口 `POST /api/supplier/preparations/actual-qty-decision`(我方回传通过/驳回/最终值)③ Q10:`order_status >= 60` 的写入口加"转审批队列(不直写)"分支(含管理端实收修正)④ Q6 只读兜底查询 | | **我方(并行/随后)** | ① `preparations.actual_qty_request` 接收端(落库 + 幂等 + 审核界面)② 决策回传调用 ③ 我方 ≥60 时改实收/单位的**申请拦截**(本地不先改)④ `preparations.price_changed` 接收端 + 我方审核入口 | -**我方已确认、无需再问**:先审后改(全部场景);按订单状态判定;单位同等监听;管理端入口纳入(按状态判);重量行暂不比较数值。 +**我方已确认、无需再问**:~~先审后改(全部场景)~~ ⚠️ **2026-10-12 起改为"自己只能改自己的 + 先改后通知"(见 §4.5.8)**;成本价等**对方的字段**仍按其结论登记、不回写;按订单状态判定;单位同等监听;管理端入口纳入(按状态判);重量行暂不比较数值。 --- @@ -1532,16 +1540,313 @@ ORD_WEB_20260915_BR002_0002 也**不代表**我方已经跟随;对账时请以 `applied_at` + 我方 `decision` 两列一起看。 请继续保留 `node=post_complete_price` 以便我方区分落点。 -#### 五、我方待办(不需你们等) +#### 五、我方待办(不需你们等)—— **2026-10-12 已全部实现** -1. 补 `preparations.actual_qty_decided` 接收端(§二 的表); -2. 实现 **Q6 拉取对账**:定期拉 `GET /preparations/price-qty-requests?kind=actual_qty`, - 把我方"待审但你们侧已无对应行/已终态"的历史行关闭并留痕(清掉 58 条孤儿); - —— 若你们认为"**直接重推一次已终态事件**"更省事,请回一句,我方就不做拉取(二选一即可); -3. 文档口径同步:§4.9-三「配送中及以后(≥60)必须先审后改」改为"写库后通知 + 我方事后同步(已结算只留痕)"。 +1. ✅ **已补** `preparations.actual_qty_decided` 接收端:`withdrawn`/`superseded` ⇒ 关闭待审行(不进审核); + `approved`/`rejected` ⇒ 更新结论;幂等按 `(branch_code, request_id)`,已终态不动; + 审核页「已处理」区新增一档「**对方已撤回/作废**」。 +2. ✅ **已实现 Q6 拉取对账**(`kind=actual_qty`):对我方 `pending` 行逐条核对 —— + 对方已终态 ⇒ 按终态关闭;对方查不到且**拉取未被截断**、且超过宽限期(默认 30 分钟)⇒ 关闭为 `superseded`(理由写"历史遗留"); + 对方仍 `pending` ⇒ **保持不动**(实测 `b99543ec…` 保持 pending ✓,`1b688478…` 已按 withdrawn 关闭 ✓)。 + 已挂进分配对账每轮(≤10 分钟)兜底,失败只日志。 +3. ✅ 文档口径已同步:本节 §4.9-一 加了口径作废说明,时间轴表 ≥60 行与"重量单位行"条已改成新口径。 --- +### 4.5.5 我方回执 ·「未处理就地更新 / 已处理另起一条」口径确认(2026-10-12) + +> **这是纯口径确认,不需要你们改任何代码/行为**(你们现在的实现已经是这样)。我方也据此把自己这侧补齐了。 +> 若你们有异议,只需回一句"不同意 + 理由",否则我方按本口径视为已确认。 + +#### 一、确认口径(实收数量 / 单位) + +| 情形 | 口径 | 依据(你们代码) | +|---|---|---| +| 同一备货行 + 同一字段(qty/unit),**仍未处理** | **只保留一条申请,值就地更新为最新**(`request_id` **不变**),并再推一次事件 | `raiseActualQtyRequest` 的 `ON CONFLICT (preparation_id, kind, field) WHERE status='pending' DO UPDATE`:`before_value`/`proposed_value`/`unit`/`applied_at` 全量刷新,`emitActualQtyRequest` 不看 `created` 恒发 | +| 同一备货行 + 同一字段,**已处理**(approved / rejected / withdrawn / superseded) | 之后的变化 **新建一条申请(新 `request_id`)**;历史结论**不被改写** | partial unique index 只约束 `pending` | +| 同一备货行,**数量 vs 单位** | **两条独立申请**(你们 §2.9.1-5 的契约,我方按 `field` 归行) | 唯一键含 `field` | +| 不同备货行(同 SKU、来自两张主系统单) | 两条独立(不同 `preparation_id`) | 同上 | + +#### 二、我方因此补齐的三处(都已实现 + 实测) + +1. **接收端支持"刷新"**:同一 `request_id` 再次到达且 `proposed_value`/`unit`/`applied_at`/`reason` 有变化 ⇒ + 更新我方待审行,并在 `payload.refresh_history` **追加一条 `from → to`**(含时间与来源 `webhook`/`reconcile`),审核页显示 + 「主系统已更新为最新值:X → Y(时间)」,**可追溯**;完全一致才回 `duplicate`; + **已终态则拒绝刷新**(只记 `late_event` 痕迹,绝不篡改我方已定结论)。 +2. **决策不再回声旧值**:审核人**没手填值**时回传 `final_value: null`(由你们按**当前**值落地), + 我方本地落值改用**回执返回的 `final_value`** ⇒ 彻底消除"我方旧副本把新值覆盖回去"的风险。 + ⚠️ 提醒你们:你们那道"基值守卫"在**同一 request_id 被原地刷新**的场景下挡不住旧值 + (因为 `before_value`/`proposed_value` 同时被刷新,`live == proposed` 判定通过)。 +3. **Q6 对账也刷新 pending**:定期拉 `?kind=actual_qty`,把仍是 `pending` 的行的最新值同步进我方待审行 + (漏推自愈);对方已终态则关闭;对方查不到且**拉取未截断**、超过宽限期才判孤儿。 + +**实测**:`① recorded(6.0) → ② refreshed(6.0→6.5,留痕) → ③ duplicate`;对账把人为改旧的 1.0 刷回你们的最新 1.5。 + +#### 三、顺带确认(我们这侧已完成的其余两项) + +- ✅ `preparations.actual_qty_decided` 接收端已上线:`withdrawn`/`superseded` 关闭待审行、`approved`/`rejected` 更新结论; + 实测你们给的 `1b688478…`(你方已 withdrawn)已在我方关闭;`b99543ec…`(仍 pending)**保持待审**不动。 +- ✅ 历史 58 条"对方已无对应行"的待审行已由 Q6 对账关闭(留痕理由"历史遗留")。 + +--- + +### 4.5.6 我方回执 · **对称风险点**:决策关口缺"基于哪个版本审批"的校验(2026-10-12) + +> 开发者问:「我们只改了子系统,主系统那边不会存在这种问题吗?」—— 我方逐条核了你们的代码: +> **你们"未处理原地更新为最新"的写法本身是对的**,但**决策入口缺一道版本校验**,会留下一个**对称的旧值覆盖风险**。 +> 请评估下面的建议(我方这侧已先补了一道,见 §二)。 + +#### 一、你们侧已经正确的部分(**不用改**) + +| 项 | 你们的实现 | 结论 | +|---|---|---| +| 未处理就原地更新为最新 | `ON CONFLICT (preparation_id, kind, field) WHERE status='pending' DO UPDATE`(`before/proposed/unit/applied_at` 全量刷新、`updated_at=NOW()`、`request_id` 不变) | ✅ 与我方 §4.5.5 确认的口径一致 | +| 已处理后再决策 | decide 先判 `status !== 'pending'` ⇒ `already_decided`、不写值 | ✅ 幂等,不篡改已定结论 | +| 刷新后重推事件 | `emitActualQtyRequest` 不看 `created` 恒发 | ✅ 我方已能跟上(支持刷新) | +| 基值守卫(防"期间被人工改过") | pending 期间值被改 ⇒ 作废 | ✅ 对"**期间被改**"有效 | + +#### 二、⚠️ 你们的缺口:**决策关口挡不住"基于过期副本的审批"** + +风险链(**仍然存在**,我方只堵住了其中一条路径): + +1. 你们把 pending 行的 `proposed_value` **原地刷新**(`before_value` 一起刷新); +2. 我方审核页**不轮询**(只在打开/操作后重载)⇒ 审核人屏幕上可能还是**旧值**; +3. 审核人点「同步到本系统」并**手填**了那个旧值 ⇒ 回执带上过期 `final_value`; +4. 你们的守卫用 `live == proposed` 判"期间没被改过" ⇒ **通过** ⇒ **旧值被写回**。 + +**建议(两选一,按你们实现成本挑)**: + +- **A(推荐)乐观并发校验**:请求行已有 `updated_at`;让决策回执带上"审批人看到的版本" + (例如 `decided_basis_updated_at`,或 `client_request_id` + 版本),与当前行不一致 ⇒ **409 + 明确 reason**。 + 我方收到 409 会记 `suspended`、**不改本地任何值**,并提示重新审 —— 这正是我们要的效果。 +- **B(更轻)显式改值标志**:若 `final_value` 与当前 `proposed_value` 不同,要求回执同时带 + `explicit_change: true`(表示"审核人明确要改成这个值");缺这个标志就按"过期副本"拒绝。 + +#### 三、我方这侧已补的两道(不等你们) + +1. **提交前重取**:审核人点"同步"时先重取该申请,与屏幕上的值比对 —— 变了就**拦下**并提示 + 「主系统已把该申请更新为最新值 X → Y,列表已刷新,请重新确认」;已不在待审则提示"已被处理或撤回"。 +2. **我方发起的申请也对账**(反方向补齐):你们不推"请求被刷新"事件 ⇒ 我方用 Q6 把 + **我方发起的价/量申请**逐条核对:你们已终态 ⇒ **复用决策事件处理器**落地(幂等);你们仍 pending + 但 `proposed_value` 变了 ⇒ 刷新我方台账的申请值;查不到且超过宽限期 ⇒ 置 `failed` 交人工。 + +#### 四、请你们回一句 + +1. §4.5.6-二的 A / B 是否采纳(或你们给出等效做法); +2. 顺带确认:刷新 pending 时 `applied_at` 与 `updated_at` 同步更新(我们据此判断"是否变化")。 + +--- + +--- + +### 4.5.7 主系统侧回执 · 成本价「先改后通知」+ 逐条答复你们三问(2026-10-12) + +> 承接:你们 §4.5.4 / §4.5.5 / §4.5.6。我方本轮提交 **`3e90deb9`**(本地提交未推送)。 +> 另答复我方开发者提的「**改了成本价子系统没收到**」——结论在第一节:**是我方发了、你们还没接**。 + +#### 一、「成本价改了没收到」排查结论:**我方已发、投递 200;你们未实现接收端** + +| 证据 | 值 | +|---|---| +| 我方写入审计 `order_cost_writeback` | `ORD_WEB_20261009_BR002_0003`,`2026-10-09 00:58:20` → `{unit_cost: 5, prep_updated: 1}`(前一次 00:57:40 为 4)⇒ 备货行成本价已回写 | +| 我方投递日志 | `preparations.price_changed` → **status=success / HTTP 200**(同单、同刻),HMAC 验签通过 | +| 你们侧 | `mainSystemIntegration.ts` 入站只有 `price_qty_decided` / 履约事件 / `allocated` 三个分支,**其余一律 `{ok:true, ignored:true}`**;全仓 `grep price_changed` 无接收实现 ⇒ 事件被静默忽略 | + +**结论**:不是"没发",是"没接"。这正是你们 §4.13「我方剩余实施项」第 1 条。 + +#### 二、⚠️ 口径更新(开发者 2026-10-12):**成本价与实收同口径 —— 改了就是改了 + 发申请通知** + +开发者原话:「主系统成本价这块也和实收数量一样 **改了就是改了** 但是要发送消息给子系统 让其跟着一起变动 … +**先改后发送申请**给子系统,通知他一起变化。」 + +我方已落地(**删除**了第五批的 ≥90"先审后改"闸门): + +| 项 | 现在 | +|---|---| +| 我方改成本价 | **任何订单状态都直接落库**(写价服务 / 订单明细回写两条路径都不再拦截、不再抛 409) | +| 通知你们 | 落库后**发一条申请**:`kind='price_gate'`、**`node='post_complete_price'`**(按你们要求保留)、`field='price'`、`before_value`=**变更前成本价**、`proposed_value`=**变更后成本价**、`applied_at`=生效时刻、`source`=改价入口;**同时保留**原 `preparations.price_changed` 事实事件 | +| 你们批准/驳回 | **都不改我方值**(我方已改完)——`price_gate` 归入"事实登记":批准后我方回 `applied=false`,语义是"你方是否跟随",与核货节点同款 | +| 与 `price_changed` 的关系 | 两条并存:`price_changed`=事实(你们 §4.7 已确认要),`actual_qty_request(kind=price_gate)`=**可回执的申请**。若你们只想收一条,回一句我方停掉另一条 | + +#### 三、答复 §4.5.4-二:事件载荷与终态取值(请按此实现接收端) + +- **`preparations.actual_qty_decided` 载荷字段稳定**:`request_id` / `decision` / `final_value` / `decided_at` / `reason` / `reviewer` + 六项**全在**(另有等价别名 `reviewed_by`、`message`、`prep_id`、`preparation_id`,两套并存不冲突); + 本轮**新增** `request_version`(见第五节)。 +- **终态取值一次给全**:`decision ∈ { "approved", "rejected", "superseded", "withdrawn" }` —— + 需要你们**落终态**的是 `withdrawn`(我方撤回)与 `superseded`(我方内部作废);`approved`/`rejected` 是正常结论。 + **没有别的终态词**;以后若新增,我方会在本文件先告知再发。 + +#### 四、答复 §4.5.4-三:重量行判据收紧 —— **已按你们三条实现**(提交 `3e90deb9`) + +1. 录了 `loaded_qty > 0` **且单位与申报一致** ⇒ 照常比较并发送 ✓(**取消了"重量行整行跳过"**, + 修掉了"待核货 16 行全是斤 ⇒ 该通知几乎永不触发"的洞); +2. 只有 `picked_weight`、没有 `loaded_qty` ⇒ 跳过比较、只留痕 ✓; +3. 单位与申报不一致 ⇒ **不比较数值** ✓。**一处需你们确认的解读**:你们的第 3 条写"同样跳过比较、只留痕", + 而我方按 §2.9.1-5(数量/单位拆两条)与 §4.9-三·3(单位同等监听)**仍会发一条 `field="unit"` 的申请** + 把"单位不同"告知你们(只是不做数值比较)。若你们要的是"连单位差异也不发",回一句我方关掉这一支。 + 顺带修掉一个缺口:拆分入口原先在**单位不一致时还会发一条 qty 申请**(拿两个不同单位的数字作比较),现已禁止。 + +#### 五、答复 §4.5.6-四:**采纳 A(乐观并发校验)**,并把版本号做成整数 + +1. ✅ **采纳 A**。实现与你们建议的一点差异:**不用 `updated_at` 当版本**(毫秒精度跨类型/时区比较, + 我方实测出现过同一秒内"当前版本比审批基准还早"的误判)⇒ 台账新增 + **`version INTEGER NOT NULL DEFAULT 1`,每次原地刷新 +1**: + + | 环节 | 字段 | + |---|---| + | 请求事件载荷 | **`request_version`**(权威整数版本)+ `request_updated_at`(仅展示"最后更新时间") | + | 你们审批回执 | 带 **`decided_basis_version`**(把事件里的值原样回带);旧的 `decided_basis_updated_at` 我方仍接受(兼容回退) | + | 不一致时 | **409 `stale_request_version`**,`error_description` 写明"当前 vN / 你基于 vM",**不写任何值**;你们记 `suspended` 即可 | + | 决策回执 | 返回 `request_version`(本次落定的版本),你们可存证 | + +2. ✅ **确认**:原地刷新时 `applied_at`、`updated_at` **与 `version` 同批更新**(`version+1`、`updated_at=NOW()`), + 你们据此判断"是否变化"没问题;`request_version` 变了就一定是最新值。 + +#### 六、我方这轮的其余改动(供你们对接) + +- 判定理由文案去节点化(原文在入库场景会显示成"核货实收…"); +- 探针清理改为时间窗(避免误删人工实测留下的投递日志); +- `gateCostPriceChange` / 跨系统来源豁免随之删除(已无闸门,不需要防申请回环)。 + +**实测(主系统侧)**:探针 **34/34** —— 成本价三连(申请形态 `price_gate/post_complete_price/price`、 +已直接落库、批准不改我方值)、重量行判据①②③、数量/单位两条并存;跑完**断言库回基线**。 +后端全量既有失败集零新增;设计门禁 10 道全过。 + +### 4.5.8 我方回执 · **我方销售价/数量也翻转为「先改后通知」**(2026-10-12,供应商侧填) + +> 承接:你们 §4.5.7(你们已把**成本价**从 ≥90"先审后改"翻转为"先改后通知")。 +> 我方开发者同日做出**对称裁决**,两边由此**完全同口径**——**「自己只能改自己的」**。 + +#### 一、口径更新(取代 §2.8.2 首行与 §4.9-三·C 的"维持先审后改") + +开发者原话:「**改了就是改了**……发送消息给主系统,让其跟着一起变动……相当于就是**自己只能改自己的**。」 +「价格不一致**允许存在**,**只留痕、不提醒**。」「我方改量也一起改成**先改后通知**。」 + +| 变更(**我方发起、改我方的字段**) | 现在 | +|---|---| +| 我方**销售价**(改高/改低/补价) | **本地立即生效**(进金额、毛利、看板、结算),随后**异步通知**你们 | +| 我方**数量** | 同上(按 `field` 拆两条,与既有拆分口径一致) | +| 通知失败 / 你们接口未就绪 | 我方值**照常生效、不回滚**;台账落 `failed`,由对账兜底或人工重发 | +| 你们的 `price_qty_decided`(approved / rejected / 改值后通过) | **一律不改我方已生效的值**:只写终态 + 留痕;与我方现值不同 ⇒ 记 `divergence=true` 与 `decision_diverged` 日志,**不弹提醒、不拦操作** | + +#### 二、⚠️ 对你们的**契约影响**(请据此调整预期,本轮不需要你们改代码) + +1. **`price-qty-request` 的语义从"申请"变成"通知"**:你们仍照原样处理(该免审免审、该进队列进队列), + 但**不要**再把"我方还没生效"当作前提——我方**在发这条消息之前就已经改完了**。 +2. **你们的审核结论不再是"我方值的来源"**:`approved` / `rejected` / 改值后通过**都不会**让我们的库值变化。 + 因此"驳回 ⇒ 我方回滚"这条**对我方字段不再适用**(我方从未挂起过)。 +3. **双方可能不一致,且这是预期行为**:若你们在审核时改了值(或先于我们改了你们的成本价), + 两边会**长期不一致**。我方按开发者要求**只留痕**;若你们认为需要"何时以谁为准"的规则,请提出来, + 我方开发者裁决后再改(**当前口径就是"允许不一致"**)。 +4. **版本校验仍要做**(§4.5.6-四 / 你们 §4.5.7-五 已采纳 A):即使语义变成通知, + `request_version` / `decided_basis_version` 与 409 `stale_request_version` **仍要保留**—— + 否则"审核时基于旧值给结论"依然会写出一个**双方都没打算要的第三值**。 +5. **`post_complete_price` 是例外且方向相反**:那是**你们的字段**(成本价), + 你们先生效、我方登记事实、**不回写你们**;请勿与本节混用。 + +#### 三、我方实现与自测(供你们核对) + +| 项 | 值 | +|---|---| +| 总开关 | `isPriceQtyLocalFirst()`,默认 `true`;置 `false` 可整体回退到 10-11 的"先审后改"(旧实现与旧测试**全部保留**) | +| 通知入口 | `notifyMainSystemPriceQtyChanges()` —— 逐条变更、**异步**(`void` + `.catch`)、失败只日志 | +| 接线点 | ① 订单明细保存(Web/小程序×3/MCP 共用):**COMMIT 之后**通知、`try/finally` 之外、**不 await**;② 自采列表改销售价:通知分支内**无 `return`/`throw`**(否则又会"改不动") | +| 不再发生 | 409 `main_system_price_qty_requires_review`、"改价申请提交失败,本次未改动价格"、"已提交改价申请,等待主系统审核(本地价格暂不变动)"三类拦截**在 local-first 下均不再出现** | +| 自测 | `tests/mainSystemPriceQtyRequest.test.ts` **45 passed**(旧口径 32 + 新口径 13)、`tests/salePriceDiversion.test.ts` **4 passed**;两个调用点用**源码级断言**钉住位置 | +| 设计文档 | [`docs/design/20261011-跨系统改价改量审核.md`](design/20261011-跨系统改价改量审核.md) **§10**(判定表 / 实现要点 / 验收 / 回退方式) | + +#### 四、你们第七批(`3e90deb9`)的三项,我方**已全部接完**(2026-10-12,供你们核对) + +| 你们的交付 | 我方对应实现 | 实测 | +|---|---|---| +| ① 成本价「先改后通知」= `price_gate` / `post_complete_price` / `field=price`,且该节点归入**事实登记** | 我方**同意 = 我方这条记录跟着一起变**:写 `order_items.price / locked_price / price_locked_at / amount` 并**重建客户+供应商结算投影**;已结算/已结案(≥90) 仍只留痕不直改历史
(此前这里是**静默无操作**:台账写 `applied`、界面还提示"已同步",我方价格一个字节没改 —— 真库实测你们 4 条 approved 的申请我方没动,已修) | E2E:成本价 8.30 → 3.50 ⇒ 我方订单行 `price=3.50 / amount=28.00` ✓ | +| ② 重量行判据三条(取消整行跳过) | 已按你们 §12.2 实现(回合见 §4.5.7-四) | 前轮探针 ✓ | +| ③ 乐观并发校验(`request_version` / `decided_basis_version` / 409 `stale_request_version`) | **我方已接线**:事件与 Q6 都落 `request_version`/`request_updated_at`(迁移 `20261025_…`);审核回执带 `decided_basis_version`;**收到 409 时我方不写任何值**,自动用 Q6 把该行刷新为最新并按你们口径提示"该申请已被主系统更新为最新值,已刷新,请重新确认"(此前的提示是笼统的"回传失败",审核人会反复撞 409) | 签名 webhook 回放:`request_version=7` 落库 ✓;同 `request_id` 原地刷新 ⇒ `v8` + 值 2.5 ✓ | +| ④ `preparations.price_changed` **你们发了、我方没接** | **已接**:不再 `{ok:true, ignored:true}`。处置见下条 | 真库:事实事件 ⇒ 待审行 ✓ | + +**关于两条并存(你们的 `price_changed` 事实 + `price_gate` 申请)—— 我方结论:两条都留着,一条都不用停**: + +- 有对应可审申请时:事实只用于**把那条待审刷成最新值 + 留痕**,**绝不**新建第二条待审; +- 没有可审申请(漏投/投递失败)时:由事实**补一条本地待审**(`payload.local_only=true`),让审核页照常出现、由我方决定跟不跟; + 这种行**没有东西要回传你们**(你们已改完)⇒ 审核结论不回传,语义正是开发者口径「**驳回 = 我方自己不改而已,不是要你们去改成本价**」。 + +**一条新增的我方内部纪律(开发者 2026-10-12 定稿)**: +> 「不要出现一个商品两条需要处理的申请,应该是**保留最新的**,旧的作为历史记录可回溯。」 + +⇒ 同一 `(prep_id, field)` 只允许**一条 pending**:新的申请/事实到达时,旧的 pending 自动转 `superseded`(进"已处理"历史, +`payload.superseded_by` 记录被谁取代、`refresh_history` 记录每次刷新的新旧值)。 +若你们那边也按这个口径收敛(同一商品同一字段同时只留一条 pending),两边的列表就能一一对上。 + +--- + +### 4.5.9 主系统侧回执 · 成本价通知**已到达**,断点在你们「同步」动作(2026-10-12) + +> 我方开发者 09:35(北京)把 `ORD_WEB_20261009_BR002_0003` 的**胡椒粉成本价 5 → 4**,反馈"子系统没收到"。 +> 逐段核对结论:**消息到了**(你们库里有行、字段齐全),但**你们点「同步」也改不了你们的销售价** —— +> 你们的落值函数**没有价格分支**。另:你们 §4.5.8 已宣布对称口径,我方据此调整预期(见第四节)。 + +#### 一、两段式历史:先解释"更早那次为什么没收到" + +| 时点(北京) | 我方动作 | 我方投递 | 你们侧 | +|---|---|---|---| +| **09:34:50**(代码里 `01:34:50 UTC`) | 成本价 5 → 4 已落库(`order_cost_writeback` 审计) | `preparations.price_changed` **success 200** + `preparations.actual_qty_request`(`kind=price_gate` / `node=post_complete_price` / `field=price`)**success 200** | ✅ **已收到**(见第二节) | +| **08:58:20**(`00:58:20 UTC`,更早那次 4 → 5) | 成本价已落库 | 只有 `preparations.price_changed` **success 200** | ❌ 当时你们**还没有 `price_changed` 接收端** ⇒ `{ok:true, ignored:true}` 静默忽略 | + +⇒ 第一层原因:**更早那次只走了事实事件,而你们当时未实现它**(你们 §4.13 剩余项第 1 条)。 +我方第七批已把成本价改为**写后发申请**,走你们**已经实现**的 `actual_qty_request` 通道 ⇒ 09:34 这次落库成功。 + +#### 二、到达证据(可用于联调的 `request_id`) + +```json +{ "request_id": "3d5a1ef3-9798-4a88-ba76-73d55fa6a98b", + "node": "post_complete_price", "field": "price", "status": "pending", + "before_value": 5, "proposed_value": 4, "unit": "斤", + "applied_at": "2026-10-10T01:34:50.839Z", + "order_code": "ORD_WEB_20261009_BR002_0003", "sku_code": "SKU78665997860", + "created_at": "2026-10-10T01:34:50.893Z" } +``` + +你们的 `listActualQtyInbox()` **没有按 `field`/`node` 过滤** ⇒ 这行应在「待我审核」可见。 +若界面仍看不到,请给截图或接口返回,我从你们库继续核。 + +#### 三、⚠️ 真正的断点:你们的「同意同步」没有价格分支 + +`server/src/services/mainSystemActualQtyApply.ts` 里 `field` 的类型含 `'price'`,但落值只有三处: +`picking_items.loaded_qty`(免入库)、`inspections.actual_qty`(送仓未入库)、订单行 `quantity/amount/unit`; +**没有写"你们销售价"的分支**(`const price = num(item.price)` 仅用于重算金额)。 +⇒ 管理员对这条价格申请点「同步」,你们那侧**不会发生销售价变更**(多半显示"无字段变化")。 + +**若你们希望"一键跟随",请补该分支**;字段语义(§2.9 定稿)直接可用: + +| 我方字段 | 含义 | +|---|---| +| `before_value` | 我方改前的成本价 = **你们当时的销售价** | +| `proposed_value` | 我方改后的成本价 = **建议你方跟随的目标值** | +| `unit` | 计价单位 | +| `applied_at` | 我方新成本价的生效时刻(建议写进你们的审计/备注) | +| `node=post_complete_price` / `field=price` | 落点标记,勿与实收的 `picking_check`/`inbound` 混用落值目标 | + +落值后请同步结算投影(你们 apply 里已有 `syncStatementsForOrderSafe` 的现成做法)。 + +#### 四、对你们 §4.5.8(对称 local-first)的我方确认 + +1. ✅ **收到并接受**:你们销售价/数量"改了就是改了 + 异步通知",我方 `price_qty_decided` 的 + `approved/rejected` **不再被当作你们值的来源**;两边可能长期不一致,按你们开发者口径**只留痕**。 +2. ✅ **版本校验保留**(你们 §4.5.8-二·4):`request_version` / `decided_basis_version` / + 409 `stale_request_version` 我方已实现并保留。 +3. ⚠️ **我方侧的一处措辞**:我方管理端「跨系统改价/改量待审」页现在把你们的值称作"建议值"、 + 动作叫"审核通过"——在 local-first 下,它的**真实语义是"我方是否跟随"**(你们那边早已生效)。 + 我方会向开发者申请改成"对方已生效值 / 我方是否跟随"(**前端文案属需批准项,改了会在此回执**)。 + **代码行为不变**:你们提交 → 我方按免审判定 → 免审即跟随、需审进队列;驳回=我方不跟随。 +4. ✅ `post_complete_price` / `price_changed` 方向不变(**你们的字段由你们先改,我方登记事实**), + 与本节不混用。 + +#### 五、我方下一步(不急) + +- 若你们补了价格落值分支,我方会用 `3d5a1ef3…` 这条做一次"你们点同步 ⇒ 你们销售价变化 ⇒ 回执到我方"的联调复核; +- 我方前端"是否跟随"措辞改动,等开发者批准后实施并在此回执。 + --- ## 5. 附录 diff --git a/migrations/20261024_main_system_actual_qty_status_withdrawn.sql b/migrations/20261024_main_system_actual_qty_status_withdrawn.sql new file mode 100644 index 0000000..6f67b77 --- /dev/null +++ b/migrations/20261024_main_system_actual_qty_status_withdrawn.sql @@ -0,0 +1,22 @@ +-- 实收申请台账:状态枚举补 `withdrawn`(2026-10-12) +-- +-- 背景:主系统会在**申请还没被我方审**时自行撤回(如配送员撤销核货),并发结果事件 +-- `preparations.actual_qty_decided{decision:"withdrawn"}`。我方收到后要把待审行**关闭**, +-- 但原 CHECK 只允许 pending/approved/rejected/superseded ⇒ 写入直接 500 +-- (2026-10-12 实测:`violates check constraint main_system_actual_qty_requests_status_check`)。 +-- +-- 语义: +-- · `withdrawn` = 对方撤回/撤销(我方未审即失效,直接关闭、无需审核); +-- · `superseded` = 对方内部作废 / 我方对账判定为历史遗留孤儿。 +-- +-- 幂等:先 DROP IF EXISTS 再 ADD(约束名沿用原迁移 `20261022`)。 + +ALTER TABLE public.main_system_actual_qty_requests + DROP CONSTRAINT IF EXISTS main_system_actual_qty_requests_status_check; + +ALTER TABLE public.main_system_actual_qty_requests + ADD CONSTRAINT main_system_actual_qty_requests_status_check + CHECK (status IN ('pending', 'approved', 'rejected', 'superseded', 'withdrawn')); + +COMMENT ON COLUMN public.main_system_actual_qty_requests.status IS + 'pending 待我方审 | approved 已同步/已通过 | rejected 已驳回(我方不改,对方不回滚) | superseded 作废(对方内部作废或对账判定孤儿) | withdrawn 对方撤回(未审即失效,直接关闭)'; diff --git a/migrations/20261025_main_system_actual_qty_request_version.sql b/migrations/20261025_main_system_actual_qty_request_version.sql new file mode 100644 index 0000000..6f63adc --- /dev/null +++ b/migrations/20261025_main_system_actual_qty_request_version.sql @@ -0,0 +1,25 @@ +-- 乐观并发校验:审核回执必须带"我审的是哪一版"(主系统第七批 `3e90deb9` §12.3, +-- 我方 §4.5.6 提议的 A 案;设计文档 docs/design/20261011-实收数量与单位的事后同步.md §11) +-- +-- 背景:主系统对**未处理**的申请是"**原地刷新为最新**"(`request_id` 不变、值/版本变)。 +-- 若我方审核人基于**旧值**点了同意,把旧值当结论回传,就会写出一个**双方都没打算要的第三值**。 +-- 主系统侧已加 `version INTEGER`(每次原地刷新 +1)并在请求事件里带 `request_version`; +-- 我方必须**存下它**,并在决策回执里原样回带 `decided_basis_version`,对方校验不一致 ⇒ +-- 409 `stale_request_version` 且**不写任何值**。 +-- +-- `request_updated_at` 只用于展示"对方最后更新时间",**不要**拿它当版本比较 +-- (毫秒精度 + 时区 + 跨类型比较实测会误判,主系统侧也踩过)。 +-- +-- 幂等:`IF NOT EXISTS`,可重复执行。 + +ALTER TABLE public.main_system_actual_qty_requests + ADD COLUMN IF NOT EXISTS request_version INTEGER; + +ALTER TABLE public.main_system_actual_qty_requests + ADD COLUMN IF NOT EXISTS request_updated_at TIMESTAMPTZ; + +COMMENT ON COLUMN public.main_system_actual_qty_requests.request_version IS + '主系统台账行的权威整数版本(原地刷新 +1);NULL = 对方未提供(旧版载荷),此时回执不带 decided_basis_version'; + +COMMENT ON COLUMN public.main_system_actual_qty_requests.request_updated_at IS + '主系统侧该申请的最后更新时间(仅展示;版本比较一律用 request_version)'; diff --git a/server/.env.example b/server/.env.example index 4c98e32..fa1b5bc 100644 --- a/server/.env.example +++ b/server/.env.example @@ -43,6 +43,8 @@ MAIN_SYSTEM_PRICE_QTY_ENABLED=0 # MAIN_SYSTEM_STATUS_PATH=/api/supplier/preparations/status # 实收/单位申请的决策回传路径(第五批 Q9,默认见 endpoints 表) # MAIN_SYSTEM_ACTUAL_QTY_DECISION_PATH=/api/supplier/preparations/actual-qty-decision +# 申请列表只读回读路径(Q6 对账兜底,一般不用改) +# MAIN_SYSTEM_PRICE_QTY_LIST_PATH=/api/supplier/preparations/price-qty-requests # DATABASE_URL 为本地库时允许 setup 自动创建/校验 DATABASE_URL 中的角色和数据库 SKIP_LOCAL_DB_SETUP=0 # 本地默认不灌入演示/端到端账号数据 diff --git a/server/src/modules/workflow/routes/orderRoutes.ts b/server/src/modules/workflow/routes/orderRoutes.ts index e4ce1db..844f3b0 100644 --- a/server/src/modules/workflow/routes/orderRoutes.ts +++ b/server/src/modules/workflow/routes/orderRoutes.ts @@ -317,12 +317,16 @@ router.post( ); /** - * 跨系统改价 / 改量:提交申请(2026-10-11)。 + * 跨系统改价 / 改量:**通知**主系统(2026-10-12 口径:先改后通知)。 * - * 主系统分配过来的订单行,**改销售价(= 主系统成本价)/ 改数量只能走这里**: - * 免审项(补价、改低、减量)提交后主系统立即生效 ⇒ 我们同步落地; - * 涨价/加量 ⇒ 主系统管理员审核,结果经 webhook `preparations.price_qty_decided` 回传。 - * 见 docs/design/20261011-跨系统改价改量审核.md(§4 C2/C6)。 + * 历史:2026-10-11 这里是"改销售价(= 主系统成本价)/ 改数量**只能走这里**"(先审后改); + * 现已翻转为**先改后通知** —— 明细保存(`orderManageItemsService`)与自采列表改价 + * (`purchaseLinkedSalePriceService`)都**本地照常写入**,并在 COMMIT 之后自动调用通知函数。 + * + * 因此本接口现在的用途是:**手工补发通知 / 排障重发**(例如自动通知失败后人工重发); + * 它**不再拦截**任何本地写入,也**不再**替我方向下落地(返回值 `applied_locally` 恒为 `false`)。 + * 主系统的同意/驳回**都不回改我方值**,只记台账 + 留痕。 + * 见 docs/design/20261011-跨系统改价改量审核.md(§4 C2/C6、**§10**)。 */ router.post( '/orders/:orderCode/items/:itemId/price-qty-request', @@ -503,12 +507,30 @@ router.get('/main-system/actual-qty-requests', authMiddleware, async (req: AuthR requireWorkflowPermission(ctx, ['order_edit', 'order_entry', 'order_manage', 'allocation_manage', 'purchase_manage']); const requested = readOperatingBranchCode(req); const branchCode = getEffectiveBranchCode(ctx!, requested) || ctx?.branchCode || ''; - const rows = await listActualQtyInbox({ + // 服务端分页(2026-10-12):`page`/`page_size` 翻页;`scope=pending|processed|all` 分区; + // `status=<精确值>` 优先于 scope。响应带 total/page/page_size 与两区计数,供界面标题与翻页控件用。 + const scopeRaw = String(req.query?.scope || '').trim().toLowerCase(); + const scope = + scopeRaw === 'pending' || scopeRaw === 'processed' || scopeRaw === 'all' + ? (scopeRaw as 'pending' | 'processed' | 'all') + : null; + const page = Number(req.query?.page) || 1; + const pageSize = Number(req.query?.page_size || req.query?.limit) || 20; + const result = await listActualQtyInbox({ branchCode, status: req.query?.status ? String(req.query.status) : null, - limit: Number(req.query?.limit) || 100, + scope, + page, + pageSize, + }); + return res.json({ + data: result.rows, + total: result.total, + page: result.page, + page_size: result.pageSize, + counts: result.counts, + error: null, }); - return res.json({ data: rows, error: null }); } catch (error: any) { return res.status(error?.status || 500).json({ error: error?.code || 'server_error', diff --git a/server/src/routes/mainSystemIntegration.ts b/server/src/routes/mainSystemIntegration.ts index 6d5dd66..5e99b4a 100644 --- a/server/src/routes/mainSystemIntegration.ts +++ b/server/src/routes/mainSystemIntegration.ts @@ -23,7 +23,12 @@ import { isEnabled as isPriceQtyRequestEnabled, isPriceQtyDecidedEvent, } from '../services/mainSystemPriceQtyRequest'; -import { recordActualQtyRequest } from '../services/mainSystemActualQtyInbox'; +import { + ACTUAL_QTY_DECIDED_EVENT, + handleActualQtyDecidedEvent, + recordActualQtyRequest, + recordPriceChangedFact, +} from '../services/mainSystemActualQtyInbox'; import type { MainPreparationRow } from '../services/mainSystemPreparations'; /** @@ -261,8 +266,9 @@ router.post('/main-system/webhook', async (req: Request, res: Response) => { /* ── 实收数量/单位申请(2026-10-11 第五批 Q8,主系统提交 b8519fbb)───────────── * `preparations.actual_qty_request`:对方发起、**我方审核**。 - * · 核货节点(`node=picking_check`)= 事实登记(对方值已落库)⇒ 我方驳回**不让对方回滚**; - * · `order_status >= 60` 改实收/单位、`>= 90` 改成本价 = 先审后改(pending 期间两边都不落库)。 + * · 2026-10-12 起**所有节点**(核货、撤销核货、入库核查、≥60 修正实收、≥90 改成本价) + * 都是"对方**先改自己的记录**、再发申请" = **事实登记** ⇒ 我方驳回**不让对方回滚**, + * 只决定"我方这条记录跟不跟"(成本价节点见主系统第七批 `3e90deb9` / 本仓清单 §4.5.7)。 * 纪律:幂等按对方 `request_id`;业务失败返 200(重试交给对方/对账)。 */ if (event === 'preparations.actual_qty_request') { @@ -277,6 +283,26 @@ router.post('/main-system/webhook', async (req: Request, res: Response) => { return res.json({ ok: true, ...recorded }); } + /* ── 成本价事实事件(2026-10-12 新增接收端)──────────────────────────────── + * `preparations.price_changed`:主系统**成本价**改动的事实推送(**没有 request_id**,不能决策)。 + * 主系统第七批 `3e90deb9` 起,同一笔改动还会再发一条**可审**的申请 + * (`actual_qty_request(kind=price_gate, node=post_complete_price, field=price)`); + * 本条事实的用途是:① 让"他们改了什么"在我们这边**看得见**(此前一律 ignored,他们以为我们没收到); + * ② 若那条可审申请漏投,就由它**补一条待审**,审核页照常出现、由我方决定跟不跟。 + * 纪律:同一商品同一字段**只留最新一条待审**(旧的转历史,可回溯)。 + */ + if (event === 'preparations.price_changed') { + if (!supplierCode) { + return res.json({ ok: true, ignored: true, reason: 'missing_supplier_code' }); + } + const recorded = await recordPriceChangedFact({ branchCode: supplierCode, payload }); + console.log( + `[main-system-webhook] ${supplierCode} ${event}:${recorded.status}` + + `${recorded.reason ? ` — ${recorded.reason}` : ''}` + ); + return res.json({ ok: true, ...recorded }); + } + if (!supplierCode) { // 没有供应商编码就无法定位分公司:200 收下但忽略,避免主系统反复重试 return res.json({ ok: true, ignored: true }); @@ -316,6 +342,21 @@ router.post('/main-system/webhook', async (req: Request, res: Response) => { return res.json({ ok: true, duplicate: handled.duplicate, ...handled.outcome }); } + /* 实收数量/单位申请的**结果事件**(2026-10-12 补,对接清单 §4.5.4): + * 主系统会在申请还没被我方审时撤回/作废(如配送员撤销核货)⇒ 收到即关闭/更新我方台账, + * 否则审核页会拿着已失效的值让人审。幂等:以 (branch_code, request_id) 更新,已终态不动。 */ + if (event === ACTUAL_QTY_DECIDED_EVENT) { + const handled = await handleActualQtyDecidedEvent({ + branchCode: supplierCode, + payload, + }); + console.log( + `[main-system-webhook] ${supplierCode} ${event} ${payload?.request_id || ''}:${handled.status}` + + `${handled.reason ? ` — ${handled.reason}` : ''}` + ); + return res.json({ ok: true, ...handled }); + } + if (event !== 'preparations.allocated') { // 其它事件一律 200 收下但忽略,避免主系统反复重试 return res.json({ ok: true, ignored: true }); diff --git a/server/src/services/mainSystem/api/preparations.ts b/server/src/services/mainSystem/api/preparations.ts index c2883dd..022d6b8 100644 --- a/server/src/services/mainSystem/api/preparations.ts +++ b/server/src/services/mainSystem/api/preparations.ts @@ -445,6 +445,102 @@ export async function lookupMainSystemPreparationStates( return { kind: 'ok', results }; } +/* ── Q6:申请列表只读回读(对账兜底) ─────────────────────────────────────── */ + +export type MainSystemRequestRow = { + requestId: string; + preparationId: string | null; + kind: string; + node: string; + field: string; + status: string; + appliedAt: string | null; + orderCode: string | null; + skuCode: string | null; + beforeValue: number | null; + proposedValue: number | null; + finalValue: number | null; + unit: string | null; + decidedAt: string | null; + reviewedBy: string | null; + message: string | null; + /** 权威整数版本(主系统第七批 §12.3);`null` = 对方未提供(旧版本/字段缺失) */ + requestVersion?: number | null; + /** 最后更新时间(只用于展示;**不要**拿它当版本比较,毫秒精度会误判) */ + requestUpdatedAt?: string | null; +}; + +export type MainSystemRequestListOutcome = + | { kind: 'ok'; rows: MainSystemRequestRow[]; truncated: boolean } + | { kind: 'not_configured'; reason: string } + | { kind: 'unavailable'; reason: string }; + +/** 单页上限(主系统默认 200;我方对账够用,取满即视为可能截断) */ +export const MAIN_SYSTEM_REQUEST_LIST_LIMIT = 200; + +/** + * 拉取本供应商(= 本分公司)的申请行(**只读**)。 + * + * 用途(对接清单 §2 Q6 + §4.5.4-五):`kind=actual_qty` 时拿到实收链的全部申请, + * 供我方对账"待审但对方已终态/已无对应行"的历史行 —— webhook 漏推、结果事件没到达时唯一的自愈通道。 + * + * ⚠️ 主系统列表有 LIMIT,取满 `limit` 说明**可能不完整**(`truncated=true`), + * 调用方不得据此把"没看到"当成"对方没有"。 + */ +export async function listMainSystemRequests( + supplierCode: string, + options?: { kind?: string | null; status?: string | null; limit?: number; updatedSince?: string | null } +): Promise { + if (!isMainSystemIntegrationEnabled()) { + return { kind: 'not_configured', reason: '主系统对接未配置' }; + } + const tokenResult = await getMainSystemToken(supplierCode); + if (tokenResult.kind !== 'ok') return { kind: 'unavailable', reason: tokenResult.reason }; + + const limit = Math.min(Math.max(Number(options?.limit) || MAIN_SYSTEM_REQUEST_LIST_LIMIT, 1), 500); + const result = await requestMainSystem({ + endpoint: 'priceQtyRequestsList', + method: 'GET', + token: tokenResult.token, + query: { + kind: options?.kind ? String(options.kind) : undefined, + status: options?.status ? String(options.status) : undefined, + updated_since: options?.updatedSince ? String(options.updatedSince) : undefined, + limit, + }, + timeoutMs: MAIN_SYSTEM_FETCH_TIMEOUT_MS, + timeoutReason: '拉取申请列表超时', + networkReasonPrefix: '拉取申请列表失败:', + }); + if (result.kind === 'not_configured') return { kind: 'not_configured', reason: result.reason }; + if (result.kind !== 'ok') return { kind: 'unavailable', reason: result.reason }; + + const payload = result.data as any; + const raw = Array.isArray(payload?.data) ? payload.data : Array.isArray(payload) ? payload : []; + const rows: MainSystemRequestRow[] = raw.map((row: any) => ({ + requestId: String(row?.request_id || ''), + preparationId: row?.preparation_id != null ? String(row.preparation_id) : null, + kind: String(row?.kind || ''), + node: row?.node != null ? String(row.node) : '', + field: row?.field != null ? String(row.field) : '', + status: String(row?.status || ''), + appliedAt: isoOrNull(row?.applied_at), + orderCode: row?.order_code != null ? String(row.order_code) : null, + skuCode: row?.sku_code != null ? String(row.sku_code) : null, + beforeValue: toNumber(row?.before_value), + proposedValue: toNumber(row?.proposed_value), + finalValue: toNumber(row?.final_value), + unit: row?.unit != null ? String(row.unit) : null, + decidedAt: isoOrNull(row?.decided_at), + reviewedBy: row?.reviewed_by != null ? String(row.reviewed_by) : null, + message: row?.message != null ? String(row.message) : null, + // 乐观并发校验(主系统第七批 `3e90deb9` §12.3):权威整数版本 + 最后更新时间(展示用) + requestVersion: toNumber(row?.request_version), + requestUpdatedAt: isoOrNull(row?.request_updated_at), + })); + return { kind: 'ok', rows, truncated: rows.length >= limit }; +} + /* ── 回写状态 ─────────────────────────────────────────────────────────────── */ export type WritebackSkippedRow = { id?: string | null; skuCode?: string | null; reason: string; message?: string }; @@ -565,7 +661,10 @@ export async function writebackMainSystemPreparationStatus(params: { * (主系统提交 `b8519fbb`,见 docs/给主系统AI的对接改造清单.md §4.10 Q9) * · `approved`:`final_value` 可选(改值后通过);不给则以对方 proposed 为准; * · `rejected`:**什么都不改**(核货节点连对方也不回滚——那是事实登记); - * · 重复调用主系统侧幂等(`message='already_decided'`)。 + * · 重复调用主系统侧幂等(`message='already_decided'`); + * · **乐观并发校验**(主系统第七批 `3e90deb9` §12.3):回执必须带 `decided_basis_version` + * (= 我方审核时看到的 `request_version`)。若对方台账在我方审核期间被**原地刷新**, + * 它会返回 **409 `stale_request_version` 且不写任何值** ⇒ 我方按"请刷新后再审"处理(见 `kind:'stale'`)。 */ export async function postMainSystemActualQtyDecision(params: { supplierCode: string; @@ -575,7 +674,13 @@ export async function postMainSystemActualQtyDecision(params: { reviewer?: string | null; decidedAt?: string | null; reason?: string | null; -}): Promise<{ kind: 'ok'; applied: boolean; finalValue: number | null; message: string | null } | { kind: 'unavailable'; reason: string }> { + /** 我方审核所依据的版本(= 事件/Q6 里的 `request_version`;未拿到时不传,对方按"不校验"处理) */ + decidedBasisVersion?: number | null; +}): Promise< + | { kind: 'ok'; applied: boolean; finalValue: number | null; message: string | null; requestVersion: number | null } + | { kind: 'stale'; reason: string; currentVersion: number | null } + | { kind: 'unavailable'; reason: string } +> { if (!isMainSystemIntegrationEnabled()) { return { kind: 'unavailable', reason: '主系统对接未配置' }; } @@ -598,10 +703,24 @@ export async function postMainSystemActualQtyDecision(params: { ...(params.reviewer ? { reviewer: params.reviewer } : {}), ...(params.decidedAt ? { decided_at: params.decidedAt } : {}), ...(params.reason ? { reason: params.reason } : {}), + ...(params.decidedBasisVersion === null || params.decidedBasisVersion === undefined + ? {} + : { decided_basis_version: params.decidedBasisVersion }), }, }); if (result.kind !== 'ok') { - return { kind: 'unavailable', reason: result.reason || '主系统未接受决策' }; + /** + * 409 `stale_request_version`:对方台账在我方审核期间被**原地刷新**(值/版本已变), + * 它**不写任何值**。这不是"回传失败",而是"你审的那一版已经过期" ⇒ 必须单独分类, + * 让审核页明确提示"请刷新后再审",而不是笼统报错(否则审核人会反复点同意、每次都撞 409)。 + */ + const status = Number((result as { status?: number }).status || 0); + const reason = result.reason || '主系统未接受决策'; + if (status === 409 || /stale_request_version/i.test(reason)) { + const m = /v(\d+)/.exec(reason); + return { kind: 'stale', reason, currentVersion: m ? Number(m[1]) : null }; + } + return { kind: 'unavailable', reason }; } const data = (result.payload as any)?.data ?? result.payload ?? {}; return { @@ -609,5 +728,6 @@ export async function postMainSystemActualQtyDecision(params: { applied: data?.applied === true, finalValue: data?.final_value != null ? Number(data.final_value) : null, message: data?.message != null ? String(data.message) : null, + requestVersion: data?.request_version != null ? Number(data.request_version) : null, }; } diff --git a/server/src/services/mainSystem/config.ts b/server/src/services/mainSystem/config.ts index 16f7464..d810aee 100644 --- a/server/src/services/mainSystem/config.ts +++ b/server/src/services/mainSystem/config.ts @@ -23,6 +23,11 @@ export const MAIN_SYSTEM_DEFAULT_PATHS = { priceQtyRequest: '/api/supplier/preparations/price-qty-request', // 实收/单位申请的决策回传(Q9,主系统提交 b8519fbb) actualQtyDecision: '/api/supplier/preparations/actual-qty-decision', + /** + * 申请列表**只读**回读(Q6 兜底,主系统 `d107e6d4` 起支持;`?kind=actual_qty` 取实收链)。 + * 用途:webhook 漏推 / 结果事件没到达时,我方对账用它关闭"已失效/已无对应行"的待审行。 + */ + priceQtyRequestsList: '/api/supplier/preparations/price-qty-requests', supplierLogin: '/api/supplier/login', } as const; diff --git a/server/src/services/mainSystem/endpoints.ts b/server/src/services/mainSystem/endpoints.ts index 1851f96..981f6a6 100644 --- a/server/src/services/mainSystem/endpoints.ts +++ b/server/src/services/mainSystem/endpoints.ts @@ -30,6 +30,8 @@ function pathOverride(endpoint: MainSystemEndpoint): string | undefined { return flags.priceQtyRequestPath; case 'actualQtyDecision': return process.env.MAIN_SYSTEM_ACTUAL_QTY_DECISION_PATH; + case 'priceQtyRequestsList': + return process.env.MAIN_SYSTEM_PRICE_QTY_LIST_PATH; case 'supplierLogin': return config.mainSystem.supplierLoginPath; default: diff --git a/server/src/services/mainSystemActualQtyApply.ts b/server/src/services/mainSystemActualQtyApply.ts index a331ac1..bcec64f 100644 --- a/server/src/services/mainSystemActualQtyApply.ts +++ b/server/src/services/mainSystemActualQtyApply.ts @@ -15,6 +15,11 @@ import { syncStatementsForOrderSafe } from './financeReconciliationService'; * ② **驳回不调用本模块**(我方零改动,只留痕); * ③ **计划量跟着实收一起改**("确保账一致")⇒ `order_items.quantity` 与 `amount` 一起重算。 * + * 字段(`field`)落点: + * · `qty` / `unit` ⇒ ①实收落点 + ②计划量/金额; + * · `price` ⇒ ③**我方销售价**(对方在 `post_complete_price` 节点"先改它的成本价再发申请", + * 我方同意 = 我方这条记录跟着一起变;改后同样要重建结算投影)。 + * * 分级(§4,开发者已批准): * · 免入库行(`skipInbound=true`)⇒ 改 `picking_items.loaded_qty`(我方装车核货量,不牵动库存); * · 送仓行 **未入库** ⇒ 改该验收行 `inspections.actual_qty`(无库存批次,安全); @@ -144,6 +149,45 @@ export async function applyActualQtySyncValue(params: { const changes: string[] = []; const targetQty = params.field === 'qty' ? params.finalValue : null; const targetUnit = params.field === 'unit' ? (params.unit || null) : null; + /** + * 我方**销售价**(= 主系统成本价)。对方在 `post_complete_price` 节点上**已先改它的值** + * (主系统第七批 `3e90deb9`:删掉 ≥90"先审后改"闸门 ⇒ 任何状态都先落库再发申请), + * 我方「同意」的语义就是**我方这条记录跟着一起变**(开发者 2026-10-12: + * 「改了就是改了…发送消息给系统,让其跟着一起变动」)。 + * + * ⚠️ 2026-10-12 前这里是**静默无操作**:`field='price'` 不落任何值,台账却写 `applied`、 + * 界面还提示"已同步到本系统(最终值 X)" ⇒ 真库实测 4 条 approved 的成本价申请我方价格没动 + * (`SUP35143228` before=7 → 8.23)。详见 `docs/给主系统AI的对接改造清单.md` §4.5.8。 + */ + const targetPrice = params.field === 'price' ? params.finalValue : null; + let effectivePrice = num(item.price); + if (targetPrice !== null) { + const newPrice = round2(targetPrice); + const newAmount = num(item.quantity) !== null ? round2(Number(item.quantity) * newPrice) : num(item.amount); + // 与 `purchaseLinkedSalePriceService` 的写价口径保持一致(含锁价三列),避免同一字段两种写法 + await runWithTenantDataAccess(branchCode, async (client) => + client.query( + `UPDATE order_items + SET price = $2::numeric, + locked_price = $2::numeric, + price_locked_at = NOW(), + amount = $3::numeric, + needs_customer_price = CASE WHEN $2::numeric > 0 THEN false ELSE needs_customer_price END + WHERE id = $1::uuid`, + [String(item.id), newPrice, newAmount] + ) + ); + effectivePrice = newPrice; + changes.push(`我方销售价 ${num(item.price) ?? '—'} → ${newPrice}、金额 → ${newAmount ?? '—'}`); + /** + * ⚠️ **结算单是订单的投影**(`orderSaleChangeSyncsStatements.test.ts` 钉住): + * 改了订单行销售字段就必须重建客户 + 供应商结算投影,否则结算停在旧价。 + * 本函数只处理"未结算、未结案"的单(已结算/≥90 已在上面的分级里返回 `skipped_settled`)。 + */ + // ⚠️ 必须包在**租户上下文**里:它内部用裸连接查 orders/结算表,无 ALS 上下文时会静默失败 + // (只打日志不抛)⇒ 结算投影停在旧值。本函数可能在 webhook 等无上下文请求里执行。 + await runWithTenantDbContext(branchCode, () => syncStatementsForOrderSafe(orderCode, null)); + } // ① 实收落点 if (skipInbound) { @@ -250,7 +294,8 @@ export async function applyActualQtySyncValue(params: { // ② 计划量 + 金额("计划量跟着实收一起变动,确保账一致") const beforeQty = num(item.quantity); - const price = num(item.price); + // 价可能刚在上面被改过 ⇒ 金额必须按**生效后的价**重算(否则量变了、价也变了时金额会少算一次) + const price = effectivePrice; const nextQty: number | null = targetQty !== null ? round3(targetQty) : beforeQty; const nextAmount: number | null = nextQty !== null && price !== null ? round2(nextQty * price) : num(item.amount); @@ -273,7 +318,9 @@ export async function applyActualQtySyncValue(params: { * 否则结算停在旧值。本函数只改"未结算、未结案"的单(已结算走 skipped_settled 分支), * 所以这里的同步会正常生效;同步失败内部已 catch(不阻断落值)。 */ - await syncStatementsForOrderSafe(orderCode, null); + // ⚠️ 必须包在**租户上下文**里:它内部用裸连接查 orders/结算表,无 ALS 上下文时会静默失败 + // (只打日志不抛)⇒ 结算投影停在旧值。本函数可能在 webhook 等无上下文请求里执行。 + await runWithTenantDbContext(branchCode, () => syncStatementsForOrderSafe(orderCode, null)); } await writeAudit({ @@ -283,7 +330,12 @@ export async function applyActualQtySyncValue(params: { changes, status: 'applied', itemId: String(item.id), - before: { quantity: beforeQty, amount: num(item.amount), unit: item.unit }, + before: { + quantity: beforeQty, + amount: num(item.amount), + unit: item.unit, + price: num(item.price), + }, }); return { status: 'applied', note: changes.join(';') || '无字段变化', changes }; } catch (error: unknown) { diff --git a/server/src/services/mainSystemActualQtyInbox.ts b/server/src/services/mainSystemActualQtyInbox.ts index bab35ba..41c7107 100644 --- a/server/src/services/mainSystemActualQtyInbox.ts +++ b/server/src/services/mainSystemActualQtyInbox.ts @@ -2,18 +2,21 @@ * 「实收数量 / 单位」申请的**接收端**(对方发起 → 我方审核)。 * * 主系统提交 `b8519fbb` 已交付(事件 `preparations.actual_qty_request` + 反向决策接口)。 - * 定稿语义(开发者 2026-10-11,见 docs/给主系统AI的对接改造清单.md §4.9/§4.10/§4.11): - * · **核货节点** = 事实登记:对方值已落库,发申请只为**告知**;我方通过 ⇒ 台账对齐; - * 带 final_value 通过 ⇒ 对方按协商值改写;我方**驳回 ⇒ 对方不回滚**(`fact_registered=true`)。 - * · **order_status >= 60**(配送中及以后改实收/单位)与 **>= 90**(完结后改成本价) - * = 先审后改:pending 期间两边都不落库,批准按 `final_value ?? proposed_value` 落地,驳回什么都不改。 + * 定稿语义(开发者 2026-10-11 起,2026-10-12 **全部翻转为"先改后审/通知"**, + * 见 docs/给主系统AI的对接改造清单.md §4.9/§4.10/§4.11/§4.5.4/§4.5.7): + * · **对方先改自己的记录、再发申请**(核货 / 撤销核货 / 入库 / 管理端 ≥60 修正实收 / 成本价≥90) + * = **事实登记**:`fact_registered=true`;我方通过 ⇒ 台账对齐 +(按我方决定)跟随改我方自己的记录; + * 带 final_value 通过 ⇒ 对方按协商值改写(`applied=true`);我方**驳回 ⇒ 对方不回滚**,只留痕。 + * · 上述**全部节点**(含 ≥60 改实收/单位、≥90 改成本价)现均为"先改后审":不再有"未获批前对方不落库"的节点。 * * 幂等键 = 对方的 `request_id`(同一分公司内唯一)。业务失败不抛错(webhook 不可重放,重试交给对方/对账)。 */ import { pool } from '../db'; import { writeAuditLog } from './auditService'; +import { listMainSystemRequests } from './mainSystem/api/preparations'; import { applyActualQtySyncValue } from './mainSystemActualQtyApply'; import { postMainSystemActualQtyDecision } from './mainSystem/api/preparations'; +import { deterministicUuid } from '../utils/deterministicUuid'; export type ActualQtyInboxRow = { id: string; @@ -32,7 +35,7 @@ export type ActualQtyInboxRow = { operator: string | null; reason: string | null; client_request_id: string | null; - status: 'pending' | 'approved' | 'rejected' | 'superseded'; + status: 'pending' | 'approved' | 'rejected' | 'superseded' | 'withdrawn'; final_value: string | number | null; reviewer: string | null; decided_at: string | null; @@ -40,6 +43,10 @@ export type ActualQtyInboxRow = { fact_registered: boolean; /** 主系统实际值在其侧生效的时刻(新口径"事实登记"的时间锚点;NULL = 对方未提供) */ applied_at: string | null; + /** 主系统台账行的权威整数版本(原地刷新 +1);NULL = 对方未提供(旧版载荷) */ + request_version: number | null; + /** 主系统侧最后更新时间(仅展示;版本比较一律用 request_version) */ + request_updated_at: string | null; payload: unknown; created_at: string; updated_at: string; @@ -56,14 +63,32 @@ const num = (v: unknown): number | null => { /** * **事实登记**节点:这些节点的 `proposed_value` 是对方**已经生效**的实际值 - * (新口径 2026-10-11:对方先改自己的记录再发请求)⇒ 我方**驳回也只留痕、不让对方回滚**。 + * (新口径 2026-10-11/10-12:对方先改自己的记录再发请求)⇒ 我方**驳回也只留痕、不让对方回滚**。 * - * · `picking_check`:免入库单,主系统配送员核货("核货多少就是多少"); - * · `inbound` :送仓单,主系统**入库核查**后的实际入库实收。 + * · `picking_check` :免入库单,主系统配送员核货("核货多少就是多少"); + * · `picking_check_revert`:配送员**撤销核货**(对方把实收改回去了,改完才通知我们作废申请); + * · `inbound` :送仓单,主系统**入库核查**后的实际入库实收; + * · `admin_received_qty` :他们管理端在 ≥60 时修正实收(`05ce5d6f` 起改为"写库后通知"); + * · `post_complete_price` :**他们的成本价**(= 我方销售价)改动(`3e90deb9` 第七批起改为"写库后通知")。 + * + * ⚠️ **`post_complete_price` 自 2026-10-12 起属于事实登记**(主系统 `3e90deb9`,其设计文档 §12.1): + * 对方**已把新成本价写进自己的库**(`applied_at` = 生效时刻),发申请只为**告知并征求我方是否跟随**; + * 我方批准 ⇒ 由我方决定是否把自己的销售价改到该值(他们的值**不因我方批准而变**:回执 `applied=false`); + * 我方驳回 ⇒ **对方不回滚**,只留痕。 + * (历史:2026-10-11 的 ≥90 成本价曾是"先审后改",2026-10-12 开发者已翻转 —— 见 + * `docs/给主系统AI的对接改造清单.md` §4.5.7 与 §4.5.8。) + * ⚠️ 但**"我方跟随改销售价"这一步是否落值**另见 `mainSystemActualQtyApply.ts` 的 `field='price'` 分支。 + * ⚠️ 新增节点时必须回到这里判断它属于哪一类(默认 **非事实登记**,宁可保守)。 * * 见 docs/design/20261011-实收数量与单位的事后同步.md §4。 */ -const FACT_NODES = new Set(['picking_check', 'inbound']); +const FACT_NODES = new Set([ + 'picking_check', + 'picking_check_revert', + 'inbound', + 'admin_received_qty', + 'post_complete_price', +]); /** 事件载荷 → 台账字段(字段名以对方 §4.10 的 12 个为准) */ export function mapActualQtyRequestPayload(payload: any) { @@ -88,11 +113,106 @@ export function mapActualQtyRequestPayload(payload: any) { payload?.applied_at != null && String(payload.applied_at).trim() ? String(payload.applied_at).trim() : null, + /** + * 乐观并发校验(主系统第七批 `3e90deb9` §12.3):`request_version` 是**权威整数版本**, + * 每次"原地刷新" +1。我方存下它,并在审核回执里回带 `decided_basis_version`; + * 对方校验不一致 ⇒ 409 `stale_request_version` 且不写值(防止用旧值当结论)。 + * `request_updated_at` 只展示用(毫秒精度比较会误判,不用它当版本)。 + */ + requestVersion: num(payload?.request_version), + requestUpdatedAt: + payload?.request_updated_at != null && String(payload.request_updated_at).trim() + ? String(payload.request_updated_at).trim() + : null, factRegistered: FACT_NODES.has(node), }; } -export type RecordOutcome = { status: 'recorded' | 'duplicate' | 'ignored'; reason: string; rowId: string | null }; +export type RecordOutcome = { + /** recorded=首次落库;refreshed=同一 request_id 的值被刷新为最新;duplicate=完全一致或已终态;ignored=载荷不可用 */ + status: 'recorded' | 'refreshed' | 'duplicate' | 'ignored'; + reason: string; + rowId: string | null; +}; + +/** 数值比较(容忍浮点误差) */ +function sameNumber(a: unknown, b: unknown): boolean { + const x = num(a); + const y = num(b); + if (x === null && y === null) return true; + if (x === null || y === null) return false; + return Math.abs(x - y) < 1e-9; +} + +/** 时间比较(允许 ISO 与 Postgres 时间戳混用;都空视为相同) */ +function sameInstant(a: unknown, b: unknown): boolean { + const toMs = (v: unknown): number | null => { + if (v === null || v === undefined || v === '') return null; + const t = new Date(String(v)).getTime(); + return Number.isNaN(t) ? null : t; + }; + const x = toMs(a); + const y = toMs(b); + if (x === null && y === null) return true; + if (x === null || y === null) return false; + return x === y; +} + +/** + * **同一商品 + 同一字段只保留一条待审**(开发者 2026-10-12 定稿): + * 「不要出现一个商品两条需要处理的申请,应该是保留最新的,旧的作为历史记录可回溯」。 + * + * 主系统侧对"未处理"的申请是**原地刷新**(同 `request_id`,由 `recordActualQtyRequest` 的刷新分支处理); + * 但它也可能**新开一条**(新 `request_id`,例如价格连改两次、或 `price_changed` 事实先于我方的可审申请到达) + * ⇒ 我方必须把**旧的 pending 关成 `superseded`**(进"已处理"历史,`payload.superseded_by` 可回溯谁取代了它)。 + * + * 按 `(prep_id, field)` 归组:同一备货行的"价"与"量"是两条独立申请(对方也按 `field` 拆条), + * 互不取代;`node` 不参与归组(核货/入库/撤销核货对同一行同一字段本就只能有一条有效值)。 + */ +async function supersedeOlderPending(params: { + branchCode: string; + prepId: string | null; + field: string; + keepRequestId: string; +}): Promise> { + const res = await pool.query<{ id: string; request_id: string }>( + `UPDATE public.main_system_actual_qty_requests + SET status = 'superseded', + decided_at = NOW(), + decision_reason = $5, + payload = COALESCE(payload, '{}'::jsonb) || jsonb_build_object( + 'superseded_by', jsonb_build_object('request_id', $4::text, 'at', NOW(), 'reason', $5::text) + ), + updated_at = NOW() + WHERE branch_code = $1 + AND status = 'pending' + AND field = $3 + AND request_id <> $4::text + AND prep_id IS NOT DISTINCT FROM $2::uuid + RETURNING id, request_id`, + [ + params.branchCode, + params.prepId, + params.field, + params.keepRequestId, + '已被该商品更新的申请取代(同一商品/字段只保留最新一条待审)', + ] + ); + for (const row of res.rows) { + await writeAuditLog({ + operatorId: null, + operatorRole: 'main_system', + operationType: 'main_system_actual_qty_request_superseded', + targetTable: 'main_system_actual_qty_requests', + targetId: row.id, + oldValue: { status: 'pending', request_id: row.request_id }, + newValue: { status: 'superseded', superseded_by: params.keepRequestId, field: params.field }, + branchCode: params.branchCode, + actionCategory: 'order', + }).catch(() => undefined); + } + return res.rows; +} /** 落库(幂等:同分公司 + 同 request_id 只落一条;重复投递返回 duplicate,不覆盖已审结论) */ export async function recordActualQtyRequest(params: { @@ -110,13 +230,120 @@ export async function recordActualQtyRequest(params: { return { status: 'ignored', reason: `request_id 非 UUID,已忽略:${mapped.requestId.slice(0, 40)}`, rowId: null }; } - const existing = await pool.query<{ id: string; status: string }>( - `SELECT id, status FROM public.main_system_actual_qty_requests + const existing = await pool.query( + `SELECT * FROM public.main_system_actual_qty_requests WHERE branch_code = $1 AND request_id = $2 LIMIT 1`, [branchCode, mapped.requestId] ); if (existing.rowCount) { - return { status: 'duplicate', reason: `已存在(${existing.rows[0].status})`, rowId: String(existing.rows[0].id) }; + const cur = existing.rows[0]; + /** + * 主系统对**未处理**的申请是"原地更新为最新"(唯一键 `(preparation_id, kind, field)` + `WHERE status='pending'`, + * `request_id` 不变)⇒ 我方必须跟着刷新,否则页面与决策都停在旧值,回传时会把**旧值覆盖新值**(2026-10-12 定稿)。 + */ + if (cur.status !== 'pending') { + // 已是终态:按对方语义同一 request_id 不应再刷新(它已离开 pending)⇒ 覆盖会篡改我方已定结论, + // 只留一条"迟到事件"痕迹,人工可查。 + await pool + .query( + `UPDATE public.main_system_actual_qty_requests + SET payload = COALESCE(payload, '{}'::jsonb) || jsonb_build_object( + 'late_event', jsonb_build_object('at', NOW(), 'incoming', $3::jsonb) + ), + updated_at = NOW() + WHERE branch_code = $1 AND id = $2::uuid`, + [branchCode, cur.id, JSON.stringify({ node: mapped.node, field: mapped.field, proposed: mapped.proposedValue, appliedAt: mapped.appliedAt })] + ) + .catch(() => undefined); + return { status: 'duplicate', reason: `已是终态(${cur.status}),本次不刷新`, rowId: String(cur.id) }; + } + const changed = + !sameNumber(cur.proposed_value, mapped.proposedValue) || + !sameNumber(cur.before_value, mapped.beforeValue) || + String(cur.unit ?? '') !== String(mapped.unit ?? '') || + String(cur.before_unit ?? '') !== String(mapped.beforeUnit ?? '') || + !sameInstant(cur.applied_at, mapped.appliedAt) || + // 版本变了也算变化:对方原地刷新时值可能恰好相同(回改成原值),但"审核依据"已经变了 + (mapped.requestVersion !== null && num(cur.request_version) !== mapped.requestVersion) || + String(cur.reason ?? '') !== String(mapped.reason ?? ''); + if (!changed) { + return { status: 'duplicate', reason: '值与生效时间均未变化(幂等)', rowId: String(cur.id) }; + } + await pool.query( + `UPDATE public.main_system_actual_qty_requests + SET node = $3, field = $4, before_value = $5, proposed_value = $6, + before_unit = $7, unit = $8::text, operator = $9, reason = $10, -- 显式 ::text:同参数也用于 jsonb to_unit,混用 varchar/text 会报 inconsistent types + client_request_id = $11, applied_at = $12::timestamptz, + request_version = COALESCE($16::int, request_version), + request_updated_at = COALESCE($17::timestamptz, request_updated_at), + payload = COALESCE(payload, '{}'::jsonb) + || jsonb_build_object( + 'refresh', jsonb_build_object( + 'at', NOW(), 'from_value', $13::numeric, 'from_unit', $14::text, + 'to_value', $6::numeric, 'to_unit', $8::text, 'prev_applied_at', $15::timestamptz + ) + ) + -- 完整历史数组:审核页可追溯"每次被刷新成什么"(开发者 2026-10-12:要能追溯) + || jsonb_build_object( + 'refresh_history', + COALESCE(payload->'refresh_history', '[]'::jsonb) || jsonb_build_array( + jsonb_build_object( + 'at', NOW(), 'from_value', $13::numeric, 'from_unit', $14::text, + 'to_value', $6::numeric, 'to_unit', $8::text, 'source', 'webhook' + ) + ) + ), + updated_at = NOW() + WHERE branch_code = $1 AND id = $2::uuid AND status = 'pending'`, + [ + branchCode, + cur.id, + mapped.node, + mapped.field, + mapped.beforeValue, + mapped.proposedValue, + mapped.beforeUnit, + mapped.unit, + mapped.operator, + mapped.reason, + mapped.clientRequestId, + mapped.appliedAt, + cur.proposed_value, + cur.unit, + cur.applied_at, + mapped.requestVersion, + mapped.requestUpdatedAt, + ] + ); + await writeAuditLog({ + operatorId: null, + operatorRole: 'main_system', + operationType: 'main_system_actual_qty_request_refreshed', + targetTable: 'main_system_actual_qty_requests', + targetId: cur.id, + oldValue: { proposed_value: cur.proposed_value, unit: cur.unit, applied_at: cur.applied_at }, + newValue: { + proposed_value: mapped.proposedValue, + unit: mapped.unit, + applied_at: mapped.appliedAt, + node: mapped.node, + field: mapped.field, + }, + branchCode, + actionCategory: 'order', + }).catch(() => undefined); + // 刷新的是同一条(request_id 不变),但可能另有一条不同 request_id 的待审(例如 price_changed 建的本地事实行) + await supersedeOlderPending({ + branchCode, + prepId: cur.prep_id ? String(cur.prep_id) : null, + field: String(cur.field), + keepRequestId: String(cur.request_id), + }); + return { + status: 'refreshed', + reason: `已按最新值刷新(${cur.proposed_value ?? '—'} → ${mapped.proposedValue ?? '—'},同一 request_id)`, + rowId: String(cur.id), + }; } // 关联我方订单(有 prep 台账就带上我们的单号,便于界面直接跳转) @@ -134,20 +361,29 @@ export async function recordActualQtyRequest(params: { `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, applied_at, payload) - VALUES ($1,$2,$3::uuid,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,'pending',$16,$17::timestamptz,$18::jsonb) + status, fact_registered, applied_at, request_version, request_updated_at, payload) + VALUES ($1,$2,$3::uuid,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,'pending',$16,$17::timestamptz,$18::int,$19::timestamptz,$20::jsonb) ON CONFLICT (branch_code, request_id) DO NOTHING RETURNING *`, [ branchCode, mapped.requestId, mapped.prepId, mapped.orderCode, ourOrderCode, mapped.skuCode, mapped.node, mapped.field, mapped.beforeValue, mapped.proposedValue, mapped.beforeUnit, mapped.unit, mapped.operator, mapped.reason, mapped.clientRequestId, - mapped.factRegistered, mapped.appliedAt, JSON.stringify(params.payload ?? null), + mapped.factRegistered, mapped.appliedAt, mapped.requestVersion, mapped.requestUpdatedAt, + JSON.stringify(params.payload ?? null), ] ); const row = inserted.rows[0]; if (!row) return { status: 'duplicate', reason: '并发重复', rowId: null }; + // 同一商品 + 同一字段只留最新一条待审(旧的转历史、可回溯)——见 supersedeOlderPending + const superseded = await supersedeOlderPending({ + branchCode, + prepId: row.prep_id ? String(row.prep_id) : null, + field: String(row.field), + keepRequestId: String(row.request_id), + }); + await writeAuditLog({ operatorId: null, operatorRole: 'main_system', @@ -179,28 +415,638 @@ export async function recordActualQtyRequest(params: { } /** 待审/已审列表(界面用) */ +/** + * 列表查询(**服务端分页**,2026-10-12 开发者要求)。 + * + * `scope`: + * · `pending` = 待我审核; + * · `processed` = 已处理历史(非 pending); + * · `all` = 全部。 + * `status`(精确值)优先于 `scope`;两者都不给 = `all`。 + * 返回 `total`(当前过滤条件的总行数)与 `counts`(两个区各自的总数,供界面标题显示)。 + */ +/** + * `preparations.price_changed`(**事实事件**,主系统 §4.7 / `supplierPriceChangeNotice.ts`)接收端。 + * + * 为什么要有它:主系统**成本价**改动会同时发两条 —— + * ① `price_changed`:纯事实(**没有 `request_id`**,不能被"决策"); + * ② `actual_qty_request(kind=price_gate, node=post_complete_price, field=price)`:**可审**的申请。 + * 此前我方只收 ② ,① 一律 `{ok:true, ignored:true}` ⇒ 主系统那边看到的是"改了成本价、子系统没收到" + * (其第七批 commit ④ 专门排查过这件事)。 + * + * 现在的处置(开发者 2026-10-12:「主系统发出的修改,我们这边肯定要展示」+ + * 「不要出现一个商品两条需要处理的申请,保留最新的」): + * · 该 `(prep_id, field=price)` **已有待审** ⇒ **把那条待审原地刷成这次事实的最新值** + * (值/生效时间/刷新历史;开发者:「只需要确保为最新的就行」),**绝不新建**第二行; + * · **没有待审**(例如可审申请漏投/投递失败) ⇒ 建一条**本地待审事实行**,让审核页照常出现、 + * 由我方决定"跟不跟";该行 `payload.local_only=true` ⇒ 审核结论**不回传**主系统 + * (它已经改完了,没有什么要它做的;这与"驳回 = 我方自己不改而已"完全一致)。 + * + * 幂等键:对方给的 `client_request_id`(`pc___`,同一行同一对新旧价恒定) + * ⇒ 我方按它派生**确定性 UUID** 当 `request_id`,重推不会产生第二行。 + */ +export function mapPriceChangedPayload(payload: any) { + const beforeValue = num(payload?.before_price ?? payload?.before_value); + const afterValue = num(payload?.final_price ?? payload?.after_value); + return { + prepId: + payload?.preparation_id != null + ? String(payload.preparation_id) + : payload?.prep_id != null + ? String(payload.prep_id) + : null, + orderCode: payload?.order_code != null ? String(payload.order_code) : null, + skuCode: payload?.sku_code != null ? String(payload.sku_code) : null, + beforeValue, + afterValue, + unit: payload?.unit != null ? String(payload.unit) : null, + source: payload?.source != null ? String(payload.source) : null, + changedAt: payload?.changed_at != null ? String(payload.changed_at) : null, + clientRequestId: payload?.client_request_id != null ? String(payload.client_request_id) : null, + }; +} + +/** 确定性 UUID 的实现见 `../utils/deterministicUuid`(纯函数,便于单测) */ + +export async function recordPriceChangedFact(params: { + branchCode: string; + payload: any; +}): Promise { + const branchCode = String(params.branchCode || '').trim(); + if (!branchCode) return { status: 'ignored', reason: '缺少分公司', rowId: null }; + const mapped = mapPriceChangedPayload(params.payload); + if (!mapped.prepId) return { status: 'ignored', reason: '缺少 preparation_id', rowId: null }; + if (mapped.beforeValue === null || mapped.afterValue === null) { + return { status: 'ignored', reason: '缺少 before/final 价格', rowId: null }; + } + if (sameNumber(mapped.beforeValue, mapped.afterValue)) { + return { status: 'ignored', reason: '价格未变化(对方也按此过滤,属于重推)', rowId: null }; + } + + // 关联我方订单(台账有 prep_id 对照就带上,便于审核页直接跳转) + const link = await pool.query<{ our_order_code: string | null }>( + `SELECT our_order_code FROM public.main_system_order_import_items + WHERE branch_code = $1 AND prep_id = $2::uuid LIMIT 1`, + [branchCode, mapped.prepId] + ).catch(() => ({ rows: [] as Array<{ our_order_code: string | null }> })); + + const fact = { + at: new Date().toISOString(), + source: mapped.source, + before_price: mapped.beforeValue, + final_price: mapped.afterValue, + unit: mapped.unit, + changed_at: mapped.changedAt, + client_request_id: mapped.clientRequestId, + }; + + // ① 已有待审(通常是那条可审的 price_gate 申请)⇒ 只附事实,不新建第二行 + const pending = await pool.query( + `SELECT * FROM public.main_system_actual_qty_requests + WHERE branch_code = $1 AND prep_id = $2::uuid AND field = 'price' AND status = 'pending' + ORDER BY created_at DESC LIMIT 1`, + [branchCode, mapped.prepId] + ); + if (pending.rows[0]) { + const row = pending.rows[0]; + /** + * 开发者 2026-10-12:「只需要确保为最新的就行,不要出现一个商品两条需要处理的申请」。 + * 所以已有待审行时:**新事实的值更新就把这一行刷成最新**(值/生效时间/留痕), + * 而不是把新事实附在旧值上(那会让审核人去审一个对方早已改掉的旧价)。 + */ + const valueChanged = !sameNumber(row.proposed_value, mapped.afterValue); + await pool.query( + `UPDATE public.main_system_actual_qty_requests + SET proposed_value = CASE WHEN $4::boolean THEN $5::numeric ELSE proposed_value END, + before_value = CASE WHEN $4::boolean THEN $6::numeric ELSE before_value END, + applied_at = CASE WHEN $4::boolean THEN COALESCE($7::timestamptz, applied_at) ELSE applied_at END, + decision_reason = CASE WHEN $4::boolean THEN '主系统成本价已更新为最新(事实事件)' ELSE decision_reason END, + payload = COALESCE(payload, '{}'::jsonb) + || jsonb_build_object('price_changed_fact', $3::jsonb) + || CASE WHEN $4::boolean THEN jsonb_build_object( + 'refresh_history', + COALESCE(payload->'refresh_history', '[]'::jsonb) || jsonb_build_array( + jsonb_build_object( + 'at', NOW(), 'from_value', $8::numeric, 'from_unit', $9::text, + 'to_value', $5::numeric, 'to_unit', $9::text, 'source', 'price_changed' + ) + ) + ) ELSE '{}'::jsonb END, + updated_at = NOW() + WHERE branch_code = $1 AND id = $2::uuid AND status = 'pending'`, + [ + branchCode, + row.id, + JSON.stringify(fact), + valueChanged, + mapped.afterValue, + mapped.beforeValue, + mapped.changedAt, + row.proposed_value, + row.unit, + ] + ); + return { + status: valueChanged ? 'refreshed' : 'duplicate', + reason: valueChanged + ? `该商品已有待审的价格申请 ⇒ 已按最新事实刷新为 ${mapped.afterValue}(不新建第二条待审)` + : '该商品已有待审的价格申请,且值一致 ⇒ 本次事实只作留痕(不新建第二条待审)', + rowId: String(row.id), + attachedTo: String(row.request_id), + }; + } + + // ② 没有待审 ⇒ 建一条**本地待审事实行**,让审核页照常出现、由我方决定跟不跟 + const seed = mapped.clientRequestId || `pc_${mapped.prepId}_${mapped.beforeValue}_${mapped.afterValue}`; + const requestId = deterministicUuid(seed); + const existing = await pool.query( + `SELECT * FROM public.main_system_actual_qty_requests + WHERE branch_code = $1 AND request_id = $2 LIMIT 1`, + [branchCode, requestId] + ); + if (existing.rows[0]) { + return { status: 'duplicate', reason: '同一笔价格事实此前已落库(幂等)', rowId: String(existing.rows[0].id) }; + } + const inserted = await pool.query( + `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, applied_at, request_version, request_updated_at, payload) + VALUES ($1,$2,$3::uuid,$4,$5,$6,'post_complete_price','price',$7,$8,NULL,$9::text,$10,$11,$12, + 'pending',true,$13::timestamptz,NULL,NULL,$14::jsonb) + ON CONFLICT (branch_code, request_id) DO NOTHING + RETURNING *`, + [ + branchCode, + requestId, + mapped.prepId, + mapped.orderCode, + link.rows[0]?.our_order_code ? String(link.rows[0].our_order_code) : null, + mapped.skuCode, + mapped.beforeValue, + mapped.afterValue, + mapped.unit, + params.payload?.operator != null ? String(params.payload.operator) : null, + '主系统改了成本价(事实事件,无可审申请)', + mapped.clientRequestId, + mapped.changedAt, + JSON.stringify({ price_changed_fact: fact, local_only: true, raw: params.payload ?? null }), + ] + ); + const row = inserted.rows[0]; + if (!row) return { status: 'duplicate', reason: '并发重复', rowId: null }; + await supersedeOlderPending({ + branchCode, + prepId: mapped.prepId, + field: 'price', + keepRequestId: requestId, + }); + await writeAuditLog({ + operatorId: null, + operatorRole: 'main_system', + operationType: 'main_system_price_changed_fact_recorded', + targetTable: 'main_system_actual_qty_requests', + targetId: row.id, + oldValue: { price: mapped.beforeValue }, + newValue: { price: mapped.afterValue, source: mapped.source, local_only: true }, + branchCode, + actionCategory: 'order', + }).catch(() => undefined); + return { + status: 'recorded', + reason: `已登记为待审(无对应可审申请):成本价 ${mapped.beforeValue} → ${mapped.afterValue}`, + rowId: String(row.id), + }; +} + export async function listActualQtyInbox(params: { branchCode: string; status?: string | null; + scope?: 'pending' | 'processed' | 'all' | null; + page?: number; + pageSize?: number; + /** 兼容旧调用:等价于 pageSize */ limit?: number; -}): Promise { - const args: unknown[] = [params.branchCode]; - const where = ['branch_code = $1']; - if (params.status) { - args.push(params.status); - where.push(`status = $${args.length}`); +}): Promise<{ + rows: ActualQtyInboxRow[]; + total: number; + page: number; + pageSize: number; + counts: { pending: number; processed: number }; +}> { + const branchCode = String(params.branchCode || ''); + const pageSize = Math.min(Math.max(Number(params.pageSize ?? params.limit) || 20, 1), 200); + const page = Math.max(Number(params.page) || 1, 1); + const offset = (page - 1) * pageSize; + + const args: unknown[] = [branchCode]; + const where = ['r.branch_code = $1']; + const status = String(params.status || '').trim(); + if (status) { + args.push(status); + where.push(`r.status = $${args.length}`); + } else if (params.scope === 'pending') { + where.push(`r.status = 'pending'`); + } else if (params.scope === 'processed') { + where.push(`r.status <> 'pending'`); } - args.push(Math.min(Math.max(Number(params.limit) || 100, 1), 500)); - const result = await pool.query( - `SELECT r.*, i.item_name - FROM public.main_system_actual_qty_requests r - LEFT JOIN public.main_system_order_import_items i - ON i.branch_code = r.branch_code AND i.prep_id = r.prep_id - WHERE ${where.map((w) => w.replace(/branch_code/, 'r.branch_code').replace(/status/, 'r.status')).join(' AND ')} - ORDER BY r.created_at DESC LIMIT $${args.length}`, - args + const whereSql = where.join(' AND '); + + /** + * ⚠️ 商品名兜底(2026-10-12):历史行的 `prep_id` 可能已不在对照台账里(对方重同步/清理过), + * 只靠 LEFT JOIN 会让"商品名"整列显示 `-`。按优先级兜底: + * 台账 item_name → 事件载荷里的 item_name(`payload.data[0].item_name`)→ sku_code → prep_id。 + */ + const itemNameSql = `COALESCE( + i.item_name, + NULLIF(TRIM(COALESCE(r.payload->'data'->0->>'item_name', '')), ''), + NULLIF(TRIM(COALESCE(r.sku_code, '')), ''), + r.prep_id::text + ) AS item_name`; + + const [rows, totalRes, countsRes] = await Promise.all([ + pool.query( + `SELECT r.*, ${itemNameSql} + FROM public.main_system_actual_qty_requests r + LEFT JOIN public.main_system_order_import_items i + ON i.branch_code = r.branch_code AND i.prep_id = r.prep_id + WHERE ${whereSql} + ORDER BY r.created_at DESC, r.id DESC + LIMIT $${args.length + 1} OFFSET $${args.length + 2}`, + [...args, pageSize, offset] + ), + pool.query<{ n: number }>( + `SELECT count(*)::int AS n + FROM public.main_system_actual_qty_requests r + WHERE ${whereSql}`, + args + ), + pool.query<{ pending: number; processed: number }>( + `SELECT count(*) FILTER (WHERE status = 'pending')::int AS pending, + count(*) FILTER (WHERE status <> 'pending')::int AS processed + FROM public.main_system_actual_qty_requests + WHERE branch_code = $1`, + [branchCode] + ), + ]); + + return { + rows: rows.rows, + total: Number(totalRes.rows[0]?.n || 0), + page, + pageSize, + counts: { + pending: Number(countsRes.rows[0]?.pending || 0), + processed: Number(countsRes.rows[0]?.processed || 0), + }, + }; +} + +export const ACTUAL_QTY_DECIDED_EVENT = 'preparations.actual_qty_decided'; + +/** 主系统侧对该申请的终态(`applied` 只会出现在免审的价格链,这里一并兼容) */ +const DECIDED_TERMINAL: Record = { + withdrawn: 'withdrawn', + superseded: 'superseded', + approved: 'approved', + rejected: 'rejected', + // 免审直接生效的价格链用 applied;实收链目前不发,兼容处理为"已通过" + applied: 'approved', +}; + +export type ActualQtyDecidedOutcome = { + status: 'updated' | 'duplicate' | 'ignored'; + reason: string; + requestRowId: string | null; +}; + +/** + * 处理主系统的**结果事件** `preparations.actual_qty_decided`(2026-10-12 补,见对接清单 §4.5.4)。 + * + * 为什么必须有:主系统会在**申请还没被我方审**时自行撤回/作废(例如配送员撤销核货), + * 事件到达前我方台账仍是 `pending` ⇒ 审核页会拿着**已失效的值**让人审。 + * + * 语义(主系统 `supplierActualQtyRequestService.emitActualQtyDecided`): + * · `withdrawn` = 对方撤回核货/撤销申请 ⇒ 我方**直接关闭**、无需审核; + * · `superseded` = 对方内部作废(被新值覆盖)⇒ 同上关闭 + 留痕; + * · `approved` / `rejected` = 对方自己定的结论(≥60 管理端路径)⇒ 更新我方行结论。 + * **幂等**:已是终态则不动(返回 duplicate);本系统无此申请则 ignored(可能是别的供应商/已清理)。 + */ +export async function handleActualQtyDecidedEvent(params: { + branchCode: string | null; + payload: any; +}): Promise { + const branchCode = String(params.branchCode || '').trim(); + const payload = params.payload || {}; + const requestId = String(payload?.request_id || '').trim(); + const decisionRaw = String(payload?.decision || '').trim().toLowerCase(); + if (!branchCode) return { status: 'ignored', reason: '缺少分公司', requestRowId: null }; + if (!requestId) return { status: 'ignored', reason: '缺少 request_id', requestRowId: null }; + const nextStatus = DECIDED_TERMINAL[decisionRaw]; + if (!nextStatus) { + return { status: 'ignored', reason: `未知 decision:${decisionRaw || '(空)'}`, requestRowId: null }; + } + + const found = await pool.query( + `SELECT * FROM public.main_system_actual_qty_requests + WHERE branch_code = $1 AND request_id = $2 LIMIT 1`, + [branchCode, requestId] ); - return result.rows; + const row = found.rows[0]; + if (!row) { + return { status: 'ignored', reason: `本系统无此申请(${requestId})`, requestRowId: null }; + } + if (row.status !== 'pending') { + return { status: 'duplicate', reason: `已是终态 ${row.status}`, requestRowId: String(row.id) }; + } + + const decidedAtRaw = payload?.decided_at != null ? String(payload.decided_at) : ''; + const decidedAt = decidedAtRaw && !Number.isNaN(new Date(decidedAtRaw).getTime()) + ? new Date(decidedAtRaw).toISOString() + : new Date().toISOString(); + const reason = + (payload?.reason != null && String(payload.reason).trim()) || + (payload?.message != null && String(payload.message).trim()) || + (decisionRaw === 'withdrawn' + ? '主系统撤回申请(我方未审即失效,直接关闭)' + : decisionRaw === 'superseded' + ? '主系统内部作废(被新值覆盖)' + : `主系统结论:${decisionRaw}`); + /** + * ⚠️ 只在**事件真的带了** `final_value` 时才写终值:用我方台账里可能过期的 `proposed_value` 兜底, + * 会在"同一 request_id 被原地刷新"的场景里把旧值写成最终值(与本批 latest-wins 口径冲突)。 + * 事件没带值时留 `null`,界面显示"—",由 Q6 对账另行刷新。 + */ + const finalValue = nextStatus === 'approved' ? num(payload?.final_value) : null; + + await pool.query( + `UPDATE public.main_system_actual_qty_requests + SET status = $3, final_value = $4, decided_at = $5, decision_reason = $6, + reviewer = COALESCE($7::text, reviewer), + payload = COALESCE(payload, '{}'::jsonb) || jsonb_build_object( + 'decided_event', jsonb_build_object( + 'decision', $8::text, 'reason', $6::text, 'at', $5::timestamptz, + 'reviewer', $7::text + ) + ), + updated_at = NOW() + WHERE branch_code = $1 AND id = $2::uuid AND status = 'pending'`, + [ + branchCode, + row.id, + nextStatus, + finalValue, + decidedAt, + reason, + payload?.reviewer != null + ? String(payload.reviewer) + : payload?.reviewed_by != null + ? String(payload.reviewed_by) + : null, + decisionRaw, + ] + ); + + await writeAuditLog({ + operatorId: null, + operatorRole: 'main_system', + operationType: `main_system_actual_qty_request_${nextStatus}`, + targetTable: 'main_system_actual_qty_requests', + targetId: row.id, + oldValue: { status: 'pending', node: row.node, field: row.field, proposed_value: row.proposed_value }, + newValue: { status: nextStatus, final_value: finalValue, reason, decided_at: decidedAt, event: ACTUAL_QTY_DECIDED_EVENT }, + branchCode, + actionCategory: 'order', + }).catch(() => undefined); + + return { + status: 'updated', + reason: + nextStatus === 'withdrawn' || nextStatus === 'superseded' + ? `已按主系统事件关闭(${nextStatus}):${reason}` + : `已按主系统结论更新为 ${nextStatus}`, + requestRowId: String(row.id), + }; +} + +export type ReconcileOutcome = { + /** 主系统侧拉到的申请行数 */ + pulled: number; + /** 我方在宽限期内被检查的待审行数 */ + checked: number; + /** 被关闭(对方已终态 / 对方已无此申请)的行数 */ + closed: number; + /** 主系统侧仍是 pending、但值已更新 ⇒ 被我方刷新为最新的行数 */ + refreshed: number; + /** 仍在对方侧待审且值未变化、保持原状的行数 */ + kept: number; + /** 拉取被截断(命中对方 limit)⇒ 本次**不做**"对方没有 ⇒ 孤儿"的判定 */ + truncated: boolean; + reason?: string; +}; + +/** + * **对账兜底**:用 Q6 只读接口核对我方待审行与主系统侧的真实状态(2026-10-12 补,清单 §4.5.4-五)。 + * + * 为什么需要:webhook 漏推 / 结果事件没到达时,我方台账会留着一批**永远不会被审**的 `pending` + * (实测 60 条里 58 条在对方侧已查不到 —— 历史联调轮次的数据被清掉了)。 + * + * 判定(保守,宁可留着也不误关): + * · 对方侧该 `request_id` **有行且非 pending** ⇒ 按终态关闭(withdrawn/superseded/approved/rejected); + * · 对方侧**查不到**该 `request_id`,且**本次拉取没有被截断**,且该行已超过宽限期 ⇒ 关闭为 `superseded` + * (理由写明"历史遗留");**截断时一律不判孤儿**("没看到"≠"没有")。 + * · 对方侧仍是 `pending` ⇒ 保持不动。 + */ +export async function reconcilePendingActualQtyRequests(params: { + branchCode: string; + /** 只处理创建时间早于 now()-N 分钟的待审行(默认 30,给 webhook 留出到达窗口) */ + graceMinutes?: number; + limit?: number; +}): Promise { + const branchCode = String(params.branchCode || '').trim(); + const empty: ReconcileOutcome = { + pulled: 0, + checked: 0, + closed: 0, + refreshed: 0, + kept: 0, + truncated: false, + }; + if (!branchCode) return { ...empty, reason: '缺少分公司' }; + + const pulled = await listMainSystemRequests(branchCode, { kind: 'actual_qty', limit: params.limit }); + if (pulled.kind !== 'ok') return { ...empty, reason: pulled.reason }; + + const theirStatus = new Map< + string, + { + status: string; + decidedAt: string | null; + message: string | null; + proposedValue: number | null; + unit: string | null; + appliedAt: string | null; + requestVersion: number | null; + requestUpdatedAt: string | null; + } + >(); + for (const row of pulled.rows) { + if (row.requestId) { + theirStatus.set(row.requestId, { + status: row.status, + decidedAt: row.decidedAt, + message: row.message, + proposedValue: row.proposedValue, + unit: row.unit, + appliedAt: row.appliedAt, + requestVersion: row.requestVersion ?? null, + requestUpdatedAt: row.requestUpdatedAt ?? null, + }); + } + } + + const grace = Math.max(0, Number(params.graceMinutes ?? 30)); + const graceMs = grace * 60 * 1000; + // ⚠️ 取**全部**待审(不按宽限期筛):宽限期只用于"对方查不到 ⇒ 判孤儿", + // 而"对方仍是 pending 但值变了 ⇒ 刷新为最新"对任何年龄的行都安全(对方列表是权威)。 + const pendingRows = await pool.query( + `SELECT * FROM public.main_system_actual_qty_requests + WHERE branch_code = $1 AND status = 'pending' + ORDER BY created_at`, + [branchCode] + ); + + let closed = 0; + let refreshed = 0; + let kept = 0; + for (const row of pendingRows.rows) { + const theirs = theirStatus.get(String(row.request_id)); + if (theirs && theirs.status === 'pending') { + /** + * 主系统"未处理就原地更新为最新" ⇒ 对账把最新值同步进我方待审行, + * 免得页面/决策基于旧值(webhook 漏推时这是唯一自愈通道)。 + */ + const changed = + !sameNumber(row.proposed_value, theirs.proposedValue) || + String(row.unit ?? '') !== String(theirs.unit ?? '') || + !sameInstant(row.applied_at, theirs.appliedAt) || + // 版本变了必须同步:审核回执要带最新版本,否则对方会判 409 stale + (theirs.requestVersion !== null && num(row.request_version) !== theirs.requestVersion); + if (!changed) { + kept += 1; + continue; + } + const res = await pool.query( + `UPDATE public.main_system_actual_qty_requests + SET proposed_value = $3, unit = $4::text, applied_at = $5::timestamptz, + request_version = COALESCE($9::int, request_version), + request_updated_at = COALESCE($10::timestamptz, request_updated_at), + payload = COALESCE(payload, '{}'::jsonb) + || jsonb_build_object( + 'reconcile_refresh', jsonb_build_object( + 'at', NOW(), 'from_value', $6::numeric, 'from_unit', $7::text, + 'to_value', $3::numeric, 'to_unit', $4::text, 'prev_applied_at', $8::timestamptz + ) + ) + || jsonb_build_object( + 'refresh_history', + COALESCE(payload->'refresh_history', '[]'::jsonb) || jsonb_build_array( + jsonb_build_object( + 'at', NOW(), 'from_value', $6::numeric, 'from_unit', $7::text, + 'to_value', $3::numeric, 'to_unit', $4::text, 'source', 'reconcile' + ) + ) + ), + updated_at = NOW() + WHERE branch_code = $1 AND id = $2::uuid AND status = 'pending'`, + [ + branchCode, + row.id, + theirs.proposedValue, + theirs.unit, + theirs.appliedAt, + row.proposed_value, + row.unit, + row.applied_at, + theirs.requestVersion, + theirs.requestUpdatedAt, + ] + ); + if (res.rowCount) { + refreshed += 1; + await writeAuditLog({ + operatorId: null, + operatorRole: 'system_reconcile', + operationType: 'main_system_actual_qty_request_reconcile_refreshed', + targetTable: 'main_system_actual_qty_requests', + targetId: row.id, + oldValue: { proposed_value: row.proposed_value, unit: row.unit, applied_at: row.applied_at }, + newValue: { proposed_value: theirs.proposedValue, unit: theirs.unit, applied_at: theirs.appliedAt }, + branchCode, + actionCategory: 'order', + }).catch(() => undefined); + } else { + kept += 1; + } + continue; + } + let nextStatus: ActualQtyInboxRow['status']; + let reason: string; + let decidedAt: string; + if (theirs) { + nextStatus = DECIDED_TERMINAL[theirs.status] ?? 'superseded'; + reason = `对账关闭:主系统侧已是 ${theirs.status}${theirs.message ? `(${theirs.message})` : ''}`; + decidedAt = theirs.decidedAt || new Date().toISOString(); + } else { + if (pulled.truncated) { + // 拉取不完整 ⇒ 不得把"没看到"当成"对方没有" + kept += 1; + continue; + } + const createdMs = new Date(String(row.created_at)).getTime(); + if (Number.isFinite(createdMs) && Date.now() - createdMs < graceMs) { + // 还在宽限期内:webhook 可能仍在路上,先不动 + kept += 1; + continue; + } + nextStatus = 'superseded'; + reason = '对账关闭:主系统侧已无此申请(历史遗留或已被清理)'; + decidedAt = new Date().toISOString(); + } + const res = await pool.query( + `UPDATE public.main_system_actual_qty_requests + SET status = $3, decided_at = $4, decision_reason = $5, + payload = COALESCE(payload, '{}'::jsonb) || jsonb_build_object( + 'reconcile', jsonb_build_object('at', NOW(), 'main_status', $6::text, 'reason', $5::text) + ), + updated_at = NOW() + WHERE branch_code = $1 AND id = $2::uuid AND status = 'pending'`, + [branchCode, row.id, nextStatus, decidedAt, reason, theirs?.status ?? null] + ); + if (res.rowCount) { + closed += 1; + await writeAuditLog({ + operatorId: null, + operatorRole: 'system_reconcile', + operationType: `main_system_actual_qty_request_reconciled_${nextStatus}`, + targetTable: 'main_system_actual_qty_requests', + targetId: row.id, + oldValue: { status: 'pending', request_id: row.request_id }, + newValue: { status: nextStatus, reason, main_status: theirs?.status ?? null }, + branchCode, + actionCategory: 'order', + }).catch(() => undefined); + } + } + + return { + pulled: pulled.rows.length, + checked: pendingRows.rowCount || 0, + closed, + refreshed, + kept, + truncated: pulled.truncated, + }; } export type DecideOutcome = { @@ -217,6 +1063,71 @@ export type DecideOutcome = { * · `rejected`:**什么都不改**(核货节点连对方也不回滚——那是事实登记); * · 幂等:本地已终态 ⇒ 不再回传(`duplicate=true`)。 */ +/** + * 单行刷新(409 `stale_request_version` 专用):从主系统 Q6 只读列表把**该 request_id 的最新值** + * 拉回来覆盖我方待审行(仅当对方仍是 pending),并返回是否刷新成功。 + * + * 为什么不用整轮 `reconcilePendingActualQtyRequests`:那个会顺带把"对方查不到"的待审行判成孤儿关闭, + * 拿它当"审核失败后的副作用"太危险(宽限期内也不该关)。这里只碰**这一行**。 + */ +async function refreshOnePendingRowFromMainSystem(params: { + branchCode: string; + row: ActualQtyInboxRow; +}): Promise { + const pulled = await listMainSystemRequests(params.branchCode, { kind: 'actual_qty', limit: 200 }); + if (pulled.kind !== 'ok') return false; + const theirs = pulled.rows.find((r) => String(r.requestId) === String(params.row.request_id)); + if (!theirs) return false; + const res = await pool.query( + `UPDATE public.main_system_actual_qty_requests + SET proposed_value = $3, unit = $4::text, applied_at = $5::timestamptz, + request_version = COALESCE($6::int, request_version), + request_updated_at = COALESCE($7::timestamptz, request_updated_at), + payload = COALESCE(payload, '{}'::jsonb) + || jsonb_build_object( + 'reconcile_refresh', jsonb_build_object( + 'at', NOW(), 'from_value', $8::numeric, 'from_unit', $9::text, + 'to_value', $3::numeric, 'to_unit', $4::text, 'source', 'stale_409' + ) + ) + || jsonb_build_object( + 'refresh_history', + COALESCE(payload->'refresh_history', '[]'::jsonb) || jsonb_build_array( + jsonb_build_object( + 'at', NOW(), 'from_value', $8::numeric, 'from_unit', $9::text, + 'to_value', $3::numeric, 'to_unit', $4::text, 'source', 'stale_409' + ) + ) + ), + updated_at = NOW() + WHERE branch_code = $1 AND id = $2::uuid AND status = 'pending'`, + [ + params.branchCode, + params.row.id, + theirs.proposedValue, + theirs.unit, + theirs.appliedAt, + theirs.requestVersion ?? null, + theirs.requestUpdatedAt ?? null, + params.row.proposed_value, + params.row.unit, + ] + ); + if (!res.rowCount) return false; + await writeAuditLog({ + operatorId: null, + operatorRole: 'system_reconcile', + operationType: 'main_system_actual_qty_request_stale_refreshed', + targetTable: 'main_system_actual_qty_requests', + targetId: params.row.id, + oldValue: { proposed_value: params.row.proposed_value, unit: params.row.unit, request_version: params.row.request_version }, + newValue: { proposed_value: theirs.proposedValue, unit: theirs.unit, request_version: theirs.requestVersion ?? null }, + branchCode: params.branchCode, + actionCategory: 'order', + }).catch(() => undefined); + return true; +} + export async function decideActualQtyRequest(params: { branchCode: string; rowId: string; @@ -239,20 +1150,52 @@ export async function decideActualQtyRequest(params: { // 对方已先落库的事实登记(核货):驳回只改我们的台账结论,不让对方回滚 const decidedAt = new Date().toISOString(); - const finalValue = - params.decision === 'approved' - ? (params.finalValue ?? num(row.proposed_value)) + /** + * ⚠️ **不要用我们台账里的旧值兜底**(2026-10-12 定稿):主系统对未处理的申请是"原地刷新为最新", + * 我方台账可能落后一步;若把本地 `proposed_value` 当 `final_value` 回传,就会**用旧值覆盖新值**。 + * ⇒ 审核人**没手填值**时回传 `null`,让主系统按**它当前**的值落地;本地落值改用**回执返回的** `final_value`。 + */ + const requestedFinalValue = + params.decision === 'approved' && params.finalValue !== null && params.finalValue !== undefined + ? Number(params.finalValue) : null; + const finalValue = requestedFinalValue; - const sent = await postMainSystemActualQtyDecision({ - supplierCode: branchCode, - requestId: String(row.request_id), - decision: params.decision, - finalValue: typeof finalValue === 'number' ? finalValue : null, - reviewer: params.reviewer ?? null, - decidedAt, - reason: params.reason ?? null, - }); + /** + * **本地事实行**(`payload.local_only=true`):由 `preparations.price_changed` 事实补建的待审行 + * (对方只推了事实、没给可审的 `request_id`)⇒ 没有东西要回传给它,直接走本地落值。 + * 语义完全吻合开发者口径:「驳回 = 我方自己不改而已,而不是还得去改主系统的成本价」。 + */ + const isLocalOnly = Boolean((row.payload as Record | null)?.local_only); + const sent = isLocalOnly + ? ({ kind: 'ok', applied: false, finalValue: null, message: '本地事实行(对方已生效),无需回执' } as const) + : await postMainSystemActualQtyDecision({ + supplierCode: branchCode, + requestId: String(row.request_id), + decision: params.decision, + finalValue: typeof finalValue === 'number' ? finalValue : null, + reviewer: params.reviewer ?? null, + decidedAt, + reason: params.reason ?? null, + // 乐观并发校验:把我方审核所依据的版本原样回带;对方不一致 ⇒ 409 stale_request_version + decidedBasisVersion: row.request_version ?? null, + }); + if (sent.kind === 'stale') { + /** + * 对方台账在我方审核期间被**原地刷新**(值/版本已变),它**不写任何值** ⇒ + * 我方也**不得**用旧值落我方库,先把最新值拉回来刷新本行,再让审核人重新确认。 + * (开发者 2026-10-12 定稿提示语:"该申请已被主系统更新为最新值,已刷新,请重新确认"。) + */ + const refreshed = await refreshOnePendingRowFromMainSystem({ branchCode, row }); + return { + status: 'suspended', + reason: refreshed + ? '该申请已被主系统更新为最新值,已刷新,请重新确认' + : `主系统已把该申请更新为最新(${sent.reason}),请刷新后重新确认`, + requestRowId: row.id, + duplicate: false, + }; + } if (sent.kind !== 'ok') { return { status: 'suspended', @@ -270,13 +1213,18 @@ export async function decideActualQtyRequest(params: { */ let applyNote: string | null = null; let applyStatus: string | null = null; + /** 落值以**主系统回执的最终值**为准(它才是真正生效的那个值) */ + const appliedValue = + typeof sent.finalValue === 'number' && Number.isFinite(sent.finalValue) + ? sent.finalValue + : requestedFinalValue ?? num(row.proposed_value); if (params.decision === 'approved' && row.our_order_code) { const applyOutcome = await applyActualQtySyncValue({ branchCode, ourOrderCode: String(row.our_order_code), prepId: row.prep_id ? String(row.prep_id) : null, field: row.field, - finalValue: typeof finalValue === 'number' ? finalValue : null, + finalValue: appliedValue, unit: row.unit, requestRowId: String(row.id), reviewer: params.reviewer ?? null, @@ -287,6 +1235,9 @@ export async function decideActualQtyRequest(params: { applyNote = '未关联到本系统订单(台账无对照),本次只回执、未落值'; applyStatus = 'failed'; } + if (isLocalOnly && applyNote === null) { + applyNote = '本地事实行:只改我方自己的记录,不回传主系统(对方已生效)'; + } await pool.query( `UPDATE public.main_system_actual_qty_requests @@ -300,7 +1251,7 @@ export async function decideActualQtyRequest(params: { branchCode, row.id, params.decision, - finalValue, + appliedValue, params.reviewer ?? null, decidedAt, params.reason ?? null, @@ -337,7 +1288,7 @@ export async function decideActualQtyRequest(params: { status: 'done', reason: params.decision === 'approved' - ? `已同步到本系统(最终值 ${finalValue ?? '—'})${applyNote ? `|${applyNote}` : ''}` + ? `已同步到本系统(最终值 ${appliedValue ?? '—'})${applyNote ? `|${applyNote}` : ''}` : row.fact_registered ? '已驳回(对方为事实登记,不回滚;我方不做修改,仅留痕)' : '已驳回(双方均不改值)', diff --git a/server/src/services/mainSystemOrderImport.ts b/server/src/services/mainSystemOrderImport.ts index 5489d9c..0bbfa97 100644 --- a/server/src/services/mainSystemOrderImport.ts +++ b/server/src/services/mainSystemOrderImport.ts @@ -26,6 +26,8 @@ import { import { followMainSystemPrepChanges } from './mainSystemReturnFollow'; import { retryPendingWritebacksForBranch } from './mainSystemWriteback'; import { refreshInFlightActualFactsForBranch } from './mainSystemActualFacts'; +import { reconcilePendingActualQtyRequests } from './mainSystemActualQtyInbox'; +import { reconcileOurPriceQtyRequestsWithMainSystem } from './mainSystemPriceQtyRequest'; import { reconcileFulfillmentFromPull, retryPendingFulfillmentEvents, @@ -1480,6 +1482,41 @@ export async function importMainSystemOrdersForAllSupplierBranches(): Promise<{ (fulfillError as Error)?.message || fulfillError ); } + // 实收申请台账的对账兜底(2026-10-12):用 Q6 只读接口核对我方待审行 —— + // webhook 漏推/结果事件没到达时,把"对方已终态/已无此申请"的历史 pending 关掉, + // 否则审核页会一直挂着永远不会被审的行。失败只日志。 + try { + const rec = await reconcilePendingActualQtyRequests({ branchCode }); + if (rec.closed > 0 || rec.kept > 0) { + console.log( + `[main-system-actual-qty] ${branchCode}:对账 拉取 ${rec.pulled} / 待审 ${rec.checked} ⇒ 关闭 ${rec.closed} / 刷新 ${rec.refreshed} / 保留 ${rec.kept}` + + (rec.truncated ? '(⚠️ 拉取被截断,未判孤儿)' : '') + + (rec.reason ? `(${rec.reason})` : '') + ); + } + } catch (reconcileError: unknown) { + console.error( + `[main-system-actual-qty] ${branchCode} 申请台账对账异常:`, + (reconcileError as Error)?.message || reconcileError + ); + } + // **我方发起**的价/量申请对账(2026-10-12):他们不推"请求被刷新"的事件, + // 靠 Q6 把终态落地(复用决策事件处理器)、把 pending 的最新申请值刷进我方台账。 + try { + const recOur = await reconcileOurPriceQtyRequestsWithMainSystem({ branchCode }); + if (recOur.closed > 0 || recOur.refreshed > 0) { + console.log( + `[main-system-price-qty] ${branchCode}:我方申请对账 拉取 ${recOur.pulled} / 待审 ${recOur.checked} ⇒ 落地 ${recOur.closed} / 刷新 ${recOur.refreshed} / 保留 ${recOur.kept}` + + (recOur.truncated ? '(⚠️ 拉取被截断)' : '') + + (recOur.reason ? `(${recOur.reason})` : '') + ); + } + } catch (recOurError: unknown) { + console.error( + `[main-system-price-qty] ${branchCode} 我方申请对账异常:`, + (recOurError as Error)?.message || recOurError + ); + } // 核货/入库事实的定时兜底(2026-10-11):主系统"等量核货"不发事件, // 详情页的「核货完毕」标记只能靠拉。这里每轮给在飞单刷一次(最多 10 单),失败只日志。 try { diff --git a/server/src/services/mainSystemPriceQtyRequest.ts b/server/src/services/mainSystemPriceQtyRequest.ts index 34ad845..0e64634 100644 --- a/server/src/services/mainSystemPriceQtyRequest.ts +++ b/server/src/services/mainSystemPriceQtyRequest.ts @@ -2,6 +2,7 @@ import { randomUUID } from 'crypto'; import { pool } from '../db'; import { runWithTenantDataAccess } from './tenantSchemaService'; import { runWithTenantDbContext } from './tenantDbContext'; +import { listMainSystemRequests } from './mainSystem/api/preparations'; import { MAIN_SYSTEM_AMEND_STATUS, fetchMainSystemPriceAmendRows, @@ -104,6 +105,11 @@ export function assertMainSystemPriceQtyReviewed(params: { if (params.approved) return; if (!params.isMainSystemOrder || !params.changes.length) return; if (!isEnabled()) return; + /** + * 2026-10-12 口径:**先改后通知** ⇒ 不再抛错拦人;由调用方在写库**之后**调用 + * `notifyMainSystemPriceQtyChanges` 异步通知主系统(对方同意/驳回都不改我方值)。 + */ + if (isPriceQtyLocalFirst()) return; const detail = params.changes .slice(0, 5) .map((c) => `${c.itemName}(${c.field === 'price' ? '价格' : '数量'} ${c.from} → ${c.to})`) @@ -117,6 +123,104 @@ export function assertMainSystemPriceQtyReviewed(params: { ); } +/** + * **先改后通知**总口径(2026-10-12 开发者定稿): + * + * 实收数量/单位与销售价一律遵循「**自己只能改自己的**」—— + * · 我方改**我方**字段(销售价 / 数量)⇒ **本地立即生效**(改了就是改了,含金额/毛利/看板/结算), + * **随后异步通知**主系统,由它决定是否让自己的值跟着变;它同意或驳回**都不影响我方已生效的值**; + * · 对方改**对方**字段 ⇒ 它先生效再发请求,我方决定是否同步自己的(见 `mainSystemActualQtyInbox`)。 + * + * 因此本模块内两处旧行为被反转: + * 1. `assertMainSystemPriceQtyReviewed` 不再拦截改价/改量(改为**通知**,见 `notifyMainSystemPriceQtyChanges`); + * 2. `submitPriceQtyRequest` 的"免审⇒本地落地"与 `decidePriceQtyRequest` 的"按其结论覆盖我方值"都**关掉** + * —— 本地值由**发起改动的那个入口**写,主系统的结论只记台账 + 留痕(价格不一致时只记录、不提醒)。 + * + * 置 `false` 可整体回退到 2026-10-11 的"先审后改"(仅用于线上异常回退,回退前请先确认没有在途 pending)。 + */ +let priceQtyLocalFirst = true; + +/** 当前是否"先改后通知"口径(默认 true;见上面的说明) */ +export function isPriceQtyLocalFirst(): boolean { + return priceQtyLocalFirst; +} + +/** + * 仅供测试:切换口径开关。 + * 保留旧"先审后改"路径的实现与其既有测试(回退时仍可用),默认不被生产代码调用。 + */ +export function __setPriceQtyLocalFirstForTests(value: boolean): void { + priceQtyLocalFirst = value; +} + +/** 读我方订单行当前的价/量(用于"主系统结论 vs 我方实际值"的差异留痕) */ +async function readOurOrderItemPriceQty(params: { + branchCode: string; + ourOrderCode: string; + ourOrderItemId: string; +}): Promise<{ price: number | null; quantity: number | null } | null> { + const rows = await runWithTenantDbContext(params.branchCode, () => + pool.query<{ price: string | number | null; quantity: string | number | null }>( + `SELECT price, quantity FROM order_items WHERE order_code = $1 AND id = $2::uuid LIMIT 1`, + [params.ourOrderCode, params.ourOrderItemId] + ) + ); + const row = rows.rows[0]; + if (!row) return null; + return { price: num(row.price), quantity: num(row.quantity) }; +} + +/** + * **通知**主系统:我方已经把价/量改了(先改后通知,2026-10-12 口径)。 + * + * 与旧 `assertMainSystemPriceQtyReviewed` 的关系:那个是**拦截**;本函数是**事后通知**。 + * 调用时机:调用方的**本地写入提交之后**(本函数异步执行,失败只记台账 + 日志,绝不回滚本地值)。 + * + * 逐条变更发一条申请(价/量分开,主系统按 `field` 归行);每条独立成败,互不影响。 + * 失败/未就绪时台账落 `failed`(带原因),由对账兜底或人工重发;**我方值保持已改后的值**。 + */ +export function notifyMainSystemPriceQtyChanges(params: { + branchCode: string; + ourOrderCode: string; + changes: PriceQtyChange[]; + actor: PriceQtyActor; + reason?: string | null; +}): void { + if (!isEnabled() || !isPriceQtyLocalFirst()) return; + const changes = Array.isArray(params.changes) ? params.changes : []; + if (!changes.length) return; + for (const change of changes) { + const isPrice = change.field === 'price'; + void submitPriceQtyRequest({ + branchCode: params.branchCode, + ourOrderCode: params.ourOrderCode, + ourOrderItemId: change.itemId, + proposedPrice: isPrice ? change.to : null, + proposedQty: isPrice ? null : change.to, + // **改动前**的值由调用方给出:此刻库里已是新值(COMMIT 之后才通知),回表必然读到新值 + beforePrice: isPrice ? change.from : undefined, + beforeQty: isPrice ? undefined : change.from, + reason: params.reason || (isPrice ? '订单明细改销售价(先改后通知)' : '订单明细改数量(先改后通知)'), + actor: params.actor, + }) + .then((outcome) => { + if (outcome.kind !== 'ok') { + const reason = (outcome as { reason?: string }).reason || outcome.kind; + console.error( + `[price-qty-notify] ${params.branchCode} ${params.ourOrderCode} ${change.itemName} 通知主系统失败(本地值已生效,不回滚):`, + reason + ); + } + }) + .catch((error: unknown) => { + console.error( + `[price-qty-notify] ${params.branchCode} ${params.ourOrderCode} ${change.itemName} 通知异常(本地值已生效,不回滚):`, + (error as Error)?.message || error + ); + }); + } +} + /* ── 行解析:本系统订单行 ↔ 主系统备货行 ───────────────────────────────────── */ export type MainSystemLineRef = { @@ -560,6 +664,17 @@ export async function submitPriceQtyRequest(params: { reason?: string | null; actor: PriceQtyActor; clientRequestId?: string; + /** + * **改动前**的值(可选,但"先改后通知"路径**必须**传)。 + * + * 为什么必须:本函数默认从**当前**订单行读 before 值来判"值有没有变"。 + * local-first 下调用方是**先写完库、COMMIT 之后**才通知的 —— 此刻库里已经是**新值**, + * 默认读法会得到 `before == proposed` ⇒ 判 `no_change` **根本不通知**, + * 台账 `before_*` 也会记成新值(发给主系统的 `before_value` 同样错)。 + * 实测复现(2026-10-12 E2E):改价 8.30 → 9.10 后通知,主系统端完全收不到(我方值照常生效 ⇒ 静默漏发)。 + */ + beforePrice?: number | null; + beforeQty?: number | null; }): Promise { if (!isEnabled()) { return { @@ -582,8 +697,15 @@ export async function submitPriceQtyRequest(params: { ) ); if (!current.rowCount) return { kind: 'invalid', reason: '订单行不存在' }; - const beforePrice = num(current.rows[0].price); - const beforeQty = num(current.rows[0].quantity); + // ⚠️ before 的取值口径见 params 注释:local-first 下库里已是新值,必须用调用方给的旧值。 + const beforePrice = + params.beforePrice !== undefined && params.beforePrice !== null + ? num(params.beforePrice) + : num(current.rows[0].price); + const beforeQty = + params.beforeQty !== undefined && params.beforeQty !== null + ? num(params.beforeQty) + : num(current.rows[0].quantity); const itemName = current.rows[0].item_name ? String(current.rows[0].item_name) : ''; const proposedPrice = num(params.proposedPrice); @@ -783,6 +905,7 @@ export async function submitPriceQtyRequest(params: { outcome.message, JSON.stringify({ submit: outcome.raw ?? null, + mode: isPriceQtyLocalFirst() ? 'notify_only' : 'review_gated', replaced_pending: replaced.rowCount || 0, // 已决/未决字段留痕:对账与排障时一眼看清哪一项已生效、哪一项在审 decided_kinds: [appliedPrice !== null ? 'price' : null, appliedQty !== null ? 'qty' : null].filter(Boolean), @@ -794,7 +917,12 @@ export async function submitPriceQtyRequest(params: { let appliedLocally = false; let applyNote: string | null = null; - if (hasAppliedPart) { + /** + * ⚠️ 2026-10-12 口径:**先改后通知** ⇒ 我方值由**发起改动的入口**写, + * 这里不再按主系统结论写我们的库(否则会出现"两个写入者 + 谁后写谁赢")。 + * 主系统"免审已生效"仅作为**通知已送达**的凭据记录在台账上。 + */ + if (hasAppliedPart && !isPriceQtyLocalFirst()) { // ⚠️ 一致性红线:主系统**已经生效**,本地必须跟上;落地失败时**不能让台账停在终态** // (否则对账不再重试 ⇒ "主系统变了、我方没变"永久存在)。失败就把台账退回 pending 等待重试, // 并把原因写进 decision_reason + 操作日志,前端按 applied_locally=false 提示"本地待同步"。 @@ -1066,6 +1194,69 @@ export async function decidePriceQtyRequest(params: { }; } + /** + * ⚠️ 2026-10-12 口径:**自己只能改自己的** ⇒ 主系统对我方申请的结论(通过/改值后通过) + * **不再覆盖我方已生效的值**,只记台账 + 留痕;若它的最终值与我方当前值不同, + * 记一条 `divergence` 痕迹(开发者选择"允许不一致,只留痕不提醒")。 + */ + if (isPriceQtyLocalFirst()) { + const current = await readOurOrderItemPriceQty({ + branchCode: row.branch_code, + ourOrderCode: row.our_order_code, + ourOrderItemId: String(row.our_order_item_id), + }).catch(() => null); + const priceDiffers = + finalPrice !== null && current?.price !== null && Math.abs(Number(current?.price) - finalPrice) > 1e-9; + const qtyDiffers = + finalQty !== null && current?.quantity !== null && Math.abs(Number(current?.quantity) - finalQty) > 1e-9; + await pool.query( + `UPDATE public.main_system_price_qty_requests + SET payload = COALESCE(payload, '{}'::jsonb) || jsonb_build_object( + 'local_first', jsonb_build_object( + 'at', NOW(), 'decision', $2::text, 'final_price', $3::numeric, 'final_qty', $4::numeric, + 'our_price', $5::numeric, 'our_quantity', $6::numeric, + 'divergence', $7::boolean + ) + ), + updated_at = NOW() + WHERE id = $1::uuid`, + [ + row.id, + String(targetStatus), + finalPrice, + finalQty, + current?.price ?? null, + current?.quantity ?? null, + Boolean(priceDiffers || qtyDiffers), + ] + ); + await writePriceQtyAuditLog({ + branchCode: row.branch_code, + actor, + operationType: priceDiffers || qtyDiffers + ? 'main_system_price_qty_decision_diverged' + : 'main_system_price_qty_decision_recorded', + row, + oldValue: { price: current?.price ?? null, quantity: current?.quantity ?? null }, + newValue: { + decision: targetStatus, + final_price: finalPrice, + final_qty: finalQty, + divergence: Boolean(priceDiffers || qtyDiffers), + source: params.source, + }, + }); + return { + status: 'done', + reason: + priceDiffers || qtyDiffers + ? `已记录主系统结论(${targetStatus});其最终值与我方当前值不同,按"自己只能改自己的"**不覆盖我方值**(留痕)` + : `已记录主系统结论(${targetStatus});与我方当前值一致`, + requestRowId: row.id, + duplicate: false, + }; + } + let applied: { changed: boolean; reason: string }; try { applied = await applyFinalPriceQtyToOurOrderItem({ @@ -1158,6 +1349,224 @@ export async function decidePriceQtyRequest(params: { /* ── webhook 接收(C3)──────────────────────────────────────────────────── */ +export type OurRequestReconcileOutcome = { + pulled: number; + checked: number; + closed: number; + refreshed: number; + kept: number; + truncated: boolean; + reason?: string; +}; + +/** + * 主系统申请行状态 → 我方决策事件的 `decision`。 + * + * ⚠️ 决策事件处理器只认 `approved` / `rejected` / `applied`(`withdrawn`/`superseded` 会被忽略), + * 所以"对方作废/撤回"映射为 **rejected + 写明原因**(`payload.decided_event.status` 留存真实状态), + * 避免出现"对账把行标成已关、实际没落地"的假成功。 + */ +const OUR_REQUEST_TERMINAL: Record = { + approved: { decision: 'approved', label: 'approved' }, + applied: { decision: 'approved', label: 'applied' }, + rejected: { decision: 'rejected', label: 'rejected' }, + superseded: { decision: 'rejected', label: 'superseded' }, + withdrawn: { decision: 'rejected', label: 'withdrawn' }, +}; + +/** + * **我方发起**的价/量申请:用 Q6 只读接口与主系统对账(2026-10-12,开发者要求补齐反方向)。 + * + * 为什么需要:我方第二次提交同一 prep 行的改动会**原地刷新他们那条 pending**(唯一键 `(preparation_id, kind, field)`), + * 但他们**不会**为"请求被刷新"推事件;若 `price_qty_decided` 漏推,我方台账会一直挂着 `pending`。 + * + * 判定(保守): + * · 对方侧该 `request_id` 已终态 ⇒ **复用** `handlePriceQtyDecidedEvent`(按 Q6 行合成载荷)落地结论,幂等; + * · 对方侧仍是 `pending` 但 `proposed_value` 变了 ⇒ 刷新我方待审行的申请值(只动我们自己的视图); + * · 对方侧查不到 ⇒ 且拉取未截断、且超过宽限期 ⇒ 置 `failed`(理由"主系统侧已无此申请"),交人工。 + */ +export async function reconcileOurPriceQtyRequestsWithMainSystem(params: { + branchCode: string; + graceMinutes?: number; + limit?: number; +}): Promise { + const branchCode = String(params.branchCode || '').trim(); + const empty: OurRequestReconcileOutcome = { + pulled: 0, + checked: 0, + closed: 0, + refreshed: 0, + kept: 0, + truncated: false, + }; + if (!branchCode) return { ...empty, reason: '缺少分公司' }; + + const pulled = await listMainSystemRequests(branchCode, { limit: params.limit }); + if (pulled.kind !== 'ok') return { ...empty, reason: pulled.reason }; + + type TheirRequestState = { + kind: string; + status: string; + proposed: number | null; + final: number | null; + decidedAt: string | null; + reviewer: string | null; + message: string | null; + orderCode: string | null; + skuCode: string | null; + }; + const theirs = new Map( + pulled.rows + // ⚠️ **只认同链**:`actual_qty` 链的 request_id 不得被当成我方价/量申请的对端 + //(两条链的台账不同,按 id 硬套会把核货量写成价格)。kind 必须是 price / qty。 + .filter((row) => row.requestId && (row.kind === 'price' || row.kind === 'qty')) + .map((row): [string, TheirRequestState] => [ + row.requestId, + { + kind: row.kind, + status: row.status, + proposed: row.proposedValue, + final: row.finalValue, + decidedAt: row.decidedAt, + reviewer: row.reviewedBy, + message: row.message, + orderCode: row.orderCode, + skuCode: row.skuCode, + }, + ]) + ); + + // ⚠️ 我方价/量申请台账在 **public**(`public.main_system_price_qty_requests`), + // 2026-10-12 核查发现首版误写成 `supplier_price_qty_requests`(本库无此表)⇒ 整段对账静默失效。 + const pendingRows = await pool.query<{ + id: string; + request_id: string | null; + kind: string; + proposed_price: string | number | null; + proposed_qty: string | number | null; + created_at: string; + }>( + `SELECT id::text AS id, request_id, kind, proposed_price, proposed_qty, created_at + FROM public.main_system_price_qty_requests + WHERE branch_code = $1 AND status = 'pending' + ORDER BY created_at`, + [branchCode] + ); + + const graceMs = Math.max(0, Number(params.graceMinutes ?? 30)) * 60 * 1000; + let closed = 0; + let refreshed = 0; + let kept = 0; + + for (const row of pendingRows.rows) { + const requestId = row.request_id ? String(row.request_id) : ''; + const theirRaw = requestId ? theirs.get(requestId) : undefined; + // 对方行的 kind 必须与我方台账行一致(防跨链串行) + const their = theirRaw && theirRaw.kind === row.kind ? theirRaw : undefined; + + if (their && OUR_REQUEST_TERMINAL[their.status]) { + /** + * ⚠️ 只有 `kind ∈ {price, qty}` 才能安全复用决策事件处理器: + * 处理器用 `kind` 决定把 `final_value` 落到价还是量;`both` 行在对方侧是**按字段拆行**的, + * 单条对方行给不出两个值 ⇒ 硬套会把另一个字段写成同一个数(错账)。`both` 交人工。 + */ + if (row.kind !== 'price' && row.kind !== 'qty') { + kept += 1; + continue; + } + const mapped = OUR_REQUEST_TERMINAL[their.status]; + const terminalValue = their.final ?? their.proposed ?? null; + // 复用既有决策事件处理器:它负责落值/留痕/幂等,避免在这里另写一套 + await handlePriceQtyDecidedEvent({ + branchCode, + payload: { + request_id: requestId, + client_request_id: null, + kind: row.kind, + decision: mapped.decision, + final_value: terminalValue, + final_price: row.kind === 'price' ? terminalValue : null, + final_qty: row.kind === 'qty' ? terminalValue : null, + reviewer: their.reviewer ?? null, + reviewed_by: their.reviewer ?? null, + reason: + mapped.label === their.status + ? their.message ?? `对账落地:主系统侧已是 ${their.status}` + : `对账落地:主系统侧已${mapped.label === 'withdrawn' ? '撤回' : '作废'}(${their.status})${ + their.message ? `:${their.message}` : '' + }`, + decided_at: their.decidedAt, + source: 'reconcile', + }, + }); + closed += 1; + continue; + } + + if (their && their.status === 'pending') { + // 同理由:`both` 行在对方侧按字段拆行,单条 pending 行不足以刷新两个值 ⇒ 不动 + if (row.kind !== 'price' && row.kind !== 'qty') { + kept += 1; + continue; + } + const ours = Number(row.kind === 'price' ? row.proposed_price : row.proposed_qty); + const changed = + their.proposed !== null && + Number.isFinite(ours) && + Math.abs(ours - Number(their.proposed)) > 1e-9; + if (!changed) { + kept += 1; + continue; + } + await pool.query( + `UPDATE public.main_system_price_qty_requests + SET proposed_price = CASE WHEN kind = 'price' THEN $3::numeric ELSE proposed_price END, + proposed_qty = CASE WHEN kind = 'qty' THEN $3::numeric ELSE proposed_qty END, + payload = COALESCE(payload, '{}'::jsonb) || jsonb_build_object( + 'reconcile_refresh', jsonb_build_object( + 'at', NOW(), 'prev_value', $4::numeric, 'to_value', $3::numeric, 'kind', kind + ) + ), + updated_at = NOW() + WHERE branch_code = $1 AND id = $2::uuid AND status = 'pending'`, + [branchCode, row.id, their.proposed, ours] + ); + refreshed += 1; + continue; + } + + if (pulled.truncated) { + kept += 1; + continue; + } + const createdMs = new Date(String(row.created_at)).getTime(); + if (Number.isFinite(createdMs) && Date.now() - createdMs < graceMs) { + kept += 1; + continue; + } + await pool.query( + `UPDATE public.main_system_price_qty_requests + SET status = 'failed', decision_reason = $3, decided_at = NOW(), + payload = COALESCE(payload, '{}'::jsonb) || jsonb_build_object( + 'reconcile', jsonb_build_object('at', NOW(), 'reason', $3::text) + ), + updated_at = NOW() + WHERE branch_code = $1 AND id = $2::uuid AND status = 'pending'`, + [branchCode, row.id, '对账关闭:主系统侧已无此申请(历史遗留或已被清理)'] + ); + closed += 1; + } + + return { + pulled: pulled.rows.length, + checked: pendingRows.rowCount || 0, + closed, + refreshed, + kept, + truncated: pulled.truncated, + }; +} + export const PRICE_QTY_DECIDED_EVENT = 'preparations.price_qty_decided'; export function isPriceQtyDecidedEvent(event: unknown): boolean { @@ -1258,7 +1667,8 @@ export async function handlePriceQtyDecidedEvent(params: { reviewer: payload?.reviewer != null ? String(payload.reviewer) : null, decidedAt: payload?.decided_at != null ? String(payload.decided_at) : null, reason: payload?.reason != null ? String(payload.reason) : null, - source: 'webhook', + // 对账复用同一处理器 ⇒ 让来源如实落在台账/审计里(webhook 漏推时是靠 reconcile 补的) + source: String(payload?.source || '') === 'reconcile' ? 'poll' : 'webhook', payload, }); } diff --git a/server/src/services/orderManageItemsService.ts b/server/src/services/orderManageItemsService.ts index 378c4b3..7db246e 100644 --- a/server/src/services/orderManageItemsService.ts +++ b/server/src/services/orderManageItemsService.ts @@ -38,6 +38,7 @@ import { writeAuditLog } from './auditService'; import { assertMainSystemPriceQtyReviewed, isEnabled as isPriceQtyRequestEnabled, + notifyMainSystemPriceQtyChanges, isMainSystemAllocatedLines, type PriceQtyChange, } from './mainSystemPriceQtyRequest'; @@ -861,6 +862,8 @@ export async function syncOrderManageItems(params: { const inboundReattributeItemIds = new Set(); let existingItemsForAudit: ExistingOrderItemForAudit[] = []; const client = await connectExclusiveTenantClient(); + /** 先改后通知:本次明细保存中被改动的"主系统行"价/量变更(COMMIT 后异步通知主系统) */ + let priceQtyNotices: ReturnType = []; try { await client.query('BEGIN'); @@ -967,11 +970,15 @@ export async function syncOrderManageItems(params: { } } - // 主系统分配过来的订单:**改价/改量要走申请**(开发者 2026-10-11 口径)。 - // 为什么拦在服务层:改明细有 5 个入口(Web / 小程序 ×3 / MCP),只在界面分流会被绕过; - // 免审项(补价、改低、减量)在申请入口提交后立即生效,涨价/加量等主系统管理员审核。 - // 开关关闭时(默认)本守卫直接放行 ⇒ 与改造前逐字节一致。 - // 已审核/免审的落地路径传 `params.mainSystemPriceQtyApproved = true` 放行。 + // 主系统分配过来的订单:**改价/改量统一"先改后通知"**(开发者 2026-10-12 口径)。 + // 为什么放在服务层:改明细有 5 个入口(Web / 小程序 ×3 / MCP),只在界面处理会被绕过; + // 这里的职责是"收集变更 → 照常写库 → COMMIT 之后异步通知主系统",不拦人。 + // 开关关闭时(默认)直接放行 ⇒ 与改造前逐字节一致(也不通知)。 + /** + * ⚠️ 2026-10-12 口径:**先改后通知** —— 守卫已改为"放行"(`assertMainSystemPriceQtyReviewed` + * 在 local-first 下直接 return),真正的动作变成**写完库之后异步通知主系统**(见下方 notify)。 + * 这里保留收集逻辑:既用于通知,也用于审计留痕。 + */ if (!params.mainSystemPriceQtyApproved && isPriceQtyRequestEnabled()) { const changes = collectMainSystemPriceQtyChanges(existingMap, incoming); if (changes.length) { @@ -992,6 +999,8 @@ export async function syncOrderManageItems(params: { isMainSystemOrder: true, changes: changes.filter((change) => guarded.has(change.itemId)), }); + // local-first:守卫不拦,改为"写库后通知主系统" + priceQtyNotices = changes.filter((change) => guarded.has(change.itemId)); } } @@ -1604,6 +1613,24 @@ export async function syncOrderManageItems(params: { client.release(); } + /** + * **先改后通知**(2026-10-12 口径):明细写入已 COMMIT ⇒ 现在**异步通知**主系统我方改了价/量。 + * 非阻塞、失败不改我方值;主系统的同意/驳回都不回改我方(只留痕)。 + */ + if (priceQtyNotices.length) { + notifyMainSystemPriceQtyChanges({ + branchCode: order.branch_code || '', + ourOrderCode: orderCode, + changes: priceQtyNotices, + actor: { + userId: params.operatorId ?? null, + roles: params.operatorRoles ?? null, + requestedBy: params.operatorId ?? null, + }, + reason: '订单明细改价/改量(先改后通知)', + }); + } + const allocateNewRowsAtStatus50 = orderStatus === 50 && (params.purchaserDirectAllocation diff --git a/server/src/services/purchaseLinkedSalePriceService.ts b/server/src/services/purchaseLinkedSalePriceService.ts index 3c098c3..0841297 100644 --- a/server/src/services/purchaseLinkedSalePriceService.ts +++ b/server/src/services/purchaseLinkedSalePriceService.ts @@ -115,9 +115,10 @@ export async function writeOrderItemSalePrice( throw Object.assign(new Error('关联订单明细不存在'), { status: 404, code: 'not_found' }); } - // 跨系统改价审核守卫(2026-10-11):主系统分配过来的订单行,销售价(= 主系统成本价)的改动 - // 必须走申请入口。这里是最容易被绕过的写点(裸 UPDATE,不经改明细服务)。 - // 开关关闭(默认)时直接放行 ⇒ 与改造前逐字节一致。 + // 跨系统改价通知(2026-10-12):主系统分配过来的订单行,销售价(= 主系统成本价)的改动 + // **本地照常写入**,只额外**通知**主系统一起变("自己只能改自己的 / 改了就是改了")。 + // 这里是最容易被绕过的写点(裸 UPDATE,不经改明细服务),所以通知也放在这里发。 + // 开关关闭(默认)时直接放行 ⇒ 与改造前逐字节一致(不通知)。 if (!input.priceQtyApproved && isPriceQtyRequestEnabled()) { const oldPrice = Number(before.rows[0].price) || 0; if (Math.abs(oldPrice - input.salePrice) > 1e-6) { @@ -129,21 +130,23 @@ export async function writeOrderItemSalePrice( ); if (mainSystemOrder.rowCount) { /** - * 2026-10-11 开发者定稿:**统一分流**(原来这里是直接抛错,导致"自采列表改价改不动"—— - * 自采列表没有申请分流入口,撞上守卫就只表现为"保存无效/失败")。 + * 2026-10-12 开发者定稿:**先改后通知**("改了就是改了 / 自己只能改自己的")。 * - * 现在: - * · **免审**(补价 0→正常价 / 改低 / 减量)⇒ 主系统当场生效、我方同步落地 ⇒ - * **继续走下面的原写入**(值已一致,等同幂等,调用方拿到的金额/合计仍正确); - * · **需审核**(涨价 / 加量)⇒ 提交申请、**本地价格不变**,抛一条**说明性**业务错误, - * 让界面明确显示"已提交,等待主系统审核",不再静默; - * · 提交失败/未就绪 ⇒ 同样明确报错。 + * 历史:最早这里直接抛错 ⇒ 表现为"自采列表改价改不动";随后做成"先审后改"分流, + * 又变成"我改自己的销售价还得等主系统点头"。现在统一为: + * · 命中的**主系统订单行**:仅**通知**主系统(提交改价申请 / 改量申请), + * 不论对方"免审当场生效"还是"进它的审核队列",都**不阻止**下面的本地写入; + * · 本地值**立即生效**,参与全部财务口径(金额/毛利/看板/结算); + * · 对方同意/驳回**都不回改我方值**("自己只能改自己的"),不一致只留痕、不提醒; + * · 提交失败/未就绪 ⇒ 只记日志 + 台账 failed(对账兜底 / 人工重发),**不回滚**本地值。 */ const outcome = await submitPriceQtyRequest({ branchCode: input.branchCode, ourOrderCode: input.orderCode, ourOrderItemId: input.orderItemId, proposedPrice: input.salePrice, + // 本条在**本地写入之前**调用,库里仍是旧值;仍显式传一次,语义不依赖调用顺序 + beforePrice: oldPrice, unit: before.rows[0].unit != null ? String(before.rows[0].unit) : null, reason: '自购/自采列表改销售价(自动转改价申请)', actor: { @@ -153,23 +156,20 @@ export async function writeOrderItemSalePrice( }, }).catch((e: unknown) => ({ kind: 'failed', reason: (e as Error)?.message || String(e), retryable: true } as const)); + /** + * ⚠️ 2026-10-12 口径:**先改后通知** —— 上面这次提交只是**通知**主系统, + * 不论它是"免审当场生效"还是"进它的审核队列",**都不再阻止我方本地改价**: + * 值由下面的原写入立即生效(改了就是改了,含金额/毛利/看板/结算); + * 它同意/驳回**都不回改我方**("自己只能改自己的");不一致只留痕。 + * 提交失败也不回滚本地值,只记日志 + 台账 failed(对账兜底/人工重发)。 + */ if (outcome.kind !== 'ok') { - throw Object.assign( - new Error( - `改价申请提交失败,本次未改动价格:${ - 'reason' in outcome && outcome.reason ? outcome.reason : outcome.kind - }` - ), - { status: 409, code: 'price_request_failed' } + const reason = (outcome as { reason?: string }).reason || outcome.kind; + console.error( + `[price-qty-notify] ${input.branchCode} ${input.orderCode} 自采列表改价通知主系统失败(本地值照常生效):`, + reason ); } - if (outcome.status !== 'applied') { - throw Object.assign( - new Error('已提交改价申请,等待主系统审核(本地价格暂不变动)'), - { status: 409, code: 'main_system_review_pending' } - ); - } - // 免审已生效 ⇒ 落到下面的原写入(同值幂等),保持调用方返回结构不变 } } } diff --git a/server/src/utils/deterministicUuid.ts b/server/src/utils/deterministicUuid.ts new file mode 100644 index 0000000..46a43a3 --- /dev/null +++ b/server/src/utils/deterministicUuid.ts @@ -0,0 +1,19 @@ +import { createHash } from 'node:crypto'; + +/** + * 由**业务幂等键**派生**确定性 UUID**。 + * + * 用途:主系统的 `preparations.price_changed` 是**纯事实事件**(没有 `request_id`,无法被"决策"), + * 但我方待审台账的主键/唯一键需要 UUID。用事件自带的业务幂等键 + * (`pc___`,同一行同一对新旧价恒定)派生 ⇒ **重推得到同一个 UUID** + * ⇒ "同一事实只落一行"这件事由数据库唯一键天然保证,不需要额外的去重表。 + * + * 纯函数、零依赖(便于单测;`mainSystemActualQtyInbox` 会连带初始化连接池,不能直接 import 测)。 + */ +export function deterministicUuid(seed: string): string { + const hex = createHash('sha1').update(String(seed)).digest('hex').slice(0, 32).split(''); + hex[12] = '5'; // 版本位(v5 风格,仅为形态合规) + hex[16] = ((parseInt(hex[16], 16) & 0x3) | 0x8).toString(16); // variant 位 + const h = hex.join(''); + return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20, 32)}`; +} diff --git a/server/tests/actualQtyDecidedAndReconcile.test.ts b/server/tests/actualQtyDecidedAndReconcile.test.ts new file mode 100644 index 0000000..53a5271 --- /dev/null +++ b/server/tests/actualQtyDecidedAndReconcile.test.ts @@ -0,0 +1,172 @@ +import { describe, expect, it } from 'vitest'; +import { readFileSync } from 'node:fs'; +import path from 'node:path'; + +/** + * 主系统结果事件 `preparations.actual_qty_decided` + Q6 对账兜底(2026-10-12 补,对接清单 §4.5.4)。 + * + * 背景:主系统会在申请**还没被我方审**时撤回/作废(如配送员撤销核货)⇒ 我方台账若一直 pending, + * 审核页就会拿着已失效的值让人审(实测 60 条 pending 里 58 条在对方侧已查不到)。 + * + * 钉住四件事: + * ① 事件接收端存在、四种 decision 都落终态、幂等(已终态不动); + * ② webhook 路由必须在"其它事件 200 忽略"**之前**拦下它; + * ③ Q6 客户端用 `kind=actual_qty` 只读拉取,取满即标 `truncated`; + * ④ 对账**保守**:对方仍 pending ⇒ 不动;拉取被截断 ⇒ 不判孤儿;孤儿关闭要过宽限期。 + */ +const inbox = readFileSync( + path.join(__dirname, '../src/services/mainSystemActualQtyInbox.ts'), + 'utf8' +); +const route = readFileSync( + path.join(__dirname, '../src/routes/mainSystemIntegration.ts'), + 'utf8' +); +const api = readFileSync( + path.join(__dirname, '../src/services/mainSystem/api/preparations.ts'), + 'utf8' +); +const importLoop = readFileSync( + path.join(__dirname, '../src/services/mainSystemOrderImport.ts'), + 'utf8' +); + +describe('结果事件接收端(withdrawn / superseded / approved / rejected)', () => { + it('四种决策都映射到终态,未知决策忽略', () => { + const idx = inbox.indexOf('const DECIDED_TERMINAL'); + const block = inbox.slice(idx, idx + 500); + for (const key of ['withdrawn', 'superseded', 'approved', 'rejected']) { + expect(block, `缺少 ${key} 映射`).toContain(`${key}:`); + } + expect(inbox).toMatch(/if \(!nextStatus\)/); + }); + + it('同一 request_id 未处理 ⇒ 刷新为最新;已终态 ⇒ 不覆盖只留痕(2026-10-12 定稿)', () => { + // 主系统"未处理就原地更新为最新"(唯一键 (preparation_id, kind, field) + WHERE status='pending') + expect(inbox).toMatch(/status: 'refreshed'/); + expect(inbox).toMatch(/main_system_actual_qty_request_refreshed/); + // 终态行被再次投递时只记迟到痕迹,不覆盖我方结论 + expect(inbox).toMatch(/late_event/); + expect(inbox).toMatch(/已是终态(\$\{cur\.status\}),本次不刷新/); + // 比较值/单位/生效时间,完全一致才 duplicate + expect(inbox).toMatch(/sameNumber\(cur\.proposed_value/); + expect(inbox).toMatch(/sameInstant\(cur\.applied_at/); + }); + + it('决策不回声我方旧值:未手填值回传 null,本地落值用回执返回值', () => { + expect(inbox).toMatch(/const requestedFinalValue =/); + expect(inbox).toMatch(/const appliedValue =/); + expect(inbox).toMatch(/sent\.finalValue/); + // 不得再用本地 proposed_value 兜底当回传值 + expect(inbox).not.toMatch(/params\.finalValue \?\? num\(row\.proposed_value\)/); + }); + + it('幂等 + 只关 pending(已终态不动)', () => { + expect(inbox).toMatch(/if \(row\.status !== 'pending'\)/); + expect(inbox).toMatch(/AND status = 'pending'/); + }); + + it('webhook 在"其它事件 200 忽略"之前拦下该事件', () => { + const handlerIdx = route.indexOf('event === ACTUAL_QTY_DECIDED_EVENT'); + const ignoreIdx = route.indexOf("if (event !== 'preparations.allocated')"); + expect(handlerIdx).toBeGreaterThan(-1); + expect(ignoreIdx).toBeGreaterThan(-1); + expect(handlerIdx).toBeLessThan(ignoreIdx); + expect(route).toMatch(/handleActualQtyDecidedEvent\(/); + }); +}); + +describe('Q6 只读拉取 + 对账', () => { + it('客户端按 kind 过滤、只读 GET,取满即标 truncated', () => { + expect(api).toMatch(/endpoint: 'priceQtyRequestsList'/); + expect(api).toMatch(/method: 'GET'/); + expect(api).toMatch(/truncated: rows\.length >= limit/); + }); + + it('对账:对方 pending ⇒ 值不同就刷新为最新;截断不判孤儿;孤儿需过宽限期', () => { + const idx = inbox.indexOf('export async function reconcilePendingActualQtyRequests'); + expect(idx).toBeGreaterThan(-1); + const body = inbox.slice(idx, idx + 6000); + expect(body).toMatch(/theirs\.status === 'pending'/); + expect(body).toMatch(/reconcile_refresh/); + expect(body).toMatch(/refreshed \+= 1/); + expect(body).toMatch(/if \(pulled\.truncated\)/); + expect(body).toMatch(/graceMs/); + expect(body).toMatch(/kind: 'actual_qty'/); + }); + + it('对账已挂进分配对账(每轮兜底,失败只日志)', () => { + expect(importLoop).toMatch(/reconcilePendingActualQtyRequests\(\{ branchCode \}\)/); + }); +}); + +/** + * 代码核查(2026-10-12)抓到的 4 处问题的回归钉子: + * ① 决策事件处理器只认 approved/rejected/applied ⇒ 我方申请对账不得把 withdrawn/superseded 原样传进去 + * (否则处理器忽略、行却已被计成"已关闭"= 假成功);必须映射为 rejected + 写明作废/撤回。 + * ② 我方申请对账对 `kind='both'` 必须**不动**:单条对方行给不出价/量两个值,硬套会把另一个字段写错。 + * ③ 审核页"提交前重取"必须在 `setActingId` **之前**(先置 busy 再 return 会让按钮永远停在忙碌态)。 + * ④ `actual_qty_decided` 没带 `final_value` 时不得用我方(可能过期的)proposed 兜底。 + */ +const priceQtySrc = readFileSync( + path.join(__dirname, '../src/services/mainSystemPriceQtyRequest.ts'), + 'utf8' +); +const pageSrc = readFileSync( + path.join(__dirname, '../../src/pages/orders/PriceQtyRequestsPage.tsx'), + 'utf8' +); + +describe('代码核查回归(2026-10-12)', () => { + it('① withdrawn/superseded 映射为 rejected,不原样丢给决策处理器', () => { + const idx = priceQtySrc.indexOf('const OUR_REQUEST_TERMINAL'); + const block = priceQtySrc.slice(idx, idx + 600); + expect(block).toMatch(/superseded: \{ decision: 'rejected'/); + expect(block).toMatch(/withdrawn: \{ decision: 'rejected'/); + expect(block).not.toMatch(/decision: 'superseded'/); + expect(block).not.toMatch(/decision: 'withdrawn'/); + }); + + it('② kind=both 在我方申请对账里被排除(不猜两值)', () => { + const idx = priceQtySrc.indexOf('export async function reconcileOurPriceQtyRequestsWithMainSystem'); + const body = priceQtySrc.slice(idx, idx + 6000); + const guards = body.match(/row\.kind !== 'price' && row\.kind !== 'qty'/g) || []; + expect(guards.length).toBeGreaterThanOrEqual(2); // 终态落地 + pending 刷新 各一处 + }); + + it('③ 审核页提交前重取在 setActingId 之前(不会卡住按钮)', () => { + const idx = pageSrc.indexOf('const decideInbox = async'); + const body = pageSrc.slice(idx, idx + 3000); + const refetchIdx = body.indexOf('listMainSystemActualQtyRequestsApi({ status: \'pending\''); + const busyIdx = body.indexOf('setActingId(row.id);'); + expect(refetchIdx).toBeGreaterThan(-1); + expect(busyIdx).toBeGreaterThan(-1); + expect(refetchIdx).toBeLessThan(busyIdx); + }); + + it('⑤ 我方价/量申请对账必须查 public.main_system_price_qty_requests(首版写错表名 ⇒ 整段静默失效)', () => { + const refs = priceQtySrc.match(/supplier_price_qty_requests/g) || []; + const correct = priceQtySrc.match(/main_system_price_qty_requests/g) || []; + // 只允许出现在注释里(首版误用的记录),不得再作为表名出现 + const bad = [...priceQtySrc.matchAll(/FROM\s+supplier_price_qty_requests|UPDATE\s+supplier_price_qty_requests|INTO\s+supplier_price_qty_requests/g)]; + expect(bad.length).toBe(0); + expect(correct.length).toBeGreaterThan(5); + expect(refs.length).toBeGreaterThan(0); + }); + + it('⑥ 同一 $N 不得既当 varchar 又当 text(PostgreSQL: inconsistent types deduced)', () => { + // 2026-10-12 实测:接收端刷新 unit=$8 / 对账刷新 unit=$4 / decided 事件 reviewer=$7 都踩过 + expect(inbox).toMatch(/unit = \$8::text/); + expect(inbox).toMatch(/unit = \$4::text/); + expect(inbox).toMatch(/COALESCE\(\$7::text, reviewer\)/); + expect(inbox).not.toMatch(/unit = \$8,(?!\s*$)/m); + }); + + it('④ 决策事件不带 final_value 时不写终值(不用我方 proposed 兜底)', () => { + const idx = inbox.indexOf('const finalValue = nextStatus'); + expect(idx).toBeGreaterThan(-1); + const line = inbox.slice(idx, idx + 200); + expect(line).toMatch(/num\(payload\?\.final_value\)/); + expect(line).not.toMatch(/row\.proposed_value/); + }); +}); diff --git a/server/tests/actualQtyFactSync.test.ts b/server/tests/actualQtyFactSync.test.ts index 670ab54..2b2516a 100644 --- a/server/tests/actualQtyFactSync.test.ts +++ b/server/tests/actualQtyFactSync.test.ts @@ -56,6 +56,41 @@ describe('同意才落值:只改我方、驳回零改动', () => { expect(applyIdx).toBeGreaterThan(sentIdx); }); + it('成本价申请(field=price)同意即"跟随落值":写我方销售价 + 重算金额 + 重建结算投影', () => { + // 背景(真库实测):主系统第七批 `3e90deb9` 起成本价改为"先改它的值再发申请", + // 我方同意必须让**我方这条记录跟着变**;此前 field='price' 是**静默无操作** + // (台账写 applied、界面提示"已同步",我方价格一个字节没改)。 + expect(apply).toMatch(/params\.field === 'price' \? params\.finalValue : null/); + const idx = apply.indexOf('const targetPrice ='); + expect(idx).toBeGreaterThan(-1); + const body = apply.slice(idx, idx + 2200); + expect(body).toContain('UPDATE order_items'); + for (const col of ['price = $2::numeric', 'locked_price = $2::numeric', 'price_locked_at = NOW()', 'amount = $3::numeric']) { + expect(body, `成本价落值缺列:${col}`).toContain(col); + } + // ⚠️ 结算单是订单的投影:改了销售字段必须重建,否则结算停在旧价 + expect(body).toContain('syncStatementsForOrderSafe(orderCode, null)'); + // 金额必须按**生效后的价**重算(否则量+价同时变时会少算一次) + expect(apply).toMatch(/const price = effectivePrice;/); + }); + + it('结算投影同步必须在**租户上下文**内调用(否则静默失败、结算停在旧值)', () => { + // 背景:`syncStatementsForOrderSafe` 内部用裸连接查 orders/结算表;无 ALS 上下文时只打日志不抛 + // ⇒ 真库 E2E 实测出现 "relation \"orders\" does not exist",价格改了、结算单停在旧价。 + const calls = apply.match(/runWithTenantDbContext\(branchCode, \(\) => syncStatementsForOrderSafe\(orderCode, null\)\)/g) ?? []; + expect(calls.length).toBeGreaterThanOrEqual(2); // 价分支 + 量分支 + expect(apply).not.toMatch(/^\s+await syncStatementsForOrderSafe\(orderCode, null\);$/m); + }); + + it('成本价同样受"已结算/已结案不直改历史"分级约束(分级判断必须在写价之前)', () => { + const guardIdx = apply.indexOf("status: 'skipped_settled'"); + const priceIdx = apply.indexOf('const targetPrice ='); + expect(guardIdx).toBeGreaterThan(-1); + expect(priceIdx).toBeGreaterThan(guardIdx); + // 审计里要能看出改前的价 + expect(apply).toMatch(/price: num\(item\.price\)/); + }); + it('落值模块不外呼主系统(自己只能改自己的)', () => { expect(apply).not.toMatch(/postMainSystem|requestMainSystem|writeback/i); }); diff --git a/server/tests/actualQtyInbox.test.ts b/server/tests/actualQtyInbox.test.ts index 4462fe1..74dc38b 100644 --- a/server/tests/actualQtyInbox.test.ts +++ b/server/tests/actualQtyInbox.test.ts @@ -10,6 +10,94 @@ const route = readFileSync(new URL('../src/routes/mainSystemIntegration.ts', imp const api = readFileSync(new URL('../src/services/mainSystem/api/preparations.ts', import.meta.url), 'utf8'); const cfg = readFileSync(new URL('../src/services/mainSystem/config.ts', import.meta.url), 'utf8'); +describe('"同一商品只留最新一条待审"(开发者 2026-10-12)', () => { + it('新申请到达 ⇒ 同 (prep_id, field) 的旧 pending 关成 superseded(旧的可回溯)', () => { + expect(inbox).toContain('async function supersedeOlderPending'); + const idx = inbox.indexOf('async function supersedeOlderPending'); + const body = inbox.slice(idx, idx + 1400); + expect(body).toContain("SET status = 'superseded'"); + expect(body).toContain('prep_id IS NOT DISTINCT FROM $2::uuid'); + expect(body).toContain("AND field = $3"); + expect(body).toContain("AND status = 'pending'"); + // 可回溯:谁取代了它 + 原因 + expect(body).toContain("'superseded_by'"); + // 插入与刷新两条路径都要收敛 + const insert = inbox.indexOf('const superseded = await supersedeOlderPending'); + expect(insert).toBeGreaterThan(-1); + expect(inbox.match(/await supersedeOlderPending\(/g)?.length ?? 0).toBeGreaterThanOrEqual(3); + }); +}); + +describe('preparations.price_changed 事实接收端(2026-10-12 新增)', () => { + const routeHasBranch = route.includes("event === 'preparations.price_changed'"); + + it('事件已接线(此前一律 200 ignored ⇒ 主系统以为我们没收到)', () => { + expect(routeHasBranch).toBe(true); + expect(route).toContain('recordPriceChangedFact'); + }); + + it('有可审申请时只附事实、**不新建**第二条待审', () => { + const idx = inbox.indexOf('export async function recordPriceChangedFact'); + const body = inbox.slice(idx, idx + 4000); + expect(body).toContain("'price_changed_fact'"); + expect(body).toMatch(/该商品已有待审的价格申请/); + // 幂等键派生确定性 UUID(重推不产生第二行) + expect(inbox).toContain("from '../utils/deterministicUuid'"); + }); + + it('无对应申请时补一条**本地待审**(审核页照常出现,由我方决定跟不跟)', () => { + const idx = inbox.indexOf('export async function recordPriceChangedFact'); + const body = inbox.slice(idx, idx + 9000); + expect(body).toContain("local_only: true"); + expect(body).toContain("'post_complete_price'"); + // 本地事实行不回传主系统(对方已生效;驳回 = 我方自己不改而已) + expect(inbox).toContain('const isLocalOnly = Boolean'); + expect(inbox).toContain('本地事实行(对方已生效),无需回执'); + }); +}); + +describe('确定性 UUID(事实事件的幂等键 → request_id)', () => { + it('同一 seed 恒定、不同 seed 不同,且形态合规(能被 UUID 校验放行)', async () => { + const { deterministicUuid } = await import('../src/utils/deterministicUuid'); + const a = deterministicUuid('pc_prep-1_3_4'); + const b = deterministicUuid('pc_prep-1_3_4'); + const c = deterministicUuid('pc_prep-1_3_5'); + expect(a).toBe(b); + expect(a).not.toBe(c); + expect(a).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/); + }); +}); + +describe('乐观并发校验(主系统第七批 §12.3 / 我方 §4.5.6-A)', () => { + const migration = readFileSync( + new URL('../../migrations/20261025_main_system_actual_qty_request_version.sql', import.meta.url), + 'utf8' + ); + + it('迁移加 request_version / request_updated_at(NULL = 对方未提供,行为与旧版一致)', () => { + expect(migration).toMatch(/ADD COLUMN IF NOT EXISTS request_version INTEGER/); + expect(migration).toMatch(/ADD COLUMN IF NOT EXISTS request_updated_at TIMESTAMPTZ/); + }); + + it('事件/Q6 都映射版本,回执带 decided_basis_version,409 单独分类并自动刷新', () => { + expect(inbox).toMatch(/requestVersion: num\(payload\?\.request_version\)/); + expect(inbox).toContain('decidedBasisVersion: row.request_version ?? null'); + expect(api).toContain('decided_basis_version: params.decidedBasisVersion'); + expect(api).toContain("kind: 'stale'"); + expect(api).toMatch(/stale_request_version/); + expect(inbox).toContain('该申请已被主系统更新为最新值,已刷新,请重新确认'); + }); + + it('成本价同意落值:写我方销售价 + 重算金额 + 重建结算投影(不再静默无操作)', () => { + const apply = readFileSync( + new URL('../src/services/mainSystemActualQtyApply.ts', import.meta.url), + 'utf8' + ); + expect(apply).toMatch(/params\.field === 'price' \? params\.finalValue : null/); + expect(apply).toContain('syncStatementsForOrderSafe(orderCode, null)'); + }); +}); + describe('实收申请接收端', () => { it('事件已接线且幂等键用对方 request_id', () => { expect(route).toContain("preparations.actual_qty_request"); @@ -18,15 +106,28 @@ describe('实收申请接收端', () => { expect(inbox).toContain('ON CONFLICT (branch_code, request_id) DO NOTHING'); }); - it('事实登记节点 = 核货 + 入库(驳回不回滚),>=60/>=90 = 先审后改', () => { - // 2026-10-11 口径变更:入库核查(inbound)也是事实登记(对方先改自己的实际值再发请求) - expect(inbox).toMatch(/const FACT_NODES = new Set\(\['picking_check', 'inbound'\]\)/); + it('事实登记节点 = 核货 + 撤销核货 + 入库 + ≥60 修正 + 成本价(全部"先改后审",驳回不回滚)', () => { + // 2026-10-12 终态:主系统**所有**节点都是"先改自己的值再发请求" ⇒ 全部事实登记。 + // 成本价 `post_complete_price` 于主系统第七批 `3e90deb9`(其设计文档 §12.1)从 ≥90"先审后改" + // 翻转为"写库后通知" ⇒ 2026-10-12 起我方也必须把它算作事实登记(否则驳回文案会谎称"双方均不改值")。 + expect(inbox).toMatch( + /const FACT_NODES = new Set\(\[[^\]]*'post_complete_price'[^\]]*\]\)/ + ); + for (const node of ['picking_check', 'picking_check_revert', 'inbound', 'admin_received_qty', 'post_complete_price']) { + expect(inbox).toContain(`'${node}'`); + } + // 不得再有"成本价先审后改"的过期断言/注释 + expect(inbox).not.toMatch(/`post_complete_price` 不在其列/); expect(inbox).toContain('fact_registered'); // 驳回:不回传 final_value,且文案明确"对方不回滚、我方只留痕" expect(inbox).toContain("params.decision === 'approved'"); expect(inbox).toContain('事实登记,不回滚'); - // 通过:以 final_value ?? proposed_value 为准 - expect(inbox).toContain('params.finalValue ?? num(row.proposed_value)'); + // 2026-10-12 口径:审核人没手填值时**回传 null**(让主系统按它当前值落地), + // 本地落值改用**回执返回的 final_value** —— 不再用我方台账里的(可能是旧的)proposed_value 兜底, + // 否则在"同一 request_id 被原地刷新"的情况下会把旧值覆盖回去。 + expect(inbox).toContain('const requestedFinalValue ='); + expect(inbox).toContain('const appliedValue ='); + expect(inbox).not.toContain('params.finalValue ?? num(row.proposed_value)'); }); it('决策回传打到主系统的 actual-qty-decision(路径只在 endpoints/config 定义)', () => { diff --git a/server/tests/mainSystemPriceQtyRequest.test.ts b/server/tests/mainSystemPriceQtyRequest.test.ts index 0aec8a6..48b92f1 100644 --- a/server/tests/mainSystemPriceQtyRequest.test.ts +++ b/server/tests/mainSystemPriceQtyRequest.test.ts @@ -3,7 +3,12 @@ import { readFileSync } from 'node:fs'; import path from 'node:path'; /** - * 跨系统改价 / 改量审核(我方实现,2026-10-11)。 + * 跨系统改价 / 改量审核(我方实现,2026-10-11;**2026-10-12 口径翻转为"先改后通知"**)。 + * + * ⚠️ 本文件默认跑**旧口径(先审后改)**:那是仍保留、可回退的实现路径(`mode: review_gated`), + * 也是"主系统主动改它的东西"时的正常通道,A1–A8 的既有断言全部继续有效。 + * 新口径(**自己只能改自己的 / 本地先生效 + 异步通知**)在文件末尾的 + * `先改后通知(local-first)` describe 里单独钉住,两套语义互不掩盖。 * * 覆盖设计文档 docs/design/20261011-跨系统改价改量审核.md 的 A1–A8: * · 免审(applied)⇒ 台账 applied + **立即落地** + 留日志; @@ -48,8 +53,10 @@ vi.mock('../src/services/tenantDbContext', async (importOriginal) => { }); import { + __setPriceQtyLocalFirstForTests, assertMainSystemPriceQtyReviewed, handlePriceQtyDecidedEvent, + notifyMainSystemPriceQtyChanges, submitPriceQtyRequest, } from '../src/services/mainSystemPriceQtyRequest'; @@ -90,6 +97,9 @@ function ledgerRow(overrides: Record = {}) { } beforeEach(() => { + // ⚠️ 默认跑**旧口径(先审后改)**:保住既有 32 条断言的语义(可回退路径不能变成"没人跑的死码")。 + // 新口径(先改后通知)的用例在文件末尾的 describe 里显式切回 true。 + __setPriceQtyLocalFirstForTests(false); query.mockReset(); submit.mockReset(); fetchAmend.mockReset(); @@ -1013,3 +1023,345 @@ describe('申请列表:必须给出「商品名」', () => { expect(String(insert?.[0])).toContain('item_name, main_sku_code'); }); }); + +/* ══════════════════════════════════════════════════════════════════════════════ + * 先改后通知(local-first)—— 开发者 2026-10-12 定稿,取代上面那套"先审后改"。 + * + * 三条铁律(本 describe 逐条钉住): + * ① 我方改**我方**字段(销售价 / 数量)⇒ **本地立即生效**,谁都不许拦(守卫直接放行); + * ② 只**通知**主系统(异步、逐条、失败只记日志);对方同意/驳回**都不回改我方值**; + * ③ 主系统的结论只记台账 + 留痕;与我方值不同 ⇒ 记 `divergence`,**只留痕不提醒**。 + * ══════════════════════════════════════════════════════════════════════════════ */ +describe('先改后通知(local-first)', () => { + beforeEach(() => { + __setPriceQtyLocalFirstForTests(true); + }); + + /** + * local-first 的 `decide` 会**读我方订单行现值**(用于算 divergence), + * 所以桩里必须有一条 `SELECT price, quantity FROM order_items ... id = $2::uuid`。 + */ + function stubDecideLocalFirst(row: Record, our: { price: number | null; quantity: number | null }) { + query.mockImplementation(async (sql: string) => { + const text = String(sql); + if (text.includes('FROM public.main_system_price_qty_requests') && text.includes('request_id = $1')) { + return { rowCount: 1, rows: [row] }; + } + if (text.startsWith('UPDATE public.main_system_price_qty_requests')) return { rowCount: 1, rows: [row] }; + if (text.includes('FROM order_items') && text.includes('SELECT price, quantity')) { + return { rowCount: 1, rows: [our] }; + } + return { rowCount: 0, rows: [] }; + }); + } + + it('① 守卫直接放行:改价/改量都不再抛 409("改了就是改了")', () => { + expect(() => + assertMainSystemPriceQtyReviewed({ + isMainSystemOrder: true, + changes: [{ itemId: ITEM, itemName: '土豆', field: 'price', from: 5, to: 6.5 }], + }) + ).not.toThrow(); + expect(() => + assertMainSystemPriceQtyReviewed({ + isMainSystemOrder: true, + changes: [{ itemId: ITEM, itemName: '土豆', field: 'quantity', from: 10, to: 12 }], + }) + ).not.toThrow(); + }); + + it('② 通知是逐条独立的:价/量各提交一次,且失败只吞不抛、不回滚', async () => { + stubSubmitQueries(); + submit.mockImplementation(async (params: { proposedPrice?: unknown }) => + params.proposedPrice != null + ? { kind: 'ok', requestId: 'MS-REQ-PRICE', status: 'pending', reviewRequired: true, finalPrice: null, finalQty: null, message: null, raw: {} } + : { kind: 'failed', reason: '网络超时' } + ); + // 不 await:通知是**异步**的(本地写入早已提交,绝不让它拖住请求) + notifyMainSystemPriceQtyChanges({ + branchCode: BRANCH, + ourOrderCode: ORDER, + changes: [ + { itemId: ITEM, itemName: '土豆', field: 'price', from: 5, to: 6.5 }, + { itemId: ITEM, itemName: '土豆', field: 'quantity', from: 10, to: 12 }, + ], + actor: { userId: 'u1' }, + }); + await vi.waitFor(() => expect(submit).toHaveBeenCalledTimes(2)); + const priceCall = submit.mock.calls[0][0] as any; + const qtyCall = submit.mock.calls[1][0] as any; + expect(priceCall.proposedPrice).toBe(6.5); + expect(priceCall.proposedQty).toBeNull(); + expect(qtyCall.proposedQty).toBe(12); + expect(qtyCall.proposedPrice).toBeNull(); + // 两条同源同一备货行,只差被改的字段(一条失败不影响另一条) + expect(priceCall.prepId).toBe('prep-1'); + expect(qtyCall.prepId).toBe('prep-1'); + expect((audit.mock.calls.map((c) => (c[0] as any).operationType))).toContain('main_system_price_qty_requested'); + }); + + it('② 【实测回归】COMMIT 后再通知:必须用调用方给的"改动前"值,否则被判 no_change 静默不发', async () => { + // 真库 E2E 复现过:调用方先把 8.30 写成 9.10 并 COMMIT,再通知; + // 此时回表读到的是 9.10 ⇒ 与 proposed 相同 ⇒ no_change ⇒ **主系统端完全收不到**(我方值却已变)。 + stubSubmitQueries(); // 桩里 order_items.price = 5(模拟"库里已是新值") + submit.mockResolvedValue({ + kind: 'ok', + requestId: 'MS-REQ-1', + status: 'pending', + reviewRequired: true, + finalPrice: null, + finalQty: null, + message: null, + raw: {}, + }); + await submitPriceQtyRequest({ + branchCode: BRANCH, + ourOrderCode: ORDER, + ourOrderItemId: ITEM, + proposedPrice: 5, // 与"库里当前值"相同 —— 若不带 beforePrice 就会被判 no_change + beforePrice: 3, // 真实的改动前值 + actor: { userId: 'u1' }, + }); + expect(submit, '未带 beforePrice 时会静默判 no_change、根本不通知').toHaveBeenCalledTimes(1); + // 台账 before_* 与发给主系统的 before_value 都必须是**旧值** + const insert = query.mock.calls.find((c) => String(c[0]).startsWith('INSERT INTO public.main_system_price_qty_requests')); + const values = insert?.[1] as unknown[]; + expect(values[7]).toBe(3); // before_price + expect(values[9]).toBe(5); // proposed_price + }); + + it('② 通知兜异常:submit 直接 reject 也不冒泡(本地值已生效)', async () => { + stubSubmitQueries(); + submit.mockRejectedValue(new Error('connect ECONNREFUSED')); + expect(() => + notifyMainSystemPriceQtyChanges({ + branchCode: BRANCH, + ourOrderCode: ORDER, + changes: [{ itemId: ITEM, itemName: '土豆', field: 'price', from: 5, to: 6.5 }], + actor: { userId: 'u1' }, + }) + ).not.toThrow(); + await vi.waitFor(() => expect(submit).toHaveBeenCalledTimes(1)); + // 让它把 catch 里的日志也走完,避免未处理拒绝泄漏到下一个用例 + await new Promise((r) => setTimeout(r, 0)); + }); + + it('② 开关关闭 / 无变更 / 旧口径 ⇒ 不通知(与改造前逐字节一致)', () => { + isEnabledFlag.value = false; + notifyMainSystemPriceQtyChanges({ + branchCode: BRANCH, + ourOrderCode: ORDER, + changes: [{ itemId: ITEM, itemName: '土豆', field: 'price', from: 5, to: 6.5 }], + actor: { userId: 'u1' }, + }); + isEnabledFlag.value = true; + notifyMainSystemPriceQtyChanges({ branchCode: BRANCH, ourOrderCode: ORDER, changes: [], actor: { userId: 'u1' } }); + __setPriceQtyLocalFirstForTests(false); + notifyMainSystemPriceQtyChanges({ + branchCode: BRANCH, + ourOrderCode: ORDER, + changes: [{ itemId: ITEM, itemName: '土豆', field: 'price', from: 5, to: 6.5 }], + actor: { userId: 'u1' }, + }); + expect(submit).not.toHaveBeenCalled(); + }); + + it('① 提交只上报、**不**替我改本地(本地值由发起入口写,避免两个写入者)', async () => { + stubSubmitQueries(); + submit.mockResolvedValue({ + kind: 'ok', + requestId: 'MS-REQ-1', + status: 'applied', + reviewRequired: false, + finalPrice: 6.5, + finalQty: 10, + message: '已生效(低于原价,免审)', + raw: {}, + }); + const outcome = await submitPriceQtyRequest({ + branchCode: BRANCH, + ourOrderCode: ORDER, + ourOrderItemId: ITEM, + proposedPrice: 6.5, + unit: '斤', + actor: { userId: 'u1', roles: 'admin' }, + }); + expect(outcome.kind).toBe('ok'); + if (outcome.kind !== 'ok') return; + // 对方"免审已生效"仍然照记台账,但**不落本地** + expect(outcome.status).toBe('applied'); + expect(outcome.appliedLocally).toBe(false); + expect(syncItems).not.toHaveBeenCalled(); + // 台账 payload 标 notify_only:排障时一眼看出这不是"先审后改" + const update = query.mock.calls.find((c) => String(c[0]).includes("mode: JSON.stringify") || String(c[0]).includes('payload = $8::jsonb')); + expect(JSON.stringify(update?.[1] ?? [])).toContain('notify_only'); + // 且**不得**写 auto_applied 那种"本地已落地"的日志 + const types = audit.mock.calls.map((c) => (c[0] as any).operationType); + expect(types).not.toContain('main_system_price_qty_auto_applied'); + }); + + it('① 需审(pending)在 local-first 下同样不落本地、只留 requested 日志', async () => { + stubSubmitQueries(); + submit.mockResolvedValue({ + kind: 'ok', + requestId: 'MS-REQ-1', + status: 'pending', + reviewRequired: true, + finalPrice: null, + finalQty: null, + message: '已提交,等待管理员确认', + raw: {}, + }); + const outcome = await submitPriceQtyRequest({ + branchCode: BRANCH, + ourOrderCode: ORDER, + ourOrderItemId: ITEM, + proposedPrice: 8, + actor: { userId: 'u1' }, + }); + expect(outcome.kind).toBe('ok'); + if (outcome.kind !== 'ok') return; + expect(outcome.appliedLocally).toBe(false); + expect(syncItems).not.toHaveBeenCalled(); + expect((audit.mock.calls.map((c) => (c[0] as any).operationType))).toContain('main_system_price_qty_requested'); + }); + + it('③ 主系统"通过"⇒ 不覆盖我方值:只记台账 + 留痕(值不同 ⇒ divergence)', async () => { + // 台账里我方现值已被改成 9(先改后通知),主系统给的最终值是 7.25 + stubDecideLocalFirst(ledgerRow({ proposed_price: 9, payload: {} }), { price: 9, quantity: 10 }); + const outcome = await handlePriceQtyDecidedEvent({ + branchCode: BRANCH, + payload: { + event: 'preparations.price_qty_decided', + request_id: 'MS-REQ-1', + prep_id: 'prep-1', + decision: 'approved', + final_price: 7.25, + reviewer: '主系统管理员', + }, + }); + expect(outcome.status).toBe('done'); + expect(outcome.reason).toMatch(/不覆盖我方值/); + // 核心:**没有**改我方库 + expect(syncItems).not.toHaveBeenCalled(); + // 终态照常写(否则对账永远重试) + const statusUpdate = query.mock.calls.find((c) => String(c[0]).includes('SET status = $2::varchar')); + expect(statusUpdate).toBeTruthy(); + expect((statusUpdate?.[1] as unknown[])?.[1]).toBe('approved'); + // 差异留痕:local_first.divergence + 一条 diverged 日志 + const trace = query.mock.calls.find((c) => String(c[0]).includes("'local_first'")); + expect(trace, '没有写 local_first 留痕').toBeTruthy(); + expect((trace?.[1] as unknown[])?.[6]).toBe(true); + expect((audit.mock.calls.map((c) => (c[0] as any).operationType))).toContain('main_system_price_qty_decision_diverged'); + }); + + it('③ 主系统结论与我方值一致 ⇒ 只记 recorded,不留 divergence', async () => { + stubDecideLocalFirst(ledgerRow({ proposed_price: 6.5 }), { price: 6.5, quantity: 10 }); + const outcome = await handlePriceQtyDecidedEvent({ + branchCode: BRANCH, + payload: { + event: 'preparations.price_qty_decided', + request_id: 'MS-REQ-1', + decision: 'approved', + final_price: 6.5, + reviewer: '主系统管理员', + }, + }); + expect(outcome.status).toBe('done'); + expect(outcome.reason).toMatch(/与我方当前值一致/); + expect(syncItems).not.toHaveBeenCalled(); + const trace = query.mock.calls.find((c) => String(c[0]).includes("'local_first'")); + expect((trace?.[1] as unknown[])?.[6]).toBe(false); + expect((audit.mock.calls.map((c) => (c[0] as any).operationType))).toContain('main_system_price_qty_decision_recorded'); + }); + + it('③ 主系统"驳回"⇒ 我方值同样不动(驳回 ≠ 回滚)', async () => { + stubDecideLocalFirst(ledgerRow({ proposed_price: 9 }), { price: 9, quantity: 10 }); + const outcome = await handlePriceQtyDecidedEvent({ + branchCode: BRANCH, + payload: { + event: 'preparations.price_qty_decided', + request_id: 'MS-REQ-1', + decision: 'rejected', + reason: '价格过高', + reviewer: '主系统管理员', + }, + }); + expect(outcome.status).toBe('done'); + expect(syncItems).not.toHaveBeenCalled(); + expect((audit.mock.calls.map((c) => (c[0] as any).operationType))).toContain('main_system_price_qty_rejected'); + }); + + it('③ 旧 amend 轮询补齐路径同样受 local-first 管:只记录、不覆盖', async () => { + const pending = ledgerRow({ request_id: null }); + query.mockImplementation(async (sql: string) => { + const text = String(sql); + if (text.includes("status = 'pending'") && text.includes('FROM public.main_system_price_qty_requests')) { + return { rowCount: 1, rows: [pending] }; + } + if (text.startsWith('UPDATE public.main_system_price_qty_requests')) return { rowCount: 1, rows: [pending] }; + if (text.includes('FROM order_items')) { + return { rowCount: 1, rows: [{ price: 5, quantity: 10 }] }; + } + return { rowCount: 0, rows: [] }; + }); + fetchAmend.mockResolvedValue({ + kind: 'ok', + rows: [ + { + prepId: 'prep-1', + orderCode: ORDER, + prepareQty: 10, + purchasePrice: 5, + unit: '斤', + amendRequest: { id: 'MS-REQ-1', status: 20, statusLabel: '已确认', proposedPrice: 6.8, proposedQty: null, proposedUnit: null, reviewRemark: null, requestedAt: null }, + }, + ], + }); + const { reconcileMainSystemPriceQtyRequests } = await import('../src/services/mainSystemPriceQtyRequest'); + const result = await reconcileMainSystemPriceQtyRequests({ branchCode: BRANCH }); + expect(result.checked).toBe(1); + expect(result.closed).toBe(1); // 终态照常写(不再重复拉取) + expect(syncItems).not.toHaveBeenCalled(); // 但不覆盖我方值 + }); +}); + +/* ══════════════════════════════════════════════════════════════════════════════ + * 接线钉子:口径对了,但**接错位置**照样会出事故(本项目踩过: + * `tryAdvanceOrderToDelivery` 把 (branchCode, orderCode) 传反 ⇒ 回写静默不生效)。 + * 这里用源码级断言把两个调用点的**位置**钉住。 + * ══════════════════════════════════════════════════════════════════════════════ */ +describe('调用点接线:必须"写库 COMMIT 之后"才通知,且通知不阻塞', () => { + const manageSrc = readFileSync(path.join(__dirname, '../src/services/orderManageItemsService.ts'), 'utf8'); + const saleSrc = readFileSync(path.join(__dirname, '../src/services/purchaseLinkedSalePriceService.ts'), 'utf8'); + + it('订单明细:守卫保留(不删)+ 变更收集保留 + 通知在 COMMIT 之后', () => { + expect(manageSrc).toContain('assertMainSystemPriceQtyReviewed({'); + expect(manageSrc).toContain('collectMainSystemPriceQtyChanges(existingMap, incoming)'); + expect(manageSrc).toContain('priceQtyNotices = changes.filter((change) => guarded.has(change.itemId))'); + const notifyAt = manageSrc.indexOf('notifyMainSystemPriceQtyChanges({'); + expect(notifyAt).toBeGreaterThan(0); + // 通知必须在 `await client.query('COMMIT')` 之后(否则回滚了还去通知对方"我改了") + const commitAt = manageSrc.indexOf("await client.query('COMMIT')"); + expect(commitAt).toBeGreaterThan(0); + expect(notifyAt).toBeGreaterThan(commitAt); + // 且必须在 try/catch/finally 之外(不占用请求级连接、不被 ROLLBACK 分支吞掉) + expect(manageSrc.slice(commitAt, notifyAt)).toContain('finally'); + // 不 await:通知是"发出去就算",绝不拖住明细保存 + expect(manageSrc.slice(notifyAt - 60, notifyAt)).not.toContain('await'); + }); + + it('自采列表改价:通知在本地 UPDATE 之前发出,且之后没有任何 return/throw 拦写入', () => { + const guardStart = saleSrc.indexOf('跨系统改价通知'); + const guardEnd = saleSrc.indexOf('const quantity = Number(before.rows[0].quantity)'); + const guard = saleSrc.slice(guardStart, guardEnd); + expect(guard).toContain('await submitPriceQtyRequest('); + expect(guard).not.toMatch(/\bthrow\b/); + expect(guard).not.toMatch(/\breturn\b/); + }); + + it('两条链的通知都只走 submitPriceQtyRequest(不各自发明上报格式)', () => { + expect(saleSrc).toContain("import { submitPriceQtyRequest } from './mainSystemPriceQtyRequest'"); + expect(manageSrc).toContain('notifyMainSystemPriceQtyChanges'); + }); +}); diff --git a/server/tests/salePriceDiversion.test.ts b/server/tests/salePriceDiversion.test.ts index 69a54d5..69be419 100644 --- a/server/tests/salePriceDiversion.test.ts +++ b/server/tests/salePriceDiversion.test.ts @@ -2,33 +2,44 @@ import { readFileSync } from 'node:fs'; import { describe, expect, it } from 'vitest'; /** - * 自采列表改销售价:**统一分流**(开发者 2026-10-11 定稿)。 + * 自采列表改销售价:**先改后通知**(开发者 2026-10-12 定稿 · 取代 2026-10-11 的"先审后改")。 * - * 事故:自采列表保存销售价 → 命中"主系统分配行改价必须走审核"守卫 → 直接抛错 → - * 界面表现为"改不动/保存无效"。修法:守卫不再直接抛,改为**提交改价申请**: - * · 免审(补价 0→正常价 / 改低 / 减量)⇒ 主系统当场生效、我方同步落地 ⇒ 继续原写入(同值幂等); - * · 需审(涨价 / 加量)⇒ 提交后**本地不变**,抛说明性错误(界面提示"已提交待审")。 + * 三代口径(这文件专门钉住"不许退回上一代"): + * ① 最早:撞守卫**直接抛错** ⇒ 界面表现为"改不动/保存无效"(已废弃); + * ② 2026-10-11:**先审后改** —— 免审当场落地、需审抛说明性错误(已废弃); + * ③ 2026-10-12:**先改后通知** —— 本地立即生效,只额外通知主系统一起变; + * 对方结论不回改我方("自己只能改自己的"),失败只记日志不回滚。 */ const src = readFileSync(new URL('../src/services/purchaseLinkedSalePriceService.ts', import.meta.url), 'utf8'); -const guard = src.slice(src.indexOf('跨系统改价审核守卫'), src.indexOf('const quantity = Number(before.rows[0].quantity)')); +const guard = src.slice(src.indexOf('跨系统改价通知'), src.indexOf('const quantity = Number(before.rows[0].quantity)')); -describe('销售价写入:主系统分配行的统一分流', () => { - it('命中守卫时提交改价申请(不再直接 assert 抛错)', () => { +describe('销售价写入:主系统分配行只通知、不拦本地写入', () => { + it('命中时只提交通知(既不再直接 assert 抛错,也不再抛"待审"错误)', () => { expect(src).toContain("import { submitPriceQtyRequest } from './mainSystemPriceQtyRequest'"); expect(guard).toContain('await submitPriceQtyRequest('); expect(guard).not.toContain('assertMainSystemPriceQtyReviewed('); + // ② 的两条"本地不变"分支必须消失(否则界面又会"改不动") + expect(guard).not.toContain('改价申请提交失败,本次未改动价格'); + expect(guard).not.toContain('已提交改价申请,等待主系统审核(本地价格暂不变动)'); + expect(guard).not.toContain("if (outcome.status !== 'applied')"); }); - it('三种结果都有明确处置:提交失败 / 待审 / 免审放行', () => { + it('通知失败只记日志、不拦写入(值照常落地 + 台账 failed 兜底)', () => { expect(guard).toContain("if (outcome.kind !== 'ok')"); - expect(guard).toContain('改价申请提交失败,本次未改动价格'); - expect(guard).toContain("if (outcome.status !== 'applied')"); - expect(guard).toContain('已提交改价申请,等待主系统审核(本地价格暂不变动)'); - // 免审 ⇒ 继续走原写入(注释即口径) - expect(guard).toContain('免审已生效 ⇒ 落到下面的原写入'); + expect(guard).toContain('通知主系统失败(本地值照常生效)'); + expect(guard).toContain('console.error('); + // 关键:提交分支结束后**继续往下走**到原 UPDATE,中间没有 return/throw + expect(guard).not.toMatch(/\breturn\b/); + expect(guard).not.toMatch(/\bthrow\b/); }); - it('我方自建行不受影响(守卫只在"主系统订单"命中时才分流)', () => { + it('本地写入在通知之后,且写入的是本次提交的新价(先改后通知的顺序)', () => { + const updateIdx = src.indexOf('await client.query(\n `UPDATE order_items'); + expect(updateIdx).toBeGreaterThan(src.indexOf('await submitPriceQtyRequest(')); + expect(src.slice(updateIdx, updateIdx + 600)).toContain('[input.salePrice, lineAmount, input.orderItemId, input.orderCode]'); + }); + + it('我方自建行不受影响(只在"主系统订单"命中时才通知)', () => { expect(guard).toContain('FROM public.main_system_order_imports'); expect(guard).toContain('if (mainSystemOrder.rowCount) {'); }); diff --git a/src/i18n/locales/en/orders.ts b/src/i18n/locales/en/orders.ts index 1dafa3e..b436aa8 100644 --- a/src/i18n/locales/en/orders.ts +++ b/src/i18n/locales/en/orders.ts @@ -575,13 +575,21 @@ export const orders: MessageDict = { 'priceQty.colBefore': 'Before', 'priceQty.colProposed': 'Proposed', 'priceQty.colFinal': 'Final', + 'priceQty.refreshHint': 'Main system updated to the latest: {pair} ({at})', + 'priceQty.inboxStaleRefreshed': 'The main system updated this request to {from} → {to}; the list has been refreshed, please confirm again', + 'priceQty.inboxStaleGone': 'This request is no longer pending (decided or withdrawn); the list has been refreshed', + 'priceQty.refreshHintMore': '{count} updates in total', + 'priceQty.refreshSourceWebhook': 'webhook', + 'priceQty.refreshSourceReconcile': 'reconcile', 'priceQty.colMainActual': 'Main system actual (effective)', 'priceQty.colAppliedAt': 'Effective at', 'priceQty.colApplyNote': 'Applied on our side', 'priceQty.historyTitle': 'Processed (synced / rejected)', 'priceQty.historyEmpty': 'No processed requests yet', + 'priceQty.pageInfo': 'Page {page} / {total}', 'priceQty.statusSynced': 'Synced', 'priceQty.statusRejectedNoSync': 'Rejected (not synced)', + 'priceQty.statusWithdrawn': 'Withdrawn by main system', 'priceQty.colDecidedAt': 'Decided at', 'priceQty.colStatus': 'Status', 'priceQty.inboxTitle': 'Pending my review (raised by main system)', @@ -597,6 +605,8 @@ export const orders: MessageDict = { 'priceQty.rejectReason': 'Reject reason', 'priceQty.nodePickingCheck': 'Picking check', 'priceQty.nodeInbound': 'Inbound check', + 'priceQty.nodePickingCheckRevert': 'Picking check reverted', + 'priceQty.statusSuperseded': 'Voided / closed by reconcile', 'priceQty.nodeAdminReceivedQty': 'Admin correction', 'priceQty.nodePostCompletePrice': 'Post-completion price', 'priceQty.fieldQty': 'Received qty', diff --git a/src/i18n/locales/id/orders.ts b/src/i18n/locales/id/orders.ts index 8984bbf..63bbe3b 100644 --- a/src/i18n/locales/id/orders.ts +++ b/src/i18n/locales/id/orders.ts @@ -576,13 +576,21 @@ export const orders: MessageDict = { 'priceQty.colBefore': 'Sebelum', 'priceQty.colProposed': 'Diusulkan', 'priceQty.colFinal': 'Final', + 'priceQty.refreshHint': 'Sistem utama memperbarui ke nilai terbaru: {pair} ({at})', + 'priceQty.inboxStaleRefreshed': 'Sistem utama memperbarui permintaan ini menjadi {from} → {to}; daftar telah dimuat ulang, mohon konfirmasi lagi', + 'priceQty.inboxStaleGone': 'Permintaan ini tidak lagi menunggu (sudah diputuskan/ditarik); daftar telah dimuat ulang', + 'priceQty.refreshHintMore': 'Total {count} pembaruan', + 'priceQty.refreshSourceWebhook': 'webhook', + 'priceQty.refreshSourceReconcile': 'rekonsiliasi', 'priceQty.colMainActual': 'Aktual sistem utama (berlaku)', 'priceQty.colAppliedAt': 'Berlaku pada', 'priceQty.colApplyNote': 'Hasil penerapan di sisi kami', 'priceQty.historyTitle': 'Sudah diproses (sinkron / ditolak)', 'priceQty.historyEmpty': 'Belum ada permintaan yang diproses', + 'priceQty.pageInfo': 'Halaman {page} / {total}', 'priceQty.statusSynced': 'Tersinkron', 'priceQty.statusRejectedNoSync': 'Ditolak (tidak sinkron)', + 'priceQty.statusWithdrawn': 'Ditarik/dibatalkan sistem utama', 'priceQty.colDecidedAt': 'Waktu keputusan', 'priceQty.colStatus': 'Status', 'priceQty.inboxTitle': 'Menunggu persetujuan saya (dari sistem utama)', @@ -598,6 +606,8 @@ export const orders: MessageDict = { 'priceQty.rejectReason': 'Alasan penolakan', 'priceQty.nodePickingCheck': 'Pemeriksaan', 'priceQty.nodeInbound': 'Pemeriksaan masuk', + 'priceQty.nodePickingCheckRevert': 'Pemeriksaan dibatalkan', + 'priceQty.statusSuperseded': 'Dibatalkan / ditutup rekonsiliasi', 'priceQty.nodeAdminReceivedQty': 'Koreksi admin', 'priceQty.nodePostCompletePrice': 'Harga setelah selesai', 'priceQty.fieldQty': 'Jumlah diterima', diff --git a/src/i18n/locales/zh-CN/orders.ts b/src/i18n/locales/zh-CN/orders.ts index 9537c44..dfcd820 100644 --- a/src/i18n/locales/zh-CN/orders.ts +++ b/src/i18n/locales/zh-CN/orders.ts @@ -566,13 +566,21 @@ export const orders: MessageDict = { 'priceQty.colBefore': '原值', 'priceQty.colProposed': '建议值', 'priceQty.colFinal': '最终值', + 'priceQty.refreshHint': '主系统已更新为最新值:{pair}({at})', + 'priceQty.inboxStaleRefreshed': '主系统已把该申请更新为最新值:{from} → {to},列表已刷新,请重新确认', + 'priceQty.inboxStaleGone': '该申请已被处理或撤回(不再是待审),列表已刷新', + 'priceQty.refreshHintMore': '共 {count} 次更新', + 'priceQty.refreshSourceWebhook': '事件推送', + 'priceQty.refreshSourceReconcile': '对账校正', 'priceQty.colMainActual': '主系统实际值(已生效)', 'priceQty.colAppliedAt': '对方生效时间', 'priceQty.colApplyNote': '我方落值结果', 'priceQty.historyTitle': '已处理(已同步 / 已驳回)', 'priceQty.historyEmpty': '暂无已处理的申请', + 'priceQty.pageInfo': '第 {page} / {total} 页', 'priceQty.statusSynced': '已同步', 'priceQty.statusRejectedNoSync': '已驳回(未同步)', + 'priceQty.statusWithdrawn': '对方已撤回/作废', 'priceQty.colDecidedAt': '决策时间', 'priceQty.colStatus': '状态', 'priceQty.inboxTitle': '待我审核(主系统发起)', @@ -588,6 +596,8 @@ export const orders: MessageDict = { 'priceQty.rejectReason': '驳回原因', 'priceQty.nodePickingCheck': '核货', 'priceQty.nodeInbound': '入库核查', + 'priceQty.nodePickingCheckRevert': '核货撤回', + 'priceQty.statusSuperseded': '已作废/对账关闭', 'priceQty.nodeAdminReceivedQty': '管理端修正', 'priceQty.nodePostCompletePrice': '完结后改价', 'priceQty.fieldQty': '实收数量', diff --git a/src/pages/orders/PriceQtyRequestsPage.render.test.tsx b/src/pages/orders/PriceQtyRequestsPage.render.test.tsx index cda8387..b8570ce 100644 --- a/src/pages/orders/PriceQtyRequestsPage.render.test.tsx +++ b/src/pages/orders/PriceQtyRequestsPage.render.test.tsx @@ -65,36 +65,76 @@ const rows = [ }, ]; -vi.mock('../../utils/workflowApi', () => ({ - listMainSystemPriceQtyRequestsApi: vi.fn(async () => ({ data: rows, enabled: true })), - // 待我审核(主系统发起):本用例给一条核货实收不一致申请 - listMainSystemActualQtyRequestsApi: vi.fn(async () => ({ - data: [ +/** 待审行的固定数据(mock 里两处引用,避免重复字面量) */ +const PENDING_ROW = { + id: 'inbox-1', + request_id: 'ms-aqr-1', + prep_id: 'prep-9', + order_code: 'ORD_WEB_20261008_BR002_0002', + our_order_code: 'ORD_API_1', + sku_code: 'SKU9', + node: 'picking_check', + field: 'qty', + before_value: 1, + proposed_value: 0.9, + before_unit: '袋', + unit: '袋', + operator: 'rider-001', + reason: '核货实测', + status: 'pending', + final_value: null, + reviewer: null, + decided_at: null, + decision_reason: null, + fact_registered: true, + created_at: '2026-10-11T09:30:00+08:00', + item_name: '思丰牌面粉', + // 主系统"未处理就地更新为最新"留下的可追溯痕迹(审核页要显示出来) + payload: { + refresh_history: [ { - id: 'inbox-1', - request_id: 'ms-aqr-1', - prep_id: 'prep-9', - order_code: 'ORD_WEB_20261008_BR002_0002', - our_order_code: 'ORD_API_1', - sku_code: 'SKU9', - node: 'picking_check', - field: 'qty', - before_value: 1, - proposed_value: 0.9, - before_unit: '袋', - unit: '袋', - operator: 'rider-001', - reason: '核货实测', - status: 'pending', - final_value: null, - reviewer: null, - decided_at: null, - decision_reason: null, - fact_registered: true, - created_at: '2026-10-11T09:30:00+08:00', - item_name: '思丰牌面粉', + at: '2026-10-11T09:45:00+08:00', + from_value: 1.2, + from_unit: '袋', + to_value: 0.9, + to_unit: '袋', + source: 'webhook', }, ], + }, +} as const; + +vi.mock('../../utils/workflowApi', () => ({ + listMainSystemPriceQtyRequestsApi: vi.fn(async () => ({ data: rows, enabled: true })), + /** + * 待我审核(主系统发起): + * · `status=pending` ⇒ 一条待审(核货实收不一致); + * · 不带 status(历史用)⇒ 再加一条**已被主系统撤回**(`withdrawn`)的行, + * 验证 §4.5.4 新口径下「对方已撤回/作废」这一档能显示出来。 + */ + listMainSystemActualQtyRequestsApi: vi.fn(async (params?: { status?: string; scope?: string }) => ({ + total: params?.scope === 'pending' ? 1 : 2, + page: 1, + page_size: 20, + counts: { pending: 1, processed: 1 }, + data: + params?.scope === 'pending' || params?.status === 'pending' + ? [PENDING_ROW] + : [ + PENDING_ROW, + { + ...PENDING_ROW, + id: 'inbox-2', + request_id: 'ms-aqr-2', + status: 'withdrawn', + before_value: 2.5, + proposed_value: 1.8, + unit: '个', + reason: '配送员撤销核货(主系统侧撤回)', + decided_at: '2026-10-11T10:10:00+08:00', + decision_reason: '已按主系统事件关闭(withdrawn)', + }, + ], })), decideMainSystemActualQtyRequestApi: vi.fn(async () => ({ status: 'done', reason: 'ok', duplicate: false })), })); @@ -187,18 +227,34 @@ describe('待我审核区(主系统发起)', () => { it('渲染出「待我审核」区、核货节点、字段、原值→主系统实际值,动作是"同步/驳回(不同步)"', async () => { renderPage(); expect(await screen.findByText(/待我审核/)).toBeTruthy(); - expect(screen.getByText('核货')).toBeTruthy(); - expect(screen.getByText('实收数量')).toBeTruthy(); + // 历史区也会渲染同名列 ⇒ 用 getAllByText(不能假定只有一个"核货") + expect(screen.getAllByText('核货').length).toBeGreaterThan(0); + expect(screen.getAllByText('实收数量').length).toBeGreaterThan(0); expect(document.body.textContent).toContain('原1'); expect(document.body.textContent).toContain('0.9'); expect(screen.getAllByText('同步到本系统').length).toBeGreaterThan(0); expect(screen.getAllByText('驳回(不同步)').length).toBeGreaterThan(0); // 生效时间列存在(对方实际值何时生效) expect(screen.getAllByText('对方生效时间').length).toBeGreaterThan(0); + // 主系统把未处理的申请原地刷新过 ⇒ 显示可追溯的更新痕迹(开发者 2026-10-12 要求) + expect(document.body.textContent).toContain('主系统已更新为最新值'); + expect(document.body.textContent).toContain('1.2袋 → 0.9袋'); }); - it('已处理历史区照常展示(已同步 / 已驳回)', async () => { + it('服务端分页:两区都有翻页控件与页码(2026-10-12 开发者要求)', async () => { + renderPage(); + expect(await screen.findByText(/待我审核/)).toBeTruthy(); + // 区标题用**服务端计数**(不再用当前页行数) + expect(document.body.textContent).toContain('已处理(已同步 / 已驳回)(1)'); + expect(screen.getAllByText('第 1 / 1 页').length).toBeGreaterThanOrEqual(2); + expect(screen.getAllByText('首页').length).toBeGreaterThanOrEqual(2); + expect(screen.getAllByText('末页').length).toBeGreaterThanOrEqual(2); + }); + + it('已处理历史区照常展示(已同步 / 已驳回 / 对方已撤回)', async () => { renderPage(); expect(await screen.findByText(/已处理(已同步 \/ 已驳回)/)).toBeTruthy(); + // 主系统在未审前撤回 ⇒ 该行落在历史区并显示「对方已撤回/作废」 + expect(await screen.findByText('对方已撤回/作废')).toBeTruthy(); }); }); diff --git a/src/pages/orders/PriceQtyRequestsPage.tsx b/src/pages/orders/PriceQtyRequestsPage.tsx index 2b935f0..781dfc3 100644 --- a/src/pages/orders/PriceQtyRequestsPage.tsx +++ b/src/pages/orders/PriceQtyRequestsPage.tsx @@ -1,5 +1,5 @@ import React, { useCallback, useEffect, useState } from 'react'; -import { RefreshCw } from 'lucide-react'; +import { ChevronLeft, ChevronRight, RefreshCw } from 'lucide-react'; import { MenuLabel } from '../../components/MenuLabel'; import { notify } from '../../utils/notify'; import { useI18n } from '../../i18n/I18nProvider'; @@ -10,9 +10,32 @@ import { listMainSystemActualQtyRequestsApi, decideMainSystemActualQtyRequestApi, type MainSystemPriceQtyRequestDto, + type MainSystemActualQtyRefreshEntry, type MainSystemActualQtyRequestDto, } from '../../utils/workflowApi'; +/** + * 取该行的"主系统更新历史"(2026-10-12):主系统对**未处理**的申请是"原地更新为最新", + * 每次刷新都会在 `payload.refresh_history` 追加一条 `from → to`(webhook / 对账两种来源)。 + * 审核页要把它显示出来,避免审核人按旧印象审批,同时保证可追溯。 + */ +function readRefreshHistory(row: MainSystemActualQtyRequestDto): MainSystemActualQtyRefreshEntry[] { + const list = Array.isArray(row.payload?.refresh_history) ? row.payload!.refresh_history! : []; + if (list.length) return list; + // 兼容只有单次痕迹的旧数据 + const single = row.payload?.refresh ?? row.payload?.reconcile_refresh; + return single ? [single] : []; +} + +/** `6 → 6.5 斤` 形式的展示片段 */ +function formatRefreshPair(entry: MainSystemActualQtyRefreshEntry): string { + const from = entry.from_value ?? null; + const to = entry.to_value ?? null; + const fromText = from === null ? '—' : `${from}${entry.from_unit || ''}`; + const toText = to === null ? '—' : `${to}${entry.to_unit || ''}`; + return `${fromText} → ${toText}`; +} + type PriceQtyStatus = MainSystemPriceQtyRequestDto['status']; const STATUS_FILTERS = ['all', 'pending', 'applied', 'approved', 'rejected', 'failed'] as const; @@ -88,9 +111,16 @@ export function PriceQtyRequestsPage() { /* ── 待我审核:主系统发起的实收/单位/完结后成本价申请(2026-10-11 第五批 Q8/Q9)── */ const [inboxRows, setInboxRows] = useState([]); - /** 已处理(已同步 / 已驳回)历史:事实登记 + 双方留痕,供对账与追责 */ + /** 已处理(已同步 / 已驳回 / 对方撤回)历史:事实登记 + 双方留痕,供对账与追责 */ const [inboxHistoryRows, setInboxHistoryRows] = useState([]); const [inboxLoading, setInboxLoading] = useState(false); + /** 服务端分页(2026-10-12):两区各自页码/总数;`counts` 用于区标题(不受分页影响) */ + const [inboxPage, setInboxPage] = useState(1); + const [inboxTotal, setInboxTotal] = useState(0); + const [historyPage, setHistoryPage] = useState(1); + const [historyTotal, setHistoryTotal] = useState(0); + const [inboxCounts, setInboxCounts] = useState({ pending: 0, processed: 0 }); + const INBOX_PAGE_SIZE = 20; /** 每行的草稿:改值(approved 用)与驳回原因 */ const [inboxDraft, setInboxDraft] = useState>({}); const [actingId, setActingId] = useState(null); @@ -98,21 +128,63 @@ export function PriceQtyRequestsPage() { const loadInbox = useCallback(async () => { setInboxLoading(true); try { - const [pending, all] = await Promise.all([ - listMainSystemActualQtyRequestsApi({ status: 'pending', limit: 100 }), - // 历史:一次取回后在本地按状态拆分(后端只支持单状态过滤) - listMainSystemActualQtyRequestsApi({ limit: 100 }), + // 服务端分页:待审 / 已处理两区各自取一页(不再一次拉全量) + const [pending, processed] = await Promise.all([ + listMainSystemActualQtyRequestsApi({ + scope: 'pending', + page: inboxPage, + pageSize: INBOX_PAGE_SIZE, + }), + listMainSystemActualQtyRequestsApi({ + scope: 'processed', + page: historyPage, + pageSize: INBOX_PAGE_SIZE, + }), ]); setInboxRows(Array.isArray(pending?.data) ? pending.data : []); - setInboxHistoryRows( - (Array.isArray(all?.data) ? all.data : []).filter((row) => row.status !== 'pending') - ); + setInboxTotal(Number(pending?.total) || 0); + setInboxHistoryRows(Array.isArray(processed?.data) ? processed.data : []); + setHistoryTotal(Number(processed?.total) || 0); + if (processed?.counts) setInboxCounts(processed.counts); + else if (pending?.counts) setInboxCounts(pending.counts); } catch (error: any) { notify.error(error?.message || t('orders.priceQty.inboxEmpty')); } finally { setInboxLoading(false); } - }, [t]); + }, [t, inboxPage, historyPage]); + + /** + * **提交前重取**(2026-10-12,开发者要求):主系统对"未处理"的申请是**原地更新为最新**, + * 而本页不轮询 ⇒ 审核人屏幕上可能是**旧值**。若拿旧值审批(尤其手填了旧值), + * 会把旧值写回去(对方那道基值守卫挡不住,因为它比对的是"期间是否被改",而 before/proposed 是一起刷新的)。 + * ⇒ 决策前先重取一次:值变了 / 已不是待审 ⇒ **拦下并要求重新确认**。 + */ + const isInboxRowStale = ( + shown: MainSystemActualQtyRequestDto, + fresh: MainSystemActualQtyRequestDto + ): boolean => { + const sameNum = (a: unknown, b: unknown) => { + const x = a === null || a === undefined || a === '' ? null : Number(a); + const y = b === null || b === undefined || b === '' ? null : Number(b); + if (x === null && y === null) return true; + if (x === null || y === null) return false; + return Math.abs(x - y) < 1e-9; + }; + const sameTime = (a: unknown, b: unknown) => { + const x = a ? new Date(String(a)).getTime() : null; + const y = b ? new Date(String(b)).getTime() : null; + if (x === null && y === null) return true; + if (x === null || y === null) return false; + return x === y; + }; + return ( + !sameNum(shown.proposed_value, fresh.proposed_value) || + !sameNum(shown.before_value, fresh.before_value) || + String(shown.unit ?? '') !== String(fresh.unit ?? '') || + !sameTime(shown.applied_at, fresh.applied_at) + ); + }; const decideInbox = async (row: MainSystemActualQtyRequestDto, decision: 'approved' | 'rejected') => { const draft = inboxDraft[row.id] || { finalValue: '', reason: '' }; @@ -122,6 +194,31 @@ export function PriceQtyRequestsPage() { notify.error(t('orders.priceQty.inboxField')); return; } + // ⚠️ 顺序很重要:**先重取、后置 busy**。若先 setActingId 再 return,按钮会永远停在忙碌态。 + try { + const freshList = await listMainSystemActualQtyRequestsApi({ status: 'pending', limit: 100 }); + const fresh = (Array.isArray(freshList?.data) ? freshList.data : []).find((r) => r.id === row.id); + if (!fresh) { + notify.error(t('orders.priceQty.inboxStaleGone')); + await loadInbox(); + return; + } + if (isInboxRowStale(row, fresh)) { + const shownValue = row.field === 'unit' ? row.unit : row.proposed_value; + const freshValue = fresh.field === 'unit' ? fresh.unit : fresh.proposed_value; + notify.error( + t('orders.priceQty.inboxStaleRefreshed', { + from: `${shownValue ?? '—'}`, + to: `${freshValue ?? '—'}`, + }) + ); + await loadInbox(); + return; + } + } catch (error: any) { + // 重取失败不阻断审核(保守:宁可让人审,也不因为一次查询失败卡死流程),但要把原因说清楚 + console.error('提交前重取实收申请失败:', error); + } setActingId(row.id); try { const result = await decideMainSystemActualQtyRequestApi(row.id, { @@ -129,7 +226,17 @@ export function PriceQtyRequestsPage() { final_value: decision === 'approved' ? finalValue : null, reason: draft.reason.trim() || null, }); - notify.success(result?.reason || t('common.save')); + /** + * ⚠️ 结果可能是 **suspended**(没有落成)——最常见的是版本过期: + * 主系统在我方审核期间把该申请**原地刷新**了,它会返回 409 且**不写任何值**, + * 后端已把最新值拉回来刷新本行并给出「请重新确认」的说明。 + * 这种情况**不能**报成功(否则审核人以为审完了,实际什么都没发生)。 + */ + if (result?.status === 'suspended') { + notify.error(result?.reason || t('common.save')); + } else { + notify.success(result?.reason || t('common.save')); + } await loadInbox(); void load(); } catch (error: any) { @@ -267,7 +374,7 @@ export function PriceQtyRequestsPage() {
{t('orders.priceQty.inboxTitle')} - {inboxRows.length ? `(${inboxRows.length})` : ''} + {inboxCounts.pending ? `(${inboxCounts.pending})` : ''} {t('orders.priceQty.inboxReviewNote')}
@@ -301,6 +408,7 @@ export function PriceQtyRequestsPage() { ) : null} {inboxRows.map((row, index) => { const draft = inboxDraft[row.id] || { finalValue: '', reason: '' }; + const refreshTrail = readRefreshHistory(row); const nodeKey = row.node === 'picking_check' ? 'orders.priceQty.nodePickingCheck' @@ -341,9 +449,38 @@ export function PriceQtyRequestsPage() { {row.unit && row.field === 'unit' ? row.unit : row.proposed_value} + {refreshTrail.length ? ( + + `${formatTime(entry.at)} ${formatRefreshPair(entry)}(${ + entry.source === 'reconcile' + ? t('orders.priceQty.refreshSourceReconcile') + : t('orders.priceQty.refreshSourceWebhook') + })` + ) + .join('\n')} + > + {t('orders.priceQty.refreshHint', { + pair: formatRefreshPair(refreshTrail[refreshTrail.length - 1]), + at: formatTime(refreshTrail[refreshTrail.length - 1].at), + })} + {refreshTrail.length > 1 + ? ` ${t('orders.priceQty.refreshHintMore', { count: refreshTrail.length })}` + : ''} + + ) : null} - - {row.applied_at ? formatTime(row.applied_at) : '—'} + + {row.applied_at ? formatTime(row.applied_at) : '—'} + {/* 版本徽标(主系统第七批 §12.3):纯数字,v3 = 你审的是第 3 版;对方"原地刷新"后数字会跳 */} + {typeof row.request_version === 'number' ? ( + + v{row.request_version} + + ) : null} {formatTime(row.created_at)} @@ -396,6 +533,43 @@ export function PriceQtyRequestsPage() { })} +
+ + {t('orders.priceQty.pageInfo', { page: inboxPage, total: Math.max(1, Math.ceil(inboxTotal / INBOX_PAGE_SIZE)) })} + + + + + +
{/* 已处理历史(2026-10-11 口径):事实登记 + 双方留痕 —— 主系统实际值/生效时间、 @@ -404,7 +578,7 @@ export function PriceQtyRequestsPage() {
{t('orders.priceQty.historyTitle')} - {inboxHistoryRows.length ? `(${inboxHistoryRows.length})` : ''} + {inboxCounts.processed ? `(${inboxCounts.processed})` : ''}
@@ -457,13 +631,15 @@ export function PriceQtyRequestsPage() { const nodeKey = row.node === 'picking_check' ? 'orders.priceQty.nodePickingCheck' - : row.node === 'inbound' - ? 'orders.priceQty.nodeInbound' - : row.node === 'admin_received_qty' - ? 'orders.priceQty.nodeAdminReceivedQty' - : row.node === 'post_complete_price' - ? 'orders.priceQty.nodePostCompletePrice' - : ''; + : row.node === 'picking_check_revert' + ? 'orders.priceQty.nodePickingCheckRevert' + : row.node === 'inbound' + ? 'orders.priceQty.nodeInbound' + : row.node === 'admin_received_qty' + ? 'orders.priceQty.nodeAdminReceivedQty' + : row.node === 'post_complete_price' + ? 'orders.priceQty.nodePostCompletePrice' + : ''; const fieldKey = row.field === 'qty' ? 'orders.priceQty.fieldQty' @@ -471,11 +647,16 @@ export function PriceQtyRequestsPage() { ? 'orders.priceQty.fieldUnit' : 'orders.priceQty.fieldPrice'; const synced = row.status === 'approved'; + // 2026-10-12:对方可在未审前撤回/作废(结果事件关闭该行)⇒ 单独一档展示 + const withdrawn = row.status === 'withdrawn' || row.status === 'superseded'; const applyNote = row.payload?.apply?.note || ''; + const historyTrail = readRefreshHistory(row); return ( - + ); })}
{index + 1}{row.item_name || row.prep_id || '-'} + {row.item_name || row.sku_code || row.prep_id || '-'} + {row.our_order_code || '-'} - {synced ? t('orders.priceQty.statusSynced') : t('orders.priceQty.statusRejectedNoSync')} + {synced + ? t('orders.priceQty.statusSynced') + : row.status === 'withdrawn' + ? t('orders.priceQty.statusWithdrawn') + : row.status === 'superseded' + ? t('orders.priceQty.statusSuperseded') + : t('orders.priceQty.statusRejectedNoSync')} @@ -512,12 +699,55 @@ export function PriceQtyRequestsPage() { {applyNote || row.decision_reason || '—'} + {historyTrail.length ? ( + + {t('orders.priceQty.refreshHintMore', { count: historyTrail.length })}: + {historyTrail.map((entry) => formatRefreshPair(entry)).join(' / ')} + + ) : null}
+
+ + {t('orders.priceQty.pageInfo', { page: historyPage, total: Math.max(1, Math.ceil(historyTotal / INBOX_PAGE_SIZE)) })} + + + + + +
diff --git a/src/pages/orders/orderManagement/OrderManagementPage.tsx b/src/pages/orders/orderManagement/OrderManagementPage.tsx index ec4ba8e..b54454c 100644 --- a/src/pages/orders/orderManagement/OrderManagementPage.tsx +++ b/src/pages/orders/orderManagement/OrderManagementPage.tsx @@ -87,7 +87,6 @@ import { reportOrderItemStockoutApi, listOrdersManagementApi, listOrderTrashApi, - submitOrderItemPriceQtyRequestApi, saveOrderItemsWithFulfillmentApi, updateOrderDeliveryDateApi, updateOrderDeliveryAddressApi, @@ -1730,16 +1729,19 @@ export const OrderManagement: React.FC = () => { const ORDER_ITEM_NUMBER_EPS = 1e-6; /** - * 跨系统改价/改量分流(设计 20261011 §4 C2/C6,2026-10-11 开发者口径): - * 主系统分配行的 price/quantity 变化**不走既有明细保存**,逐行提交申请; - * - 免审项(补价/改低/减量)提交后立即生效 ⇒ 回填最终生效值; - * - 涨价/加量 ⇒ pending 等主系统审核 ⇒ 回填原值(本地不落未审核的价/量); - * - 功能未开启(503 price_qty_disabled,当前默认关)⇒ **静默整批回退**:改动带回编辑值走既有链路 - * (后端守卫在开关关闭时同样放行,回退安全),不弹提示; - * - 其它失败(主系统未就绪/暂不可用/被拒)⇒ 回填原值(该行价/量不落地)+ 逐条汇总原因。 + * 跨系统改价/改量:**不再在界面上分流**(开发者 2026-10-12 口径:**先改后通知**)。 * - * 注意:这些行**不能从保存载荷里剔除** —— 明细保存是整单全量语义,后端把缺席的明细 id 判为 - * 「删除行」并 409(main_system_item_locked),故一律保留行、只回填价/量后再交回既有链路。 + * 为什么保留这个空壳而不是删掉调用点:调用点牵连保存主流程的三处 notify 汇总与 + * `itemsToSave` 变量,改结构属于范围外;这里只把"分流"行为取消,返回值恒等于"未改动", + * 于是 `itemsToSave === itemsToPersist`(用户编辑值原样交给既有保存链路)。 + * + * 旧行为(2026-10-11"先审后改")为什么必须取消: + * - 涨价/加量 pending ⇒ **回填原值** ⇒ 用户改完保存后界面又变回旧值(正是"改不动"); + * - 免审项 ⇒ 走单独的 `price-qty-request` 接口,与明细保存**两个写入者**,谁后写谁赢。 + * 新链路:明细保存照常写库 ⇒ 后端在 **COMMIT 之后**异步通知主系统 + * (`orderManageItemsService` 的 `notifyMainSystemPriceQtyChanges`),对方同意/驳回都不回改我方值。 + * 自采列表的改销售价同理(`purchaseLinkedSalePriceService`)。 + * 见 docs/design/20261011-跨系统改价改量审核.md §10。 */ const routeMainSystemPriceQtyChanges = async (params: { order: Order; @@ -1749,105 +1751,20 @@ export const OrderManagement: React.FC = () => { items: OrderItem[]; applied: number; pending: number; - /** 主系统已生效但本地落地失败(`applied_locally=false`):本地保持原值,等后端自动重试 */ + /** 保留字段:新口径下恒为 0(本地落地由后端写入,不存在"主系统已生效但本地没落") */ notLanded: number; notLandedNotes: string[]; failures: string[]; - }> => { - const unchanged = { + }> => + // 保留行、不改值:明细保存是整单全量语义,缺席的明细 id 会被后端判为「删除行」并 409。 + ({ items: params.items, applied: 0, pending: 0, notLanded: 0, notLandedNotes: [] as string[], failures: [] as string[], - }; - const originalById = new Map(params.originals.map((row) => [row.id, row])); - const candidates = params.items.filter((item) => { - if (item.is_returned || isTempOrderItemId(item.id)) return false; - const original = originalById.get(item.id); - if (!original) return false; - if (!isMainSystemOrderLine(params.order, item)) return false; - return ( - Math.abs((Number(original.price) || 0) - (Number(item.price) || 0)) > - ORDER_ITEM_NUMBER_EPS || - Math.abs((Number(original.quantity) || 0) - (Number(item.quantity) || 0)) > - ORDER_ITEM_NUMBER_EPS - ); }); - if (!candidates.length) return unchanged; - - const overrideById = new Map(); - let applied = 0; - let pending = 0; - let notLanded = 0; - let featureDisabled = false; - const notLandedNotes: string[] = []; - const failures: string[] = []; - for (const item of candidates) { - const original = originalById.get(item.id) as OrderItem; - const beforePrice = Number(original.price) || 0; - const beforeQty = Number(original.quantity) || 0; - const nextPrice = Number(item.price) || 0; - const nextQty = Number(item.quantity) || 0; - const priceChanged = Math.abs(beforePrice - nextPrice) > ORDER_ITEM_NUMBER_EPS; - const qtyChanged = Math.abs(beforeQty - nextQty) > ORDER_ITEM_NUMBER_EPS; - const label = String(item.item_name || item.sku_name || '').trim() || item.id; - try { - const result = await submitOrderItemPriceQtyRequestApi(params.order.order_code, item.id, { - proposed_price: priceChanged ? nextPrice : undefined, - proposed_qty: qtyChanged ? nextQty : undefined, - }); - if (result.status === 'applied') { - if (result.applied_locally === false) { - // ⚠️ 主系统已生效、本地落地失败(如订单已结案/并发改动):本地**必须保持原值**, - // 否则等于"没落地却按新值保存",两边彻底错位;后端已把台账退回 pending 自动重试。 - notLanded += 1; - notLandedNotes.push(`${label}: ${result.apply_note || '本地待同步'}`); - overrideById.set(item.id, { price: beforePrice, quantity: beforeQty }); - } else { - applied += 1; - overrideById.set(item.id, { - price: Number(result.final_price ?? nextPrice), - quantity: Number(result.final_qty ?? nextQty), - }); - } - } else { - pending += 1; - overrideById.set(item.id, { price: beforePrice, quantity: beforeQty }); - } - } catch (err) { - const code = String((err as { code?: unknown } | null)?.code || ''); - // 功能未开启(默认关):整批静默回退到既有保存链路,不再逐行试提交 - if (code === 'price_qty_disabled') { - featureDisabled = true; - break; - } - // 目标值已等于主系统侧现值(重复保存/上一轮已生效)⇒ 编辑值本来就在库里,无需提交 - if (code === 'no_change') continue; - // 后端判定该行不属于主系统分配 ⇒ 老链路本来就是对的(真属于则由后端守卫再拦) - if (code === 'not_main_system_item') continue; - overrideById.set(item.id, { price: beforePrice, quantity: beforeQty }); - failures.push(`${label}: ${err instanceof Error ? err.message : '提交失败'}`); - } - } - const items = params.items.map((item) => { - const override = overrideById.get(item.id); - if (!override) return item; - const next = { ...item, ...override }; - next.amount = Math.round(Number(next.quantity) * Number(next.price) * 100) / 100; - return next; - }); - // 功能未开启:不报错(正常状态),已提交成功的少数行仍按其生效值回填 - return { - items, - applied, - pending, - notLanded, - notLandedNotes, - failures: featureDisabled ? [] : failures, - }; - }; /** 提交结果一次性汇总(沿用页面既有 notify 提示):N 项已生效 / M 项待审核 / K 项提交失败 */ const buildPriceQtySubmitSummary = (result: { @@ -1926,7 +1843,7 @@ export const OrderManagement: React.FC = () => { ); } - // 跨系统改价/改量:主系统来源行的价/量变化先走申请,其余行照旧(设计 20261011 C6) + // 跨系统改价/改量:**先改后通知**,界面不再分流(2026-10-12 口径,见函数注释) const priceQtyRouting = itemsEditable ? await routeMainSystemPriceQtyChanges({ order: selectedOrder, diff --git a/src/pages/orders/orderManagement/orderManagementPage.priceQtyLocalFirst.test.ts b/src/pages/orders/orderManagement/orderManagementPage.priceQtyLocalFirst.test.ts new file mode 100644 index 0000000..804e6cc --- /dev/null +++ b/src/pages/orders/orderManagement/orderManagementPage.priceQtyLocalFirst.test.ts @@ -0,0 +1,41 @@ +import { readFileSync } from 'node:fs'; +import { describe, expect, it } from 'vitest'; + +/** + * 订单明细页:跨系统改价/改量的**界面分流必须保持关闭**(开发者 2026-10-12 口径:先改后通知)。 + * + * 事故背景(这条钉子的由来):2026-10-11 的"先审后改"在界面做了一次分流 —— + * 主系统来源行的价/量改动**不走明细保存**,改走高一个 `price-qty-request` 接口, + * 并把"待审核"的行**回填成原值**。表现就是用户改完保存后**值又变回去了("改不动")**, + * 而且与明细保存形成**两个写入者**(谁后写谁赢)。 + * + * 新口径下:明细保存照常写库,后端在 **COMMIT 之后**异步通知主系统; + * 因此界面必须**原样把用户编辑值交给保存链路**(`itemsToSave === itemsToPersist`)。 + */ +const src = readFileSync(new URL('./OrderManagementPage.tsx', import.meta.url), 'utf8'); + +describe('订单明细页:主系统行改价/改量不再被界面回填/拦截', () => { + it('分流函数恒为"未改动":不回填原值、不计数、不报失败', () => { + const start = src.indexOf('const routeMainSystemPriceQtyChanges = async'); + expect(start).toBeGreaterThan(0); + const body = src.slice(start, src.indexOf('const buildPriceQtySubmitSummary')); + expect(body).toContain('items: params.items'); + expect(body).toContain('applied: 0'); + expect(body).toContain('pending: 0'); + expect(body).toContain('notLanded: 0'); + expect(body).toContain('failures: [] as string[]'); + // 不得再出现"回填"逻辑与逐行提交 + expect(body).not.toContain('overrideById'); + expect(body).not.toContain('beforePrice'); + expect(body).not.toContain('submitOrderItemPriceQtyRequestApi'); + }); + + it('页面不再导入/调用改价改量申请接口(通知由后端在 COMMIT 后发)', () => { + expect(src).not.toContain('submitOrderItemPriceQtyRequestApi'); + }); + + it('保存链路仍以分流结果为输入(结构未动,便于后续再切回)', () => { + expect(src).toContain('const itemsToSave = priceQtyRouting.items;'); + expect(src).toContain('priceQtySummary = buildPriceQtySubmitSummary(priceQtyRouting);'); + }); +}); diff --git a/src/utils/workflowApi.ts b/src/utils/workflowApi.ts index 0ff7009..08fa0a6 100644 --- a/src/utils/workflowApi.ts +++ b/src/utils/workflowApi.ts @@ -778,6 +778,17 @@ export async function submitOrderItemPriceQtyRequestApi( /** 跨系统改价/改量申请列表(只读台账);`enabled` 为功能总开关,关闭时列表恒空 */ /** 对方(主系统)发起、**我方审核**的实收/单位/完结后成本价申请 */ +/** 主系统把**未处理**的申请原地刷新为最新值时留下的痕迹(from → to,含时间与来源) */ +export interface MainSystemActualQtyRefreshEntry { + at?: string | null; + from_value?: number | null; + from_unit?: string | null; + to_value?: number | null; + to_unit?: string | null; + /** webhook=事件到达时刷新;reconcile=Q6 对账刷新 */ + source?: string | null; +} + export interface MainSystemActualQtyRequestDto { id: string; request_id: string; @@ -793,7 +804,7 @@ export interface MainSystemActualQtyRequestDto { unit: string | null; operator: string | null; reason: string | null; - status: 'pending' | 'approved' | 'rejected' | 'superseded'; + status: 'pending' | 'approved' | 'rejected' | 'superseded' | 'withdrawn'; final_value: number | null; reviewer: string | null; decided_at: string | null; @@ -802,21 +813,53 @@ export interface MainSystemActualQtyRequestDto { fact_registered: boolean; /** 主系统实际值在其侧生效的时刻(新口径"事实登记"的时间锚点) */ applied_at: string | null; + /** + * 主系统台账行的**权威整数版本**(原地刷新 +1;主系统第七批 §12.3)。 + * 审核回执会把它原样回带(`decided_basis_version`);对方发现版本不一致 ⇒ 409 且不写值, + * 后端会把最新值拉回来刷新本行并提示"请重新确认"。`null` = 对方未提供(旧版载荷)。 + */ + request_version?: number | null; /** 我方落值结论(审核同意时由后端写入:status/note/at) */ - payload?: { apply?: { status?: string; note?: string; at?: string } } | null; + payload?: { + apply?: { status?: string; note?: string; at?: string }; + /** 单次刷新痕迹(最近一次,兼容旧数据) */ + refresh?: MainSystemActualQtyRefreshEntry; + reconcile_refresh?: MainSystemActualQtyRefreshEntry; + /** **完整刷新历史**:主系统"未处理就地更新为最新"时逐次追加,审核页可追溯 */ + refresh_history?: MainSystemActualQtyRefreshEntry[]; + } | null; /** 台账 LEFT JOIN 出来的商品名 */ item_name?: string | null; created_at: string; } -export async function listMainSystemActualQtyRequestsApi(params?: { status?: string; limit?: number }) { +/** + * 实收申请列表(**服务端分页**,2026-10-12): + * · `scope`:`pending` 待我审核 / `processed` 已处理历史 / `all`; + * · `status` 精确值优先于 `scope`; + * · 返回 `total`(当前过滤的总行数)与 `counts`(两区各自总数,供区标题显示)。 + */ +export async function listMainSystemActualQtyRequestsApi(params?: { + status?: string; + scope?: 'pending' | 'processed' | 'all'; + page?: number; + pageSize?: number; + limit?: number; +}) { const query = new URLSearchParams(); if (params?.status) query.set('status', params.status); + if (params?.scope) query.set('scope', params.scope); + if (params?.page) query.set('page', String(params.page)); + if (params?.pageSize) query.set('page_size', String(params.pageSize)); if (params?.limit) query.set('limit', String(params.limit)); const suffix = query.toString() ? `?${query.toString()}` : ''; - return workflowFetch<{ data: MainSystemActualQtyRequestDto[] }>( - `/main-system/actual-qty-requests${suffix}` - ); + return workflowFetch<{ + data: MainSystemActualQtyRequestDto[]; + total: number; + page: number; + page_size: number; + counts: { pending: number; processed: number }; + }>(`/main-system/actual-qty-requests${suffix}`); } /** 审核结论回传主系统(成功后才改本地台账):通过 / 改值后通过 / 驳回 */ @@ -824,6 +867,7 @@ export async function decideMainSystemActualQtyRequestApi( id: string, body: { decision: 'approved' | 'rejected'; final_value?: number | null; reason?: string | null } ) { + // status: done=已落结论;ignored=已是终态/不存在;**suspended=未落结论**(如版本过期 409、回执失败) return workflowFetch<{ data: { status: string; reason: string; duplicate: boolean } }>( `/main-system/actual-qty-requests/${encodeURIComponent(id)}/decision`, { method: 'POST', body: JSON.stringify(body) }