feat(报价单): 报价同步(成本价同步/改价审核/双向价格传递)+ 待报价软删除
合并 feat/quote-price-sync 的报价单与竞价台账改动,补齐类型(includeDeleted/deletedAt)与缺失文件 (mainSystem/api/quotePriceProposals.ts、迁移 20261058)。
This commit is contained in:
@@ -0,0 +1,166 @@
|
||||
# SKU 映射与成本传递(供应商系统侧)
|
||||
|
||||
- 日期:2026-10-18(第四个增量)
|
||||
- 用户原话:「两个系统的 sku 哪怕是同一个商品 sku 都是不一致的 所以映射这个需要建立…同一个商品 看 sku 匹配基本上 匹配到的全是错误的」
|
||||
- 冻结契约:`.team/sku-mapping-shared-sheet/contract.md`(不入库)
|
||||
- 前序交付:`docs/design/20261018-报价单双向价格传递与审批.md`(A/B 双向提议、T1–T10 裁定)、
|
||||
`docs/design/20261018-报价单成本价同步推送.md`(rearm 推送通道)
|
||||
- 本文件只写**供应商系统侧**(配送侧 D4/D5 的服务实现、共享单写入与批次回滚见对方仓库)
|
||||
|
||||
## 1. 用户冻结的 4 个决策
|
||||
|
||||
1. 允许写共享单(配送侧改)、审核前预检、批次可回滚 —— **配送侧**实现,本侧不碰;
|
||||
2. **SKU 映射在配送系统维护,供应商侧只读同步**(不可编辑、不按名称猜);
|
||||
3. 单位不一致 ⇒ **跳过并标注**(不引入换算);
|
||||
4. 写价范围保持"该分公司所有生效报价单里命中该 SKU 的行" —— 配送侧口径,本侧不变。
|
||||
|
||||
## 2. 本地映射副本(tenant 表)
|
||||
|
||||
迁移:`migrations/20261018_main_system_sku_mappings.sql`(新增业务表四步:建表 → 登记
|
||||
`public.tenant_business_tables()` **118 → 119** → `ensure_tenant_schemas_match_template()` →
|
||||
`assert_tenant_template_matches_business_tables()`;可重放)。
|
||||
|
||||
`main_system_sku_mappings`(每个分公司 schema 一份):
|
||||
|
||||
| 列 | 说明 |
|
||||
| --- | --- |
|
||||
| `supplier_sku_code` | 我方 `skus.sku_code`(D4 推送的字典项) |
|
||||
| `supplier_sku_name` / `supplier_unit` | 我方名称/单位快照(只展示) |
|
||||
| `delivery_sku_code` | 配送侧商品编码;NULL / `pending` = 未映射 |
|
||||
| `delivery_sku_name` | 配送侧名称快照 |
|
||||
| `status` | 照抄对方:`active` / `disabled` / `pending`(CHECK 三值) |
|
||||
| `synced_at` | 最近一次 D5 同步时间(排障/定时任务) |
|
||||
|
||||
索引:
|
||||
|
||||
- 唯一 `(supplier_sku_code)` ⇒ **一个我方 SKU 只有一行**(D5 的 `ON CONFLICT` upsert 才真正幂等);
|
||||
- 部分唯一 `(delivery_sku_code) WHERE delivery_sku_code IS NOT NULL AND status='active'`
|
||||
⇒ 一个配送商品不被两个我方 SKU 占用(方向 B 反查唯一);
|
||||
- `(status, supplier_sku_code)` 列表/筛选。
|
||||
|
||||
> 只有 `status='active'` **且** `delivery_sku_code` 非空才算"已映射";`pending`/`disabled` 一律算未映射。
|
||||
|
||||
## 3. 出站两个动作(只走既有 token/http 封装)
|
||||
|
||||
| # | 端点(配送侧) | 本侧封装 |
|
||||
| --- | --- | --- |
|
||||
| **D4** | `POST {skuMappings}/sync`,body `{main_branch_code, items:[{sku_code,name,unit}]}`(≤**5000**/批) | `mainSystem/api/skuMappings.ts#pushSkuDictionary` |
|
||||
| **D5** | `GET {skuMappings}?main_branch_code=&status=&limit=&cursor=` | `#pullSkuMappings` |
|
||||
|
||||
- 端点表加一行 `skuMappings: '/api/supplier/sku-mappings'`(`mainSystem/config.ts`);
|
||||
D4 子路径 `mainSystemSkuMappingSyncPath()` 唯一拼装;路径可被 `MAIN_SYSTEM_SKU_MAPPINGS_PATH` 覆盖
|
||||
(已登记 `.env.example` 与部署手册)。
|
||||
- `supplier_code` 只由 token 决定(请求体不带);401 强制刷新一次;403 视为语义拒绝。
|
||||
- D4 回执 `{matched, pending, kept, total}`;D5 行字段照契约表(`supplier_sku_code`/`delivery_sku_code`/
|
||||
`delivery_sku_name`/`supplier_sku_name`/`supplier_unit`/`status`/`match_type`/`updated_at`),支持 `next_cursor`。
|
||||
- **出站全部在事务之外**。
|
||||
|
||||
## 4. 服务(`server/src/services/skuMappingService.ts`)
|
||||
|
||||
| 函数 | 行为 |
|
||||
| --- | --- |
|
||||
| `isSkuMappingEnabled()` | 复用开关 `MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL`(默认关;关 ⇒ 零出站) |
|
||||
| `pushSkuDictionaryForBranch(branchCode)` | 取本分公司 `skus` 中 `status IS NULL OR status=1` 的商品(`sku_code/sku_name/unit`),**按 5000 分批**推 D4,汇总 matched/pending/kept/total |
|
||||
| `pullMappingsFromMainSystem(branchCode)` | D5 按 `next_cursor` 翻页直到 null(上限 50 页 × 200),逐行**幂等 upsert**;**只有证明拉全**才删除远端已不存在的行(见下) |
|
||||
| `getMappingByDeliverySku(branch, deliverySku)` | 方向 B 反查:只认 `status='active'` 且 `delivery_sku_code` 非空 |
|
||||
| `getSheetMappingStats(quoteSheetCode)` | 「本单 N 个商品,已映射 X / 未映射 Y」+ 未映射清单(**不按名称猜**) |
|
||||
| `listLocalSkuMappings(branch)` | 只读列表 + 汇总(total/mapped/unmapped) |
|
||||
| `pullMappingsForAllBranches()` | 定时任务入口:按 `public.main_supplier_bindings` 的 active 分公司逐个拉;单点失败记 errors 不中断 |
|
||||
|
||||
- **完整性判据(verifier 阻断项:>200 行误删本地映射)**:`complete` 必须成立才允许 `DELETE ... WHERE supplier_sku_code <> ALL(拉到的集合)`:
|
||||
- 翻页到 `next_cursor` 为 null,**且**(已收行数 ≥ 对方 `total`,或**最后一页是短页** rows < limit);
|
||||
- 首屏恰好 200 行、对方既没给 `total` 也没给 `next_cursor` ⇒ **无法证明拉全 ⇒ `truncated=true`、本次不删**;
|
||||
- 任一页失败 / 翻页超上限 / 无法证明完整 ⇒ `truncated=true`、**不删**本地多余行,只做部分 upsert,并 `console.warn` 记日志。
|
||||
- 拉取写入统一用 `runWithTenantDbContext(branch, ..., {isolate:true, requestClient:false})`:
|
||||
定时任务与请求内走同一条路径,不必区分有没有请求级连接(`skus` 读取同样在该上下文里)。
|
||||
- upsert 万一撞"配送商品唯一"约束 ⇒ 跳过该行 + `conflicts++` + 日志(不破坏已有映射)。
|
||||
|
||||
## 5. 方向 B 审批改造(`quotePriceProposalService.ts`)
|
||||
|
||||
提议 `items[].sku_code` 是**配送 SKU**:
|
||||
|
||||
1. 逐条 `getMappingByDeliverySku(branch, deliverySku)` 反查我方 SKU;查不到 ⇒ skip **`sku_unmapped`**(不写价);
|
||||
2. 多个配送 SKU 映射到同一我方 SKU ⇒ 只处理第一个,其余 skip `duplicate_supplier_sku`(避免重复计数/审计);
|
||||
3. 我方 SKU 不在本单 ⇒ skip `sku_not_in_sheet`;单位不一致(payload 单位 vs 行单位,双方非空)⇒ `unit_mismatch`;
|
||||
4. 其余**完全沿用上一轮 T3 口径**:`UPDATE customer_quote_sheet_items SET sale_price=$3, price=$3 WHERE quote_sheet_code=$1 AND sku_code=$2`(按行、只改已有行、不 INSERT/DELETE);
|
||||
5. **通过后不再调用 `triggerQuoteCostSync`**(2026-10-18 verifier 阻断项):旧通道按 `sku_code` 直猜且跳过共享单,
|
||||
两个系统 SKU 本就不一致 ⇒ 配送 `cost_price` 会静默不变。现在只发 **D3 回执 `approved`(带 `applied`)**,
|
||||
由**配送侧**用提议里的**配送 SKU** 落地写价(共享单同样按映射写)。
|
||||
`triggerQuoteCostSync` 只保留在**报价单生效自动推**那条链路(`quoteSheetService`)。
|
||||
6. **绝不按 sku_code 直接猜**(旧逻辑作废)。
|
||||
|
||||
列表「改前 → 改后」也按映射反查;未映射行标 `change='unmapped'`。
|
||||
|
||||
## 6. 提交前映射统计
|
||||
|
||||
`POST /quote/sheets/:code/price-proposals` 的响应新增:
|
||||
|
||||
```json
|
||||
"mapping": { "quote_sheet_code": "QS...", "total": 12, "mapped": 9, "unmapped": 3,
|
||||
"unmapped_skus": [{"sku_code": "SKU9", "sku_name": "…"}] }
|
||||
```
|
||||
|
||||
未映射**不阻止**提交(配送侧写价会 skip `sku_unmapped`),但响应里必须给出计数;前端在提交前另调
|
||||
`GET /quote/sheets/:code/mapping-stats` 先提示「本单 N 个商品,已映射 X / 未映射 Y」。
|
||||
|
||||
## 7. 内部端点(不新增对外 HTTP 接口)
|
||||
|
||||
| 端点 | 权限 | 行为 |
|
||||
| --- | --- | --- |
|
||||
| `POST /workflow/quote/sku-mappings/sync-dictionary` | `customer_manage` | 推 D4(分批)→ 拉 D5 刷新本地副本,返回 `{push, pull}` |
|
||||
| `GET /workflow/quote/sku-mappings?refresh=1&status=&q=&limit=` | `customer_manage \| order_manage` | 只读列表 + 汇总;`refresh=1` 先拉 D5 |
|
||||
| `GET /workflow/quote/sheets/:code/mapping-stats` | `customer_manage \| order_manage` | 提交前映射统计 |
|
||||
|
||||
开关关闭 ⇒ 三条一律 503 `feature_disabled`;本侧**没有任何写映射的端点**(映射由配送侧维护)。
|
||||
|
||||
## 8. 定时任务
|
||||
|
||||
`scheduledJobs.ts` 主系统锁块内新增 `runSkuMappingSync()`:
|
||||
|
||||
- **每天一次**(进程内按本地日期去重;重启多跑一次,安全);
|
||||
- 按 active 绑定分公司逐个 **先推 D4 字典、再拉 D5 映射**(`syncDictionaryAndMappingsForAllBranches`);
|
||||
- 日志同时给两个计数:`推送字典 X 条(B 批)、写入映射 Y 行、异常 Z`;
|
||||
- 开关关闭 ⇒ 直接返回(零出站);单点失败只记日志/计数,不中断其它任务。
|
||||
|
||||
## 9. 前端
|
||||
|
||||
- 报价单页工具栏新增「同步商品字典」按钮(`customer_manage`):D4 推 + D5 拉,成功提示
|
||||
「商品字典已同步:已匹配 {matched} 个、待映射 {pending} 个」;
|
||||
- 点「提交配送商审核」前先取映射统计并提示「本单 N 个商品,已映射 X / 未映射 Y」,未映射**不阻止**提交;
|
||||
- 新增页内页签「商品映射」(只读):展示 我方商品/SKU ↔ 配送商品/SKU、单位、状态;「只看未映射」筛选 + 关键字搜索;
|
||||
**没有编辑/绑定/解绑入口**(映射在配送侧维护);
|
||||
- 开关关闭 ⇒ 空态显示后端原文,不弹 toast;
|
||||
- i18n 三语(`zh-CN`/`en`/`id`)同增同名 key。
|
||||
|
||||
## 10. 本轮不做 / 已知限制
|
||||
|
||||
1. 字典推送有两条路径:报价单页「同步商品字典」按钮(即时)+ **每天一次的定时推送**;我方商品新增/改名最迟次日进入对方自动配对。
|
||||
2. 本地映射是**只读副本**,D5 之前可能短暂过期;方向 B 审批依赖本地副本(配送侧修好映射后需等一次同步/手动刷新)。
|
||||
3. D5 分页游标参数名沿用 `cursor`;真实环境已验证会返回 `next_cursor`(10 行数据实测 pages=2,见交付报告)。
|
||||
4. 截断(>50 页)时**不删除**本地多余行(宁可保留旧行也不误删)。
|
||||
5. 共享单写入、审核前 preview(P1)、批次回滚(P3)属**配送侧**本增量范围,本侧不实现。
|
||||
6. 未真机联调;所有出站均 mock/契约文本为准。
|
||||
|
||||
## 11. 验收对照
|
||||
|
||||
| # | 判据 | 怎么验 |
|
||||
| --- | --- | --- |
|
||||
| 1 | 迁移:tenant 表 + 名单 118→119 + 可重放 | 本地重放 + `assert_tenant_template_matches_business_tables` |
|
||||
| 2 | D4:只推有效商品、>5000 分批、汇总 | 单测(5001 条 → 2 批) |
|
||||
| 3 | D5:翻页 + 幂等 upsert + 完整拉取删多余 + 截断不删 | 单测 + 真库(唯一键/upsert/删除) |
|
||||
| 4 | 开关关闭 ⇒ 零出站 | 单测(D4 503、D5 空跑、定时 skipped) |
|
||||
| 5 | 方向 B:未映射 ⇒ skip `sku_unmapped` 零写价 | 单测 |
|
||||
| 6 | 方向 B:已映射(配送 SKU ≠ 我方 SKU)⇒ 写我方行 | 单测 |
|
||||
| 7 | 提交响应带 total/mapped/unmapped | 单测 + 页面接线契约测试 |
|
||||
| 8 | 前端:同步按钮 + 只读映射页签 + 提交前统计 | render 测试 + 契约测试 |
|
||||
| 9 | **B 审批不再走旧成本同步通道** | 单测:`triggerQuoteCostSync` 未被调用;D3 `approved` 带 `applied` |
|
||||
| 10 | **D5 >200 行不误删** | 单测:首屏 200 行无 cursor 无 total ⇒ truncated=true、deleted=0、本地行原样;翻页中途失败同理;完整拉取才删 |
|
||||
| 11 | **每天定时 D4+D5** | 单测:`syncDictionaryAndMappingsForAllBranches` 返回 push/pull 计数;开关关 ⇒ skipped |
|
||||
| 12 | 不新增对外 HTTP 接口 | 本侧只有内部 `/workflow/*` 路由 |
|
||||
| 13 | 三语 key 齐备 | i18n 三文件同 key |
|
||||
|
||||
## 12. 回滚
|
||||
|
||||
1. 开关 `MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL=0` ⇒ 映射同步/审批全部零出站(已落库副本保留只读);
|
||||
2. 代码回滚 = 还原 `skuMappingService`/`api/skuMappings`/路由/前端面板与页签;迁移表保留(纯追加);
|
||||
3. 迁移文件不含"用本地数据覆盖线上"的语句。
|
||||
@@ -0,0 +1,200 @@
|
||||
# 报价单双向价格传递与审批(供应商系统侧)
|
||||
|
||||
- 日期:2026-10-18
|
||||
- 用户原话:「报价单 供应商可以提起传递让配送商审核供应商的销售价;配送商可以提起传递让供应商审核配送商的成本价;审核通过就可以传递到报价单,然后和报价单相关的客户订单里面的价格按照报价单来进行。」
|
||||
- 冻结契约:`.team/quote-price-cross-approval/contract.md`(不入库)+ Lead 2026-10-18 的 T1–T10 裁定
|
||||
- 复用前置交付:`docs/design/20261018-报价单成本价同步推送.md`(台账 + rearm 推送)、
|
||||
`docs/design/20261018-报价单改价审核与成本同步.md`(内部改价审核)
|
||||
- 本文件只写**供应商系统侧**;配送系统侧见对方仓库同名设计文档
|
||||
|
||||
## 1. 一句话与两个方向
|
||||
|
||||
一个金额 V(我方 `sale_price` = 配送商 `cost_price`,**同一个数**)可在两个方向协商:
|
||||
|
||||
| 方向 | 谁发起 | 谁审 | 通过后写谁 | 同步方式 |
|
||||
|---|---|---|---|---|
|
||||
| **A `to_delivery`** | 我方(供应商) | 配送商 | 配送商写自己 `cost_price` | 对方内部写入(我方不推) |
|
||||
| **B `from_delivery`** | 配送商 | 我方(供应商) | 我方写自己 `sale_price` | **既有成本价同步通道** rearm 推对方 `cost_price` |
|
||||
|
||||
两边都**不新增反向写入通道**:结果靠对方只读接口轮询(D2),不新增 webhook 事件。
|
||||
|
||||
## 2. 关键裁定(T1–T10)与本侧落点
|
||||
|
||||
| # | 裁定 | 本侧实现 |
|
||||
|---|---|---|
|
||||
| T1 | 订单价不变,只改成本(订单行价读 `sale_price`;协商的是成本价,变化的是毛利) | **不碰订单取价公式**;B 通过只写 `customer_quote_sheet_items.sale_price/price` |
|
||||
| T2 | 方向 B 目标单按 `MAIN_<main_branch_code>` 解析**唯一生效单**;0 张 ⇒ 409 `no_quote_sheet`,多张 ⇒ 409 `ambiguous_sheet`(不扇出) | `resolveActiveSheetCodeForMainBranch()`:`status=1 & approval_status=30 & 未过期 & EXISTS(客户=MAIN_X)`;同步拉回时解析、审批时再解析兜底 |
|
||||
| T3 | 方向 B **只改被提出的 SKU**(合并语义,按行 UPDATE),**禁止整表替换** | 见 §4 的 SQL 形态;**不调用** `applyQuoteSheetUpdate` |
|
||||
| T4 | B 通过不再走内部审核(不生成 `quote_sheet_change_requests`) | B 审批只写 proposal 状态,不碰内部审核表 |
|
||||
| T5 | 方向 A 写价沿用配送侧"分公司扇出";共享单整张跳过(配送侧内核) | 本侧只负责提交,评价口径属配送侧 |
|
||||
| T6 | 同方向重复提交:覆盖旧 pending(旧的置 `superseded`)+ 同 `client_request_id` 同 hash 回放、不同 hash 409 | 见 §5 |
|
||||
| T7 | pending 不过期 | 无自动作废逻辑;列表返回 `waited_days` 供 UI 展示等待天数 |
|
||||
| T8 | D3 回执失败补偿:不新建回执表;下次 D2 轮询发现"本地终态 + 远端 pending"时重发(幂等) | `applyRemoteRow()` 内重发 D3 |
|
||||
| T9 | A 通过但配送侧零写入:状态仍 `approved`,`applied.updated=0` + skipped 原因照实展示 | 同步只回写状态;`applied` 原样保存在对方回执里(本侧列表不伪造) |
|
||||
| T10 | D2 游标:服务端 `next_cursor`(复合 `(updated_at, id)`),客户端带上,不全量扫 | `syncCursors` 按 supplier_code 记忆,D2 请求带 `cursor`,用返回的 `next_cursor` 更新 |
|
||||
|
||||
## 3. 数据模型(tenant 表)
|
||||
|
||||
迁移:`migrations/20261018_quote_price_proposals.sql`(按仓库「新增业务表四步」):
|
||||
|
||||
1. 各租户 schema 建表(锚点 = `customer_quote_sheets` 存在);
|
||||
2. `public.tenant_business_tables()` 117 → **118**;
|
||||
3. `ensure_tenant_schemas_match_template()` 补建;
|
||||
4. `assert_tenant_template_matches_business_tables()` 断言。
|
||||
|
||||
`quote_price_proposals`:
|
||||
|
||||
| 列 | 含义 |
|
||||
| --- | --- |
|
||||
| `id` | uuid 主键 |
|
||||
| `branch_code` / `quote_sheet_code` / `main_branch_code` | 我方分公司 / 我方报价单 / 对方(主系统)分公司 |
|
||||
| `direction` | `to_delivery`(A)/ `from_delivery`(B) |
|
||||
| `items` | 整单快照 `[{sku_code, unit, price}]`(A=我方销售价;B=对方成本价,同一个数) |
|
||||
| `payload_hash` | 提交快照的 sha256(T6 回放判据 / 排障) |
|
||||
| `status` | `pending` / `approved` / `rejected` / `cancelled` / **`superseded`**(T6) |
|
||||
| `reject_reason` | 驳回理由(两方向都可读) |
|
||||
| `client_request_id` | D1 幂等号(B 行为空,由对方发起) |
|
||||
| `remote_proposal_id` | 对方 proposal id:A 结果同步 / B 的 D3 回执都靠它 |
|
||||
| `requested_by` / `requested_at` | 发起人(B 由 D2 拉回时为空,展示对方为发起方)+ 时间(T7 等待天数基准) |
|
||||
| `reviewed_by` / `reviewed_at` / `applied_at` / `updated_at` | 审批留痕 |
|
||||
|
||||
索引:
|
||||
|
||||
- **partial unique** `(branch_code, quote_sheet_code, direction) WHERE status='pending'` ⇒ 一张单一个方向只允许一条在途;
|
||||
- `(branch_code, direction, status, requested_at DESC)` 列表;
|
||||
- `(remote_proposal_id)` 对账定位。
|
||||
|
||||
> ⚠️ **`status` CHECK 必须含 `superseded`**(T6)。迁移里对已存在的表先 `DROP CONSTRAINT IF EXISTS` 再
|
||||
> `ADD CONSTRAINT` ⇒ **可重放**;真库 integration 钉住(`quotePriceProposalDb.integration.test.ts`)。
|
||||
|
||||
## 4. 出站(只走既有封装)
|
||||
|
||||
| 动作 | 端点(对方) | 本侧封装 |
|
||||
|---|---|---|
|
||||
| A 提交 | `POST /api/supplier/quote-sheets/price-proposals`(D1) | `mainSystem/api/quotePriceProposals.ts#submitQuotePriceProposal` |
|
||||
| A 结果 + B 拉取 | `GET .../price-proposals?status=&cursor=&limit=`(D2) | `#listQuotePriceProposals` |
|
||||
| B 回执 | `POST .../price-proposals/:id/decision`(D3) | `#decideQuotePriceProposal` |
|
||||
|
||||
- 端点路径只在 `mainSystem/config.ts` 端点表 + `endpoints.ts` 拼(`MAIN_SYSTEM_QUOTE_PRICE_PROPOSALS_PATH` 可覆盖,
|
||||
D3 子路径由 `mainSystemQuotePriceProposalDecisionPath()` 唯一拼装);token 走 `mainSystem/token.ts`(401 强制刷新一次);
|
||||
HTTP 走 `mainSystem/http.ts`(四态 + 403 语义拒绝)。
|
||||
- **出站 HTTP 永远在数据库事务之外**(提交先 D1 成功、再开事务落本地行)。
|
||||
|
||||
### T3 的唯一写价 SQL(方向 B 通过)
|
||||
|
||||
```sql
|
||||
-- 对 payload 里出现的每个 sku_code 逐行执行(只改已有行;不 INSERT / 不 DELETE / 不改单结构)
|
||||
UPDATE customer_quote_sheet_items
|
||||
SET sale_price = $3, price = $3
|
||||
WHERE quote_sheet_code = $1 AND sku_code = $2
|
||||
RETURNING id::text AS id;
|
||||
```
|
||||
|
||||
- 命中 0 行 ⇒ 记为 `sku_not_in_sheet` 跳过;
|
||||
- 单位(双方都非空且 trim/lower 不等)⇒ `unit_mismatch` 跳过;
|
||||
- 金额 `>0 且 ≤9999999.99`,按 2 位小数归一;非法 ⇒ `invalid_price` 跳过;
|
||||
- 与现值差 ≤1e-6 ⇒ 不写(计入 `unchanged`);
|
||||
- 覆盖式;**不调用** `applyQuoteSheetUpdate`(它是整表 DELETE+INSERT,会删掉未被提出的 SKU —— 本轮明确禁止);
|
||||
- 单事务;**每行一条 `writeAuditLog`**(`operationType=quote_price_proposal_apply`、`target_table=customer_quote_sheet_items`、
|
||||
`target_id=行 id`、old/new 含单号/SKU/售价/来源 proposal id),提交后 best-effort。
|
||||
- 由于只按行 UPDATE:`customer_quote_versions` 不物化(与 T3「不改单结构」一致),订单仍是新订单读新价、历史订单快照不变。
|
||||
|
||||
## 5. 本侧三个端点(内部 workflow,不新增对外接口)
|
||||
|
||||
| 端点 | 权限 | 行为 |
|
||||
|---|---|---|
|
||||
| `POST /workflow/quote/quote-sheets/:code/price-proposals` | `customer_manage` | A 发起:内部审核无在途 pending ⇒ 整单 items 调 D1 ⇒ 本地建 `to_delivery` pending(**不写价**) |
|
||||
| `GET /workflow/quote/price-proposals?direction=&status=&refresh=1` | `customer_manage \| order_manage` | 本地列表;`refresh=1` 先做一轮 D2 对账;pending 的 B 行附「改前 → 改后」与等待天数 |
|
||||
| `POST /workflow/quote/price-proposals/:id/approve` \| `/reject` | `customer_manage` | B 审批:通过 ⇒ 按行写 `sale_price` + rearm 推对方 `cost_price` + D3 `approved`;驳回 ⇒ D3 `rejected` + 理由,不写价 |
|
||||
|
||||
- 开关 `MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL` **默认关**:关时三个端点一律 **503 `feature_disabled`**、零出站、零写库;
|
||||
定时任务 `runQuotePriceProposalSync()` 直接返回。
|
||||
- **T6 覆盖语义**:同方向再提交 —— 本地 pending 的 `payload_hash` 相同 ⇒ 直接回放(不再出站);
|
||||
不同 ⇒ 先调 D1(出站),成功后**同一事务**把旧 pending 置 `superseded` 再插新 pending(D1 失败则旧 pending 不动)。
|
||||
- 方向 A 的前置条件(契约 §4):`quote_sheet_change_requests` 该单**无 pending**(且最近一行不是 `superseded`),
|
||||
否则 409 `internal_review_pending`;A/B 是**两层**,不合并。
|
||||
- 主系统分公司解析:报价单绑定的客户里 `MAIN_<X>` —— 0 个 ⇒ 400 `not_usage_company`;多个 ⇒ 400 `ambiguous_main_branch`
|
||||
(契约 D1 只收单个 `main_branch_code`,不扇出;需拆单)。
|
||||
|
||||
## 6. 同步与回执(D2 / D3)
|
||||
|
||||
- 定时:`scheduledJobs.ts` 的 `runQuotePriceProposalSync()`(在既有主系统锁块内,开关默认关 ⇒ 直接返回);
|
||||
页面进入「配送商成本价确认」页签时也会 `refresh=1` 手动对账。
|
||||
- 按 `public.main_supplier_bindings` 里 active 的 `main_supplier_code` 分组调 D2(T10 游标),
|
||||
行按 `branch_code`(= 我方 `main_branch_code`)路由到对应分公司的租户表:
|
||||
- 配送侧 `from_supplier` ⇒ 本地 `to_delivery`:远端终态回写本地状态(T9:`applied.updated=0` 也照实);
|
||||
- 配送侧 `to_supplier` ⇒ 本地 `from_delivery`:本地没有 ⇒ 建 pending(**T2 解析唯一生效单**,解析不到/多张 ⇒ 跳过并告警,
|
||||
审批时仍以 409 `no_quote_sheet` / `ambiguous_sheet` 兜底)。
|
||||
- **T8**:本地已终态(approved/rejected)而远端仍 pending ⇒ 重发 D3(幂等,靠 proposal id + 决策),
|
||||
重发时用「当前明细 vs 提议价」重算 `applied` 一起回执;回执失败只 `console.warn`,等下一轮。
|
||||
- **A16(verifier 阻断项,2026-10-18)—— 远端 `superseded` 是终态**:配送侧重复发起 B 时会先把旧 pending
|
||||
置 `superseded` 再插新 pending(T6)。本侧必须:
|
||||
1. `superseded` 与 approved/rejected/cancelled 一样算**终态**:本地同 remote id 的 pending ⇒ 置 `superseded`
|
||||
(`reject_reason='remote_superseded'`),**不写价、不推送**;
|
||||
2. 新远端 pending 落本地撞 partial unique 时**不得 `DO NOTHING` 静默跳过**:先查本地同键 pending,
|
||||
若其 `remote_proposal_id` 与远端最新不同 ⇒ 把旧行置 `superseded`(`reject_reason='replaced_by_remote:<新id>'`)后插新行;
|
||||
相同 ⇒ 幂等跳过(不动数据)。接管最多 4 次;**仍失败 ⇒ 抛错失败关闭**
|
||||
(sync 记 `errors` 并**重置该 supplier 游标**,下一轮从头重拉 —— 新提议不会被"游标已过"静默丢掉)。
|
||||
- **A16 双保险(审批侧,verifier 第二轮加固)**:approve 在**任何写价之前**(事务外)核对远端状态:
|
||||
1. 先带 `proposal_id` **精确查**(配送侧新增 `?proposal_id=`;不支持时对方忽略该参数);
|
||||
2. 没命中 ⇒ 用 `next_cursor` **翻页直到找到或耗尽**(上限 20 页 × 200 行)。
|
||||
⚠️ 这一步是针对 verifier 抓到的残余:D2 是 `ORDER BY updated_at ASC LIMIT 200`(最旧 200 行),
|
||||
被 supersede 的旧行 `updated_at` 很新 ⇒ **不在第一页**;旧实现"找不到就放行"(fail-open)会写已撤回价。
|
||||
3. 找到且非 pending ⇒ **409 `proposal_not_pending`**(零写价/零推送/零回执,本地行留给下一轮同步收口);
|
||||
**找不到 / 翻页超限 / D2 不可用 ⇒ 409 `remote_status_unverified`(失败关闭)**。
|
||||
4. 每次 approve 因此只发 1 次精确查(命中即止),不再固定拉 200 行。
|
||||
- **A20(verifier 阻断项)**:approve 的 D3 回执必须带 `applied:{updated,skipped}`(配送侧只记录、不写价),
|
||||
否则对方 proposal 的 `applied` 恒为 null;T8 重发时按当前明细重算后再带。
|
||||
- 游标在进程内存(`Map<supplier_code, cursor>`),重启后退化为全量拉取(安全)。
|
||||
|
||||
## 7. 前端(页内页签,不新增菜单)
|
||||
|
||||
- 报价单列表行动作新增「提交配送商审核」(仅"生效中 + 有报价单编辑权"):
|
||||
成功提示「已提交配送商审核」并切到「配送商成本价确认」页签;失败透出后端中文说明(如 409 `internal_review_pending`)。
|
||||
- 新增页内页签「配送商成本价确认」(`QuoteDeliveryPriceProposalsPanel`):
|
||||
列双向提议(方向/状态/提交人/时间/等待天数/「改前 → 改后」);仅「配送商提交 + pending + `customer_manage`」可
|
||||
通过/驳回;无权限只读(不渲染按钮、不额外加提示文案);通过后按 `applied.updated/skipped` 给摘要并刷新报价单。
|
||||
- i18n 三语(`zh-CN` / `en` / `id`)同增同名 key。
|
||||
|
||||
## 8. 本轮不做 / 已知限制(如实记录)
|
||||
|
||||
1. **不存在"取消 A 提议"的接口**:D1 没有 cancel 语义 ⇒ A 只能等配送商审(T7 pending 不过期)。
|
||||
B 的过期/撤回以远端为准:远端 `superseded` 会在下一轮 D2 收口本地行(A16);审批侧另有事务外状态核对双保险。
|
||||
2. **A 的 `applied` 摘要不落本地**(本地表无该列,冻结契约如此):`applied` 只在对方 D2 回执里,列表展示以状态为主;
|
||||
B 的 `applied` 摘要由审批响应返回。
|
||||
3. **A 提交要求报价单只绑定一个 `MAIN_` 分公司客户**(D1 单值 + 本地一个方向一条 pending);多分公司需拆单(400)。
|
||||
4. **方向 B 只按行改 `sale_price`**:报价单明细行没有 `updated_at` 列(既有表结构)⇒ 行更新不刷新时间戳;
|
||||
留痕在 `operation_logs`(每行一条)。
|
||||
5. **B 通过不做版本物化**(T3 只按行 UPDATE;`customer_quote_versions` 行为不变)。
|
||||
6. 未真机联调(配送侧端点/开关由对方确认);本仓库测试全部 mock 出站 + 真库单测约束。
|
||||
7. 契约 §2.2 的 S1(供应商对外 HTTP 接口)已由 Lead **纠偏取消** ⇒ 本侧**没有新增对外 HTTP 接口**,不扩大鉴权面。
|
||||
|
||||
## 9. 验收对照(供 verifier / tester)
|
||||
|
||||
| # | 判据 | 怎么验 |
|
||||
| --- | --- | --- |
|
||||
| 1 | 开关默认关 ⇒ 三端点 503、零出站、零写库 | 单测:`submitPriceProposal`/`approve`/`reject` 503;`sync` 零调用 |
|
||||
| 2 | A 提交不写价、内部审核在途 409 | 单测:D1 调用 + 本地 pending + `applyQuoteSheetUpdate` 未调用;`internal_review_pending` |
|
||||
| 3 | A 整单 items = 明细 sale_price,多分公司/非使用公司 400 | 单测 |
|
||||
| 4 | T6 同 hash 回放 / 不同 hash supersede | 单测 + 真库 partial unique 用例 |
|
||||
| 5 | T2 B 目标单 0/多张 ⇒ 409 `no_quote_sheet`/`ambiguous_sheet` | 单测(同步跳过 + 审批 409) |
|
||||
| 6 | **T3 只改被提出的 SKU**(payload 2 个 SKU ⇒ 其它行原样) | 单测:SQL 只 2 条 `SET sale_price=$3,price=$3`;无 DELETE/INSERT;`applyQuoteSheetUpdate` 未调用 |
|
||||
| 7 | 缺 SKU / 单位不一致 / 金额非法 ⇒ 跳过并记录;值未变不写 | 单测 |
|
||||
| 8 | 通过后 COMMIT → `triggerQuoteCostSync` → D3;回执失败等轮询补 | 单测(事件顺序)+ T8 用例 |
|
||||
| 9 | 驳回零写价、零推送、D3 带理由;重复决策 409 | 单测 |
|
||||
| 10 | T10 游标增量 | 单测(第二轮带 `next_cursor`) |
|
||||
| 11 | 迁移登记 `tenant_business_tables()` + CHECK 含 `superseded` + 可重放 | 真库 integration + 本地重放 |
|
||||
| 12 | 前端:提交按钮/页签/权限只读/摘要 | render 测试 + 页面接线契约测试 |
|
||||
| 13 | **A16** 远端 superseded 收口 + 冲突接管 | 单测:一轮内「旧 superseded + 新 pending」⇒ 旧本地行 superseded、新行落库;撞唯一键先接管再插(不静默丢);真库 SQL 用例 |
|
||||
| 14 | **A16** 旧 id approve 必须被拒 | 单测:远端 superseded ⇒ 409 `proposal_not_pending`,零写价/零推送/零回执;D2 不可用 ⇒ 409 `remote_status_unverified`(失败关闭) |
|
||||
| 15 | **A20** D3 回执带 applied | 单测:approve 的 D3 body `applied={updated,skipped}`;T8 重发按当前明细重算 |
|
||||
| 16 | **T6** 枚举含 superseded + 可重放 | 真库:CHECK 含 superseded、partial unique、supersede→insert 序列 |
|
||||
| 17 | **A16 残余(verifier 二轮)**:预检精确查 + 翻页兜底 + 找不到 fail-closed | 单测:精确查只发 1 次;>200 行目标在第 2 页 ⇒ 翻页后 409 `proposal_not_pending`、零写价零推送;耗尽找不到 ⇒ 409 `remote_status_unverified`;真库 + >200 远端行用例 |
|
||||
| 18 | **接管循环**不静默丢新提议 | 单测:接管耗尽 ⇒ `sync.errors+1` 且重置游标(下轮 cursor=null 重拉) |
|
||||
|
||||
## 10. 回滚
|
||||
|
||||
1. `MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL=0`(或删除该行)⇒ 三端点 503、定时任务零出站;已落地的本地提议行保留(只读)。
|
||||
2. 代码回滚 = 还原 `quoteRoutes.ts` 的三条路由 + 删除 `quotePriceProposalService` / 出站封装 / 前端面板与页签;
|
||||
迁移可保留(纯追加表)。
|
||||
3. 迁移文件不含任何"用本地数据覆盖线上"的语句。
|
||||
@@ -0,0 +1,225 @@
|
||||
# 报价单销售价 → 主系统报价单成本价:**推送端**(供应商系统)
|
||||
|
||||
- 日期:2026-10-18
|
||||
- 触发:用户需求「供应商系统的报价单对应的客户,如果是配送系统的使用公司,那么供应商报价单的销售价,
|
||||
就能同步到配送系统的报价单的成本价」;两系统冻结契约(跨系统,2026-10-18 冻结)把方向定为
|
||||
**我方推送 → 主系统新增端点**,我方只做**推送端**。
|
||||
- 对端(配送系统)实现:`POST /api/supplier/quote-sheets/cost-sync`(对方仓库的设计文档 + 本仓库
|
||||
`server/src/services/mainSystem/api/quoteCostSync.ts` 里的字段映射)。
|
||||
- 相关我方文档:`20261027-分公司接入编码与主系统供应商绑定.md`(出站 `supplier_code` 取法)、
|
||||
`20261011-跨系统改价改量审核.md`(主系统调用分层:`services/mainSystem/{config,endpoints,http,token}.ts` +
|
||||
`api/*.ts`,业务层不拼 URL、不裸 `fetch`)、`20261011-批次报告推送主系统.md`(出站台账 + 重试范式)。
|
||||
|
||||
## 1. 结论(口径固定,后续不得改回)
|
||||
|
||||
| 项 | 决定 |
|
||||
| --- | --- |
|
||||
| 传输方向 | **我方推送**到主系统新端点;主系统没有反向调用我方业务 API 的凭据体系 |
|
||||
| 触发时机 | **报价单审批生效之后**(`approval_status` → `30`、`status` → `1`),且必须**事务提交之后** |
|
||||
| 推送内容 | 该单明细的 `sku_code` / `unit` / `sale_price ?? price`(`sale_price > 0` 才推) |
|
||||
| 目标分公司 | 该单绑定的客户里 `customer_code` 形如 `MAIN_<主系统分公司码>` 的那个 `<码>`;一单可能命中多个 ⇒ **按分公司各推一次** |
|
||||
| 非 `MAIN_` 客户 | **一律跳过**并记 `not_usage_company`(真实客户 `CUS…`、哨兵 `__INDEPENDENT_INBOUND__` / `__RETAIL__` 都算) |
|
||||
| 我方身份 | 用该分公司在主系统的**供应商编码**换 `client_credentials` token(`main_supplier_bindings` 优先,`branches.main_supplier_code` 兜底) |
|
||||
| 幂等 | 台账 `public.main_system_quote_cost_pushes` 唯一键 `(quote_sheet_code, main_branch_code)` ⇒ **一张单 × 一个主系统分公司只推一次**;重试复用同一 `client_request_id` |
|
||||
| 失败处理 | 记台账 `failed` + `attempts+1` + `last_error`,由 `scheduledJobs.ts` 每轮重试(`attempts < 5`);`forbidden` **不重试** |
|
||||
| 开关 | `MAIN_SYSTEM_QUOTE_COST_SYNC`,**默认关**;关 ⇒ 不查库、不出站、零行为变化 |
|
||||
| 我方报价/成本口径 | **零改动**。只"多推一次",不读写本仓库任何报价/成本/财务口径,不动订单/库存/结算 |
|
||||
| 隔离 | 库 `supplier_delivery` / API `3022` / Web `3021` / `uploads-supplier` / COS 前缀 `supplier-system/` 一条不动 |
|
||||
|
||||
## 2. 为什么必须有"生效后单次推送 + 唯一键"(T4=A)
|
||||
|
||||
- 报价单的销售价在本仓库是**给客户看的价**,主系统那边要用它当**自己的成本价**(采购成本快照)。
|
||||
两边语义自洽,但方向只有一个:我方是源头,主系统是接收方。
|
||||
- 同一张单**不能重复推**:对方是"覆盖式"写成本价(含改低),重复推会反复刷新对方审计与
|
||||
`updated_at`,也会让"这批成本是哪次报价带来的"无从追溯。⇒ 唯一键把"一张单 × 一个分公司"
|
||||
钉成一行台账,重试只**复用同一行 + 同一 `client_request_id`**(对方按请求号幂等,重放返回 `replayed: true`)。
|
||||
- 编辑已生效报价单(`updateQuoteSheet` 的 DELETE+INSERT)**不触发**再推:本次口径只覆盖"审批生效那一刻";
|
||||
避免把对方"编辑中"的中间态成本价推过去。
|
||||
|
||||
## 3. 触发点(post-commit,旁路)
|
||||
|
||||
`server/src/services/quoteSheetService.ts` 里**只有** `activateQuoteSheet()` 会让报价单生效,它有三个调用点:
|
||||
|
||||
| 调用点 | 场景 |
|
||||
| --- | --- |
|
||||
| `createQuoteSheet()` | 新建报价单(旧接口:草稿直接生效) |
|
||||
| `submitQuoteSheetForApproval()` | 提交审批(旧接口:提交即生效) |
|
||||
| `approveQuoteSheet({ approved: true })` | 审批通过 |
|
||||
|
||||
三处都在 `COMMIT` 之后、`return` 之前调 `triggerQuoteCostSync({ branchCode, quoteSheetCode })`:
|
||||
|
||||
```ts
|
||||
const detail = await loadSheetDetail(input.quoteSheetCode);
|
||||
// 报价单已生效 ⇒ 事务提交之后再推送(旁路;任何失败都不得影响审批结果)
|
||||
triggerQuoteCostSync({ branchCode: detail?.branch_code, quoteSheetCode: input.quoteSheetCode });
|
||||
return detail;
|
||||
```
|
||||
|
||||
纪律(做反就是返工):
|
||||
|
||||
1. **不得在事务内出网**:HTTP 永远在 `COMMIT` 之后(`mainSystemWriteback` 同款纪律)。
|
||||
2. **任何异常都不得冒泡**:`triggerQuoteCostSync` 内部 `void push(...).catch(...)`,
|
||||
同步异常也 try/catch 兜住 ⇒ 审批/建单成功与否**与本推送无关**。
|
||||
3. **不 await**:对方 15s 级超时会拖慢审批;推送走旁路,失败靠台账 + 定时重试自愈。
|
||||
4. **后台任务必须自带租户上下文**:`pushQuoteCostSyncForSheet` 内部用
|
||||
`runWithTenantDbContext(branchCode, fn, { isolate: true, requestClient: false })`。
|
||||
不复用请求连接 —— 请求结束后请求级连接会被归还,异步任务再借到它就是踩已释放连接。
|
||||
|
||||
## 4. 台账(`public.main_system_quote_cost_pushes`)
|
||||
|
||||
平台级表(放 `public`,与 `main_supplier_bindings` / `main_system_report_pushes` 同级):
|
||||
它是**对接状态**,不是租户业务表 ⇒ 不进 `public.tenant_business_tables()`,也不进 `/api/data` 的 `ALLOWED_TABLES`。
|
||||
|
||||
| 列 | 含义 |
|
||||
| --- | --- |
|
||||
| `id` | uuid 主键 |
|
||||
| `branch_code` | 我方分公司(租户) |
|
||||
| `quote_sheet_code` | 本次推的报价单号 |
|
||||
| `main_branch_code` | 主系统分公司码;整单级跳过(无 `MAIN_` 客户/无可推行)记 `*` |
|
||||
| `client_request_id` | **本地生成** uuid,落台账后才出站;重试**复用**(对方按它幂等)。**例外**:对方明确回 409、或改价后重推时换新 uuid(见 §4 / §7 的 R-2) |
|
||||
| `status` | `pending` / `sent` / `failed` / `skipped` / `forbidden` |
|
||||
| `attempts` | 出站尝试次数(成功也计数) |
|
||||
| `last_error` | 最近一次失败原因(成功时清空) |
|
||||
| `response` | 对方回执 `data`(含 `replayed` / `updated` / `skipped`)+ 我方 `local` 口径记录 |
|
||||
| `created_at` / `updated_at` | 时间戳 |
|
||||
|
||||
唯一索引 `uq_main_system_quote_cost_pushes (quote_sheet_code, main_branch_code)`;
|
||||
扫描索引 `(status, updated_at)` 供重试。
|
||||
|
||||
状态机:
|
||||
|
||||
```text
|
||||
pending ──(2xx)──────────────────────────▶ sent (终态,不重推)
|
||||
pending ──(403 forbidden/branch_not_bound)▶ forbidden (终态,不重试)
|
||||
pending ──(400/5xx/超时/网络/401)─────────▶ failed (attempts+1,下轮重试,复用同号)
|
||||
pending ──(409 idempotency_conflict)──────▶ failed (**换新请求号** + attempts=0,下轮用新号)
|
||||
pending ──(无 MAIN_ 客户 / 无可推行 / 超 2000 条)▶ skipped (终态)
|
||||
|
||||
重试(scheduledJobs 每轮):
|
||||
failed && attempts<5 ──(复用 client_request_id)──▶ sent / failed / forbidden / skipped
|
||||
pending && updated_at < NOW()-10min ──(复用 client_request_id)──▶ 同上(R-1:收口被杀进程留下的 pending)
|
||||
任一路径遇 409 ──▶ 换新请求号、attempts=0、failed(R-2 ①:同号已绑旧 payload)
|
||||
```
|
||||
|
||||
- **R-1(pending 收口)**:`pending` 是"台账已落、结果未回写"的中间态。进程被杀会留下永久 `pending`,
|
||||
唯一键还会挡住以后所有推送 ⇒ 重试扫描**额外**收口"卡住超过 10 分钟"的 `pending`;
|
||||
重放是安全的(对方若已受理,按 `client_request_id` 回放;未受理则正常执行)。
|
||||
- **R-2(改价必须能到)**:只有对方**明确回 409** 才换请求号;超时/5xx/网络/对方不可用**仍复用同号**
|
||||
(换号可能把"对方其实已受理的旧请求"再写一次)。重试异常时把 `pending` 一并收口成 `failed`,
|
||||
让它回到 `attempts<5` 闸门内,避免无限重试。
|
||||
- `attempts < 5` 且 `status = 'failed'` 才会被重试选中;到达 5 次仍失败 ⇒ 停在 `failed` 等人工。
|
||||
- `forbidden` / `skipped` / `sent` 永不自动重试。
|
||||
- **改价重推(重触发路径,R-2 ②)**:台账唯一键冲突时不再静默 `duplicate` —— 拿当前明细指纹与台账
|
||||
`response.local.items_fingerprint`(最近一次推送的指纹)比对:
|
||||
**变了** ⇒ 复用该行 + 换新请求号 + `attempts=0` + 立即重推(`response.local.sheet_reason='rearmed_after_change'`);
|
||||
**没变** ⇒ 保持 `duplicate` 零出站;**无指纹记录**(升级前的行)⇒ 保守按 `duplicate`,交给定时重试收口。
|
||||
|
||||
## 5. 出站(不新造 HTTP 客户端)
|
||||
|
||||
| 层 | 文件 | 职责 |
|
||||
| --- | --- | --- |
|
||||
| 端点表 | `server/src/services/mainSystem/config.ts` | 新增 `quoteCostSync: '/api/supplier/quote-sheets/cost-sync'` |
|
||||
| 路径覆盖 | `server/src/services/mainSystem/endpoints.ts` | `MAIN_SYSTEM_QUOTE_COST_SYNC_PATH` 可覆盖;URL 只在这里拼 |
|
||||
| 鉴权 | `server/src/services/mainSystem/token.ts` | 既有 `getMainSystemToken(supplierCode)`(缓存 / 退避 / 提前刷新) |
|
||||
| HTTP | `server/src/services/mainSystem/http.ts` | 既有四态 `ok / rejected / unavailable / not_configured`;**401 强制刷新后重试一次** |
|
||||
| 封装 | `server/src/services/mainSystem/api/quoteCostSync.ts` | 唯一做字段映射(snake_case)的地方 |
|
||||
| 业务 | `server/src/services/mainSystemQuoteCostSync.ts` | 拆分公司、台账、状态回写、重试 |
|
||||
|
||||
请求体(字段名照契约,`supplier_code` **不进 body**,只由 token 决定):
|
||||
|
||||
```json
|
||||
{
|
||||
"client_request_id": "<uuid>",
|
||||
"supplier_quote_sheet_code": "QS...",
|
||||
"main_branch_code": "BR002",
|
||||
"activated_at": "2026-10-18T02:00:00.000Z",
|
||||
"items": [{ "sku_code": "SKU...", "unit": "斤", "sale_price": 12.34 }]
|
||||
}
|
||||
```
|
||||
|
||||
- `activated_at` 取该单 `effective_at ?? approved_at`(ISO;不可解析则整字段省略),仅溯源,对方忽略非法值。
|
||||
- `items[].unit`:明细行 `unit` 归一(trim)后长度 1~20 才带,否则带 `null`(对方按 `skus.unit` 比)。
|
||||
- `items[]` 上限 2000(对方硬限):**超过则不推**,整单记 `skipped` + `too_many_items`,
|
||||
绝不截断成"只同步了一部分还被当成全量"。
|
||||
|
||||
错误码映射:
|
||||
|
||||
| 对方 | 我方台账 | 是否重试 |
|
||||
| --- | --- | --- |
|
||||
| 2xx(含 `replayed: true`) | `sent` | 否(终态) |
|
||||
| 403 `forbidden` / `branch_not_bound` | `forbidden` | **否**(绑定不成立重试也不会成立) |
|
||||
| 400 `invalid_request` / `items_required` / `too_many_items` | `failed` | 是(≤5 次) |
|
||||
| 409 `idempotency_conflict` | `failed` + **换新请求号**、`attempts=0`、`last_error='payload_changed_rotate_id'` | 是(下一轮用**新号**;同号不同 payload 换号后即可推送) |
|
||||
| 503 `feature_disabled` | `failed` | 是(≤5 次;对方开关打开后重试可自愈) |
|
||||
| 5xx / 超时 / 网络 | `failed` | 是(≤5 次) |
|
||||
| 2xx 但响应不可识别(无 `data` 对象) | `failed` | 是(不得当"已同步") |
|
||||
|
||||
> 只有 **409** 会换 `client_request_id`;其它失败(400 / 5xx / 超时 / 网络 / 对方不可用)**一律复用同号**。
|
||||
|
||||
## 6. 开关(默认关)
|
||||
|
||||
```bash
|
||||
# 默认关:不查库、不出站,行为与改造前逐字节一致
|
||||
MAIN_SYSTEM_QUOTE_COST_SYNC=0
|
||||
# 打开
|
||||
MAIN_SYSTEM_QUOTE_COST_SYNC=1
|
||||
# 端点路径可覆盖(一般不用改)
|
||||
# MAIN_SYSTEM_QUOTE_COST_SYNC_PATH=/api/supplier/quote-sheets/cost-sync
|
||||
```
|
||||
|
||||
- 取值 `1` / `true` / `on`(大小写不敏感)为开,其余(含未设置)为关。
|
||||
- 关时:`triggerQuoteCostSync` 与 `retryQuoteCostSyncPushes` 都 **立即返回**(连台账都不查)。
|
||||
- 打开前提:① 该分公司在主系统有**有效授权行**(否则对方 403 `branch_not_bound`,我方记 `forbidden`);
|
||||
② 对方已开 `SUPPLIER_QUOTE_COST_SYNC_ENABLED`(否则 503 `feature_disabled`,我方记 `failed`)。
|
||||
- **环境隔离**:`MAIN_SYSTEM_BASE_URL` 指向线上时,打开本开关会**改写线上成本价**。
|
||||
本开关未并入 `warnIfRemoteMainSystemWithWriteback()` 的"危险开关"集合(本次不改既有告警函数),
|
||||
现场开启前请人工确认 base url(见 §8 已知风险)。
|
||||
|
||||
## 7. 验收对照(供 verifier / tester 逐条打勾)
|
||||
|
||||
| # | 判据 | 怎么验 |
|
||||
| --- | --- | --- |
|
||||
| 1 | 开关关 ⇒ 零出站、零台账读写 | 单测:`triggerQuoteCostSync` / `retryQuoteCostSyncPushes` 在未设开关时 `fetch` 与 `pool.query` 均 0 调用 |
|
||||
| 2 | 客户码闸门 | 单测:`MAIN_BR002` → `BR002`;`__RETAIL__` / `__INDEPENDENT_INBOUND__` / `CUS…` → `not_usage_company` |
|
||||
| 3 | 一单多分公司各推一次 | 单测:两个 `MAIN_` 客户 ⇒ 2 条台账行、2 次出站、`main_branch_code` 各不同 |
|
||||
| 4 | 无 `MAIN_` 客户 / 无可推行 | 单测:台账 1 行 `skipped`(`main_branch_code='*'`),出站 0 |
|
||||
| 5 | 一张单一个分公司只推一次 | 单测:重复触发 ⇒ 第二次不新增台账行、不出站 |
|
||||
| 6 | 重试复用同一 `client_request_id` | 单测:首次 5xx 失败 → 重试函数出站 body 的 `client_request_id` 与台账行一致 |
|
||||
| 7 | `forbidden` 不重试 | 单测:403 后重试函数不选中该行 |
|
||||
| 8 | 事务提交之后才出网 | 单测:`createQuoteSheet` 的 SQL 事件顺序里 `COMMIT` 早于 `fetch` |
|
||||
| 9 | 推送失败不影响审批 | 单测:出站抛错 / 5xx 时 `createQuoteSheet` / `approveQuoteSheet` 仍正常返回 |
|
||||
| 10 | 只改推送、不碰报价口径 | `git diff` 复核:`quoteSheetService.ts` 只新增触发调用;无报价/成本/财务逻辑改动 |
|
||||
| 11 | 隔离标识未改回主系统 | `git diff -- server/.env webpack.config.js` 为空;`grep supplier_delivery` 仍在 |
|
||||
| 12 | 迁移可重放、唯一键生效 | `npm --prefix server run migrate` 后 `\d public.main_system_quote_cost_pushes`;重放不报错 |
|
||||
| 13 | **R-1** 卡住的 `pending` 会被收口 | 单测:`updated_at` 11 分钟前的 `pending` ⇒ 本轮扫描到、用**原** `client_request_id` 重放;刚落的不抢跑 |
|
||||
| 14 | **R-2①** 409 才换号 | 单测:重试遇 409 ⇒ 换新 uuid + `attempts=0` + `last_error=payload_changed_rotate_id`,下一轮用新号成功;5xx/超时仍复用同号 |
|
||||
| 15 | **R-2②** 改价必须能推出去 | 单测:首推成功后改价再触发 ⇒ `duplicate=0`、出站 1 次、请求号换新、`response.local.sheet_reason='rearmed_after_change'` |
|
||||
| 16 | **R-2③** 未改价仍是幂等 | 单测:未改价再触发 ⇒ `duplicate=1`、零出站、请求号不变 |
|
||||
| 17 | R-1/R-2 的 SQL 真库跑得通 | `node .team/supplier-quote-cost-sync/repro-r1-r2-db.mjs`(本地 `supplier_delivery`,事务内做完回滚) |
|
||||
|
||||
## 8. 已知风险与未覆盖(如实记录)
|
||||
|
||||
1. **`pending` 卡死已收口(R-1)**:进程在"台账已落、结果未回写"之间被杀留下的 `pending`,
|
||||
由定时重试在"卡住 >10 分钟"后收口(重放安全)。残余:如果进程**每一轮**都在同一行上被杀,
|
||||
该行会一直 pending —— 但每轮都会产生日志与 `updated_at` 变化,可从台账直接定位。
|
||||
2. **改价重推的指纹判据(R-2)**:只比对 `sku_code` / `unit` / `sale_price`。若对方关心而我方没推的字段变了,
|
||||
不会触发重推(例如报价单标题、备注);这是故意的:那两个字段不进 payload。
|
||||
另:**无指纹记录的老行**(本功能上线前的行)重触发仍按 `duplicate` 保守处理,靠定时重试收口。
|
||||
3. **环境隔离告警未覆盖本开关**:`warnIfRemoteMainSystemWithWriteback()` 的危险开关集合本次未扩展(见 §6)。
|
||||
4. **`branches.main_supplier_code` 本地为空**:本机 `BR002` 该列为空,只能靠
|
||||
`main_supplier_bindings`(本地有 `SUP37831443`);两者都为空 ⇒ 该单记 `failed` 并等人工补绑定。
|
||||
5. **`updateQuoteSheet` 编辑生效单不触发推送**(T4=A 冻结口径只推审批生效那一刻)。**但改价后再次触发
|
||||
(重新审批/重新提交)会按 R-2 ② 换号重推新价**;不重触发则主系统不会自动跟随 —— 需要另立"销售价变更即推"需求。
|
||||
6. **未真机联调**:本机主系统侧端点可能尚未上线/开关未开,端到端只能由对方联调确认;
|
||||
本仓库测试全部 mock 出站。
|
||||
7. **2000 条上限**:超过即整单 `skipped`,不做分批(分批会让"部分成功"难以对账)。
|
||||
8. **`forbidden` 行改价再触发也会 rearm 重推**:绑定若已恢复则成功;未恢复仍是 403 `forbidden`(不重试),
|
||||
`last_error` 会被新一轮结果覆盖(回执里保留 `response.last_conflict_409` 等排障信息)。
|
||||
|
||||
## 9. 回滚
|
||||
|
||||
1. 关开关(`MAIN_SYSTEM_QUOTE_COST_SYNC=0` / 删除该行)⇒ 立即零出站,审批行为与改造前一致。
|
||||
2. 台账表可保留(纯追加,不影响任何业务查询);如需彻底回退,`DROP TABLE public.main_system_quote_cost_pushes;`
|
||||
并删 `server/src/services/mainSystemQuoteCostSync.ts` 与三处触发调用即可 —— **对方已写入的成本价不会自动回滚**,
|
||||
需要对方按其审计留痕人工处理。
|
||||
3. 本改动**不含**任何"用本地数据覆盖线上"的语句(迁移只建表 + 索引)。
|
||||
@@ -0,0 +1,260 @@
|
||||
# 编辑生效报价单改价 → 需审核,审核通过才同步(2026-10-18 增量)
|
||||
|
||||
- 日期:2026-10-18
|
||||
- 用户原话:「编辑生效单改价需要有同步审核,审核通过就同步」
|
||||
- 前置交付:`docs/design/20261018-报价单成本价同步推送.md`(成本价同步通道 + rearm 重推)
|
||||
- 冻结决策 D1–D5 + Lead 2026-10-18 裁定(见 `.team/quote-edit-cost-sync-approval/brief.md`,不入库)
|
||||
|
||||
## 1. 结论(口径固定,后续不得改回)
|
||||
|
||||
| 项 | 决定 |
|
||||
| --- | --- |
|
||||
| 待审范围 | **只审价格相关变化**(D5):入参含 `items`(增删改明细)或 `auto_sale_price_by_cost` **真的变了** |
|
||||
| 非价格改动 | 只改标题 / 周期 / 生效日 / 客户 ⇒ **维持现有直接保存**(`applied:true`),不写变更单 |
|
||||
| 保存时 | 价格相关 ⇒ **报价单一点不动**,只写/覆盖一条 `pending` 变更单,响应 `applied:false` |
|
||||
| 审核粒度 | **整单一次审核**(D2):保存时的整单入参作为一条变更单 |
|
||||
| 同一 SKU 重复 | 提交时 **400 `duplicate_sku`**(不去重、不落库)——重复行会让审批后的明细出现两份同 SKU |
|
||||
| 待审期间再改 | **直接覆盖旧待审**(D4):旧 `pending` 置 `superseded`,一张单只留一条 pending |
|
||||
| 审核通过 | **单事务**应用(复用 `applyQuoteSheetUpdate`)→ 提交后调既有 `triggerQuoteCostSync`(rearm) |
|
||||
| 审核驳回 | 只改变更单状态(`rejected` + 理由),报价单不变、**零推送** |
|
||||
| 重复决策 | `409 already_decided`(幂等,不重复应用、不重复推送) |
|
||||
| 目标单已变 | **整单拒绝**:`409 base_changed` + 变更单置 `rejected`(理由 `base_changed`)、零应用、零推送 |
|
||||
| 开关 | `QUOTE_EDIT_APPROVAL` **默认开**;`0/false/off` 回滚成"直接保存"且**不写**变更单表 |
|
||||
| 权限 | **一分二**:提交 `customer_manage \| order_manage`;查看列表 `customer_manage \| order_manage`;**通过/驳回只认 `customer_manage`** |
|
||||
| 历史 | 变更单历史**永久保留**,不做清理 |
|
||||
| 隔离 | 库 `supplier_delivery` / API `3022` / Web `3021` / `uploads-supplier` / COS 前缀 `supplier-system/` 一条不动 |
|
||||
|
||||
## 2. 本轮**不做**(已知旁路,如实登记)
|
||||
|
||||
用户只要求「编辑生效单改价」这一条入口。以下写入路径**本轮不纳入审核**:
|
||||
|
||||
| 旁路 | 为什么本轮不做 |
|
||||
| --- | --- |
|
||||
| `POST /quote/sheets/:code/append-items` | 由订单链路调用(补价追加),纳入审核会让下单/备货链路卡在人工审批 |
|
||||
| `POST /quote/upsert-costs` | 订单列表改成本的既有交互(`order_entry` 权限),属另一条业务链 |
|
||||
| `PATCH /quote/sheets/:code/auto-sale-price` | 单独开关接口,本次只审 `PUT` 里的 `auto_sale_price_by_cost` 变化 |
|
||||
| 通用网关 `/api/data` 直写 `customer_quote_sheet_items` | 通用网关卡(`ALLOWED_TABLES`/`DENY_WRITE_TABLES`)是平台冻结面;本次不改平台白名单 |
|
||||
|
||||
⇒ 这四条**仍可绕过审核直接改价**(其中 `/api/data` 由平台白名单决定能否写)。已登记为已知风险;
|
||||
要收口需另立需求(各自都会动到别的冻结面)。
|
||||
|
||||
## 3. 数据模型:`quote_sheet_change_requests`(**租户业务表**)
|
||||
|
||||
迁移:`migrations/20261018_quote_sheet_change_requests.sql`,按「新增业务表四步」落地:
|
||||
|
||||
1. 各租户 schema 建表(锚点 = `customer_quote_sheets` 存在,与报价单同域);
|
||||
2. 同步名单 `public.tenant_business_tables()`(116 → 117);
|
||||
3. `ensure_tenant_schemas_match_template()` 给已有分公司补建;
|
||||
4. `assert_tenant_template_matches_business_tables()` 断言(漏登记即中断迁移)。
|
||||
|
||||
| 列 | 含义 |
|
||||
| --- | --- |
|
||||
| `id` | uuid 主键 |
|
||||
| `branch_code` | 我方分公司(= 租户) |
|
||||
| `quote_sheet_code` | 被编辑的报价单 |
|
||||
| `payload` | jsonb:整单编辑入参(`title` / `customer_codes` / `items` / `auto_sale_price_by_cost` / `quote_cycle` / `effective_at`),**只存提交时给了的字段** |
|
||||
| `base_version_no` | 提交时的 `version_no` —— **只留痕、不作判据**(见 §4) |
|
||||
| `base_items_fingerprint` | 提交时**当前明细**指纹(复用 `quoteCostSyncItemsFingerprint`:`sku_code`/`unit`/`sale_price` 排序后 sha256)——**判"目标单有没有被改过"的唯一判据** |
|
||||
| `status` | `pending` / `approved` / `rejected` / `superseded` |
|
||||
| `requested_by` / `requested_at` | 提交人 / 时间(自审允许,D3) |
|
||||
| `reviewed_by` / `reviewed_at` / `reject_reason` | 审核留痕(D3:必须留 reviewer) |
|
||||
| `applied_at` | 实际应用时间 |
|
||||
| `created_at`(= `requested_at`)/ `updated_at` | 时间戳 |
|
||||
|
||||
索引:
|
||||
|
||||
- **partial unique**:`(branch_code, quote_sheet_code) WHERE status='pending'` ⇒ 一张单只有一条待审(D4 的硬约束);
|
||||
- `(branch_code, status, requested_at DESC)` 待审列表;
|
||||
- `(quote_sheet_code, requested_at DESC)` 单张单的历史留痕。
|
||||
|
||||
> 为什么不用 `version_no` 判"变没变":`customer_quote_sheets.version_no` 在编辑时不涨
|
||||
> (`updateQuoteSheet` 不 bump),`setQuoteSheetAutoSalePriceByCost` 连 `updated_at` 都不更新
|
||||
> ⇒ 版本号永远判不出变化。改用**明细指纹**(Lead 裁定 #4)。
|
||||
|
||||
## 4. 保存分流(`PUT /quote/sheets/:code`)
|
||||
|
||||
`server/src/modules/workflow/routes/quoteRoutes.ts` → `saveQuoteSheetEdit()`:
|
||||
|
||||
```text
|
||||
读报价单(必须 生效中:status=1 && approval_status=30 && 未过期)
|
||||
│
|
||||
├─ 开关关 或 非价格相关 ──▶ updateQuoteSheet(...)(逐字不变的旧行为)→ applied:true
|
||||
│ 非价格时额外 triggerQuoteCostSync(见 §6)
|
||||
│
|
||||
└─ 价格相关(开关开)
|
||||
├─ 同一 SKU 重复?→ 400 duplicate_sku(不写库)
|
||||
├─ 归一/非空校验 + 客户归属校验(fail fast)
|
||||
├─ 记录 base_items_fingerprint(当前明细)
|
||||
└─ 事务:旧 pending → superseded;插入新 pending
|
||||
→ applied:false + change_request(含摘要)
|
||||
```
|
||||
|
||||
- **价格相关判定(D5)**:`items !== undefined` ⇒ 相关;`auto_sale_price_by_cost` 与当前值不同 ⇒ 相关;
|
||||
只改 `title`/`quote_cycle`/`effective_at`/`customer_codes` ⇒ 不相关。
|
||||
- **不落报价单**:价格相关分支**不调用** `updateQuoteSheet`,`customer_quote_sheets` /
|
||||
`customer_quote_sheet_items` / `customer_quote_sheet_customers` / `customer_quote_versions` 均零写入。
|
||||
- **并发提交**:撞 partial unique index(23505)⇒ 回滚后**重跑一次**(重跑时旧 pending 已可见可覆盖)。
|
||||
- 响应形状:价格相关 `{ data: <当前单详情,未变>, applied: false, change_request: {...} }`;
|
||||
其它 `{ data, applied: true }`。
|
||||
|
||||
## 5. 审核(通过 / 驳回 / 列表)
|
||||
|
||||
### 5.1 通过 `POST /quote/change-requests/:id/approve`
|
||||
|
||||
**单事务**(`pool.connect()` → `BEGIN`):
|
||||
|
||||
```text
|
||||
SELECT ... FOR UPDATE -- 锁变更单(防重复决策)
|
||||
├─ 不存在 ⇒ 404 change_request_not_found
|
||||
├─ branch_code ≠ 当前 ctx 分公司 ⇒ 403 branch_mismatch
|
||||
└─ status ≠ pending ⇒ 409 already_decided
|
||||
重算当前明细指纹 ≠ base_items_fingerprint
|
||||
⇒ UPDATE status='rejected', reject_reason='base_changed';COMMIT;409 base_changed(零应用、零推送)
|
||||
校验目标单仍可改(生效中/未过期)⇒ 否则 409(走既有守卫文案)
|
||||
校验 payload 仍可应用:
|
||||
· items 的 sku_code 必须仍在 skus(status=1) ⇒ 否则 409 sku_unavailable
|
||||
· customer_codes 必须仍属本分公司 ⇒ 否则 409 invalid_customer
|
||||
applyQuoteSheetUpdate(payload, { client }) -- 同一事务:改单头/明细/刷版本
|
||||
UPDATE status='approved', reviewed_by/at, applied_at
|
||||
COMMIT
|
||||
↓ 提交之后
|
||||
triggerQuoteCostSync({ branchCode, quoteSheetCode }) -- 既有 rearm:指纹变了换号重推
|
||||
```
|
||||
|
||||
**硬约束(analyst 复核要求)**:
|
||||
|
||||
- **绝不调用** `approveQuoteSheet` / `activateQuoteSheet`:后者会把**同分公司共享客户的其它生效单**
|
||||
置 `status=3`、重写审批字段。本路径只复用抽出的 `applyQuoteSheetUpdate`;
|
||||
⇒ 目标单 `approval_status` / `approved_by` / `approved_at` / `status` **四个审批字段一个都不动**,
|
||||
其它共享单不被置 3;`customer_quote_versions` 行为与改造前 `updateQuoteSheet` **完全一致**
|
||||
(`materializeQuoteVersions(..., { expireSheetVersionsFirst: true })`)。
|
||||
- `applyQuoteSheetUpdate` 的抽取是**逐字搬移**:不传 `client` 时仍自己 `BEGIN/COMMIT/ROLLBACK`
|
||||
(`updateQuoteSheet` 行为不变);传 `client` 时事务归调用方。
|
||||
- 守卫失败时变更单**保持 pending**(不静默丢弃,也不自动驳回)——由审核人看清原因后决定驳回(需填理由)。
|
||||
- **校验顺序(P3-1,红队第三轮)**:审批的校验顺序固定为
|
||||
**① 目标单可用性(`loadQuoteSheetForUpdate`)→ ② 指纹(`base_items_fingerprint`)→ ③ SKU 存活 / 客户归属 → ④ 应用**。
|
||||
为什么①必须在②之前:目标单被**硬删除**时 `customer_quote_sheet_items` 是空集 ⇒ 指纹"必然不一致" ⇒ 会误走
|
||||
`base_changed` 的自动驳回;而 A12③ 要求这种情况是 **409 `target_unavailable` + 变更单保持 pending**。
|
||||
软删(`status=0`)与硬删都因此落到 `target_unavailable`;**目标仍可用但指纹变了 ⇒ 仍 `base_changed` + 自动 rejected**(不回退)。
|
||||
- **A12 修订(2026-10-18,verifier 复核后)**:只有 `base_items_fingerprint` 不一致才**自动** `rejected`(`base_changed`);
|
||||
**其它守卫失败一律 409 + 变更单保持 pending**:`target_unavailable`(目标单不存在/非执行中/已过期/已被取代)、
|
||||
`sku_unavailable`(`skus.status≠1`)、`invalid_customer`(客户不属本分公司)。
|
||||
- `target_unavailable` 的映射**只发生在审批路径**:`loadQuoteSheetForUpdate` / `applyQuoteSheetUpdate` 在三连守卫上
|
||||
抛的是**普通 Error**(编辑路径的既有语义,**不得**改),审批服务把这三句既有文案映射成 409 `target_unavailable`;
|
||||
其它错误(库/网络)仍按 500。
|
||||
|
||||
### 5.2 驳回 `POST /quote/change-requests/:id/reject`
|
||||
|
||||
`{ reason }` 必填(400 `reject_reason_required`);条件更新 `WHERE id=? AND status='pending'`
|
||||
(并发下第二次得到 409 `already_decided`);**不应用、不推送**。
|
||||
|
||||
### 5.3 列表 `GET /quote/change-requests?status=pending&limit=`
|
||||
|
||||
按分公司 + 状态取最近 N 条,**`LEFT JOIN public.profiles`** 带出提交人/审核人姓名;
|
||||
`pending` 行附带**审核摘要**(与前明细比对:`added` / `removed` / `updated` + 每行「改前 → 改后」,
|
||||
最多 30 行 + `truncated` 标记)。
|
||||
|
||||
> ⚠️ **A29(verifier 阻断项,2026-10-18)**:展示名在 **`public.profiles`(`full_name`/`username`)**,
|
||||
> **不在 `auth.users`**(那是 Supabase 兼容表的子集,没有这两列)。最初写成 `LEFT JOIN auth.users` ⇒
|
||||
> 真库 `GET /quote/change-requests` 直接 500、前端面板加载不出来。已改正,并补**真库 integration**
|
||||
> (`server/tests/quoteSheetChangeRequestDb.integration.test.ts`)钉住:① `auth.users` 确实没有这两列;
|
||||
> ② 列表返回的 `requested_by_name`/`reviewed_by_name` 非空。单测 mock 永远发现不了"列不存在",故必须真库。
|
||||
|
||||
### 5.4 业务审计(A26)
|
||||
|
||||
提交(新 pending / 覆盖旧 pending)、通过、驳回、`base_changed` 自动驳回 —— 每条路径写一条
|
||||
`writeAuditLog`(`operation_logs`):
|
||||
|
||||
| 字段 | 值 |
|
||||
| --- | --- |
|
||||
| `operation_type` | `quote_sheet_change_request_submit` / `_approve` / `_reject` |
|
||||
| `target_table` / `target_id` | `quote_sheet_change_requests` / 变更单 id |
|
||||
| `old_value` / `new_value` | `{change_request_id, quote_sheet_code, status}` → 加上 `action` 与 `reason`(驳回理由 / `base_changed` / `superseded:<旧id>`) |
|
||||
| `branch_code` / `action_category` | 分公司 / `quote_edit_approval` |
|
||||
|
||||
- **best-effort**:审计在**事务提交之后**写(避免审计失败把主事务带进 aborted 状态),任何异常只
|
||||
`console.warn`,绝不影响提交/审批结果。
|
||||
- 全局 `operationAuditMiddleware` 的 `api_*` 行**不能替代**业务审计(前者没有四要素)。
|
||||
|
||||
## 6. 同步(复用上一轮通道,不新造推送)
|
||||
|
||||
- **审核通过** ⇒ 只调 `triggerQuoteCostSync({ branchCode, quoteSheetCode })`:
|
||||
同一单再次触发 + 明细指纹变化 ⇒ 上一轮的 **rearm** 路径换新 `client_request_id` 重推;
|
||||
明细没变 ⇒ `duplicate` 零出站。**未通过审核绝不推送**(成本价同步与审核强绑定)。
|
||||
- **非价格编辑**(只改标题/周期/生效日/客户)⇒ 直接保存后**也调用一次** `triggerQuoteCostSync`:
|
||||
若新增了 `MAIN_<某分公司>` 客户,目标分公司集合变了 ⇒ 自然补推;否则指纹未变 ⇒ `duplicate` 零出站。
|
||||
- **开关关(回滚)** ⇒ 价格相关编辑走直接保存,**不调用**推送(= 改造前行为)。
|
||||
|
||||
## 7. 开关与权限
|
||||
|
||||
```bash
|
||||
# 默认开(用户明确要这个行为)
|
||||
QUOTE_EDIT_APPROVAL=1
|
||||
# 回滚成"直接保存"(= 改造前),且不写变更单表
|
||||
QUOTE_EDIT_APPROVAL=0
|
||||
```
|
||||
|
||||
| 操作 | 权限 |
|
||||
| --- | --- |
|
||||
| 提交编辑(PUT,含待审提交) | `customer_manage` **或** `order_manage`(沿用现有) |
|
||||
| 查看待审列表(A24) | `customer_manage` **或** `order_manage`(提交人能看到自己的状态;只读) |
|
||||
| 通过 / 驳回 | **仅 `customer_manage`**(只有 `order_manage` 的人能提不能审,属预期) |
|
||||
|
||||
> **A22(开关口径)**:关开关 ⇒ 新编辑直接保存、不写变更单表;**已存在的 pending 仍可通过/驳回**
|
||||
> (不让在途变更单卡死);`PUT` 响应**始终**带 `applied` 字段(老前端没有该字段时按 `applied !== false` 兼容)。
|
||||
>
|
||||
> **A25(跨租户)**:别的分公司的变更单在 schema 隔离下**不可见 ⇒ 404**(不泄漏存在性);
|
||||
> 只有"当前 schema 内却带其它 `branch_code`"的异常行才 403。
|
||||
|
||||
## 8. 前端(报价单页内,不新增菜单)
|
||||
|
||||
- `src/pages/customers/QuoteVersionManagement.tsx`:新增页内页签「待审改价」(`quotes.tab.pendingCharges`),
|
||||
只对有报价单编辑权的人可见;该页签不显示客户筛选。
|
||||
- 保存返回 `applied === false` ⇒ 提示「已提交审核」(`quotes.toast.submittedForApproval`)并切到「待审改价」,
|
||||
**不**提示"报价单已更新"(报价单确实没动)。
|
||||
- `src/pages/customers/QuoteChangeRequestsPanel.tsx`:待审列表 + 变更摘要(改前 → 改后)+ 通过/驳回,
|
||||
驳回需填理由;`canApprove=false` ⇒ 只读(不渲染操作按钮,不额外加提示文案)。
|
||||
- i18n:`zh-CN` / `en` / `id` 三份 `quotes.ts` 同增同名 key(中文文案由 Lead 指定)。
|
||||
|
||||
## 9. 验收对照
|
||||
|
||||
| # | 判据 | 怎么验 |
|
||||
| --- | --- | --- |
|
||||
| 1 | 未审期间报价单与配送系统都不变 | 单测:价格相关保存后 `updateQuoteSheet` 未被调用、零报价写库、零推送 |
|
||||
| 2 | 通过后:报价单更新 + 台账新请求号 + 推送一次 | 单测:`applyQuoteSheetUpdate` 收到同事务 client;`triggerQuoteCostSync` 在 COMMIT 之后调用 |
|
||||
| 3 | 通过不碰审批字段、不置其它共享单为 3 | 单测(源码/事件):无 `approval_status = 30`、无 `SET status = 3`、不出现 `quote_sheet_code <> $1` |
|
||||
| 4 | 驳回后:报价单不变、状态 rejected、不推送 | 单测:reject 路径零 apply、零 trigger |
|
||||
| 5 | 覆盖:二次提交旧 pending → superseded | 单测:两次提交后 pending=1 / superseded=1 |
|
||||
| 6 | 非价格编辑不需要审核 | 单测:只改标题 ⇒ `applied:true` 且无变更单写入 |
|
||||
| 7 | 同一 SKU 重复 ⇒ 400 duplicate_sku | 单测 |
|
||||
| 8 | base 已变 ⇒ 409 base_changed + rejected + 零推送 | 单测 |
|
||||
| 9 | SKU 停用 / 客户跨分公司 ⇒ 409,零应用零推送 | 单测(应用前守卫) |
|
||||
| 10 | 权限:无 `customer_manage` 不能审批 | 路由层权限(`requireWorkflowPermission(ctx,['customer_manage'])`);前端只读按钮 |
|
||||
| 11 | 开关关闭 ⇒ 直接保存、无变更单写入 | 单测 |
|
||||
| 12 | 隔离标识未改回主系统 | `git diff -- server/.env webpack.config.js` 为空 |
|
||||
| 13 | 迁移:表进 `tenant_business_tables()` + 断言通过 | 本地 dry-run:表/索引存在、名单命中 1;`migrate` 阶段守卫通过 |
|
||||
| 14 | **A29** 列表在真库可用(不是 mock 通过) | 真库 integration:`public.profiles` join、`requested_by_name`/`reviewed_by_name` 非空;前提断言 `auth.users` 无这两列 |
|
||||
| 15 | **A26** 三条路径各有业务审计 | 单测:submit/approve/reject 各 1 条 `quote_sheet_change_request_*`(四要素齐);审计抛错不影响主流程 |
|
||||
| 16 | **A12** 目标单失效 ⇒ 409 `target_unavailable` + 变更单 pending | 单测:三句既有文案各一例;编辑路径仍抛普通 Error(语义不变) |
|
||||
| 17 | **A22/A24/A25** 口径 | 开关关不写表、存量 pending 可审批;列表权限 `customer_manage\|order_manage`;跨租户 404 |
|
||||
| 18 | **P3-1** 目标单硬删 ⇒ 409 `target_unavailable` + pending | 真库用例:建临时单→插 CR→硬删单与明细→审批 ⇒ 409 target_unavailable、CR 仍 pending、零台账;单测另钉「目标可用+指纹变 ⇒ base_changed + rejected」不回退 |
|
||||
|
||||
## 10. 风险与未覆盖
|
||||
|
||||
1. **已知旁路**(§2):`append-items` / `upsert-costs` / `PATCH auto-sale-price` / `/api/data` 不经审核。
|
||||
2. **base 判据只覆盖 `sku_code`/`unit`/`sale_price`**:提交后若只被人改了 `cost_price`(经旁路),
|
||||
指纹不变 ⇒ 审批不会被判 `base_changed`,通过时会用**提交时的成本价**覆盖。属已知偏差(Lead 裁定 #4 指定该算法)。
|
||||
3. **审批前守卫失败不自动驳回**:变更单留 pending 等人工处理(避免静默丢单)。运营若不清理会一直显示在待审列表。
|
||||
4. **跨分公司变更单**:租户 schema 隔离使别家分公司的变更单**查不到**(404 而非 403);
|
||||
只有"在当前 schema 里却带别的 branch_code"这种异常行才走 403(更严格,不泄露存在性)。
|
||||
5. **非价格编辑的触发**:只改客户时若没有新增 `MAIN_`,会触发一次但被判 `duplicate` 零出站(无害、多一次本地查询)。
|
||||
6. **未真机联调**:主系统侧成本价同步端点是否已上线由对方确认;本仓库测试全部 mock 出站。
|
||||
|
||||
## 11. 回滚
|
||||
|
||||
1. `QUOTE_EDIT_APPROVAL=0` ⇒ 立即回到"编辑直接保存"(不写变更单表)。
|
||||
2. 代码回滚 = 还原 `quoteRoutes.ts` 的 PUT 分流 + 删除 `quoteSheetChangeRequestService` /
|
||||
前端面板与页签;`applyQuoteSheetUpdate` 抽取是行为中性的,可保留。
|
||||
3. 表可保留(纯追加):`DROP TABLE qsr.quote_sheet_change_requests`(各租户 schema)并从
|
||||
`tenant_business_tables()` 移除。
|
||||
4. 本次改动**不含**任何"用本地数据覆盖线上"的语句(迁移只建表 + 索引 + 名单)。
|
||||
@@ -0,0 +1,27 @@
|
||||
-- 主系统竞价「待报价」台账:**软删除(本地隐藏 + 可恢复)**
|
||||
--
|
||||
-- 背景(Lead 裁决 .team/bid-delete-status/decisions.md Q1/Q2/Q3/Q8/Q9):
|
||||
-- · 本页是主系统的**镜像台账**,事实源在主系统;我方「删除」只能是把这一行从
|
||||
-- 我方列表里隐藏,**不通知主系统、不硬删**(硬删会被下一次同步重建,且审计失去关联对象);
|
||||
-- · 允许删除的状态只有 `pending` / `expired`(服务层校验,不信任前端);
|
||||
-- · 上游再次推送/同步同一轮 ⇒ **保持隐藏**(`upsertInvitationHeader` 的
|
||||
-- `ON CONFLICT DO UPDATE` 不写这两列;唯一键仍只有 1 行);
|
||||
-- · 恢复 = 管理员手动把 `deleted_at` 复位(只加列,不动 `local_status` 的 CHECK)。
|
||||
--
|
||||
-- 纪律:
|
||||
-- · 只做 DDL:不加 NOT NULL、不加 DEFAULT(存量行 = NULL = 未删除)、
|
||||
-- 不写任何数据修复/回填(红线:迁移不得内嵌用本地数据覆盖线上数据);
|
||||
-- · 本表是**已有表加列**,不是新业务表 ⇒ 不需要登记 `public.tenant_business_tables()`。
|
||||
--
|
||||
-- 幂等:两条 `ADD COLUMN IF NOT EXISTS` + 一条 `CREATE INDEX IF NOT EXISTS`,可重复执行。
|
||||
|
||||
ALTER TABLE public.main_system_bid_invitations
|
||||
ADD COLUMN IF NOT EXISTS deleted_at timestamptz;
|
||||
|
||||
-- 谁删的(仅留痕,不参与业务判定;恢复时置回 NULL)
|
||||
ALTER TABLE public.main_system_bid_invitations
|
||||
ADD COLUMN IF NOT EXISTS deleted_by uuid;
|
||||
|
||||
-- 列表页按分公司取「未删除」行是热路径(`deleted_at IS NULL` / 「显示已删除」两种口径都用)
|
||||
CREATE INDEX IF NOT EXISTS idx_main_system_bid_invitations_branch_deleted
|
||||
ON public.main_system_bid_invitations (branch_code, deleted_at);
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Router, Response } from 'express';
|
||||
import { authMiddleware, type AuthRequest } from '../../../middleware/auth';
|
||||
import { getEffectiveBranchCode, readOperatingBranchCode } from '../../../services/tenantScope';
|
||||
import { getWorkflowCtx, requireWorkflowPermission, sendWorkflowError } from '../context';
|
||||
import { getWorkflowCtx, requireAdminRole, requireWorkflowPermission, sendWorkflowError } from '../context';
|
||||
import {
|
||||
listBidInvitations,
|
||||
refreshBidInvitation,
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
syncBidInvitations,
|
||||
type BidFailure,
|
||||
} from '../../../services/mainSystemBidQuotes';
|
||||
import { restoreBidInvitation, softDeleteBidInvitation } from '../../../services/mainSystemBidInbox';
|
||||
|
||||
/**
|
||||
* 主系统竞价「待报价」——**我方只报价、不定标**(开发者 2026-10-17 裁决)。
|
||||
@@ -55,9 +56,11 @@ export function mountMainSystemBidWorkflowRoutes(router: Router): void {
|
||||
}
|
||||
const rawStatus = String(req.query?.status || '').trim().toLowerCase();
|
||||
const status = rawStatus === 'pending' || rawStatus === 'history' ? rawStatus : 'all';
|
||||
const includeDeleted = String(req.query?.include_deleted || '') === '1';
|
||||
const result = await listBidInvitations({
|
||||
branchCode,
|
||||
status,
|
||||
includeDeleted,
|
||||
limit: Number(req.query?.limit) || 50,
|
||||
});
|
||||
return res.json({ data: result.rows, summary: result.summary, error: null });
|
||||
@@ -115,6 +118,46 @@ export function mountMainSystemBidWorkflowRoutes(router: Router): void {
|
||||
});
|
||||
|
||||
/** 提交报价(唯一写主系统的入口;成功才回填本地) */
|
||||
/**
|
||||
* 软删除一条竞价邀约(本系统台账里隐藏)。
|
||||
* **仅管理员**(开发者裁决 Q7);只有「待报价 / 已截止」可删(Q2);
|
||||
* 不通知主系统(Q8);上游再推保持隐藏(Q3);可用 restore 恢复。
|
||||
*/
|
||||
router.post('/main-system/bid-invitations/:roundId/delete', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const ctx = await getWorkflowCtx(req);
|
||||
requireAdminRole(ctx, '仅管理员可删除竞价邀约');
|
||||
const branchCode = branchOf(req, ctx) || ctx?.branchCode || '';
|
||||
const roundId = String(req.params?.roundId || '');
|
||||
const supplierCode = req.body?.supplier_code ?? req.query?.supplier_code ?? null;
|
||||
const result = await softDeleteBidInvitation({ branchCode, roundId, supplierCode, userId: ctx?.userId ?? null });
|
||||
if (!result.ok) {
|
||||
return res.status(result.status).json({ error: result.code, error_description: result.message });
|
||||
}
|
||||
return res.json({ data: { round_code: result.roundCode, deleted: true } });
|
||||
} catch (error) {
|
||||
return sendWorkflowError(res, error, '删除竞价邀约失败');
|
||||
}
|
||||
});
|
||||
|
||||
/** 恢复一条被软删的邀约(仅管理员) */
|
||||
router.post('/main-system/bid-invitations/:roundId/restore', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const ctx = await getWorkflowCtx(req);
|
||||
requireAdminRole(ctx, '仅管理员可恢复竞价邀约');
|
||||
const branchCode = branchOf(req, ctx) || ctx?.branchCode || '';
|
||||
const roundId = String(req.params?.roundId || '');
|
||||
const supplierCode = req.body?.supplier_code ?? req.query?.supplier_code ?? null;
|
||||
const result = await restoreBidInvitation({ branchCode, roundId, supplierCode });
|
||||
if (!result.ok) {
|
||||
return res.status(result.status).json({ error: result.code, error_description: result.message });
|
||||
}
|
||||
return res.json({ data: { round_code: result.roundCode, deleted: false } });
|
||||
} catch (error) {
|
||||
return sendWorkflowError(res, error, '恢复竞价邀约失败');
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/main-system/bid-invitations/:roundId/quotes', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const ctx = await getWorkflowCtx(req);
|
||||
|
||||
@@ -0,0 +1,398 @@
|
||||
import { getMainSystemToken } from '../token';
|
||||
import { requestMainSystem, type MainSystemResult } from '../http';
|
||||
import { mainSystemQuotePriceProposalDecisionPath } from '../endpoints';
|
||||
import {
|
||||
MAIN_SYSTEM_FETCH_TIMEOUT_MS,
|
||||
isMainSystemIntegrationEnabled,
|
||||
mainSystemTimeoutMs,
|
||||
} from '../config';
|
||||
|
||||
/**
|
||||
* 报价单**双向价格传递**(2026-10-18 冻结契约 §2.1)的出站封装。
|
||||
*
|
||||
* 三个动作(全部走既有 token/http 封装,不新造客户端):
|
||||
* · **D1** `POST {path}`:我方(供应商)把整张单的销售价交配送商审;对方建 pending 行、**不写价**;
|
||||
* · **D2** `GET {path}?status=&updated_since=&limit=`:① 方向 A 的结果轮询;② 方向 B 提议拉取;
|
||||
* · **D3** `POST {path}/:id/decision`:我方对方向 B 的回执(`approved|rejected`),对方**只改状态、不写价**。
|
||||
*
|
||||
* 身份:`supplier_code` 只由 token 决定(请求体不带)。
|
||||
* 幂等:D1 用 `client_request_id`(同号同 hash ⇒ replayed;不同 hash/归属 ⇒ 409)。
|
||||
*
|
||||
* 设计:docs/design/20261018-报价单双向价格传递与审批.md §3
|
||||
*/
|
||||
|
||||
export type QuotePriceProposalItemPayload = {
|
||||
sku_code: string;
|
||||
/** 单位可空(对方按自己的行/商品比;我方提交时尽量带上) */
|
||||
unit?: string | null;
|
||||
/** 同一个数:我方销售价 = 配送商成本价 */
|
||||
price: number;
|
||||
};
|
||||
|
||||
export type SubmitQuotePriceProposalInput = {
|
||||
supplierCode: string;
|
||||
clientRequestId: string;
|
||||
supplierQuoteSheetCode: string;
|
||||
mainBranchCode: string;
|
||||
note?: string | null;
|
||||
items: QuotePriceProposalItemPayload[];
|
||||
};
|
||||
|
||||
export type SubmitQuotePriceProposalOutcome =
|
||||
| {
|
||||
kind: 'ok';
|
||||
status: number;
|
||||
data: { proposal_id: string; status: string; replayed: boolean };
|
||||
}
|
||||
| {
|
||||
kind: 'rejected' | 'unavailable' | 'not_configured';
|
||||
status: number;
|
||||
code: string;
|
||||
reason: string;
|
||||
payload: unknown;
|
||||
};
|
||||
|
||||
/** D2 返回的一行(字段名照契约,缺省一律兜空值) */
|
||||
export type RemoteQuotePriceProposalRow = {
|
||||
proposal_id: string;
|
||||
/** 配送侧的视角:`from_supplier` = 我方提交的 A;`to_supplier` = 配送商发起的 B */
|
||||
direction: string;
|
||||
status: string;
|
||||
supplier_quote_sheet_code: string;
|
||||
/** 配送侧的分公司码(= 我方的 main_branch_code) */
|
||||
branch_code: string;
|
||||
items: QuotePriceProposalItemPayload[];
|
||||
note: string | null;
|
||||
reject_reason: string | null;
|
||||
applied: { updated: number; skipped: unknown } | null;
|
||||
created_at: string | null;
|
||||
reviewed_at: string | null;
|
||||
};
|
||||
|
||||
export type ListQuotePriceProposalsOutcome =
|
||||
| {
|
||||
kind: 'ok';
|
||||
status: number;
|
||||
rows: RemoteQuotePriceProposalRow[];
|
||||
summary: { pending: number; approved: number; rejected: number } | null;
|
||||
/** T10 游标:复合 `(updated_at, id)`,下一轮带上它增量拉取(只按 status 全量拉会越拉越慢) */
|
||||
nextCursor: string | null;
|
||||
}
|
||||
| {
|
||||
kind: 'rejected' | 'unavailable' | 'not_configured';
|
||||
status: number;
|
||||
code: string;
|
||||
reason: string;
|
||||
payload: unknown;
|
||||
};
|
||||
|
||||
export type DecideQuotePriceProposalOutcome =
|
||||
| { kind: 'ok'; status: number }
|
||||
| {
|
||||
kind: 'rejected' | 'unavailable' | 'not_configured';
|
||||
status: number;
|
||||
code: string;
|
||||
reason: string;
|
||||
payload: unknown;
|
||||
};
|
||||
|
||||
function toText(value: unknown): string | null {
|
||||
if (value === null || value === undefined) return null;
|
||||
const text = String(value).trim();
|
||||
return text ? text : null;
|
||||
}
|
||||
|
||||
function toNumber(value: unknown): number | null {
|
||||
if (value === null || value === undefined || value === '') return null;
|
||||
const num = Number(value);
|
||||
return Number.isFinite(num) ? num : null;
|
||||
}
|
||||
|
||||
/** 对方错误码(`payload.error`);没带就用状态码兜一个稳定的内部码 */
|
||||
export function readQuotePriceProposalErrorCode(payload: unknown, status: number): string {
|
||||
const p = payload as { error?: unknown; code?: unknown } | null;
|
||||
const raw = toText(p?.error) || toText(p?.code);
|
||||
if (raw) return raw;
|
||||
if (status === 401) return 'unauthorized';
|
||||
if (status === 403) return 'forbidden';
|
||||
if (status === 404) return 'not_found';
|
||||
if (status === 409) return 'conflict';
|
||||
if (status === 503) return 'feature_disabled';
|
||||
if (status >= 500) return 'main_system_error';
|
||||
return 'request_failed';
|
||||
}
|
||||
|
||||
function toFailure(
|
||||
result: Exclude<MainSystemResult<unknown>, { kind: 'ok' }>
|
||||
): { kind: 'rejected' | 'unavailable' | 'not_configured'; status: number; code: string; reason: string; payload: unknown } {
|
||||
const status = Number(result.status) || 0;
|
||||
const payload = (result as { payload?: unknown }).payload ?? null;
|
||||
return {
|
||||
kind: result.kind,
|
||||
status,
|
||||
code: result.kind === 'not_configured' ? 'not_configured' : readQuotePriceProposalErrorCode(payload, status),
|
||||
reason: result.reason || '调用主系统失败',
|
||||
payload,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 换 token + 调用 + **401 强制刷新重试一次**(与 `api/bids.ts` / `api/quoteCostSync.ts` 同款)。
|
||||
* 真正 401 说明对方已判失效,再刷也白刷 ⇒ 第二次失败直接上报。
|
||||
*/
|
||||
async function callWithToken<T>(
|
||||
supplierCode: string,
|
||||
call: (token: string) => Promise<MainSystemResult<T>>
|
||||
): Promise<MainSystemResult<T>> {
|
||||
const first = await getMainSystemToken(supplierCode);
|
||||
if (first.kind !== 'ok') {
|
||||
return {
|
||||
kind: first.kind === 'not_configured' ? 'not_configured' : 'unavailable',
|
||||
status: 0,
|
||||
reason: first.reason,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
const result = await call(first.token);
|
||||
if (result.kind === 'ok' || Number(result.status) !== 401) return result;
|
||||
const refreshed = await getMainSystemToken(supplierCode, { forceRefresh: true });
|
||||
if (refreshed.kind !== 'ok') {
|
||||
return {
|
||||
kind: refreshed.kind === 'not_configured' ? 'not_configured' : 'unavailable',
|
||||
status: 0,
|
||||
reason: refreshed.reason,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
return call(refreshed.token);
|
||||
}
|
||||
|
||||
/**
|
||||
* 403 在本项目 HTTP 层的默认归类是"暂态"(下轮重试),但本端点 403 是**语义拒绝**
|
||||
* (未绑定该分公司 / 无权看这张单)⇒ `classify` 改成 rejected,业务层按终态处理。
|
||||
*/
|
||||
const classifyQuotePriceProposal = (input: { status: number }) =>
|
||||
input.status === 403 ? ('rejected' as const) : null;
|
||||
|
||||
/** 归一 D1 回执 */
|
||||
export function normalizeSubmitResult(raw: unknown): {
|
||||
proposal_id: string;
|
||||
status: string;
|
||||
replayed: boolean;
|
||||
} {
|
||||
const body = (raw || {}) as Record<string, unknown>;
|
||||
const data = (body.data && typeof body.data === 'object' ? body.data : body) as Record<string, unknown>;
|
||||
return {
|
||||
proposal_id: toText(data.proposal_id) || '',
|
||||
status: toText(data.status) || 'pending',
|
||||
replayed: data.replayed === true,
|
||||
};
|
||||
}
|
||||
|
||||
/** 归一 D2 的一行 */
|
||||
export function normalizeRemoteRow(raw: unknown): RemoteQuotePriceProposalRow | null {
|
||||
const row = (raw || {}) as Record<string, unknown>;
|
||||
const proposalId = toText(row.proposal_id);
|
||||
if (!proposalId) return null;
|
||||
const appliedRaw = (row.applied || null) as Record<string, unknown> | null;
|
||||
const itemsRaw = Array.isArray(row.items) ? row.items : [];
|
||||
return {
|
||||
proposal_id: proposalId,
|
||||
direction: toText(row.direction) || '',
|
||||
status: toText(row.status) || 'pending',
|
||||
supplier_quote_sheet_code: toText(row.supplier_quote_sheet_code) || '',
|
||||
branch_code: toText(row.branch_code) || '',
|
||||
items: itemsRaw
|
||||
.map((item): QuotePriceProposalItemPayload | null => {
|
||||
const row2 = (item || {}) as Record<string, unknown>;
|
||||
const sku = toText(row2.sku_code);
|
||||
const price = toNumber(row2.price ?? row2.sale_price);
|
||||
if (!sku || price === null) return null;
|
||||
return { sku_code: sku, unit: toText(row2.unit), price };
|
||||
})
|
||||
.filter((item): item is QuotePriceProposalItemPayload => item !== null),
|
||||
note: toText(row.note),
|
||||
reject_reason: toText(row.reject_reason),
|
||||
applied: appliedRaw
|
||||
? {
|
||||
updated: Number(appliedRaw.updated) || 0,
|
||||
skipped: appliedRaw.skipped ?? null,
|
||||
}
|
||||
: null,
|
||||
created_at: toText(row.created_at),
|
||||
reviewed_at: toText(row.reviewed_at),
|
||||
};
|
||||
}
|
||||
|
||||
/** D1:提交整单价格给配送商审(对方建 pending,**不写价**) */
|
||||
export async function submitQuotePriceProposal(
|
||||
input: SubmitQuotePriceProposalInput
|
||||
): Promise<SubmitQuotePriceProposalOutcome> {
|
||||
if (!isMainSystemIntegrationEnabled()) {
|
||||
return { kind: 'not_configured', status: 0, code: 'not_configured', reason: '主系统对接未配置', payload: null };
|
||||
}
|
||||
const supplierCode = String(input.supplierCode || '').trim();
|
||||
if (!supplierCode) {
|
||||
return {
|
||||
kind: 'not_configured',
|
||||
status: 0,
|
||||
code: 'supplier_code_missing',
|
||||
reason: '缺少主系统供应商编码(无法换取对接 token)',
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
if (!input.items?.length) {
|
||||
return { kind: 'rejected', status: 0, code: 'items_required', reason: '没有可提交的商品行', payload: null };
|
||||
}
|
||||
|
||||
const result = await callWithToken<any>(supplierCode, (token) =>
|
||||
requestMainSystem<any>({
|
||||
endpoint: 'quotePriceProposals',
|
||||
method: 'POST',
|
||||
token,
|
||||
body: {
|
||||
client_request_id: input.clientRequestId,
|
||||
supplier_quote_sheet_code: input.supplierQuoteSheetCode,
|
||||
main_branch_code: input.mainBranchCode,
|
||||
note: input.note ?? undefined,
|
||||
items: input.items.map((item) => ({
|
||||
sku_code: item.sku_code,
|
||||
...(item.unit ? { unit: item.unit } : {}),
|
||||
price: item.price,
|
||||
})),
|
||||
},
|
||||
timeoutMs: mainSystemTimeoutMs() + MAIN_SYSTEM_FETCH_TIMEOUT_MS,
|
||||
timeoutReason: '提交报价单价格提议超时(对方可能已受理,按 client_request_id 幂等重试即可)',
|
||||
networkReasonPrefix: '提交报价单价格提议失败:',
|
||||
classify: classifyQuotePriceProposal,
|
||||
})
|
||||
);
|
||||
if (result.kind !== 'ok') return toFailure(result);
|
||||
|
||||
const raw = result.data as any;
|
||||
// 退化载荷守卫:2xx 但没有 proposal_id ⇒ 不是"已受理",按不可用处理(下轮幂等重试)
|
||||
const normalized = normalizeSubmitResult(raw);
|
||||
if (!normalized.proposal_id) {
|
||||
return {
|
||||
kind: 'unavailable',
|
||||
status: result.status,
|
||||
code: 'invalid_main_system_response',
|
||||
reason: '主系统返回的价格提议回执不可识别(缺少 proposal_id)',
|
||||
payload: result.payload,
|
||||
};
|
||||
}
|
||||
return { kind: 'ok', status: result.status, data: normalized };
|
||||
}
|
||||
|
||||
/** D2:A 结果轮询 + B 提议拉取 */
|
||||
export async function listQuotePriceProposals(input: {
|
||||
supplierCode: string;
|
||||
status?: string | null;
|
||||
/** T10:上一轮返回的 `next_cursor`(有它就增量拉,不要再全量按状态扫) */
|
||||
cursor?: string | null;
|
||||
updatedSince?: string | null;
|
||||
limit?: number;
|
||||
/**
|
||||
* 按对方 proposal id **精确查**(A16 审批前状态核对用;配送侧新增 `?proposal_id=`)。
|
||||
* 不支持时对方会忽略该参数,调用方需自行翻页兜底。
|
||||
*/
|
||||
proposalId?: string | null;
|
||||
}): Promise<ListQuotePriceProposalsOutcome> {
|
||||
if (!isMainSystemIntegrationEnabled()) {
|
||||
return { kind: 'not_configured', status: 0, code: 'not_configured', reason: '主系统对接未配置', payload: null };
|
||||
}
|
||||
const supplierCode = String(input.supplierCode || '').trim();
|
||||
if (!supplierCode) {
|
||||
return {
|
||||
kind: 'not_configured',
|
||||
status: 0,
|
||||
code: 'supplier_code_missing',
|
||||
reason: '缺少主系统供应商编码(无法换取对接 token)',
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
const limit = Math.min(Math.max(Number(input.limit) || 50, 1), 200);
|
||||
const result = await callWithToken<any>(supplierCode, (token) =>
|
||||
requestMainSystem<any>({
|
||||
endpoint: 'quotePriceProposals',
|
||||
method: 'GET',
|
||||
token,
|
||||
query: {
|
||||
status: input.status ?? undefined,
|
||||
cursor: input.cursor ?? undefined,
|
||||
updated_since: input.updatedSince ?? undefined,
|
||||
proposal_id: input.proposalId ?? undefined,
|
||||
limit,
|
||||
},
|
||||
timeoutMs: MAIN_SYSTEM_FETCH_TIMEOUT_MS,
|
||||
timeoutReason: '拉取报价单价格提议超时',
|
||||
networkReasonPrefix: '拉取报价单价格提议失败:',
|
||||
classify: classifyQuotePriceProposal,
|
||||
})
|
||||
);
|
||||
if (result.kind !== 'ok') return toFailure(result);
|
||||
|
||||
const raw = result.data as any;
|
||||
const data = (raw?.data && typeof raw.data === 'object' ? raw.data : raw) as Record<string, unknown>;
|
||||
const rowsRaw = Array.isArray(data.rows) ? data.rows : [];
|
||||
const summaryRaw = (data.summary || null) as Record<string, unknown> | null;
|
||||
return {
|
||||
kind: 'ok',
|
||||
status: result.status,
|
||||
rows: rowsRaw
|
||||
.map(normalizeRemoteRow)
|
||||
.filter((row): row is RemoteQuotePriceProposalRow => Boolean(row)),
|
||||
summary: summaryRaw
|
||||
? {
|
||||
pending: Number(summaryRaw.pending) || 0,
|
||||
approved: Number(summaryRaw.approved) || 0,
|
||||
rejected: Number(summaryRaw.rejected) || 0,
|
||||
}
|
||||
: null,
|
||||
nextCursor: toText(data.next_cursor) || null,
|
||||
};
|
||||
}
|
||||
|
||||
/** D3:我方对方向 B 的回执(只改状态,不写价) */
|
||||
export async function decideQuotePriceProposal(input: {
|
||||
supplierCode: string;
|
||||
proposalId: string;
|
||||
decision: 'approved' | 'rejected';
|
||||
reason?: string | null;
|
||||
/** A20:approve 时带上写价统计(`{updated, skipped}`),配送侧只记录、不写价 */
|
||||
applied?: { updated: number; skipped: unknown } | null;
|
||||
}): Promise<DecideQuotePriceProposalOutcome> {
|
||||
if (!isMainSystemIntegrationEnabled()) {
|
||||
return { kind: 'not_configured', status: 0, code: 'not_configured', reason: '主系统对接未配置', payload: null };
|
||||
}
|
||||
const supplierCode = String(input.supplierCode || '').trim();
|
||||
const proposalId = String(input.proposalId || '').trim();
|
||||
if (!supplierCode || !proposalId) {
|
||||
return {
|
||||
kind: 'rejected',
|
||||
status: 0,
|
||||
code: 'invalid_request',
|
||||
reason: '缺少 supplier_code 或 proposal id',
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
const result = await callWithToken<any>(supplierCode, (token) =>
|
||||
requestMainSystem<any>({
|
||||
endpoint: 'quotePriceProposals',
|
||||
path: mainSystemQuotePriceProposalDecisionPath(proposalId),
|
||||
method: 'POST',
|
||||
token,
|
||||
body: {
|
||||
decision: input.decision,
|
||||
...(input.reason ? { reason: String(input.reason) } : {}),
|
||||
...(input.applied ? { applied: input.applied } : {}),
|
||||
},
|
||||
timeoutMs: mainSystemTimeoutMs() + MAIN_SYSTEM_FETCH_TIMEOUT_MS,
|
||||
timeoutReason: '回执报价单价格提议超时(对方可能已受理,可重试)',
|
||||
networkReasonPrefix: '回执报价单价格提议失败:',
|
||||
classify: classifyQuotePriceProposal,
|
||||
})
|
||||
);
|
||||
if (result.kind !== 'ok') return toFailure(result);
|
||||
return { kind: 'ok', status: result.status };
|
||||
}
|
||||
@@ -39,6 +39,8 @@ export type BidInvitationDto = {
|
||||
localStatus: BidLocalStatus;
|
||||
quotedAt: string | null;
|
||||
lastSyncedAt: string | null;
|
||||
/** 本地软删除时间(NULL = 正常显示;2026-10-18 台账软删除) */
|
||||
deletedAt: string | null;
|
||||
};
|
||||
|
||||
export type BidInvitationItemDto = {
|
||||
@@ -89,6 +91,9 @@ export type BidInvitationRow = {
|
||||
webhook_received_at: Date | string | null;
|
||||
last_synced_at: Date | string | null;
|
||||
sync_error: string | null;
|
||||
/** 软删除:非空 = 本系统列表里隐藏(不通知主系统,可恢复) */
|
||||
deleted_at?: Date | string | null;
|
||||
deleted_by?: string | null;
|
||||
payload: unknown;
|
||||
created_at: Date | string;
|
||||
updated_at: Date | string;
|
||||
@@ -149,12 +154,14 @@ export function isBidOpenedEvent(event: unknown): boolean {
|
||||
* **唯一**的「对方事实 → 我方视图状态」口径(页面 6 种状态全由它决定):
|
||||
*
|
||||
* 1. 轮次取消 ⇒ `cancelled`
|
||||
* 2. 轮次已定标 ⇒ 我方有中标行 `won`,没有 `lost`
|
||||
* 3. 邀约过期(对方说 expired,或截止时间已过)⇒ `expired`
|
||||
* 4. 已报(对方说 quoted,或本地每一行都有价)⇒ `quoted`
|
||||
* 2. 轮次已定标 ⇒ 我方有中标行 `won`;有明确落标事实 `lost`;两者都没有 ⇒ **不臆造未中标**,
|
||||
* 报过价就回落 `quoted`,否则 `pending`(分不清"真没中标"与"结果还没拉到")
|
||||
* 3. 已报(对方说 quoted,或本地每一行都有价)⇒ `quoted`
|
||||
* 报价事实**优先于截止时间**:报过价、过了截止仍显示「已报价」,不被「已截止」吃掉
|
||||
* 4. 邀约过期(对方说 expired,或截止时间已过)⇒ `expired`
|
||||
* 5. 其余 ⇒ `pending`
|
||||
*
|
||||
* 注意顺序:**先看轮次**(已定标/取消比"过期"更权威),再看邀约。
|
||||
* 注意顺序:**先看轮次**(已定标/取消比"过期"更权威),再看报价事实,最后看截止。
|
||||
* 截止时间比较用**我方服务器时钟**(与主系统同机部署,偏差可忽略);最终裁决仍在对方。
|
||||
*/
|
||||
export function deriveLocalStatus(input: {
|
||||
@@ -164,22 +171,37 @@ export function deriveLocalStatus(input: {
|
||||
itemCount: number;
|
||||
quotedCount: number;
|
||||
hasAward: boolean;
|
||||
/** 我方**明确落标**事实(明细 `award_status='lost'`)。缺省视为未知,不得据此判「未中标」 */
|
||||
hasLost?: boolean;
|
||||
now?: Date;
|
||||
}): BidLocalStatus {
|
||||
const roundStatus = String(input.roundStatus || 'open');
|
||||
if (roundStatus === 'cancelled') return 'cancelled';
|
||||
if (roundStatus === 'awarded') return input.hasAward ? 'won' : 'lost';
|
||||
|
||||
const mainStatus = input.mainInvitationStatus ? String(input.mainInvitationStatus) : '';
|
||||
const itemCount = Number(input.itemCount) || 0;
|
||||
const quotedCount = Number(input.quotedCount) || 0;
|
||||
/** 报过价:对方说 quoted,或本地每一行都有价(部分报价不算已报) */
|
||||
const quoted = mainStatus === 'quoted' || (itemCount > 0 && quotedCount >= itemCount);
|
||||
|
||||
if (roundStatus === 'awarded') {
|
||||
if (input.hasAward) return 'won';
|
||||
if (input.hasLost) return 'lost';
|
||||
/**
|
||||
* 已定标:
|
||||
* · 明细已拉到(itemCount>0)⇒ 我方没有中标行就是**对方的定标事实**,判未中标;
|
||||
* · 明细还没拉到(itemCount=0)⇒ 分不清"真没中标"与"还没拉到",不臆造,回落已报价/待报价。
|
||||
*/
|
||||
if (itemCount > 0) return 'lost';
|
||||
return quoted ? 'quoted' : 'pending';
|
||||
}
|
||||
|
||||
if (quoted) return 'quoted';
|
||||
|
||||
const deadlineMs = input.respondDeadline ? new Date(input.respondDeadline).getTime() : NaN;
|
||||
const nowMs = (input.now || new Date()).getTime();
|
||||
const deadlinePassed = Number.isFinite(deadlineMs) && deadlineMs < nowMs;
|
||||
if (mainStatus === 'expired' || deadlinePassed) return 'expired';
|
||||
|
||||
const itemCount = Number(input.itemCount) || 0;
|
||||
const quotedCount = Number(input.quotedCount) || 0;
|
||||
if (mainStatus === 'quoted') return 'quoted';
|
||||
if (itemCount > 0 && quotedCount >= itemCount) return 'quoted';
|
||||
return 'pending';
|
||||
}
|
||||
|
||||
@@ -196,6 +218,7 @@ export function toBidInvitationDto(row: BidInvitationRow): BidInvitationDto {
|
||||
localStatus: (row.local_status || 'pending') as BidLocalStatus,
|
||||
quotedAt: toIso(row.quoted_at),
|
||||
lastSyncedAt: toIso(row.last_synced_at),
|
||||
deletedAt: toIso(row.deleted_at),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -204,12 +227,23 @@ export function toBidInvitationItemDto(
|
||||
roundStatus: string
|
||||
): BidInvitationItemDto {
|
||||
const awardPrice = toNumber(row.award_price);
|
||||
/**
|
||||
* 中标判定**只认** `award_status`(won/lost)。`award_price` 非空不代表中标
|
||||
* (对方字段可能回显我方报价),不得据此判 won。
|
||||
*/
|
||||
/**
|
||||
* `won` **只认** `award_status`:`award_price` 非空可能只是对方回显我方报价,
|
||||
* 不能据此判「已中标」(2026-10-18 开发者裁决)。
|
||||
* `lost` = 明确落标,或整轮已定标(明细已拉到 ⇒ 我方没有中标行就是定标事实)。
|
||||
*/
|
||||
const awardStatus: 'won' | 'lost' | null =
|
||||
row.award_status === 'won' || awardPrice !== null
|
||||
row.award_status === 'won'
|
||||
? 'won'
|
||||
: String(roundStatus) === 'awarded'
|
||||
: row.award_status === 'lost'
|
||||
? 'lost'
|
||||
: null;
|
||||
: String(roundStatus) === 'awarded'
|
||||
? 'lost'
|
||||
: null;
|
||||
return {
|
||||
skuCode: String(row.sku_code || ''),
|
||||
skuName: row.sku_name ?? null,
|
||||
@@ -258,6 +292,8 @@ async function recomputeLocalStatus(client: any, invitationId: string): Promise<
|
||||
WHERE it.invitation_id = i.id AND it.unit_price IS NOT NULL) AS quoted_count,
|
||||
EXISTS (SELECT 1 FROM public.main_system_bid_invitation_items it
|
||||
WHERE it.invitation_id = i.id AND it.award_status = 'won') AS has_award,
|
||||
EXISTS (SELECT 1 FROM public.main_system_bid_invitation_items it
|
||||
WHERE it.invitation_id = i.id AND it.award_status = 'lost') AS has_lost,
|
||||
(SELECT MAX(it.quoted_at) FROM public.main_system_bid_invitation_items it
|
||||
WHERE it.invitation_id = i.id) AS quoted_at
|
||||
FROM public.main_system_bid_invitations i
|
||||
@@ -273,6 +309,7 @@ async function recomputeLocalStatus(client: any, invitationId: string): Promise<
|
||||
itemCount: Number(row.item_count) || 0,
|
||||
quotedCount: Number(row.quoted_count) || 0,
|
||||
hasAward: row.has_award === true,
|
||||
hasLost: row.has_lost === true,
|
||||
});
|
||||
await client.query(
|
||||
`UPDATE public.main_system_bid_invitations
|
||||
@@ -703,6 +740,7 @@ export async function findInvitationByRound(input: {
|
||||
const { rows } = await pool.query<BidInvitationRow>(
|
||||
`SELECT * FROM public.main_system_bid_invitations
|
||||
WHERE branch_code = $1 AND round_id = $2 AND upper(supplier_code) = upper($3)
|
||||
AND deleted_at IS NULL
|
||||
LIMIT 1`,
|
||||
[branchCode, roundId, supplierCode]
|
||||
);
|
||||
@@ -724,12 +762,15 @@ export async function findInvitationByRound(input: {
|
||||
export async function listInvitationRows(input: {
|
||||
branchCode: string;
|
||||
status?: 'all' | 'pending' | 'history' | null;
|
||||
/** true = 连已软删的行一起返回(页面「显示已删除」开关) */
|
||||
includeDeleted?: boolean;
|
||||
limit?: number;
|
||||
}): Promise<{ rows: BidInvitationRow[]; counts: Record<string, number> }> {
|
||||
const branchCode = String(input.branchCode || '').trim();
|
||||
if (!branchCode) return { rows: [], counts: {} };
|
||||
const limit = Math.min(Math.max(Number(input.limit) || 50, 1), 200);
|
||||
const status = input.status === 'pending' || input.status === 'history' ? input.status : null;
|
||||
const deletedSql = input.includeDeleted ? '' : 'AND deleted_at IS NULL';
|
||||
const statusSql =
|
||||
status === 'pending'
|
||||
? `AND local_status = 'pending'`
|
||||
@@ -740,7 +781,7 @@ export async function listInvitationRows(input: {
|
||||
const [rows, counts] = await Promise.all([
|
||||
pool.query<BidInvitationRow>(
|
||||
`SELECT * FROM public.main_system_bid_invitations
|
||||
WHERE branch_code = $1 ${statusSql}
|
||||
WHERE branch_code = $1 ${deletedSql} ${statusSql}
|
||||
ORDER BY (local_status = 'pending') DESC,
|
||||
CASE WHEN local_status = 'pending' THEN respond_deadline END ASC NULLS LAST,
|
||||
updated_at DESC
|
||||
@@ -750,7 +791,7 @@ export async function listInvitationRows(input: {
|
||||
pool.query<{ local_status: string; n: number }>(
|
||||
`SELECT local_status, COUNT(*)::int AS n
|
||||
FROM public.main_system_bid_invitations
|
||||
WHERE branch_code = $1
|
||||
WHERE branch_code = $1 ${deletedSql}
|
||||
GROUP BY local_status`,
|
||||
[branchCode]
|
||||
),
|
||||
@@ -761,6 +802,85 @@ export async function listInvitationRows(input: {
|
||||
return { rows: rows.rows, counts: countsMap };
|
||||
}
|
||||
|
||||
/**
|
||||
* 软删除一条竞价邀约(本系统台账里隐藏)。
|
||||
*
|
||||
* 口径(`.team/bid-delete-status/decisions.md`):**不通知主系统、不硬删**;
|
||||
* 只允许 `pending` / `expired`;上游再次推送时 `upsertInvitationHeader` 不写 `deleted_at` ⇒ 保持隐藏。
|
||||
*/
|
||||
export async function softDeleteBidInvitation(input: {
|
||||
branchCode: string;
|
||||
roundId: string;
|
||||
supplierCode?: string | null;
|
||||
userId?: string | null;
|
||||
}): Promise<
|
||||
{ ok: true; roundCode: string | null } | { ok: false; status: number; code: string; message: string }
|
||||
> {
|
||||
const branchCode = String(input.branchCode || '').trim();
|
||||
const roundId = String(input.roundId || '').trim();
|
||||
if (!branchCode || !roundId) {
|
||||
return { ok: false, status: 400, code: 'branch_required', message: '缺少分公司或竞价轮次' };
|
||||
}
|
||||
const supplierCode = String(input.supplierCode || '').trim();
|
||||
const scope = supplierCode ? 'AND upper(supplier_code) = upper($4)' : '';
|
||||
const params: unknown[] = [branchCode, roundId, input.userId || null];
|
||||
if (supplierCode) params.push(supplierCode);
|
||||
const { rows } = await pool.query(
|
||||
`UPDATE public.main_system_bid_invitations
|
||||
SET deleted_at = NOW(), deleted_by = $3, updated_at = NOW()
|
||||
WHERE branch_code = $1 AND round_id = $2 ${scope}
|
||||
AND deleted_at IS NULL
|
||||
AND local_status IN ('pending', 'expired')
|
||||
RETURNING round_code`,
|
||||
params
|
||||
);
|
||||
if (!rows.length) {
|
||||
const exists = await pool.query<{ local_status: string; deleted_at: Date | null }>(
|
||||
`SELECT local_status, deleted_at FROM public.main_system_bid_invitations
|
||||
WHERE branch_code = $1 AND round_id = $2 ${scope}
|
||||
LIMIT 1`,
|
||||
params.slice(0, supplierCode ? 4 : 2)
|
||||
);
|
||||
if (!exists.rows.length) return { ok: false, status: 404, code: 'not_found', message: '竞价邀约不存在' };
|
||||
if (exists.rows[0].deleted_at) {
|
||||
return { ok: false, status: 409, code: 'already_deleted', message: '该邀约已删除' };
|
||||
}
|
||||
return {
|
||||
ok: false,
|
||||
status: 409,
|
||||
code: 'not_deletable',
|
||||
message: '只有「待报价 / 已截止」的邀约可以删除',
|
||||
};
|
||||
}
|
||||
return { ok: true, roundCode: rows[0]?.round_code ?? null };
|
||||
}
|
||||
|
||||
/** 恢复一条被软删的邀约(仅管理员;直接把 `deleted_at` 复位) */
|
||||
export async function restoreBidInvitation(input: {
|
||||
branchCode: string;
|
||||
roundId: string;
|
||||
supplierCode?: string | null;
|
||||
}): Promise<{ ok: true; roundCode: string | null } | { ok: false; status: number; code: string; message: string }> {
|
||||
const branchCode = String(input.branchCode || '').trim();
|
||||
const roundId = String(input.roundId || '').trim();
|
||||
if (!branchCode || !roundId) {
|
||||
return { ok: false, status: 400, code: 'branch_required', message: '缺少分公司或竞价轮次' };
|
||||
}
|
||||
const supplierCode = String(input.supplierCode || '').trim();
|
||||
const scope = supplierCode ? 'AND upper(supplier_code) = upper($3)' : '';
|
||||
const params: unknown[] = [branchCode, roundId];
|
||||
if (supplierCode) params.push(supplierCode);
|
||||
const { rows } = await pool.query(
|
||||
`UPDATE public.main_system_bid_invitations
|
||||
SET deleted_at = NULL, deleted_by = NULL, updated_at = NOW()
|
||||
WHERE branch_code = $1 AND round_id = $2 ${scope} AND deleted_at IS NOT NULL
|
||||
RETURNING round_code`,
|
||||
params
|
||||
);
|
||||
if (!rows.length) return { ok: false, status: 404, code: 'not_found', message: '没有可恢复的已删邀约' };
|
||||
return { ok: true, roundCode: rows[0]?.round_code ?? null };
|
||||
}
|
||||
|
||||
export async function listInvitationItems(invitationId: string): Promise<BidInvitationItemRow[]> {
|
||||
const { rows } = await pool.query<BidInvitationItemRow>(
|
||||
`SELECT * FROM public.main_system_bid_invitation_items
|
||||
|
||||
@@ -171,6 +171,8 @@ function emptySummary() {
|
||||
export async function listBidInvitations(input: {
|
||||
branchCode: string;
|
||||
status?: 'all' | 'pending' | 'history' | null;
|
||||
/** true = 连已软删的行一起返回(页面「显示已删除」开关) */
|
||||
includeDeleted?: boolean;
|
||||
limit?: number;
|
||||
}): Promise<BidListOutcome> {
|
||||
const { rows, counts } = await listInvitationRows(input);
|
||||
|
||||
@@ -1703,6 +1703,46 @@ async function trackDayOutcome(
|
||||
mainBranchCode: bucket.mainBranchCode,
|
||||
mainOrderCodes,
|
||||
});
|
||||
/**
|
||||
* **派单/追加都要有站内通知**(开发者 2026-10-18):
|
||||
* 主系统派了货、或又追加了商品行,操作员必须在消息通知里看到,而不是"自己去列表里发现"。
|
||||
*/
|
||||
try {
|
||||
const { notifyRoleUsers } = await import('./notificationService');
|
||||
const createdRows = outcome.results.filter((r) => r.status === 'created' || r.status === 'appended');
|
||||
const ourOrderCodes = [...new Set(outcome.results.map((r) => r.ourOrderCode).filter(Boolean))];
|
||||
const itemCount = createdRows.reduce((sum, r) => sum + (Number(r.itemCount) || 0), 0);
|
||||
if (outcome.status === 'created') {
|
||||
await notifyRoleUsers({
|
||||
roles: ['admin', 'operator'],
|
||||
notifyType: 'main_system_order_created',
|
||||
title: `主系统派单:${ourOrderCodes.join('、') || bucket.deliveryDate} 已生成`,
|
||||
content:
|
||||
`主系统分配了 ${itemCount} 行商品(配送日 ${bucket.deliveryDate}),` +
|
||||
`已生成订单 ${ourOrderCodes.join('、') || '(见订单管理)'},请及时备货。`,
|
||||
relatedOrderCode: ourOrderCodes[0] || null,
|
||||
branchCode,
|
||||
dedupWithinHours: 1,
|
||||
}).catch(() => undefined);
|
||||
} else {
|
||||
await notifyRoleUsers({
|
||||
roles: ['admin', 'operator'],
|
||||
notifyType: 'main_system_items_appended',
|
||||
title: `主系统新增商品行:${ourOrderCodes.join('、') || bucket.deliveryDate}`,
|
||||
content:
|
||||
`主系统又分配了 ${itemCount} 行商品到订单 ${ourOrderCodes.join('、') || ''}` +
|
||||
`(配送日 ${bucket.deliveryDate}),已追加,请及时备货。`,
|
||||
relatedOrderCode: ourOrderCodes[0] || null,
|
||||
branchCode,
|
||||
dedupWithinHours: 1,
|
||||
}).catch(() => undefined);
|
||||
}
|
||||
} catch (notifyError) {
|
||||
console.error(
|
||||
'[main-system-import] 派单通知发送失败(不影响导入):',
|
||||
(notifyError as Error)?.message || notifyError
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(
|
||||
|
||||
@@ -100,6 +100,23 @@ export async function applyItemNoLongerOurs(input: {
|
||||
itemId: link.itemId!,
|
||||
})
|
||||
);
|
||||
// 反向变更也要有站内通知(开发者 2026-10-18):删商品行 / 改派走
|
||||
try {
|
||||
const { notifyRoleUsers } = await import('./notificationService');
|
||||
await notifyRoleUsers({
|
||||
roles: ['admin', 'operator'],
|
||||
notifyType: 'main_system_items_removed',
|
||||
title: input.reason === 'reallocated' ? '主系统改派商品,已从我方订单移除' : '主系统删除商品,已从我方订单移除',
|
||||
content:
|
||||
`订单 ${link.ourOrderCode} 的商品行已按主系统通知移除` +
|
||||
`(${input.itemName || input.skuCode || '未知商品'})。`,
|
||||
relatedOrderCode: link.ourOrderCode,
|
||||
branchCode,
|
||||
dedupWithinHours: 1,
|
||||
}).catch(() => undefined);
|
||||
} catch (error) {
|
||||
console.error('[main-system-reverse] 行移除通知失败(不影响处理):', (error as Error)?.message || error);
|
||||
}
|
||||
return {
|
||||
status: outcome === 'deleted' ? 'removed' : 'already_gone',
|
||||
ourOrderCode: link.ourOrderCode,
|
||||
@@ -196,5 +213,21 @@ export async function applyOrderCancelledByMainSystem(input: {
|
||||
);
|
||||
}
|
||||
}
|
||||
try {
|
||||
if ((updated.rowCount || 0) > 0) {
|
||||
const { notifyRoleUsers } = await import('./notificationService');
|
||||
await notifyRoleUsers({
|
||||
roles: ['admin', 'operator'],
|
||||
notifyType: 'main_system_order_cancelled',
|
||||
title: '主系统删除订单,我方已停用',
|
||||
content: `订单 ${orderCode} 已被主系统删除(原因:${reason}),我方已停用该订单,无需再备货。`,
|
||||
relatedOrderCode: orderCode,
|
||||
branchCode,
|
||||
dedupWithinHours: 1,
|
||||
}).catch(() => undefined);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[main-system-reverse] 整单停用通知失败(不影响处理):', (error as Error)?.message || error);
|
||||
}
|
||||
return { status: (updated.rowCount || 0) > 0 ? 'cancelled' : 'already' };
|
||||
}
|
||||
|
||||
@@ -103,9 +103,35 @@ describe('待报价状态派生(deriveLocalStatus,唯一口径)', () => {
|
||||
expect(deriveLocalStatus({ ...base, roundStatus: 'cancelled', respondDeadline: past })).toBe('cancelled');
|
||||
});
|
||||
|
||||
it('轮次已定标 ⇒ 有中标行 won,没有 lost(即使已过截止)', () => {
|
||||
it('轮次已定标 ⇒ 有中标行 won;有明确落标事实 lost;两者都没有不得臆造未中标', () => {
|
||||
expect(deriveLocalStatus({ ...base, roundStatus: 'awarded', hasAward: true, respondDeadline: past })).toBe('won');
|
||||
// 2026-10-18 口径变更(开发者裁决 Q5):只有我方明确落标(award_status='lost')才显示「未中标」
|
||||
expect(
|
||||
deriveLocalStatus({ ...base, roundStatus: 'awarded', hasAward: false, hasLost: true, respondDeadline: past })
|
||||
).toBe('lost');
|
||||
// 明细已拉到(itemCount>0)⇒ 我方没中标行就是对方的定标事实 ⇒ 未中标
|
||||
expect(deriveLocalStatus({ ...base, roundStatus: 'awarded', hasAward: false, respondDeadline: past })).toBe('lost');
|
||||
// 明细还没拉到(itemCount=0)⇒ 不臆造未中标:报过价回落「已报价」,否则「待报价」
|
||||
expect(
|
||||
deriveLocalStatus({ ...base, itemCount: 0, roundStatus: 'awarded', hasAward: false, respondDeadline: past })
|
||||
).toBe('pending');
|
||||
expect(
|
||||
deriveLocalStatus({
|
||||
...base,
|
||||
itemCount: 0,
|
||||
quotedCount: 2,
|
||||
roundStatus: 'awarded',
|
||||
hasAward: false,
|
||||
respondDeadline: past,
|
||||
})
|
||||
).toBe('pending');
|
||||
});
|
||||
|
||||
it('报过价 ⇒ 已报价,即使已过截止(报价事实优先于截止时间)', () => {
|
||||
// 2026-10-18 口径变更(开发者裁决 Q4):过期不再吃掉「已报价」
|
||||
expect(deriveLocalStatus({ ...base, roundStatus: 'open', quotedCount: 2, respondDeadline: past })).toBe('quoted');
|
||||
// 未报过价、已过截止 ⇒ 仍是已截止
|
||||
expect(deriveLocalStatus({ ...base, roundStatus: 'open', quotedCount: 0, respondDeadline: past })).toBe('expired');
|
||||
});
|
||||
|
||||
it('截止已过 或 对方说 expired ⇒ expired', () => {
|
||||
@@ -148,8 +174,11 @@ describe('明细 DTO:中标行的判定', () => {
|
||||
...over,
|
||||
});
|
||||
|
||||
it('轮次已定标且我这行没中标价 ⇒ lost(不是我"还没报")', () => {
|
||||
expect(toBidInvitationItemDto(row({}) as any, 'awarded').awardStatus).toBe('lost');
|
||||
it('中标判定只认 award_status:award_price 单独不再判 won;已定标无中标行判 lost', () => {
|
||||
// 2026-10-18 口径变更(开发者裁决):award_price 非空可能只是回显报价,不据此判「已中标」
|
||||
expect(toBidInvitationItemDto(row({ award_price: '12.5' }) as any, 'awarded').awardStatus).toBe('lost');
|
||||
expect(toBidInvitationItemDto(row({ award_price: '12.5' }) as any, 'open').awardStatus).toBe(null);
|
||||
expect(toBidInvitationItemDto(row({ award_status: 'lost' }) as any, 'awarded').awardStatus).toBe('lost');
|
||||
});
|
||||
|
||||
it('有中标价 ⇒ won;轮次未定标 ⇒ null', () => {
|
||||
|
||||
@@ -578,11 +578,13 @@ describe('派生口径:优先级与时钟边界(deriveLocalStatus)', () =>
|
||||
const future = new Date(Date.now() + 3600_000);
|
||||
const past = new Date(Date.now() - 3600_000);
|
||||
|
||||
it('同一组输入只改一个维度:cancelled > awarded > expired > quoted > pending', () => {
|
||||
// 每一行都比下一行多满足一条"更权威"的规则 ⇒ 顺序错就会显示成下面那行
|
||||
it('同一组输入只改一个维度:cancelled > awarded > quoted > expired > pending', () => {
|
||||
// 2026-10-18 口径变更(开发者裁决 Q4):报价事实优先于截止时间 ⇒ quoted 排在 expired 之前
|
||||
expect(deriveLocalStatus({ ...base, roundStatus: 'cancelled', respondDeadline: past, mainInvitationStatus: 'quoted' })).toBe('cancelled');
|
||||
expect(deriveLocalStatus({ ...base, roundStatus: 'awarded', respondDeadline: past, mainInvitationStatus: 'quoted' })).toBe('lost');
|
||||
expect(deriveLocalStatus({ ...base, roundStatus: 'open', respondDeadline: past, mainInvitationStatus: 'quoted' })).toBe('expired');
|
||||
expect(deriveLocalStatus({ ...base, roundStatus: 'open', respondDeadline: past, mainInvitationStatus: 'quoted' })).toBe('quoted');
|
||||
// 未报过价才会落到 expired
|
||||
expect(deriveLocalStatus({ ...base, quotedCount: 0, roundStatus: 'open', respondDeadline: past })).toBe('expired');
|
||||
expect(deriveLocalStatus({ ...base, roundStatus: 'open', respondDeadline: future, mainInvitationStatus: 'quoted' })).toBe('quoted');
|
||||
expect(deriveLocalStatus({ ...base, quotedCount: 1, roundStatus: 'open', respondDeadline: future })).toBe('pending');
|
||||
});
|
||||
@@ -598,27 +600,38 @@ describe('派生口径:优先级与时钟边界(deriveLocalStatus)', () =>
|
||||
|
||||
it('时钟边界:恰好在截止时刻**不算**过期(严格小于),早 1ms 算过期', () => {
|
||||
const now = new Date('2026-10-17T02:30:00.000Z');
|
||||
// 未报价时看截止:边界内不过期、早 1ms 过期(2026-10-18 起:报过价的单不再被过期覆盖)
|
||||
const notQuoted = { ...base, quotedCount: 0 };
|
||||
expect(
|
||||
deriveLocalStatus({ ...base, roundStatus: 'open', respondDeadline: '2026-10-17T02:30:00.000Z', now })
|
||||
).toBe('quoted');
|
||||
deriveLocalStatus({ ...notQuoted, roundStatus: 'open', respondDeadline: '2026-10-17T02:30:00.000Z', now })
|
||||
).toBe('pending');
|
||||
expect(
|
||||
deriveLocalStatus({ ...base, roundStatus: 'open', respondDeadline: '2026-10-17T02:29:59.999Z', now })
|
||||
deriveLocalStatus({ ...notQuoted, roundStatus: 'open', respondDeadline: '2026-10-17T02:29:59.999Z', now })
|
||||
).toBe('expired');
|
||||
expect(
|
||||
deriveLocalStatus({ ...base, roundStatus: 'open', respondDeadline: '2026-10-17T02:30:00.001Z', now })
|
||||
deriveLocalStatus({ ...notQuoted, roundStatus: 'open', respondDeadline: '2026-10-17T02:30:00.001Z', now })
|
||||
).toBe('pending');
|
||||
// 已报价:无论是否过期都是「已报价」
|
||||
expect(
|
||||
deriveLocalStatus({ ...base, roundStatus: 'open', respondDeadline: '2026-10-17T02:29:59.999Z', now })
|
||||
).toBe('quoted');
|
||||
});
|
||||
|
||||
it('时区:+08:00 与等价的 Z 表示必须同结论(不能按字面比字符串)', () => {
|
||||
const now = new Date('2026-10-17T02:00:00.000Z');
|
||||
const notQuoted = { ...base, quotedCount: 0 };
|
||||
// 10:00+08:00 == 02:00Z ⇒ 与 now 相等,不过期
|
||||
expect(
|
||||
deriveLocalStatus({ ...base, roundStatus: 'open', respondDeadline: '2026-10-17T10:00:00+08:00', now })
|
||||
).toBe('quoted');
|
||||
deriveLocalStatus({ ...notQuoted, roundStatus: 'open', respondDeadline: '2026-10-17T10:00:00+08:00', now })
|
||||
).toBe('pending');
|
||||
// 09:59+08:00 == 01:59Z ⇒ 已过期
|
||||
expect(
|
||||
deriveLocalStatus({ ...base, roundStatus: 'open', respondDeadline: '2026-10-17T09:59:00+08:00', now })
|
||||
deriveLocalStatus({ ...notQuoted, roundStatus: 'open', respondDeadline: '2026-10-17T09:59:00+08:00', now })
|
||||
).toBe('expired');
|
||||
// 已报价时两种时区写法同一结论(都「已报价」,不做过期判定)
|
||||
expect(
|
||||
deriveLocalStatus({ ...base, roundStatus: 'open', respondDeadline: '2026-10-17T09:59:00+08:00', now })
|
||||
).toBe('quoted');
|
||||
});
|
||||
|
||||
it('明细还没拉过(itemCount=0 且无对方状态)⇒ pending,不凭空说"已报价"', () => {
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { resolveCompleteReceivedSettlementQty } from '../src/services/orderItemSupplyUnitSync';
|
||||
|
||||
/**
|
||||
* **待补录入库量必须按「实收」口径取数,不能被核货镜像的 `loaded_qty` 覆盖**
|
||||
* (2026-10-15 统一实收口径 `15622fb` 漏改本调用方,2026-10-15 对抗式复核发现)。
|
||||
*
|
||||
* 背景:核货「没人改实配」时,`deliveryLoadingService` 会把 `required_qty`(应拣量)原样
|
||||
* 镜像进 `loaded_qty` 作为"已核货"标记(`loaded_done` 承重)。`15622fb` 把
|
||||
* `resolveCompleteReceivedSettlementQty` 改为「只有 `loaded_qty ≠ required_qty` 才算真人实配」,
|
||||
* 并给函数加了第 5 参 `requiredQty`;但 `pendingBackfillQtyService.ensureBackfillInboundOnConfirm`
|
||||
* 仍只传 4 个实参 ⇒ `required` 被当作 0 ⇒ `loaded > 0` 恒判为"真人实配" ⇒ 非斤类返回
|
||||
* 镜像的 `loaded_qty`,把真实的 `picked_qty` 覆盖掉。
|
||||
*
|
||||
* 后果:待补录「确认入账」把入库实收写成计划量(镜像值),比真实实拣少,库存/采购成本账随之少记。
|
||||
*
|
||||
* 本文件钉住:① 纯函数在给出 `required_qty` 时不再把镜像当实收;② 该调用方确实传了第 5 参,
|
||||
* 用假 db 跑 `ensureBackfillInboundOnConfirm` 断言落库量。
|
||||
*/
|
||||
|
||||
const poolQuery = vi.hoisted(() => vi.fn());
|
||||
const submitInspectionCompliance = vi.hoisted(() => vi.fn());
|
||||
const findCompletedInboundQty = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock('../src/db', () => ({
|
||||
pool: { query: (...args: unknown[]) => poolQuery(...args), connect: vi.fn() },
|
||||
query: (...args: unknown[]) => poolQuery(...args),
|
||||
getRawPoolQuery: () => (...args: unknown[]) => poolQuery(...args),
|
||||
getRawPoolConnect: () => vi.fn(),
|
||||
isRlsRoleAvailable: async () => false,
|
||||
allowRlsFailOpen: () => true,
|
||||
}));
|
||||
|
||||
vi.mock('../src/services/inspectionInboundQtyAdjust', () => ({
|
||||
findCompletedInboundQty: (...args: unknown[]) => findCompletedInboundQty(...args),
|
||||
adjustInboundInspectionQty: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../src/services/inspectionComplianceService', () => ({
|
||||
submitInspectionCompliance: (...args: unknown[]) => submitInspectionCompliance(...args),
|
||||
reconcileOrderPurchaseFromLatestInspections: vi.fn(),
|
||||
}));
|
||||
|
||||
import { ensureBackfillInboundOnConfirm } from '../src/services/pendingBackfillQtyService';
|
||||
|
||||
/** 一行待补录明细:单位为「件」,实拣 7、核货镜像 loaded=required=5,无库存抵扣 */
|
||||
function fakeRow(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
sku_code: 'SKU1',
|
||||
unit: '件',
|
||||
uncovered_qty: 7,
|
||||
cover_qty: 0,
|
||||
picked_weight: 0,
|
||||
picked_qty: 7,
|
||||
loaded_qty: 5,
|
||||
required_qty: 5,
|
||||
pick_unit: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
poolQuery.mockReset();
|
||||
submitInspectionCompliance.mockReset();
|
||||
findCompletedInboundQty.mockReset();
|
||||
findCompletedInboundQty.mockResolvedValue(null);
|
||||
submitInspectionCompliance.mockResolvedValue(undefined);
|
||||
poolQuery.mockImplementation(async (sql: string) => {
|
||||
const text = String(sql);
|
||||
if (text.includes('AS uncovered_qty')) {
|
||||
return { rowCount: 1, rows: [fakeRow()] };
|
||||
}
|
||||
// hasUnresolvedFailedInspectionForSku:无不合格未入库
|
||||
if (text.includes("COALESCE(i.quality_rating, '') IN ('D', '不合格')")) {
|
||||
return { rowCount: 0, rows: [] };
|
||||
}
|
||||
// closeOrCreateInspectionForSku:命中「待验且未写实收」的既有验收单
|
||||
if (text.includes('actual_qty IS NULL') && text.includes('quality_rating IS NULL')) {
|
||||
return { rowCount: 1, rows: [{ id: 'INS1' }] };
|
||||
}
|
||||
return { rowCount: 0, rows: [] };
|
||||
});
|
||||
});
|
||||
|
||||
describe('待补录确认入账:实收口径', () => {
|
||||
it('纯函数:给出 required_qty(=loaded)⇒ 镜像是标记不是实收,取实拣数量', () => {
|
||||
expect(resolveCompleteReceivedSettlementQty(0, 5, '件', 7, 5)).toBe(7);
|
||||
// 配送员真改过(loaded ≠ required)才取实配
|
||||
expect(resolveCompleteReceivedSettlementQty(0, 5, '件', 7, 3)).toBe(5);
|
||||
});
|
||||
|
||||
it('ensureBackfillInboundOnConfirm 落库量取实拣 7(而非镜像 loaded 5)', async () => {
|
||||
await ensureBackfillInboundOnConfirm({ orderCode: 'ORD_BACKFILL_1' });
|
||||
|
||||
expect(submitInspectionCompliance).toHaveBeenCalledTimes(1);
|
||||
const call = submitInspectionCompliance.mock.calls[0][0] as { actual_qty: number };
|
||||
expect(call.actual_qty, '应按实拣 7 入账,镜像 loaded=5 不算实收').toBe(7);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,178 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { resolveProcessingPickReservationSplit } from '../src/services/processingPickReservationService';
|
||||
import { fifoDeductInventory } from '../src/services/inventoryOutboundService';
|
||||
|
||||
/** 缺口通知会走 DB;本文件只验扣库校验,桩掉避免连库 */
|
||||
vi.mock('../src/services/inventoryShortageNotificationService', () => ({
|
||||
notifyInventoryShortage: vi.fn(async () => undefined),
|
||||
}));
|
||||
|
||||
/**
|
||||
* **加工需求单领料:他单预留必须一次排除本单全部订单号**(2026-10-15 对抗式复核)。
|
||||
*
|
||||
* 事故形态(`29fbf49` 引入):`pickDemandSheetMaterial` / 改领料补扣 用
|
||||
* 「对每个本单订单号各调一次 `sumOtherOrderReservations` 再相加」估算他单预留。
|
||||
* 但 `sumOtherOrderReservations(…, orderCode)` 每次只排除**一个** order_code:
|
||||
* · 同一需求单含 A、B 两张订单(汇单键:分公司+配送日+成品 SKU+加工方式,常态);
|
||||
* · 他单预留 O、A 预留 3、B 预留 2;
|
||||
* · 旧写法 otherReserved = sumOther(A) + sumOther(B) = (O+2) + (O+3) = 2O+5;
|
||||
* · 正确 otherReserved = O ⇒ 他单预留被算 2 倍。O=0 时(本单自己预留 5、无他单)
|
||||
* 退化成 otherReserved=5 ⇒ claimable = 毛可用 − 5,把「本单预留挡自己」的死锁又带回来。
|
||||
*
|
||||
* 修复:`他单 = 全部在用预留 − 本单自己的在用预留`(一次成型),
|
||||
* 并复用 `ownReserved` 当领料前 `planned`,不多查一次。
|
||||
*/
|
||||
|
||||
const SRC = path.join(__dirname, '..', 'src');
|
||||
const read = (rel: string) => readFileSync(path.join(SRC, rel), 'utf8');
|
||||
|
||||
type Call = { sql: string; params?: unknown[] };
|
||||
|
||||
/** T=全部在用预留,own=本单自己的在用预留;其余按查询形状分流 */
|
||||
function makeDb(total: number, own: number, calls: Call[]) {
|
||||
return {
|
||||
query: async (sql: string, params?: unknown[]) => {
|
||||
const text = String(sql);
|
||||
calls.push({ sql: text, params });
|
||||
if (text.includes('order_code = ANY($2::text[])')) {
|
||||
return { rowCount: 1, rows: [{ total: own }] };
|
||||
}
|
||||
if (text.includes('FROM inventory_reservations')) {
|
||||
return { rowCount: 1, rows: [{ total }] };
|
||||
}
|
||||
return { rowCount: 0, rows: [] };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('① 预留切分:一次排除本单全部订单号', () => {
|
||||
it('A/B 两张本单订单、无他单预留 ⇒ 他单预留为 0(旧写法会算成 5 挡住自己)', async () => {
|
||||
const calls: Call[] = [];
|
||||
const split = await resolveProcessingPickReservationSplit(makeDb(5, 5, calls) as never, {
|
||||
orderCodes: ['ORD_A', 'ORD_B'],
|
||||
skuCode: 'SKU1',
|
||||
branchCode: 'BR002',
|
||||
});
|
||||
expect(split.ownReserved).toBe(5);
|
||||
expect(split.totalReserved).toBe(5);
|
||||
expect(split.otherReserved, '本单自己的预留不是他单预留').toBe(0);
|
||||
});
|
||||
|
||||
it('有他单预留 4 ⇒ 他单预留恰为他单那部分(不是 n 倍)', async () => {
|
||||
const calls: Call[] = [];
|
||||
const split = await resolveProcessingPickReservationSplit(makeDb(9, 5, calls) as never, {
|
||||
orderCodes: ['ORD_A', 'ORD_B'],
|
||||
skuCode: 'SKU1',
|
||||
branchCode: 'BR002',
|
||||
});
|
||||
expect(split.otherReserved).toBe(4);
|
||||
});
|
||||
|
||||
it('自采/独立加工(无本单订单号)⇒ 他单 = 全部在用预留', async () => {
|
||||
const calls: Call[] = [];
|
||||
const split = await resolveProcessingPickReservationSplit(makeDb(7, 0, calls) as never, {
|
||||
orderCodes: [],
|
||||
skuCode: 'SKU1',
|
||||
branchCode: 'BR002',
|
||||
});
|
||||
expect(split.otherReserved).toBe(7);
|
||||
// 无本单订单号 ⇒ 不查 own(省一次查询;own 查询的特征是 `order_code = ANY($2::text[])`)
|
||||
expect(calls.some((c) => c.sql.includes('order_code = ANY($2::text[])'))).toBe(false);
|
||||
});
|
||||
|
||||
it('只读:不产生任何写语句', async () => {
|
||||
const calls: Call[] = [];
|
||||
await resolveProcessingPickReservationSplit(makeDb(5, 5, calls) as never, {
|
||||
orderCodes: ['ORD_A', 'ORD_B'],
|
||||
skuCode: 'SKU1',
|
||||
branchCode: 'BR002',
|
||||
});
|
||||
expect(calls.some((c) => /INSERT|UPDATE|DELETE/i.test(c.sql))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('② 两个领料入口都改走统一切分(不再逐单号循环)', () => {
|
||||
for (const rel of [
|
||||
'services/processingDemandSheetService.ts',
|
||||
'services/processingDemandPickAmendService.ts',
|
||||
]) {
|
||||
it(`${rel}:无逐单号循环,改用 resolveProcessingPickReservationSplit`, () => {
|
||||
const src = read(rel);
|
||||
expect(src).toContain('resolveProcessingPickReservationSplit(');
|
||||
// 旧写法特征:`for (const code of ownOrderCodes` + `otherReserved +=`
|
||||
expect(src).not.toMatch(/for\s*\(\s*const\s+code\s+of\s+ownOrderCodes/);
|
||||
expect(src).not.toMatch(/otherReserved\s*\+=/);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 光修预校验还不够:真正扣库的 `fifoDeductInventory` 内部还会再算一次「毛可用 − 他单预留」。
|
||||
* 若只豁免 `ownOrderCodes[0]`,同一需求单里**其它本单订单**的预留会被当成"他单"挡住自己:
|
||||
* G=5、A 预留 3、B 预留 2、无他单、要领 5 ⇒ 内部只免 A ⇒ 可领 3 < 5 ⇒ 抛"库存不足"。
|
||||
* 修复:`reservationExemptOrderCodes` 一次豁免全部本单订单号。
|
||||
*/
|
||||
describe('③ FIFO 内部预留守卫一次豁免全部本单订单', () => {
|
||||
type Call = { sql: string; params?: unknown[] };
|
||||
|
||||
function makeFifoClient(gross: number, reservations: Array<{ order: string; qty: number }>, calls: Call[]) {
|
||||
return {
|
||||
query: async (sql: string, params?: unknown[]) => {
|
||||
const text = String(sql);
|
||||
calls.push({ sql: text, params });
|
||||
if (text.includes('SUM(available_qty)')) {
|
||||
return { rowCount: 1, rows: [{ total: gross }] };
|
||||
}
|
||||
if (text.includes('FROM inventory_reservations')) {
|
||||
const exclude = Array.isArray(params?.[2]) ? (params![2] as string[]) : [];
|
||||
const other = reservations
|
||||
.filter((r) => !exclude.includes(r.order))
|
||||
.reduce((sum, r) => sum + r.qty, 0);
|
||||
return { rowCount: 1, rows: [{ total: other }] };
|
||||
}
|
||||
if (text.includes('FOR UPDATE')) {
|
||||
return {
|
||||
rowCount: 1,
|
||||
rows: [
|
||||
{
|
||||
id: 'inv1',
|
||||
batch_no: 'B1',
|
||||
available_qty: gross,
|
||||
cost_price: 3,
|
||||
supplier_code: null,
|
||||
created_at: new Date(),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
if (text.startsWith('UPDATE inventory')) return { rowCount: 1, rows: [] };
|
||||
if (text.includes('INSERT INTO inventory_logs')) return { rowCount: 1, rows: [] };
|
||||
return { rowCount: 0, rows: [] };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
it('G=5、本单 A=3/B=2、无他单 ⇒ 领 5 必须放行(旧写法只免 A 会误报不足)', async () => {
|
||||
const calls: Call[] = [];
|
||||
const deducted: number[] = [];
|
||||
await expect(
|
||||
fifoDeductInventory(
|
||||
makeFifoClient(5, [{ order: 'ORD_A', qty: 3 }, { order: 'ORD_B', qty: 2 }], calls) as never,
|
||||
{
|
||||
skuCode: 'SKU1',
|
||||
qty: 5,
|
||||
branchCode: 'BR002',
|
||||
orderCode: 'ORD_A',
|
||||
reservationExemptOrderCodes: ['ORD_A', 'ORD_B'],
|
||||
pickCode: 'T1',
|
||||
operationType: 'processing_out',
|
||||
},
|
||||
(_b, q) => deducted.push(q)
|
||||
)
|
||||
).resolves.toBeUndefined();
|
||||
expect(deducted).toEqual([5]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
/**
|
||||
* **散客单「确认完成」的并发扣库必须串行化**(2026-10-15 对抗式复核)。
|
||||
*
|
||||
* 事故形态:`confirmRetailOrderComplete` 原先在事务里**不加锁**地读 `order_status`,
|
||||
* 再 `fifoDeductInventory` 逐行扣库,最后才由 `finalizeOrderFulfillmentCore` 重读状态。
|
||||
* 两笔并发(浏览器重试 / 双端同时点 / 脚本并发)各自读到 30 并通过「已全额抵扣」后:
|
||||
* · 先到者扣库、置 90、提交;
|
||||
* · 后到者阻塞在库存行 `FOR UPDATE` 上,提交后按 READ COMMITTED 重读 `available_qty`
|
||||
* 仍然够扣 ⇒ **再扣一遍**;之后才在状态守卫处读到 90 返回 false,但扣库已落库、不回滚。
|
||||
* ⇒ 同一张散客单被扣两次库,`inventory_logs` 多出一条 `retail_out`,账实差额永久存在。
|
||||
*
|
||||
* 修复:把 `order_status` 的读取改成 `FOR UPDATE`,以订单行为串行化点。后到者阻塞到
|
||||
* 先到者提交后,重读即命中 `>= 90` 守卫(`already_completed`),不会再扣库。
|
||||
*
|
||||
* 本文件钉住:① 订单状态读取必须带 `FOR UPDATE`;② 该锁必须在 `fifoDeductInventory` 之前。
|
||||
* 与 `inventoryOutboundConcurrency.test.ts`(同类事故、同类修法)同构。
|
||||
*/
|
||||
|
||||
type QueryResult = { rowCount: number | null; rows: any[] };
|
||||
|
||||
const state = {
|
||||
sqls: [] as string[],
|
||||
lockTaken: false,
|
||||
fifoSawLock: false,
|
||||
/** 当前状态读取要返回的 order_status(用于模拟"后到者读到 90") */
|
||||
orderStatus: 30,
|
||||
client: undefined as { query: (sql: string) => Promise<QueryResult>; release: () => void } | undefined,
|
||||
};
|
||||
|
||||
const fifoDeductInventory = vi.hoisted(() => vi.fn());
|
||||
const completeOrderWithoutDriverDelivery = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock('../src/db', () => ({
|
||||
pool: { query: vi.fn(), connect: vi.fn() },
|
||||
getRawPoolQuery: () => vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../src/services/tenantSchemaService', () => ({
|
||||
runWithTenantDataAccess: async (_branch: string, fn: (c: unknown) => Promise<unknown>) =>
|
||||
fn(state.client),
|
||||
}));
|
||||
|
||||
vi.mock('../src/services/retailOrder', () => ({
|
||||
RETAIL_CUSTOMER_CODE: '__RETAIL__',
|
||||
RETAIL_CUSTOMER_NAME: '散客录单',
|
||||
isRetailCustomer: (code?: string | null) => String(code || '').trim() === '__RETAIL__',
|
||||
isRetailOrder: async () => true,
|
||||
ensureRetailCustomer: async () => undefined,
|
||||
}));
|
||||
|
||||
vi.mock('../src/services/inventoryOutboundService', () => ({
|
||||
fifoDeductInventory: (...args: unknown[]) => {
|
||||
state.fifoSawLock = state.lockTaken;
|
||||
return fifoDeductInventory(...args);
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../src/services/orderWorkflowFulfillmentService', () => ({
|
||||
completeOrderWithoutDriverDelivery: (...args: unknown[]) =>
|
||||
completeOrderWithoutDriverDelivery(...args),
|
||||
}));
|
||||
|
||||
vi.mock('../src/services/customerOrderSubmitService', () => ({
|
||||
submitMobileCustomerOrder: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../src/services/inventoryStockCoverService', () => ({
|
||||
applyStockCoverForOrder: vi.fn(),
|
||||
resolveCoverableQtyForSku: vi.fn(async () => 0),
|
||||
}));
|
||||
|
||||
import { confirmRetailOrderComplete } from '../src/services/retailOrderService';
|
||||
|
||||
function makeClient() {
|
||||
const query = async (sql: string): Promise<QueryResult> => {
|
||||
const text = String(sql);
|
||||
state.sqls.push(text);
|
||||
if (text.includes('FROM orders WHERE order_code = $1 FOR UPDATE')) {
|
||||
state.lockTaken = true;
|
||||
return {
|
||||
rowCount: 1,
|
||||
rows: [{ order_status: state.orderStatus, customer_code: '__RETAIL__' }],
|
||||
};
|
||||
}
|
||||
if (text.includes('customer_code FROM orders WHERE order_code = $1')) {
|
||||
// 修复前:无 `FOR UPDATE` 的状态读取(测试应在此版本失败)
|
||||
return {
|
||||
rowCount: 1,
|
||||
rows: [{ order_status: state.orderStatus, customer_code: '__RETAIL__' }],
|
||||
};
|
||||
}
|
||||
// 未全额抵扣校验:无缺口
|
||||
if (text.includes('COALESCE(stock_cover_qty, 0) + 1e-9 < COALESCE(quantity, 0)')) {
|
||||
return { rowCount: 0, rows: [] };
|
||||
}
|
||||
// 待出库明细行
|
||||
if (text.includes('COALESCE(stock_cover_qty, 0)::text AS cover')) {
|
||||
return { rowCount: 1, rows: [{ sku_code: 'SKU1', item_name: '牛奶', cover: '5' }] };
|
||||
}
|
||||
if (text.includes('SELECT DISTINCT operation_type FROM inventory_logs')) {
|
||||
return { rowCount: 1, rows: [{ operation_type: 'retail_out' }] };
|
||||
}
|
||||
if (text.includes('SELECT order_status FROM orders WHERE order_code = $1')) {
|
||||
return { rowCount: 1, rows: [{ order_status: 90 }] };
|
||||
}
|
||||
return { rowCount: 0, rows: [] };
|
||||
};
|
||||
return { query, release: () => undefined };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
state.sqls = [];
|
||||
state.lockTaken = false;
|
||||
state.fifoSawLock = false;
|
||||
state.orderStatus = 30;
|
||||
state.client = makeClient();
|
||||
fifoDeductInventory.mockReset();
|
||||
fifoDeductInventory.mockResolvedValue(undefined);
|
||||
completeOrderWithoutDriverDelivery.mockReset();
|
||||
completeOrderWithoutDriverDelivery.mockResolvedValue(true);
|
||||
});
|
||||
|
||||
describe('散客单并发确认完成:订单行 FOR UPDATE 串行化', () => {
|
||||
it('订单状态读取必须带 FOR UPDATE,否则后到者会再扣一遍库存', async () => {
|
||||
await confirmRetailOrderComplete('ORD_RETAIL_1', 'BR002');
|
||||
const lockIdx = state.sqls.findIndex((s) =>
|
||||
s.includes('FROM orders WHERE order_code = $1 FOR UPDATE')
|
||||
);
|
||||
expect(lockIdx, '必须对订单行取 FOR UPDATE 独占锁').toBeGreaterThan(-1);
|
||||
});
|
||||
|
||||
it('锁必须发生在 fifoDeductInventory 扣库之前', async () => {
|
||||
await confirmRetailOrderComplete('ORD_RETAIL_1', 'BR002');
|
||||
expect(fifoDeductInventory).toHaveBeenCalledTimes(1);
|
||||
expect(state.fifoSawLock, '扣库时订单行锁必须已持有').toBe(true);
|
||||
});
|
||||
|
||||
it('拿锁后读到 >= 90(并发后到者)⇒ 抛 already_completed 且完全不扣库', async () => {
|
||||
state.orderStatus = 90;
|
||||
await expect(confirmRetailOrderComplete('ORD_RETAIL_1', 'BR002')).rejects.toMatchObject({
|
||||
code: 'already_completed',
|
||||
status: 409,
|
||||
});
|
||||
expect(fifoDeductInventory).not.toHaveBeenCalled();
|
||||
expect(completeOrderWithoutDriverDelivery).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -221,5 +221,11 @@ export const bids: MessageDict = {
|
||||
'invite.btnRefresh': 'Refresh',
|
||||
'invite.toastSubmitted': 'Quotes submitted',
|
||||
'invite.deadlinePassed': 'Past the quote deadline',
|
||||
'invite.actDelete': 'Delete',
|
||||
'invite.deleteTitle': 'Delete this bid invitation?',
|
||||
'invite.deleteDesc': 'Hidden only in your ledger; the main system is not affected. You can restore it under "Show deleted".',
|
||||
'invite.deletedToast': 'Deleted (restore under "Show deleted")',
|
||||
'invite.actRestore': 'Restore',
|
||||
'invite.showDeleted': 'Show deleted',
|
||||
'invite.empty': 'No bid requests',
|
||||
};
|
||||
|
||||
@@ -225,5 +225,11 @@ export const bids: MessageDict = {
|
||||
'invite.btnRefresh': 'Segarkan',
|
||||
'invite.toastSubmitted': 'Penawaran terkirim',
|
||||
'invite.deadlinePassed': 'Melewati batas waktu',
|
||||
'invite.actDelete': 'Hapus',
|
||||
'invite.deleteTitle': 'Hapus undangan penawaran ini?',
|
||||
'invite.deleteDesc': 'Hanya disembunyikan di buku besar Anda; sistem utama tidak terpengaruh. Dapat dipulihkan di "Tampilkan yang dihapus".',
|
||||
'invite.deletedToast': 'Dihapus (pulihkan di "Tampilkan yang dihapus")',
|
||||
'invite.actRestore': 'Pulihkan',
|
||||
'invite.showDeleted': 'Tampilkan yang dihapus',
|
||||
'invite.empty': 'Belum ada permintaan penawaran',
|
||||
};
|
||||
|
||||
@@ -213,5 +213,11 @@ export const bids: MessageDict = {
|
||||
'invite.btnRefresh': '刷新',
|
||||
'invite.toastSubmitted': '报价已提交',
|
||||
'invite.deadlinePassed': '已超过报价截止时间',
|
||||
'invite.actDelete': '删除',
|
||||
'invite.deleteTitle': '删除这条竞价邀约?',
|
||||
'invite.deleteDesc': '仅在你方台账隐藏,不影响主系统;后续可在「显示已删除」里恢复。',
|
||||
'invite.deletedToast': '已删除(可在「显示已删除」里恢复)',
|
||||
'invite.actRestore': '恢复',
|
||||
'invite.showDeleted': '显示已删除',
|
||||
'invite.empty': '暂无待报价的竞价单',
|
||||
};
|
||||
|
||||
@@ -11,6 +11,15 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
* ④ 已截止 / 已中标 ⇒ 输入只读、保存按钮禁用(并给一句原因)。
|
||||
*/
|
||||
|
||||
// 页面会用管理员身份决定「删除」按钮是否出现;测试里默认给管理员
|
||||
vi.mock('../../hooks/useAuth', () => ({
|
||||
useAuth: () => ({
|
||||
profile: { id: 'u-test', username: 'admin' },
|
||||
hasRole: () => true,
|
||||
hasPermission: () => true,
|
||||
}),
|
||||
}));
|
||||
|
||||
const DEADLINE = '2026-12-31T10:00:00+08:00';
|
||||
|
||||
const PENDING_ROW = {
|
||||
|
||||
@@ -6,11 +6,15 @@ import { Modal } from '../../components/ui/Modal';
|
||||
import { ListState, PageHeader } from '../../components/ui/PagePrimitives';
|
||||
import { TablePaginationBar } from '../../components/ui/TablePaginationBar';
|
||||
import { notify } from '../../utils/notify';
|
||||
import { confirmDialog } from '../../utils/confirmDialog';
|
||||
import { useAuth } from '../../hooks/useAuth';
|
||||
import { useI18n } from '../../i18n/I18nProvider';
|
||||
import { UI_LOCALE_BCP47, type UiLocale } from '../../i18n/config';
|
||||
import {
|
||||
deleteMainSystemBidInvitationApi,
|
||||
getMainSystemBidInvitationApi,
|
||||
listMainSystemBidInvitationsApi,
|
||||
restoreMainSystemBidInvitationApi,
|
||||
submitMainSystemBidQuotesApi,
|
||||
syncMainSystemBidInvitationsApi,
|
||||
type BidInvitationDetailDto,
|
||||
@@ -86,6 +90,11 @@ function formatUnitPrice(value: number | null | undefined, locale: UiLocale): st
|
||||
export function BidInvitationsPage() {
|
||||
const { t, locale } = useI18n();
|
||||
|
||||
const { hasRole } = useAuth();
|
||||
const isAdmin = hasRole(['admin', 'super_admin']);
|
||||
const [showDeleted, setShowDeleted] = useState(false);
|
||||
/** 正在删除/恢复的行(`roundId::supplierCode`),用于行内在途锁 */
|
||||
const [mutatingKey, setMutatingKey] = useState<string | null>(null);
|
||||
const [rows, setRows] = useState<BidInvitationDto[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
@@ -111,7 +120,11 @@ export function BidInvitationsPage() {
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const result = await listMainSystemBidInvitationsApi({ status: 'all', limit: LIST_LIMIT });
|
||||
const result = await listMainSystemBidInvitationsApi({
|
||||
status: 'all',
|
||||
limit: LIST_LIMIT,
|
||||
includeDeleted: showDeleted,
|
||||
});
|
||||
setRows(Array.isArray(result?.data) ? result.data : []);
|
||||
setLoadError(null);
|
||||
} catch (error: any) {
|
||||
@@ -120,7 +133,7 @@ export function BidInvitationsPage() {
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [t]);
|
||||
}, [t, showDeleted]);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
@@ -137,6 +150,50 @@ export function BidInvitationsPage() {
|
||||
);
|
||||
}, []);
|
||||
|
||||
/** 可删除的状态:只有「待报价 / 已截止」(与后端校验一致) */
|
||||
const DELETABLE_LOCAL_STATUSES: readonly BidLocalStatus[] = ['pending', 'expired'];
|
||||
|
||||
const handleDelete = useCallback(
|
||||
async (row: BidInvitationDto) => {
|
||||
const ok = await confirmDialog({
|
||||
title: t('bids.invite.deleteTitle'),
|
||||
message: t('bids.invite.deleteDesc'),
|
||||
danger: true,
|
||||
});
|
||||
if (!ok) return;
|
||||
const key = `${row.roundId}::${row.supplierCode}`;
|
||||
setMutatingKey(key);
|
||||
try {
|
||||
await deleteMainSystemBidInvitationApi(row.roundId, row.supplierCode);
|
||||
setRows((prev) => prev.filter((r) => !(r.roundId === row.roundId && r.supplierCode === row.supplierCode)));
|
||||
if (activeRoundId === row.roundId) setActiveRoundId(null);
|
||||
notify.success(t('bids.invite.deletedToast'));
|
||||
} catch (error: any) {
|
||||
notify.error(error?.message || t('bids.invite.empty'));
|
||||
} finally {
|
||||
setMutatingKey(null);
|
||||
}
|
||||
},
|
||||
[activeRoundId, t]
|
||||
);
|
||||
|
||||
const handleRestore = useCallback(
|
||||
async (row: BidInvitationDto) => {
|
||||
const key = `${row.roundId}::${row.supplierCode}`;
|
||||
setMutatingKey(key);
|
||||
try {
|
||||
await restoreMainSystemBidInvitationApi(row.roundId, row.supplierCode);
|
||||
await load();
|
||||
notify.success(t('bids.invite.actRestore'));
|
||||
} catch (error: any) {
|
||||
notify.error(error?.message || t('bids.invite.empty'));
|
||||
} finally {
|
||||
setMutatingKey(null);
|
||||
}
|
||||
},
|
||||
[load, t]
|
||||
);
|
||||
|
||||
const buildDrafts = (items: BidInvitationItemDto[]): Record<string, BidDraft> => {
|
||||
const next: Record<string, BidDraft> = {};
|
||||
for (const item of items) {
|
||||
@@ -300,6 +357,20 @@ export function BidInvitationsPage() {
|
||||
}
|
||||
actions={
|
||||
<>
|
||||
{isAdmin ? (
|
||||
<label className="inline-flex items-center gap-1.5 text-xs app-foreground-muted mr-1">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={showDeleted}
|
||||
disabled={loading}
|
||||
onChange={(event) => {
|
||||
setShowDeleted(event.target.checked);
|
||||
setPage(1);
|
||||
}}
|
||||
/>
|
||||
{t('bids.invite.showDeleted')}
|
||||
</label>
|
||||
) : null}
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
@@ -392,6 +463,26 @@ export function BidInvitationsPage() {
|
||||
>
|
||||
{viewOnly ? t('bids.invite.actView') : t('bids.invite.actQuote')}
|
||||
</button>
|
||||
{isAdmin && row.deletedAt ? (
|
||||
<button
|
||||
type="button"
|
||||
className="app-button-secondary app-border px-3 py-1 rounded-lg text-xs ml-1.5"
|
||||
disabled={mutatingKey === `${row.roundId}::${row.supplierCode}`}
|
||||
onClick={() => void handleRestore(row)}
|
||||
>
|
||||
{t('bids.invite.actRestore')}
|
||||
</button>
|
||||
) : null}
|
||||
{isAdmin && !row.deletedAt && DELETABLE_LOCAL_STATUSES.includes(row.localStatus) ? (
|
||||
<button
|
||||
type="button"
|
||||
className="app-button-secondary app-border px-3 py-1 rounded-lg text-xs ml-1.5 app-status-danger"
|
||||
disabled={mutatingKey === `${row.roundId}::${row.supplierCode}`}
|
||||
onClick={() => void handleDelete(row)}
|
||||
>
|
||||
{t('bids.invite.actDelete')}
|
||||
</button>
|
||||
) : null}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
// @vitest-environment jsdom
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('../lib/apiConfig', () => ({
|
||||
buildApiUrl: (path: string) => path,
|
||||
}));
|
||||
|
||||
import {
|
||||
approveQuotePriceProposalApi,
|
||||
listQuotePriceProposalsApi,
|
||||
rejectQuotePriceProposalApi,
|
||||
submitQuotePriceProposalApi,
|
||||
} from './workflowApi';
|
||||
|
||||
/**
|
||||
* 报价单**双向价格传递** 4 个 API 的错误透传契约(2026-10-18 verifier UX 缺陷)。
|
||||
*
|
||||
* 根因:开关 `MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL` 关闭时后端 503 `feature_disabled`,
|
||||
* 而 `workflowFetch` 默认把 502/503 统一映射成「保存超时,服务器可能仍在处理,请勿重复点击」⇒
|
||||
* 用户在「提交配送商审核」按钮上只看到"点了没反应"。4 个 API 都必须 `preserveErrorBody: true`。
|
||||
*/
|
||||
|
||||
const DISABLED_BODY = {
|
||||
error: 'feature_disabled',
|
||||
error_description: '报价单价格传递未开启(MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL)',
|
||||
};
|
||||
|
||||
function mockFetchOnce(status: number, body: unknown) {
|
||||
const fetchMock = vi.fn(async () => ({
|
||||
ok: status >= 200 && status < 300,
|
||||
status,
|
||||
json: async () => body,
|
||||
}));
|
||||
vi.stubGlobal('fetch', fetchMock as unknown as typeof fetch);
|
||||
return fetchMock;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe('价格提议 API 错误透传(preserveErrorBody)', () => {
|
||||
it('503 feature_disabled ⇒ 抛后端原文(不是"保存超时"),并带 status/code', async () => {
|
||||
mockFetchOnce(503, DISABLED_BODY);
|
||||
await expect(submitQuotePriceProposalApi('QS1')).rejects.toMatchObject({
|
||||
message: DISABLED_BODY.error_description,
|
||||
status: 503,
|
||||
code: 'feature_disabled',
|
||||
});
|
||||
// 明确排除被吞成网关兜底文案
|
||||
await expect(submitQuotePriceProposalApi('QS1')).rejects.not.toThrow(/保存超时/);
|
||||
});
|
||||
|
||||
it('列表 / 通过 / 驳回 三个 API 同样透传 503 原文', async () => {
|
||||
for (const call of [
|
||||
() => listQuotePriceProposalsApi({ status: 'pending', refresh: true }),
|
||||
() => approveQuotePriceProposalApi('11111111-1111-4111-8111-111111111111'),
|
||||
() => rejectQuotePriceProposalApi('11111111-1111-4111-8111-111111111111', '成本谈不拢'),
|
||||
]) {
|
||||
mockFetchOnce(503, DISABLED_BODY);
|
||||
await expect(call()).rejects.toMatchObject({
|
||||
message: DISABLED_BODY.error_description,
|
||||
status: 503,
|
||||
code: 'feature_disabled',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it('409 业务拒绝(如 internal_review_pending / proposal_not_pending)⇒ 原文透传', async () => {
|
||||
mockFetchOnce(409, {
|
||||
error: 'internal_review_pending',
|
||||
error_description: '该报价单还有未完成的内部改价审核,请先审完再提交配送商审核',
|
||||
});
|
||||
await expect(submitQuotePriceProposalApi('QS1')).rejects.toMatchObject({
|
||||
message: '该报价单还有未完成的内部改价审核,请先审完再提交配送商审核',
|
||||
status: 409,
|
||||
code: 'internal_review_pending',
|
||||
});
|
||||
|
||||
mockFetchOnce(409, {
|
||||
error: 'proposal_not_pending',
|
||||
error_description: '该提议在配送侧已被新的提议替代,不能按旧价审批,请刷新列表',
|
||||
});
|
||||
await expect(
|
||||
approveQuotePriceProposalApi('11111111-1111-4111-8111-111111111111')
|
||||
).rejects.toMatchObject({
|
||||
message: '该提议在配送侧已被新的提议替代,不能按旧价审批,请刷新列表',
|
||||
status: 409,
|
||||
code: 'proposal_not_pending',
|
||||
});
|
||||
});
|
||||
|
||||
it('502 主系统未就绪也保留后端原文(不再套"保存超时")', async () => {
|
||||
mockFetchOnce(502, { error: 'main_system_error', error_description: '主系统不可用' });
|
||||
await expect(submitQuotePriceProposalApi('QS1')).rejects.toMatchObject({
|
||||
message: '主系统不可用',
|
||||
status: 502,
|
||||
code: 'main_system_error',
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user