From 3e4bc35b26177197512ecb719f7f3a23f65c101d Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Sun, 18 Oct 2026 20:10:58 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E6=8A=A5=E4=BB=B7=E5=8D=95):=20=E5=8F=8C?= =?UTF-8?q?=E5=90=91=E4=BB=B7=E6=A0=BC=E4=BC=A0=E9=80=92/=E6=94=B9?= =?UTF-8?q?=E4=BB=B7=E5=AE=A1=E6=A0=B8/SKU=20=E6=98=A0=E5=B0=84/=E6=88=90?= =?UTF-8?q?=E6=9C=AC=E5=90=8C=E6=AD=A5=E6=8E=A8=E9=80=81=EF=BC=88=E4=BE=9B?= =?UTF-8?q?=E5=BA=94=E5=95=86=E4=BE=A7=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 报价单生效自动推销售价 → 配送成本价(台账+重试+rearm,映射优先) - 编辑生效单改价走内部审核(quote_sheet_change_requests) - 双向价格传递:A 提交配送商审核 / B 拉回并反查映射后写价、D3 回执 - SKU 映射:D4 字典推送、D5 完整拉取(截断不删)、只读本地副本 - 迁移登记 tenant_business_tables(三张租户表数组互相补齐,避免顺序敏感) --- docs/design/README.md | 4 + docs/manual/02-环境要求与安装部署.md | 6 + ...20261018_main_system_quote_cost_pushes.sql | 93 ++ .../20261018_main_system_sku_mappings.sql | 230 +++ migrations/20261018_quote_price_proposals.sql | 266 +++ .../20261018_quote_sheet_change_requests.sql | 241 +++ server/.env.example | 23 + .../modules/workflow/routes/quoteRoutes.ts | 308 +++- .../services/mainSystem/api/quoteCostSync.ts | 228 +++ .../services/mainSystem/api/skuMappings.ts | 277 ++++ server/src/services/mainSystem/config.ts | 22 + server/src/services/mainSystem/endpoints.ts | 28 + server/src/services/mainSystem/index.ts | 12 + .../src/services/mainSystemQuoteCostSync.ts | 964 +++++++++++ .../src/services/quotePriceProposalService.ts | 1397 ++++++++++++++++ .../quoteSheetChangeRequestService.ts | 858 ++++++++++ server/src/services/quoteSheetService.ts | 101 +- server/src/services/scheduledJobs.ts | 77 + server/src/services/skuMappingService.ts | 492 ++++++ server/tests/mainSystemQuoteCostSync.test.ts | 1022 ++++++++++++ .../tests/mainSystemQuoteCostSyncApi.test.ts | 215 +++ ...nSystemQuoteCostSyncDb.integration.test.ts | 118 ++ server/tests/quotePriceProposal.test.ts | 1459 +++++++++++++++++ .../quotePriceProposalDb.integration.test.ts | 288 ++++ ...tePriceProposalMergeDb.integration.test.ts | 488 ++++++ server/tests/quotePriceProposalRoute.test.ts | 301 ++++ server/tests/quoteSheetChangeRequest.test.ts | 999 +++++++++++ ...teSheetChangeRequestDb.integration.test.ts | 341 ++++ .../tests/quoteSheetCostSyncTrigger.test.ts | 282 ++++ server/tests/quoteSheetUpdateApply.test.ts | 290 ++++ server/tests/skuMapping.test.ts | 491 ++++++ server/tests/skuMappingDb.integration.test.ts | 134 ++ src/i18n/locales/en/quotes.ts | 65 + src/i18n/locales/id/quotes.ts | 65 + src/i18n/locales/zh-CN/quotes.ts | 65 + .../QuoteChangeRequestsPanel.test.tsx | 186 +++ .../customers/QuoteChangeRequestsPanel.tsx | 250 +++ .../QuoteDeliveryPriceProposalsPanel.test.tsx | 188 +++ .../QuoteDeliveryPriceProposalsPanel.tsx | 277 ++++ .../customers/QuoteSkuMappingsPanel.test.tsx | 133 ++ src/pages/customers/QuoteSkuMappingsPanel.tsx | 169 ++ ...nManagement.changeRequest.contract.test.ts | 53 + ...nManagement.priceProposal.contract.test.ts | 71 + .../customers/QuoteVersionManagement.tsx | 183 ++- src/utils/workflowApi.ts | 277 +++- 45 files changed, 13996 insertions(+), 41 deletions(-) create mode 100644 migrations/20261018_main_system_quote_cost_pushes.sql create mode 100644 migrations/20261018_main_system_sku_mappings.sql create mode 100644 migrations/20261018_quote_price_proposals.sql create mode 100644 migrations/20261018_quote_sheet_change_requests.sql create mode 100644 server/src/services/mainSystem/api/quoteCostSync.ts create mode 100644 server/src/services/mainSystem/api/skuMappings.ts create mode 100644 server/src/services/mainSystemQuoteCostSync.ts create mode 100644 server/src/services/quotePriceProposalService.ts create mode 100644 server/src/services/quoteSheetChangeRequestService.ts create mode 100644 server/src/services/skuMappingService.ts create mode 100644 server/tests/mainSystemQuoteCostSync.test.ts create mode 100644 server/tests/mainSystemQuoteCostSyncApi.test.ts create mode 100644 server/tests/mainSystemQuoteCostSyncDb.integration.test.ts create mode 100644 server/tests/quotePriceProposal.test.ts create mode 100644 server/tests/quotePriceProposalDb.integration.test.ts create mode 100644 server/tests/quotePriceProposalMergeDb.integration.test.ts create mode 100644 server/tests/quotePriceProposalRoute.test.ts create mode 100644 server/tests/quoteSheetChangeRequest.test.ts create mode 100644 server/tests/quoteSheetChangeRequestDb.integration.test.ts create mode 100644 server/tests/quoteSheetCostSyncTrigger.test.ts create mode 100644 server/tests/quoteSheetUpdateApply.test.ts create mode 100644 server/tests/skuMapping.test.ts create mode 100644 server/tests/skuMappingDb.integration.test.ts create mode 100644 src/pages/customers/QuoteChangeRequestsPanel.test.tsx create mode 100644 src/pages/customers/QuoteChangeRequestsPanel.tsx create mode 100644 src/pages/customers/QuoteDeliveryPriceProposalsPanel.test.tsx create mode 100644 src/pages/customers/QuoteDeliveryPriceProposalsPanel.tsx create mode 100644 src/pages/customers/QuoteSkuMappingsPanel.test.tsx create mode 100644 src/pages/customers/QuoteSkuMappingsPanel.tsx create mode 100644 src/pages/customers/QuoteVersionManagement.changeRequest.contract.test.ts create mode 100644 src/pages/customers/QuoteVersionManagement.priceProposal.contract.test.ts diff --git a/docs/design/README.md b/docs/design/README.md index 132032a..374f74f 100644 --- a/docs/design/README.md +++ b/docs/design/README.md @@ -70,6 +70,10 @@ AI 提示词清理已停用条目(7 条归档不删、清单过滤 archived、 分拣出库**拍照留证**(分拣员点「完成分拣」时**可选**拍照,**商品级**、每商品行若干张挂 `picking_items.outbound_photos`、与发车核货补拍**独立**、不记批次;本期不调 AI)见 [20261103-分拣出库拍照留证.md](./20261103-分拣出库拍照留证.md)。 主系统商品名对不上导致**库存抵扣扣不上**(“新鲜海带丝”vs“海带丝”):根因在导入「名字→SKU」步(名字不匹配就 `create_product` 新建无库存档案);方案=主系统订单详情里**手动选“抵扣库存商品”并记忆映射**,下次自动命中(开放问题:映射键/复用 `customer_sku_aliases`/候选来源)见 [20261104-主系统商品名映射与手动选抵扣库存.md](./20261104-主系统商品名映射与手动选抵扣库存.md)。 新增拣货模式**「按区域」**(订单内按商品区域拆拣货单,区域取**批次实际区优先→商品默认区**;区域顺序在 Web 手动设置并决定任务列表先后;默认改为 zone、已配置分公司不动;Web 补区域分组)见 [20261105-分拣按区域模式与区域顺序.md](./20261105-分拣按区域模式与区域顺序.md)。 +主系统**报价单成本价同步**(推送端):我方报价单**审批生效后**把 `MAIN_<主系统分公司>` 客户的销售价推到主系统报价单成本价(合同冻结 2026-10-18;一张单 × 一个主系统分公司只推一次、失败复用同一 `client_request_id` 重试、`forbidden` 不重试、开关 `MAIN_SYSTEM_QUOTE_COST_SYNC` 默认关;不改我方任何报价/成本口径、不刷历史版本、不碰订单)见 [20261018-报价单成本价同步推送.md](./20261018-报价单成本价同步推送.md)。 +编辑**生效中**报价单的价格相关改动改为**待审**:`PUT /quote/sheets/:code` 按「是否价格相关」分流(价格相关不落单、只写一条 `pending` 变更单,`applied:false`;非价格仍直接保存);`GET/POST /quote/change-requests` 列表 + 通过/驳回(审批仅 `customer_manage`,驳回必填理由);**通过后单事务应用并走既有 rearm 重推成本价**(绝不走 `approveQuoteSheet`/`activateQuoteSheet`,不动审批字段、不置其它共享单为 3);`base_items_fingerprint` 判目标单已变 ⇒ 整单拒绝;开关 `QUOTE_EDIT_APPROVAL` 默认开、置 0 回滚为直接保存见 [20261018-报价单改价审核与成本同步.md](./20261018-报价单改价审核与成本同步.md)。 +报价单**双向价格传递**(2026-10-18):A 我方把整单销售价交配送商审(D1,不写价);B 配送商发起的成本价提议经 D2 拉回、我方审——通过时**按行 UPDATE** 只改被提出的 SKU 的 `sale_price`(T3,绝不整表替换),再走**既有**成本价同步通道 rearm 推对方 `cost_price`(T8 回执失败由下轮 D2 补发);目标单按 `MAIN_<主系统分公司>` 唯一解析(T2);同一方向重复提交覆盖旧 pending(T6 `superseded`);D2 用 `next_cursor` 增量(T10);开关 `MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL` 默认关见 [20261018-报价单双向价格传递与审批.md](./20261018-报价单双向价格传递与审批.md)。 +**SKU 映射**(2026-10-18 第四增量):两个系统 SKU 不一致 ⇒ 映射由配送侧维护、供应商侧**只读同步**(tenant 表 `main_system_sku_mappings`,D4 推商品字典 / D5 拉映射,见 [20261018-SKU映射与成本传递.md](./20261018-SKU映射与成本传递.md));方向 B 审批先按配送 SKU 反查我方 SKU,未映射 skip `sku_unmapped`(不按名称猜),写价仍按行 UPDATE;提交前给「本单 N 个商品,已映射 X / 未映射 Y」。 订单**配送地址「我方为准」**:列表「订单信息」格原来的 `cycle_code`(主系统派单恒显示 `MOBILE`)改为展示**配送地址**,主系统分配单**未发车(<60)**可**就地改**;改完置 `orders.delivery_address_overridden`、同步 `customers.address`、重新地理编码并重排该骑手未完成站点(骑手端实时读同一列,无需推送)见 [20261013-订单配送地址我方为准.md](./20261013-订单配送地址我方为准.md)。 订单列表「库存抵扣:…」点开看**已抵扣批次明细**(批次号 / 抵扣数量 / **几号入库** / 生产日期 / 保质期效期 / 区域):批次事实取 `picking_items.outbound_batches`,无计划时按先进先出现算(`source=plan|fifo`,只读)见 [20261013-订单抵扣批次明细.md](./20261013-订单抵扣批次明细.md)。 验收照片复核**新增「出库照片」Tab**:只读展示分拣出库时逐商品行拍的照片(`picking_items.outbound_photos`),与「配送补拍」独立、不排除加菜行、无删除/复核动作、**无迁移**见 [20261013-验收照片复核新增出库照片.md](./20261013-验收照片复核新增出库照片.md)。 diff --git a/docs/manual/02-环境要求与安装部署.md b/docs/manual/02-环境要求与安装部署.md index beb7143..fe6f18f 100644 --- a/docs/manual/02-环境要求与安装部署.md +++ b/docs/manual/02-环境要求与安装部署.md @@ -444,12 +444,18 @@ docker compose -f docker-compose.prod.yml --env-file .env.production up -d --bui | `MAIN_SYSTEM_REPORT_ENABLED` | 可选 | 关(`=true` 开) | 批次报告推送到主系统(第九批);关 = 不采集不推送、零出站 | | `MAIN_SYSTEM_REPORT_UPLOAD_PATH` | 可选 | `/api/storage/quality-reports/upload` | 报告文件上传端点覆盖(一般不用改) | | `MAIN_SYSTEM_REPORT_REGISTER_PATH` | 可选 | `/api/supplier/quality-reports` | 报告登记端点覆盖(一般不用改) | +| `MAIN_SYSTEM_QUOTE_COST_SYNC` | 可选 | 关(`=1` 开) | 报价单**审批生效后**把销售价推给主系统当成本价(2026-10-18 冻结契约);关 = 不查库不出站、行为与改造前一致 | +| `MAIN_SYSTEM_QUOTE_COST_SYNC_PATH` | 可选 | `/api/supplier/quote-sheets/cost-sync` | 报价单成本价同步端点覆盖(一般不用改) | +| `MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL` | 可选 | 关(`=1` 开) | 报价单双向价格传递(2026-10-18):关 = 零出站、内部端点 503;开 = A 提交配送商审 / B 拉回配送商成本价提议由我方审(通过后按行写 sale_price 并走既有成本价同步通道) | +| `MAIN_SYSTEM_QUOTE_PRICE_PROPOSALS_PATH` | 可选 | `/api/supplier/quote-sheets/price-proposals` | 价格提议端点覆盖(D1/D2;D3 = 该路径 + `/:id/decision`) | +| `MAIN_SYSTEM_SKU_MAPPINGS_PATH` | 可选 | `/api/supplier/sku-mappings` | SKU 映射端点覆盖(D4 = 该路径 + `/sync`,D5 = 该路径;映射在配送侧维护,本系统只读同步) | | `MAIN_SYSTEM_WRITEBACK` | 可选 | 关(`=1` 开) | 发车回写主系统 | | `MAIN_SYSTEM_IMPORT_CONCURRENCY` | 可选 | 4 | 分公司导入并发(上限 10);500 家绑码时并发 4 可把瞬时峰值压到个位数 QPS | | `MAIN_SYSTEM_IMPORT_SPREAD_SEC` | 可选 | 120 | 拉货**错峰窗口**(秒):把各分公司的开始时刻在窗口内均匀铺开,避免整轮一起打主系统;`0` = 关闭错峰(尽快跑完)。窗口再被「家数 × 400 ms」封顶 ⇒ 2–3 家只等几百毫秒 | | `MAIN_SYSTEM_RETURN_FOLLOW_SEC` | 可选 | 120 | **退货/删单跟随**的独立节流(秒)。跟随原先只随导入(10 分钟限流)跑 ⇒ 主系统删单/退货后我方最坏等 ~10 分钟才跟随(主系统**没有**删单/退货推送事件,轮询是唯一通道)。现改为 60 秒定时器 + 本值节流;`0` = 退回旧行为(只随导入跑)。500 家规模下可调大以降低出站量 | | `STOCK_COVER_REQUIRE_OUTSOURCED` | 可选 | 1(开) | 库存抵扣口径:开 = 只结转账外持有余额(`inventory_holding`,防同一批货计两次成本);`0` = 回退旧行为(只看物理自由库存),仅用于线上异常回退 | | `UNIT_CHANGED_AUTO_APPLY` | 可选 | 0(要审) | 主系统推 `preparations.unit_changed` 时的口径:不设/非 `1` = **登记待审**(审核页可见,人工决定跟不跟,通过才写我方单位);`1` = 回退旧行为(收到即改镜像、不建待审),仅用于线上异常回退 | +| `QUOTE_EDIT_APPROVAL` | 可选 | **开**(`=0/false/off` 关) | 编辑生效报价单的**价格相关**改动改为待审:审核通过才改单并同步成本价;关 = 回滚成"直接保存"且不写变更单表(仅用于线上异常回退) | | `MAIN_SYSTEM_BINDING_SYNC_URL` | 可选 | 空(不启用) | 「接入编码绑定」的**回读**端点(主系统只读接口全 URL);空则只依赖 `binding.changed` 回调与超管手工登记 —— 见 `docs/design/20261027-分公司接入编码与主系统供应商绑定.md` §8 P0-2 | #### 租户 / 数据库 / 存储(PG_*、TENANT_*、S3_*、STORAGE_*) diff --git a/migrations/20261018_main_system_quote_cost_pushes.sql b/migrations/20261018_main_system_quote_cost_pushes.sql new file mode 100644 index 0000000..8769123 --- /dev/null +++ b/migrations/20261018_main_system_quote_cost_pushes.sql @@ -0,0 +1,93 @@ +-- 报价单销售价 → 主系统报价单成本价:**推送台账**(2026-10-18 设计) +-- +-- 方向:我方(供应商系统)推 → 主系统(配送系统)新端点 `POST /api/supplier/quote-sheets/cost-sync`。 +-- 设计:docs/design/20261018-报价单成本价同步推送.md +-- +-- 这张表是**幂等与对账的唯一依据**: +-- · 唯一键 `(quote_sheet_code, main_branch_code)` —— 一张报价单 × 一个主系统分公司**只推一次**; +-- · `client_request_id` 在落台账后才出站,定时重试**复用同一个**(对方按请求号幂等,重放返回 replayed); +-- · `status` 终态(sent / skipped / forbidden)不自动重推;`failed` 且 `attempts < 5` 才进重试队列。 +-- +-- 平台级表(放 public,与 main_supplier_bindings / main_system_report_pushes 同级): +-- 它是**对接状态**,不是租户业务表 ⇒ 不进 public.tenant_business_tables(), +-- 也不进 /api/data 的 ALLOWED_TABLES(不给通用网关写入口)。 + +CREATE TABLE IF NOT EXISTS public.main_system_quote_cost_pushes ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + -- 我方分公司(= 租户;出站换 token / 读报价明细都按它定 schema 上下文) + branch_code VARCHAR(64) NOT NULL, + -- 本次推送的报价单(我方 customer_quote_sheets.quote_sheet_code) + quote_sheet_code VARCHAR(64) NOT NULL, + -- 主系统分公司码(由客户码 MAIN_ 解析);整单级跳过(无 MAIN_ 客户 / 无可推行)记 '*' + main_branch_code VARCHAR(64) NOT NULL, + -- 我方生成的请求号:落台账后才出站;重试复用(不重新生成) + client_request_id UUID NOT NULL, + status VARCHAR(16) NOT NULL DEFAULT 'pending', + attempts INTEGER NOT NULL DEFAULT 0, + last_error TEXT, + -- 对方回执 data(replayed / updated / sheets / skipped / warnings)+ 我方 local 口径记录 + response JSONB, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +COMMENT ON TABLE public.main_system_quote_cost_pushes IS + '报价单成本价同步出站台账(我方 → 主系统 /api/supplier/quote-sheets/cost-sync):一单 × 一个主系统分公司只推一次,重试复用 client_request_id'; +COMMENT ON COLUMN public.main_system_quote_cost_pushes.main_branch_code IS + '主系统分公司码(客户码 MAIN_ 的 X,UPPER/TRIM);''*'' = 整单级跳过(没有 MAIN_ 客户或没有可推行)'; +COMMENT ON COLUMN public.main_system_quote_cost_pushes.client_request_id IS + '我方生成的幂等请求号:落台账后才出站,失败重试复用同一个(不得重新生成)'; +COMMENT ON COLUMN public.main_system_quote_cost_pushes.status IS + 'pending=待出站/中间态;sent=已同步;failed=可重试(attempts<5);skipped=整单无可推内容(终态);forbidden=对方 403 未绑定(终态,不重试)'; +COMMENT ON COLUMN public.main_system_quote_cost_pushes.last_error IS + '最近一次失败原因(对方 error/error_description 或网络/超时文案);成功时清空'; +COMMENT ON COLUMN public.main_system_quote_cost_pushes.response IS + '对方回执 data(replayed/updated/sheets/skipped/warnings)+ 我方 local(本地跳过明细);成功才写'; + +DO $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM pg_constraint + WHERE conrelid = 'public.main_system_quote_cost_pushes'::regclass + AND conname = 'main_system_quote_cost_pushes_status_chk' + ) THEN + ALTER TABLE public.main_system_quote_cost_pushes + ADD CONSTRAINT main_system_quote_cost_pushes_status_chk + CHECK (status IN ('pending', 'sent', 'failed', 'skipped', 'forbidden')); + END IF; +END $$; + +-- 一张单 × 一个主系统分公司只有一行(T4=A:审批生效时推一次) +CREATE UNIQUE INDEX IF NOT EXISTS uq_main_system_quote_cost_pushes + ON public.main_system_quote_cost_pushes (quote_sheet_code, main_branch_code); + +-- 定时重试扫描:failed 且 attempts < 5,按 updated_at 取最旧的几条 +CREATE INDEX IF NOT EXISTS idx_main_system_quote_cost_pushes_retry + ON public.main_system_quote_cost_pushes (status, updated_at) + WHERE status = 'failed'; + +-- 排查用:某分公司推过哪些单 / 某个请求号落到哪一行 +CREATE INDEX IF NOT EXISTS idx_main_system_quote_cost_pushes_branch + ON public.main_system_quote_cost_pushes (branch_code, created_at DESC); + +-- 响亮失败守卫:表/唯一键/约束没落上就中断迁移(历史事故:BR004 少 3 张表) +DO $$ +BEGIN + IF to_regclass('public.main_system_quote_cost_pushes') IS NULL THEN + RAISE EXCEPTION '迁移未生效:public.main_system_quote_cost_pushes 不存在'; + END IF; + IF NOT EXISTS ( + SELECT 1 FROM pg_indexes + WHERE schemaname = 'public' AND tablename = 'main_system_quote_cost_pushes' + AND indexname = 'uq_main_system_quote_cost_pushes' + ) THEN + RAISE EXCEPTION '迁移未生效:(quote_sheet_code, main_branch_code) 唯一索引缺失'; + END IF; + IF NOT EXISTS ( + SELECT 1 FROM pg_constraint + WHERE conrelid = 'public.main_system_quote_cost_pushes'::regclass + AND conname = 'main_system_quote_cost_pushes_status_chk' + ) THEN + RAISE EXCEPTION '迁移未生效:status 取值约束缺失'; + END IF; +END $$; diff --git a/migrations/20261018_main_system_sku_mappings.sql b/migrations/20261018_main_system_sku_mappings.sql new file mode 100644 index 0000000..a194b44 --- /dev/null +++ b/migrations/20261018_main_system_sku_mappings.sql @@ -0,0 +1,230 @@ +-- SKU 映射(供应商系统侧只读副本,2026-10-18 增量 · task-14) +-- +-- 背景(用户原话 + 冻结契约 `.team/sku-mapping-shared-sheet/contract.md` §5): +-- 「两个系统的 sku 哪怕是同一个商品 sku 都是不一致的 所以映射这个需要建立」。 +-- 映射**在配送系统维护**(`public.supplier_sku_mappings` 是对方平台表),供应商侧 +-- **只读同步**、不可编辑;方向 B 审批时提议里的 sku_code 是**配送 SKU** ⇒ 必须用本表反查我方 SKU。 +-- +-- 本表是 **tenant 表**(每个分公司 schema 一份;`tenant_business_tables()` 118 → 119): +-- · `supplier_sku_code` = 我方 `skus.sku_code`(D4 推送的字典项); +-- · `delivery_sku_code`(可空)= 配送侧商品编码;NULL/`pending` 表示尚未映射; +-- · `delivery_sku_name` / `supplier_sku_name` / `supplier_unit` 是 D5 下发的快照(只展示、不参与猜配); +-- · `status` 照抄对方(`active` / `disabled` / `pending`),只有 `active` 且 `delivery_sku_code` 非空才算"已映射"; +-- · `synced_at` = 最近一次 D5 同步时间(排障/定时任务用)。 +-- +-- 新增业务表四步(docs/design/20260915-tenant-table-list-guard.md): +-- ① 建表(各租户 schema) ② 登记名单(118→119) ③ ensure 补建 ④ assert 断言 +-- 设计:docs/design/20261018-SKU映射与成本传递.md + +DO $$ +DECLARE + sch text; +BEGIN + FOR sch IN + SELECT nspname + FROM pg_namespace + WHERE nspname IN ('public', 'legacy_public', 'tenant_template') + OR nspname LIKE 'tenant_%' + LOOP + -- 锚点 = 报价单同域(与 quote_price_proposals 一致) + IF to_regclass(format('%I.customer_quote_sheets', sch)) IS NULL THEN + CONTINUE; + END IF; + + EXECUTE format( + 'CREATE TABLE IF NOT EXISTS %I.main_system_sku_mappings ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + supplier_sku_code VARCHAR(100) NOT NULL, + supplier_sku_name VARCHAR(200), + supplier_unit VARCHAR(20), + delivery_sku_code VARCHAR(100), + delivery_sku_name VARCHAR(200), + status VARCHAR(16) NOT NULL DEFAULT ''pending'', + synced_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + CONSTRAINT main_system_sku_mappings_status_chk + CHECK (status IN (''active'', ''disabled'', ''pending'')) + )', + sch + ); + EXECUTE format( + 'COMMENT ON TABLE %I.main_system_sku_mappings IS %L', + sch, + '主系统(配送侧)下发的 SKU 映射只读副本:我方 supplier_sku_code ↔ 配送 delivery_sku_code;本表不可人工编辑' + ); + EXECUTE format( + 'COMMENT ON COLUMN %I.main_system_sku_mappings.status IS %L', + sch, + '照抄配送侧:active=已映射/已启用;pending=待人工配对;disabled=已停用。只有 active 且 delivery_sku_code 非空才算已映射' + ); + EXECUTE format( + 'COMMENT ON COLUMN %I.main_system_sku_mappings.synced_at IS %L', + sch, + '最近一次 D5(GET /api/supplier/sku-mappings)同步时间' + ); + + -- 一个我方 SKU 只有一行 + EXECUTE format( + 'CREATE UNIQUE INDEX IF NOT EXISTS uq_main_system_sku_mappings_supplier + ON %I.main_system_sku_mappings (supplier_sku_code)', + sch + ); + -- 方向 B 反查:delivery_sku_code → supplier_sku_code + EXECUTE format( + 'CREATE UNIQUE INDEX IF NOT EXISTS uq_main_system_sku_mappings_delivery + ON %I.main_system_sku_mappings (delivery_sku_code) + WHERE delivery_sku_code IS NOT NULL AND status = ''active''', + sch + ); + EXECUTE format( + 'CREATE INDEX IF NOT EXISTS idx_main_system_sku_mappings_status + ON %I.main_system_sku_mappings (status, supplier_sku_code)', + sch + ); + + IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'canteen_app_rls') THEN + BEGIN + EXECUTE format( + 'GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE %I.main_system_sku_mappings TO canteen_app_rls', + sch + ); + EXCEPTION WHEN OTHERS THEN + RAISE NOTICE 'skip grant on %.main_system_sku_mappings: %', sch, SQLERRM; + END; + END IF; + END LOOP; +END $$; + +-- ② 名单同步(118 → 119) +CREATE OR REPLACE FUNCTION public.tenant_business_tables() +RETURNS TEXT[] +LANGUAGE sql +IMMUTABLE +AS $$ + SELECT ARRAY[ + 'after_sale_returns', + 'after_sales', + 'ai_prompt_overrides', + 'ai_prompt_revisions', + 'ai_prompt_templates', + 'alias_recognition_logs', + 'allocation_tasks', + 'assistant_conversations', + 'assistant_messages', + 'assistant_turns', + 'bid_awards', + 'bid_invitations', + 'bid_prices', + 'bid_quotes', + 'bid_round_items', + 'bid_rounds', + 'categories', + 'cost_adjustments', + 'cost_details', + 'customer_alias_stats', + 'customer_delivery_assignments', + 'customer_portal_users', + 'customer_processing_aliases', + 'customer_quote_sheet_customers', + 'customer_quote_sheet_items', + 'customer_quote_sheets', + 'customer_quote_versions', + 'customer_recipients', + 'customer_sku_aliases', + 'customer_sku_remarks', + 'customer_skus', + 'customer_statements', + 'customers', + 'delivery_location_history', + 'delivery_person_locations', + 'delivery_person_users', + 'delivery_persons', + 'delivery_schedules', + 'delivery_signatures', + 'delivery_tasks', + 'exception_tickets', + 'fixed_costs', + 'free_cost_invoice_links', + 'free_cost_invoices', + 'free_cost_payment_vouchers', + 'import_mapping_memories', + 'inspection_loss_confirmations', + 'inspection_photo_archive_entries', + 'inspection_photo_archives', + 'inspection_returns', + 'inspection_review_logs', + 'inspections', + 'inventory', + 'inventory_batch_report_matches', + 'inventory_batch_reports', + 'inventory_logs', + 'inventory_reservations', + 'invoice_statement_links', + 'invoices', + 'main_system_sku_mappings', + 'market_compare_exclusions', + 'market_external_catalog', + 'market_price_history', + 'market_price_indices', + 'market_prices', + 'market_sku_external_bindings', + 'notifications', + 'operation_logs', + 'order_allocation_batches', + 'order_item_fulfillments', + 'order_item_returns', + 'order_items', + 'orders', + 'parse_session_items', + 'parse_sessions', + 'picking_assign_rules', + 'picking_containers', + 'picking_items', + 'picking_scan_logs', + 'picking_tasks', + 'price_invert_events', + 'print_jobs', + 'processing_demand_items', + 'processing_demand_picks', + 'processing_logs', + 'processing_tasks', + 'product_catalog', + 'product_substitutions', + 'purchase_orders', + 'purchaser_users', + 'quality_report_prep_links', + 'quality_reports', + 'quote_price_proposals', + 'quote_sheet_change_requests', + 'seasonal_recommendations', + 'self_purchase_stock_inbounds', + 'sign_records', + 'sku_direct_delivery_customers', + 'sku_suppliers', + 'skus', + 'smart_classification_rules', + 'statement_disputes', + 'statement_lines', + 'statement_payments', + 'supplier_categories', + 'supplier_prep_amend_requests', + 'supplier_preparations', + 'supplier_price_agreements', + 'supplier_rating_snapshots', + 'supplier_statements', + 'supplier_users', + 'suppliers', + 'system_configs', + 'unit_conversions', + 'user_preferences', + 'voice_recognition_logs', + 'warehouse_locations', + 'warehouses', + 'weigh_devices' + ] +$$; + +-- ③④ 已有分公司补建 + 漏登记断言(漏了会中断迁移) +SELECT public.ensure_tenant_schemas_match_template(); +SELECT public.assert_tenant_template_matches_business_tables(); diff --git a/migrations/20261018_quote_price_proposals.sql b/migrations/20261018_quote_price_proposals.sql new file mode 100644 index 0000000..742a30d --- /dev/null +++ b/migrations/20261018_quote_price_proposals.sql @@ -0,0 +1,266 @@ +-- 报价单双向价格传递:本地提议台账(2026-10-18 增量) +-- +-- 背景(用户原话 + 冻结契约):报价单的价可以在两个方向发起协商 —— +-- · A 我方(供应商)→ 配送商:把整张单的销售价交对方审(出站 D1,对方写自己的 cost_price); +-- · B 配送商 → 我方:对方把成本价提议推过来(我方经 D2 拉回),我方审(通过就写自己的 sale_price, +-- 再由**既有成本价同步通道** rearm 推回对方 cost_price)。 +-- +-- 这张表只记**我方视角**的提议台账(不含价本身——价仍在 `customer_quote_sheet_items`): +-- · partial unique `(branch_code, quote_sheet_code, direction) WHERE status='pending'` +-- ⇒ 一张单一个方向只允许一条在途(并发/重复提交由索引兜底); +-- · `items` = 提交时的整单快照(sku_code/unit/price),`payload_hash` 供幂等与排障; +-- · `client_request_id` 用于 D1 幂等(同号同 hash 对方回 replay);`remote_proposal_id` 是对方的提议 id, +-- 方向 A 的结果同步、方向 B 的 D3 回执都靠它对应。 +-- +-- 新增业务表四步(见 docs/design/20260915-tenant-table-list-guard.md): +-- ① 建表(tenant_template + 各租户 schema,本文件 DO 块) +-- ② 同步名单 public.tenant_business_tables()(117 → 118) +-- ③ ensure_tenant_schemas_match_template() 给已有分公司补建 +-- ④ assert_tenant_template_matches_business_tables() 断言(漏登记即中断迁移) +-- 设计:docs/design/20261018-报价单双向价格传递与审批.md + +DO $$ +DECLARE + sch text; +BEGIN + FOR sch IN + SELECT nspname + FROM pg_namespace + WHERE nspname IN ('public', 'legacy_public', 'tenant_template') + OR nspname LIKE 'tenant_%' + LOOP + -- 只在「真实租户业务 schema」建表(锚点 = customer_quote_sheets,与报价单同域) + IF to_regclass(format('%I.customer_quote_sheets', sch)) IS NULL THEN + CONTINUE; + END IF; + + EXECUTE format( + 'CREATE TABLE IF NOT EXISTS %I.quote_price_proposals ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + branch_code VARCHAR(50) NOT NULL, + quote_sheet_code VARCHAR(64) NOT NULL, + main_branch_code VARCHAR(64) NOT NULL, + direction VARCHAR(16) NOT NULL, + items JSONB NOT NULL DEFAULT ''[]''::jsonb, + payload_hash VARCHAR(64), + status VARCHAR(16) NOT NULL DEFAULT ''pending'', + reject_reason TEXT, + client_request_id UUID, + remote_proposal_id TEXT, + requested_by UUID, + requested_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + reviewed_by UUID, + reviewed_at TIMESTAMPTZ, + applied_at TIMESTAMPTZ, + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + CONSTRAINT quote_price_proposals_direction_chk + CHECK (direction IN (''to_delivery'', ''from_delivery'')), + CONSTRAINT quote_price_proposals_status_chk + CHECK (status IN (''pending'', ''approved'', ''rejected'', ''cancelled'', ''superseded'')) + )', + sch + ); + EXECUTE format( + 'COMMENT ON TABLE %I.quote_price_proposals IS %L', + sch, + '报价单双向价格传递台账(A 我方→配送商 / B 配送商→我方);只记提议与状态,价仍在 customer_quote_sheet_items' + ); + EXECUTE format( + 'COMMENT ON COLUMN %I.quote_price_proposals.direction IS %L', + sch, + 'to_delivery=A 我方提交给配送商审;from_delivery=B 配送商提议、由我方审' + ); + EXECUTE format( + 'COMMENT ON COLUMN %I.quote_price_proposals.items IS %L', + sch, + '整单快照 [{sku_code, unit, price}](A=我方 sale_price;B=对方 cost_price=同一个数)' + ); + EXECUTE format( + 'COMMENT ON COLUMN %I.quote_price_proposals.client_request_id IS %L', + sch, + 'D1 幂等请求号(同号同 hash 对方回 replay);方向 B 的行为空(由对方发起)' + ); + EXECUTE format( + 'COMMENT ON COLUMN %I.quote_price_proposals.remote_proposal_id IS %L', + sch, + '对方(配送系统)的 proposal id:A 的结果同步与 B 的 D3 回执都靠它对应' + ); + + -- T6:status 枚举含 `superseded`(同方向重复提交时旧 pending 置它)。 + -- ⚠️ 表已存在的库也必须能拿到这个枚举 ⇒ 先 DROP CONSTRAINT IF EXISTS 再重建(迁移可重放)。 + EXECUTE format( + 'ALTER TABLE %I.quote_price_proposals DROP CONSTRAINT IF EXISTS quote_price_proposals_status_chk', + sch + ); + EXECUTE format( + 'ALTER TABLE %I.quote_price_proposals + ADD CONSTRAINT quote_price_proposals_status_chk + CHECK (status IN (''pending'', ''approved'', ''rejected'', ''cancelled'', ''superseded''))', + sch + ); + + -- 一张单一个方向只允许一条在途 + EXECUTE format( + 'CREATE UNIQUE INDEX IF NOT EXISTS uq_quote_price_proposals_pending + ON %I.quote_price_proposals (branch_code, quote_sheet_code, direction) + WHERE status = ''pending''', + sch + ); + -- 列表:按分公司 + 方向 + 状态取最近 + EXECUTE format( + 'CREATE INDEX IF NOT EXISTS idx_quote_price_proposals_list + ON %I.quote_price_proposals (branch_code, direction, status, requested_at DESC)', + sch + ); + -- 对账:按对方 proposal id 定位本地行 + EXECUTE format( + 'CREATE INDEX IF NOT EXISTS idx_quote_price_proposals_remote + ON %I.quote_price_proposals (remote_proposal_id)', + sch + ); + + IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'canteen_app_rls') THEN + BEGIN + EXECUTE format( + 'GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE %I.quote_price_proposals TO canteen_app_rls', + sch + ); + EXCEPTION WHEN OTHERS THEN + RAISE NOTICE 'skip grant on %.quote_price_proposals: %', sch, SQLERRM; + END; + END IF; + END LOOP; +END $$; + +-- ② 名单同步(117 → 118) +CREATE OR REPLACE FUNCTION public.tenant_business_tables() +RETURNS TEXT[] +LANGUAGE sql +IMMUTABLE +AS $$ + SELECT ARRAY[ + 'main_system_sku_mappings', + 'after_sale_returns', + 'after_sales', + 'ai_prompt_overrides', + 'ai_prompt_revisions', + 'ai_prompt_templates', + 'alias_recognition_logs', + 'allocation_tasks', + 'assistant_conversations', + 'assistant_messages', + 'assistant_turns', + 'bid_awards', + 'bid_invitations', + 'bid_prices', + 'bid_quotes', + 'bid_round_items', + 'bid_rounds', + 'categories', + 'cost_adjustments', + 'cost_details', + 'customer_alias_stats', + 'customer_delivery_assignments', + 'customer_portal_users', + 'customer_processing_aliases', + 'customer_quote_sheet_customers', + 'customer_quote_sheet_items', + 'customer_quote_sheets', + 'customer_quote_versions', + 'customer_recipients', + 'customer_sku_aliases', + 'customer_sku_remarks', + 'customer_skus', + 'customer_statements', + 'customers', + 'delivery_location_history', + 'delivery_person_locations', + 'delivery_person_users', + 'delivery_persons', + 'delivery_schedules', + 'delivery_signatures', + 'delivery_tasks', + 'exception_tickets', + 'fixed_costs', + 'free_cost_invoice_links', + 'free_cost_invoices', + 'free_cost_payment_vouchers', + 'import_mapping_memories', + 'inspection_loss_confirmations', + 'inspection_photo_archive_entries', + 'inspection_photo_archives', + 'inspection_returns', + 'inspection_review_logs', + 'inspections', + 'inventory', + 'inventory_batch_report_matches', + 'inventory_batch_reports', + 'inventory_logs', + 'inventory_reservations', + 'invoice_statement_links', + 'invoices', + 'market_compare_exclusions', + 'market_external_catalog', + 'market_price_history', + 'market_price_indices', + 'market_prices', + 'market_sku_external_bindings', + 'notifications', + 'operation_logs', + 'order_allocation_batches', + 'order_item_fulfillments', + 'order_item_returns', + 'order_items', + 'orders', + 'parse_session_items', + 'parse_sessions', + 'picking_assign_rules', + 'picking_containers', + 'picking_items', + 'picking_scan_logs', + 'picking_tasks', + 'price_invert_events', + 'print_jobs', + 'processing_demand_items', + 'processing_demand_picks', + 'processing_logs', + 'processing_tasks', + 'product_catalog', + 'product_substitutions', + 'purchase_orders', + 'purchaser_users', + 'quality_report_prep_links', + 'quality_reports', + 'quote_price_proposals', + 'quote_sheet_change_requests', + 'seasonal_recommendations', + 'self_purchase_stock_inbounds', + 'sign_records', + 'sku_direct_delivery_customers', + 'sku_suppliers', + 'skus', + 'smart_classification_rules', + 'statement_disputes', + 'statement_lines', + 'statement_payments', + 'supplier_categories', + 'supplier_prep_amend_requests', + 'supplier_preparations', + 'supplier_price_agreements', + 'supplier_rating_snapshots', + 'supplier_statements', + 'supplier_users', + 'suppliers', + 'system_configs', + 'unit_conversions', + 'user_preferences', + 'voice_recognition_logs', + 'warehouse_locations', + 'warehouses', + 'weigh_devices' + ] +$$; + +-- ③④ 已有分公司补建 + 漏登记断言(漏了会中断迁移) +SELECT public.ensure_tenant_schemas_match_template(); +SELECT public.assert_tenant_template_matches_business_tables(); diff --git a/migrations/20261018_quote_sheet_change_requests.sql b/migrations/20261018_quote_sheet_change_requests.sql new file mode 100644 index 0000000..df70ffc --- /dev/null +++ b/migrations/20261018_quote_sheet_change_requests.sql @@ -0,0 +1,241 @@ +-- 编辑生效报价单改价 → 待审变更单(审核通过才应用 + 才同步成本价)(2026-10-18) +-- +-- 背景(用户原话「编辑生效单改价需要有同步审核,审核通过就同步」+ 冻结决策 D1–D5): +-- · 生效中的报价单(`status=1 AND approval_status=30`)改价,过去是**直接落库**(DELETE+INSERT 明细 + 刷版本); +-- · 现在价格相关改动先落本表(`pending`),审核通过才在**单事务**内应用并触发成本价同步; +-- · 一张单只保留一条 `pending`(D4:新提交把旧的置 `superseded`);驳回/通过都留痕(reviewer / 时间 / 理由)。 +-- +-- 新增业务表四步(见 docs/design/20260915-tenant-table-list-guard.md): +-- ① 建表(tenant_template + 各租户 schema,本文件 DO 块) +-- ② 同步名单 public.tenant_business_tables()(本文件尾部) +-- ③ ensure_tenant_schemas_match_template() 给已有分公司补建 +-- ④ assert_tenant_template_matches_business_tables() 断言(漏登记即中断迁移) +-- 设计:docs/design/20261018-报价单改价审核与成本同步.md + +DO $$ +DECLARE + sch text; +BEGIN + FOR sch IN + SELECT nspname + FROM pg_namespace + WHERE nspname IN ('public', 'legacy_public', 'tenant_template') + OR nspname LIKE 'tenant_%' + LOOP + -- 只在「真实租户业务 schema」建表(锚点 = customer_quote_sheets,与报价单同域) + IF to_regclass(format('%I.customer_quote_sheets', sch)) IS NULL THEN + CONTINUE; + END IF; + + EXECUTE format( + 'CREATE TABLE IF NOT EXISTS %I.quote_sheet_change_requests ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + branch_code VARCHAR(50) NOT NULL, + quote_sheet_code VARCHAR(64) NOT NULL, + payload JSONB NOT NULL DEFAULT ''{}''::jsonb, + base_version_no INTEGER, + base_items_fingerprint VARCHAR(64), + status VARCHAR(16) NOT NULL DEFAULT ''pending'', + requested_by UUID, + requested_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + reviewed_by UUID, + reviewed_at TIMESTAMPTZ, + reject_reason TEXT, + applied_at TIMESTAMPTZ, + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + CONSTRAINT quote_sheet_change_requests_status_chk + CHECK (status IN (''pending'', ''approved'', ''rejected'', ''superseded'')) + )', + sch + ); + EXECUTE format( + 'COMMENT ON TABLE %I.quote_sheet_change_requests IS %L', + sch, + '编辑生效报价单的待审变更单:价格相关改动先入此表,审核通过才应用并同步成本价' + ); + EXECUTE format( + 'COMMENT ON COLUMN %I.quote_sheet_change_requests.payload IS %L', + sch, + '整单一次审核(D2):保存时提交的完整编辑入参(items/customer_codes/title/quote_cycle/effective_at/auto_sale_price_by_cost)' + ); + EXECUTE format( + 'COMMENT ON COLUMN %I.quote_sheet_change_requests.base_version_no IS %L', + sch, + '提交时的报价单 version_no(留档:审批时可判断期间是否被其它途径改过)' + ); + EXECUTE format( + 'COMMENT ON COLUMN %I.quote_sheet_change_requests.base_items_fingerprint IS %L', + sch, + '提交时报价单明细指纹(复用 quoteCostSyncItemsFingerprint 算法:sku_code/unit/sale_price 排序后 sha256);审批时重算不一致 ⇒ 409 base_changed 并整单拒绝' + ); + EXECUTE format( + 'COMMENT ON COLUMN %I.quote_sheet_change_requests.status IS %L', + sch, + 'pending=待审;approved=已通过并应用;rejected=已驳回(报价单不变);superseded=被新一次提交覆盖(D4)' + ); + + -- 一张单只保留一条待审(D4):新提交把旧的置 superseded + EXECUTE format( + 'CREATE UNIQUE INDEX IF NOT EXISTS uq_quote_sheet_change_requests_pending + ON %I.quote_sheet_change_requests (branch_code, quote_sheet_code) + WHERE status = ''pending''', + sch + ); + -- 待审列表:按分公司 + 状态取最近 + EXECUTE format( + 'CREATE INDEX IF NOT EXISTS idx_quote_sheet_change_requests_status + ON %I.quote_sheet_change_requests (branch_code, status, requested_at DESC)', + sch + ); + -- 单张单的历史(通过/驳回/覆盖留痕) + EXECUTE format( + 'CREATE INDEX IF NOT EXISTS idx_quote_sheet_change_requests_sheet + ON %I.quote_sheet_change_requests (quote_sheet_code, requested_at DESC)', + sch + ); + + IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'canteen_app_rls') THEN + BEGIN + EXECUTE format( + 'GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE %I.quote_sheet_change_requests TO canteen_app_rls', + sch + ); + EXCEPTION WHEN OTHERS THEN + RAISE NOTICE 'skip grant on %.quote_sheet_change_requests: %', sch, SQLERRM; + END; + END IF; + END LOOP; +END $$; + +-- ② 名单同步(116 → 117) +CREATE OR REPLACE FUNCTION public.tenant_business_tables() +RETURNS TEXT[] +LANGUAGE sql +IMMUTABLE +AS $$ + SELECT ARRAY[ + 'main_system_sku_mappings', + 'after_sale_returns', + 'after_sales', + 'ai_prompt_overrides', + 'ai_prompt_revisions', + 'ai_prompt_templates', + 'alias_recognition_logs', + 'allocation_tasks', + 'assistant_conversations', + 'assistant_messages', + 'assistant_turns', + 'bid_awards', + 'bid_invitations', + 'bid_prices', + 'bid_quotes', + 'bid_round_items', + 'bid_rounds', + 'categories', + 'cost_adjustments', + 'cost_details', + 'customer_alias_stats', + 'customer_delivery_assignments', + 'customer_portal_users', + 'customer_processing_aliases', + 'customer_quote_sheet_customers', + 'customer_quote_sheet_items', + 'customer_quote_sheets', + 'customer_quote_versions', + 'customer_recipients', + 'customer_sku_aliases', + 'customer_sku_remarks', + 'customer_skus', + 'customer_statements', + 'customers', + 'delivery_location_history', + 'delivery_person_locations', + 'delivery_person_users', + 'delivery_persons', + 'delivery_schedules', + 'delivery_signatures', + 'delivery_tasks', + 'exception_tickets', + 'fixed_costs', + 'free_cost_invoice_links', + 'free_cost_invoices', + 'free_cost_payment_vouchers', + 'import_mapping_memories', + 'inspection_loss_confirmations', + 'inspection_photo_archive_entries', + 'inspection_photo_archives', + 'inspection_returns', + 'inspection_review_logs', + 'inspections', + 'inventory', + 'inventory_batch_report_matches', + 'inventory_batch_reports', + 'inventory_logs', + 'inventory_reservations', + 'invoice_statement_links', + 'invoices', + 'market_compare_exclusions', + 'market_external_catalog', + 'market_price_history', + 'market_price_indices', + 'market_prices', + 'market_sku_external_bindings', + 'notifications', + 'operation_logs', + 'order_allocation_batches', + 'order_item_fulfillments', + 'order_item_returns', + 'order_items', + 'orders', + 'parse_session_items', + 'parse_sessions', + 'picking_assign_rules', + 'picking_containers', + 'picking_items', + 'picking_scan_logs', + 'picking_tasks', + 'price_invert_events', + 'print_jobs', + 'processing_demand_items', + 'processing_demand_picks', + 'processing_logs', + 'processing_tasks', + 'product_catalog', + 'product_substitutions', + 'purchase_orders', + 'purchaser_users', + 'quality_report_prep_links', + 'quality_reports', + 'quote_price_proposals', + 'quote_sheet_change_requests', + 'seasonal_recommendations', + 'self_purchase_stock_inbounds', + 'sign_records', + 'sku_direct_delivery_customers', + 'sku_suppliers', + 'skus', + 'smart_classification_rules', + 'statement_disputes', + 'statement_lines', + 'statement_payments', + 'supplier_categories', + 'supplier_prep_amend_requests', + 'supplier_preparations', + 'supplier_price_agreements', + 'supplier_rating_snapshots', + 'supplier_statements', + 'supplier_users', + 'suppliers', + 'system_configs', + 'unit_conversions', + 'user_preferences', + 'voice_recognition_logs', + 'warehouse_locations', + 'warehouses', + 'weigh_devices' + ] +$$; + +-- ③④ 已有分公司补建 + 漏登记断言(漏了会中断迁移) +SELECT public.ensure_tenant_schemas_match_template(); +SELECT public.assert_tenant_template_matches_business_tables(); diff --git a/server/.env.example b/server/.env.example index 40ea6d9..2dd27b4 100644 --- a/server/.env.example +++ b/server/.env.example @@ -25,6 +25,10 @@ MAIN_SYSTEM_IMPORT_SPREAD_SEC=120 # 我方人工决定跟不跟;置 1 = 回退旧行为(收到即改镜像、不建待审),仅用于线上异常回退 UNIT_CHANGED_AUTO_APPLY=0 +# 编辑生效报价单改价 → 待审(2026-10-18):默认 **开** = 价格相关改动先写待审变更单,审核通过才改单并同步成本价; +# 置 0/false/off = 回滚成改造前的「编辑直接保存」,且不写变更单表(仅用于线上异常回退) +QUOTE_EDIT_APPROVAL=1 + # 库存抵扣口径(2026-10-13):默认开 = 只允许结转账外持有余额(防同一批货计两次成本); # 置 0 = 回退旧行为(只看物理自由库存),仅用于线上异常回退 STOCK_COVER_REQUIRE_OUTSOURCED=1 @@ -111,6 +115,25 @@ MAIN_SYSTEM_INTEGRATION_CLIENT_SECRET= # MAIN_SYSTEM_REPORT_UPLOAD_PATH=/api/storage/quality-reports/upload # MAIN_SYSTEM_REPORT_REGISTER_PATH=/api/supplier/quality-reports +# --- 「报价单双向价格传递」(2026-10-18 冻结契约)--- +# 默认关:关 = 零出站、内部三个端点一律 503、不写 quote_price_proposals。 +# 打开后:方向 A 把我方整单销售价交配送商审(D1);方向 B 拉回配送商成本价提议(D2)由我方审, +# 通过后按行写本单 sale_price 并用**既有**成本价同步通道 rearm 推对方 cost_price,再 D3 回执。 +MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL=0 +# 端点路径可覆盖(一般不用改): +# MAIN_SYSTEM_QUOTE_PRICE_PROPOSALS_PATH=/api/supplier/quote-sheets/price-proposals +# SKU 映射(映射在配送侧维护,我方只读同步;D4 推字典 / D5 拉映射)端点路径可覆盖: +# MAIN_SYSTEM_SKU_MAPPINGS_PATH=/api/supplier/sku-mappings + +# --- 「报价单销售价 → 主系统报价单成本价」同步(我方推、主系统收;2026-10-18 冻结契约)--- +# 默认关:关闭时**不查库、不出站**(报价单审批/建单行为与改造前逐字节一致)。 +# 打开前提:① 该分公司在主系统有有效授权行(否则对方 403 branch_not_bound ⇒ 台账记 forbidden,不重试) +# ② 对方已开 SUPPLIER_QUOTE_COST_SYNC_ENABLED(否则 503 feature_disabled ⇒ 台账记 failed 待重试) +# ⚠️ MAIN_SYSTEM_BASE_URL 指向线上时,打开它 = 改写线上成本价,先确认环境 +MAIN_SYSTEM_QUOTE_COST_SYNC=0 +# 端点路径可覆盖(一般不用改): +# MAIN_SYSTEM_QUOTE_COST_SYNC_PATH=/api/supplier/quote-sheets/cost-sync + STORAGE_DIR=./uploads-supplier # --- 对象存储(S3 兼容:腾讯云 COS / 阿里云 OSS)--- diff --git a/server/src/modules/workflow/routes/quoteRoutes.ts b/server/src/modules/workflow/routes/quoteRoutes.ts index d00f8af..2f272a1 100644 --- a/server/src/modules/workflow/routes/quoteRoutes.ts +++ b/server/src/modules/workflow/routes/quoteRoutes.ts @@ -74,12 +74,22 @@ router.get('/quote/sheets/:code', authMiddleware, async (req: AuthRequest, res: } }); +/** + * 编辑生效中的报价单(2026-10-18 增量:改价需审核)。 + * + * 分流规则(`saveQuoteSheetEdit`): + * · **价格相关**(含 `items`,或 `auto_sale_price_by_cost` 真的变了)且开关 `QUOTE_EDIT_APPROVAL` 开 + * ⇒ 只写/覆盖「待审变更」,**不落报价单**,响应 `applied: false`; + * · 非价格(只改标题/周期/生效日/客户)或开关关 ⇒ 走现有 `updateQuoteSheet`(逐字不变),`applied: true`。 + * + * 权限一分为二:提交沿用 `customer_manage | order_manage`;**审批只认 `customer_manage`**(见下方 approve/reject)。 + */ router.put('/quote/sheets/:code', authMiddleware, async (req: AuthRequest, res: Response) => { try { const ctx = await getWorkflowCtx(req); const operatingBranch = readOperatingBranchCode(req); requireWorkflowPermission(ctx, ['customer_manage', 'order_manage']); - const { updateQuoteSheet } = await import('../../../services/quoteSheetService'); + const { saveQuoteSheetEdit } = await import('../../../services/quoteSheetChangeRequestService'); const customerCodes = Array.isArray(req.body?.customer_codes) ? req.body.customer_codes.map(String) : undefined; @@ -94,7 +104,7 @@ router.put('/quote/sheets/:code', authMiddleware, async (req: AuthRequest, res: sku_name: item.sku_name ? String(item.sku_name) : undefined, })) : undefined; - const data = await updateQuoteSheet({ + const result = await saveQuoteSheetEdit({ quoteSheetCode: req.params.code, title: req.body?.title !== undefined ? String(req.body.title || '') : undefined, autoSalePriceByCost: req.body?.auto_sale_price_by_cost === undefined @@ -106,10 +116,302 @@ router.put('/quote/sheets/:code', authMiddleware, async (req: AuthRequest, res: effectiveAt: req.body?.effective_at ? String(req.body.effective_at) : undefined, ctx, operatingBranchCode: operatingBranch, + requestedBy: req.userId || null, + }); + if (result.applied) return res.json({ data: result.data, applied: true }); + return res.json({ data: result.data, applied: false, change_request: result.changeRequest }); + } catch (error: any) { + return res.status(error?.status || 500).json({ + error: error?.code || 'server_error', + error_description: error?.message || '修改报价单失败', + }); + } +}); + +const CHANGE_REQUEST_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +/** 待审改价列表(查看:`customer_manage | order_manage`;审批操作才要求 `customer_manage`) */ +router.get('/quote/change-requests', authMiddleware, async (req: AuthRequest, res: Response) => { + try { + const ctx = await getWorkflowCtx(req); + requireWorkflowPermission(ctx, ['customer_manage', 'order_manage']); + const branchCode = getEffectiveBranchCode(ctx, readOperatingBranchCode(req)); + if (!branchCode) { + return res.status(400).json({ error: 'branch_required', error_description: '请选择当前操作分公司' }); + } + const { listQuoteSheetChangeRequests } = await import('../../../services/quoteSheetChangeRequestService'); + const data = await listQuoteSheetChangeRequests({ + branchCode, + status: req.query?.status ? String(req.query.status) : 'pending', + limit: Number(req.query?.limit) || 50, }); return res.json({ data }); } catch (error: any) { - return res.status(error?.status || 500).json({ error: 'server_error', error_description: error?.message || '修改报价单失败' }); + return res.status(error?.status || 500).json({ + error: error?.code || 'server_error', + error_description: error?.message || '加载待审改价失败', + }); + } +}); + +/** 审核通过:单事务应用变更 → 提交后触发成本价同步(rearm 路径);权限只认 `customer_manage` */ +router.post('/quote/change-requests/:id/approve', authMiddleware, async (req: AuthRequest, res: Response) => { + try { + const ctx = await getWorkflowCtx(req); + requireWorkflowPermission(ctx, ['customer_manage']); + if (!CHANGE_REQUEST_ID_RE.test(String(req.params.id || ''))) { + return res.status(400).json({ error: 'invalid_request', error_description: '变更单 ID 无效' }); + } + const { approveQuoteSheetChangeRequest } = await import('../../../services/quoteSheetChangeRequestService'); + const result = await approveQuoteSheetChangeRequest({ + id: String(req.params.id), + ctx, + operatingBranchCode: readOperatingBranchCode(req), + reviewedBy: req.userId || null, + }); + return res.json({ data: result.data, change_request: result.changeRequest }); + } catch (error: any) { + return res.status(error?.status || 500).json({ + error: error?.code || 'server_error', + error_description: error?.message || '审核通过失败', + }); + } +}); + +/** 审核驳回:只改变更单状态(报价单不变、零推送);权限只认 `customer_manage` */ +router.post('/quote/change-requests/:id/reject', authMiddleware, async (req: AuthRequest, res: Response) => { + try { + const ctx = await getWorkflowCtx(req); + requireWorkflowPermission(ctx, ['customer_manage']); + if (!CHANGE_REQUEST_ID_RE.test(String(req.params.id || ''))) { + return res.status(400).json({ error: 'invalid_request', error_description: '变更单 ID 无效' }); + } + const { rejectQuoteSheetChangeRequest } = await import('../../../services/quoteSheetChangeRequestService'); + const result = await rejectQuoteSheetChangeRequest({ + id: String(req.params.id), + reason: String(req.body?.reason || ''), + ctx, + operatingBranchCode: readOperatingBranchCode(req), + reviewedBy: req.userId || null, + }); + return res.json({ change_request: result.changeRequest }); + } catch (error: any) { + return res.status(error?.status || 500).json({ + error: error?.code || 'server_error', + error_description: error?.message || '审核驳回失败', + }); + } +}); + +/** + * **SKU 映射**(2026-10-18 冻结契约 `.team/sku-mapping-shared-sheet/contract.md` §5)—— 三条内部只读/同步端点。 + * + * 映射在**配送侧维护**,本系统只读同步(不可编辑,不按名称猜): + * · `POST /quote/sku-mappings/sync-dictionary`:把我方商品字典整批推 D4,随后拉 D5 刷新本地副本; + * · `GET /quote/sku-mappings`:本地只读列表(`refresh=1` 先拉 D5); + * · `GET /quote/sheets/:code/mapping-stats`:提交前映射统计「本单 N 个商品,已映射 X / 未映射 Y」。 + * + * 开关同样受 `MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL` 控制(关 ⇒ 零出站、本组端点 503)。 + */ +router.post('/quote/sku-mappings/sync-dictionary', authMiddleware, async (req: AuthRequest, res: Response) => { + try { + const ctx = await getWorkflowCtx(req); + requireWorkflowPermission(ctx, ['customer_manage']); + const { pushSkuDictionaryForBranch, pullMappingsFromMainSystem } = await import( + '../../../services/skuMappingService' + ); + const branchCode = getEffectiveBranchCode(ctx, readOperatingBranchCode(req)); + if (!branchCode) { + return res.status(400).json({ error: 'branch_required', error_description: '请选择当前操作分公司' }); + } + const pushed = await pushSkuDictionaryForBranch({ + branchCode, + ctx, + operatingBranchCode: readOperatingBranchCode(req), + }); + const pulled = await pullMappingsFromMainSystem({ branchCode }); + return res.json({ data: { push: pushed, pull: pulled } }); + } catch (error: any) { + return res.status(error?.status || 500).json({ + error: error?.code || 'server_error', + error_description: error?.message || '同步商品字典失败', + }); + } +}); + +router.get('/quote/sku-mappings', authMiddleware, async (req: AuthRequest, res: Response) => { + try { + const ctx = await getWorkflowCtx(req); + requireWorkflowPermission(ctx, ['customer_manage', 'order_manage']); + const { isSkuMappingEnabled, listLocalSkuMappings, pullMappingsFromMainSystem } = await import( + '../../../services/skuMappingService' + ); + if (!isSkuMappingEnabled()) { + return res.status(503).json({ + error: 'feature_disabled', + error_description: '报价单价格传递未开启(MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL)', + }); + } + const branchCode = getEffectiveBranchCode(ctx, readOperatingBranchCode(req)); + if (!branchCode) { + return res.status(400).json({ error: 'branch_required', error_description: '请选择当前操作分公司' }); + } + let pull = null; + if (String(req.query?.refresh || '') === '1') { + pull = await pullMappingsFromMainSystem({ branchCode }); + } + const result = await listLocalSkuMappings({ + branchCode, + ctx, + operatingBranchCode: readOperatingBranchCode(req), + status: req.query?.status ? String(req.query.status) : null, + keyword: req.query?.q ? String(req.query.q) : null, + limit: Number(req.query?.limit) || 200, + }); + return res.json({ data: result.rows, summary: result.summary, pull }); + } catch (error: any) { + return res.status(error?.status || 500).json({ + error: error?.code || 'server_error', + error_description: error?.message || '加载 SKU 映射失败', + }); + } +}); + +router.get('/quote/sheets/:code/mapping-stats', authMiddleware, async (req: AuthRequest, res: Response) => { + try { + const ctx = await getWorkflowCtx(req); + requireWorkflowPermission(ctx, ['customer_manage', 'order_manage']); + const { isSkuMappingEnabled, getSheetMappingStats } = await import('../../../services/skuMappingService'); + if (!isSkuMappingEnabled()) { + return res.status(503).json({ + error: 'feature_disabled', + error_description: '报价单价格传递未开启(MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL)', + }); + } + const stats = await getSheetMappingStats(String(req.params.code)); + return res.json({ data: stats }); + } catch (error: any) { + return res.status(error?.status || 500).json({ + error: error?.code || 'server_error', + error_description: error?.message || '加载映射统计失败', + }); + } +}); + +/** + * 报价单**双向价格传递**(2026-10-18 冻结契约)—— 三个内部端点: + * · `POST /quote/sheets/:code/price-proposals`:方向 A 发起(转调配送系统 D1,建对方 pending,**不写价**) + * · `GET /quote/price-proposals`:本地提议列表(`refresh=1` 先调 D2 对账;T10 游标增量) + * · `POST /quote/price-proposals/:id/approve|reject`:方向 B 审批(通过 ⇒ 按行写 sale_price + rearm 推对方 cost_price + D3 回执) + * + * 权限:发起/审批仅 `customer_manage`;查看 `customer_manage | order_manage`。 + * 开关 `MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL` 默认关 ⇒ 三个端点一律 **503**(零出站、零写库)。 + */ +router.post('/quote/sheets/:code/price-proposals', authMiddleware, async (req: AuthRequest, res: Response) => { + try { + const ctx = await getWorkflowCtx(req); + requireWorkflowPermission(ctx, ['customer_manage']); + const operatingBranch = readOperatingBranchCode(req); + const { submitPriceProposal } = await import('../../../services/quotePriceProposalService'); + const result = await submitPriceProposal({ + quoteSheetCode: req.params.code, + note: req.body?.note != null ? String(req.body.note) : undefined, + ctx, + operatingBranchCode: operatingBranch, + requestedBy: req.userId || null, + }); + return res.json({ + data: result.proposal, + applied: result.applied, + replayed: result.replayed, + mapping: result.mapping, + }); + } catch (error: any) { + return res.status(error?.status || 500).json({ + error: error?.code || 'server_error', + error_description: error?.message || '提交配送商审核失败', + }); + } +}); + +router.get('/quote/price-proposals', authMiddleware, async (req: AuthRequest, res: Response) => { + try { + const ctx = await getWorkflowCtx(req); + requireWorkflowPermission(ctx, ['customer_manage', 'order_manage']); + const branchCode = getEffectiveBranchCode(ctx, readOperatingBranchCode(req)); + if (!branchCode) { + return res.status(400).json({ error: 'branch_required', error_description: '请选择当前操作分公司' }); + } + const { isQuotePriceProposalEnabled, listPriceProposals } = await import( + '../../../services/quotePriceProposalService' + ); + if (!isQuotePriceProposalEnabled()) { + return res.status(503).json({ + error: 'feature_disabled', + error_description: '报价单价格传递未开启(MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL)', + }); + } + const refresh = String(req.query?.refresh || '') === '1'; + const result = await listPriceProposals({ + branchCode, + direction: req.query?.direction ? String(req.query.direction) : null, + status: req.query?.status ? String(req.query.status) : null, + limit: Number(req.query?.limit) || 50, + refresh, + }); + return res.json({ data: result.rows, sync: result.sync }); + } catch (error: any) { + return res.status(error?.status || 500).json({ + error: error?.code || 'server_error', + error_description: error?.message || '加载配送商价格提议失败', + }); + } +}); + +router.post('/quote/price-proposals/:id/approve', authMiddleware, async (req: AuthRequest, res: Response) => { + try { + const ctx = await getWorkflowCtx(req); + requireWorkflowPermission(ctx, ['customer_manage']); + if (!CHANGE_REQUEST_ID_RE.test(String(req.params.id || ''))) { + return res.status(400).json({ error: 'invalid_request', error_description: '提议 ID 无效' }); + } + const { approvePriceProposal } = await import('../../../services/quotePriceProposalService'); + const result = await approvePriceProposal({ + id: String(req.params.id), + ctx, + operatingBranchCode: readOperatingBranchCode(req), + reviewedBy: req.userId || null, + }); + return res.json({ data: result.proposal, applied: result.applied, receipt_sent: result.receiptSent }); + } catch (error: any) { + return res.status(error?.status || 500).json({ + error: error?.code || 'server_error', + error_description: error?.message || '审批配送商成本价失败', + }); + } +}); + +router.post('/quote/price-proposals/:id/reject', authMiddleware, async (req: AuthRequest, res: Response) => { + try { + const ctx = await getWorkflowCtx(req); + requireWorkflowPermission(ctx, ['customer_manage']); + if (!CHANGE_REQUEST_ID_RE.test(String(req.params.id || ''))) { + return res.status(400).json({ error: 'invalid_request', error_description: '提议 ID 无效' }); + } + const { rejectPriceProposal } = await import('../../../services/quotePriceProposalService'); + const result = await rejectPriceProposal({ + id: String(req.params.id), + reason: String(req.body?.reason || ''), + ctx, + operatingBranchCode: readOperatingBranchCode(req), + reviewedBy: req.userId || null, + }); + return res.json({ data: result.proposal, receipt_sent: result.receiptSent }); + } catch (error: any) { + return res.status(error?.status || 500).json({ + error: error?.code || 'server_error', + error_description: error?.message || '驳回配送商成本价失败', + }); } }); diff --git a/server/src/services/mainSystem/api/quoteCostSync.ts b/server/src/services/mainSystem/api/quoteCostSync.ts new file mode 100644 index 0000000..f62831f --- /dev/null +++ b/server/src/services/mainSystem/api/quoteCostSync.ts @@ -0,0 +1,228 @@ +import { getMainSystemToken } from '../token'; +import { requestMainSystem, type MainSystemResult } from '../http'; +import { + MAIN_SYSTEM_FETCH_TIMEOUT_MS, + isMainSystemIntegrationEnabled, + mainSystemTimeoutMs, +} from '../config'; + +/** + * 报价单销售价 → 主系统报价单成本价(**我方推、主系统收**)的接口封装。 + * + * 契约(2026-10-18 冻结):主系统新增 `POST /api/supplier/quote-sheets/cost-sync` + * · 鉴权:供应商开放 API 的 `client_credentials` token(`Authorization: Bearer`); + * `supplier_code` **只由 token 决定**,请求体里不放; + * · 幂等:同 `client_request_id` + 同 payload ⇒ 返回已存结果且 `replayed: true`;不同 payload ⇒ 409; + * · 目标分公司:由 `main_branch_code` 指定,对方按**它自己的授权行**校验(不成立 ⇒ 403 `branch_not_bound`)。 + * + * 这一层只有类型 + 字段映射(snake_case 的唯一落点)+ 结果枚举; + * URL 走端点表(`endpoints.mainSystemPath('quoteCostSync')`,可被 `MAIN_SYSTEM_QUOTE_COST_SYNC_PATH` 覆盖)、 + * token 走 `../token.ts`(全仓唯一缓存)、HTTP 走 `../http.ts`(唯一出口)。 + * + * 设计:docs/design/20261018-报价单成本价同步推送.md §5 + */ + +export type QuoteCostSyncItemPayload = { + sku_code: string; + /** 明细行单位;取不到/超长时带 null(对方按 `skus.unit` 比) */ + unit: string | null; + sale_price: number; +}; + +export type QuoteCostSyncRequestBody = { + client_request_id: string; + supplier_quote_sheet_code: string; + main_branch_code: string; + /** 仅溯源(对方忽略非法值);取不到就不带 */ + activated_at?: string; + items: QuoteCostSyncItemPayload[]; +}; + +export type QuoteCostSyncSkippedRow = { + reason: string; + sku_code?: string; + detail?: string; +}; + +/** 对方 200 回执的 `data`(字段可能缺省 ⇒ 调用方按空值兜底) */ +export type QuoteCostSyncResultData = { + client_request_id: string; + replayed: boolean; + main_branch_code: string; + updated: number; + sheets: string[]; + skipped: QuoteCostSyncSkippedRow[]; + warnings: string[]; +}; + +/** 失败三态(与既有服务层枚举一致)+ 对方错误码 */ +export type QuoteCostSyncFailure = { + kind: 'rejected' | 'unavailable' | 'not_configured'; + status: number; + code: string; + reason: string; + payload: unknown; +}; + +export type QuoteCostSyncOutcome = + | { kind: 'ok'; status: number; data: QuoteCostSyncResultData } + | QuoteCostSyncFailure; + +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 { + const num = Number(value); + return Number.isFinite(num) ? num : 0; +} + +/** 对方错误码(`payload.error`);没带就用状态码兜一个稳定的内部码 */ +export function readQuoteCostSyncErrorCode(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 'idempotency_conflict'; + if (status === 503) return 'feature_disabled'; + if (status >= 500) return 'main_system_error'; + return 'request_failed'; +} + +function toFailure(result: Exclude, { kind: 'ok' }>): QuoteCostSyncFailure { + const status = Number(result.status) || 0; + const payload = (result as { payload?: unknown }).payload; + return { + kind: result.kind, + status, + code: result.kind === 'not_configured' ? 'not_configured' : readQuoteCostSyncErrorCode(payload, status), + reason: result.reason || '调用主系统失败', + payload: payload ?? null, + }; +} + +/** + * 换 token + 调用 + **401 强制刷新重试一次**(与 `api/bids.ts` 同款)。 + * + * 为什么只重试一次:token 24h,提前刷新比例散列在 `token.ts` 里;真正 401 说明对方已判失效 + * (轮换/撤销),再刷也白刷 —— 第二次失败直接上报,交给台账重试。 + */ +async function callWithToken( + supplierCode: string, + call: (token: string) => Promise> +): Promise> { + 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 是**语义拒绝** + * (`forbidden` / `branch_not_bound`:供应商未绑定该分公司)⇒ 用 `classify` 改成 rejected, + * 由业务层落台账 `forbidden` 且**永不重试**(绑定不成立,重试也不会成立)。 + */ +const classifyQuoteCostSync = (input: { status: number }) => (input.status === 403 ? 'rejected' : null); + +/** 归一对方回执(字段缺省一律兜成空值,不让业务层解构报错) */ +export function normalizeQuoteCostSyncData(raw: unknown): QuoteCostSyncResultData { + const body = (raw || {}) as Record; + // 兼容对方包一层 `data` 的写法(契约是 `{ success, data }`) + const data = (body.data && typeof body.data === 'object' ? body.data : body) as Record; + const skippedRaw = Array.isArray(data.skipped) ? data.skipped : []; + return { + client_request_id: toText(data.client_request_id) || '', + replayed: data.replayed === true, + main_branch_code: toText(data.main_branch_code) || '', + updated: toNumber(data.updated), + sheets: (Array.isArray(data.sheets) ? data.sheets : []).map((s) => String(s)).filter(Boolean), + skipped: skippedRaw + .map((row) => { + const r = (row || {}) as Record; + return { + reason: toText(r.reason) || 'unknown', + sku_code: toText(r.sku_code) || undefined, + detail: toText(r.detail) || undefined, + }; + }) + .filter((row) => Boolean(row.reason)), + warnings: (Array.isArray(data.warnings) ? data.warnings : []).map((w) => String(w)).filter(Boolean), + }; +} + +/** + * 推送一次成本价同步。 + * + * ⚠️ 调用方必须保证:**在数据库事务之外**调用(出网 HTTP 永远不在事务里),且**失败不得冒泡到审批路径**。 + */ +export async function submitQuoteCostSync(input: { + supplierCode: string; + body: QuoteCostSyncRequestBody; +}): Promise { + 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.body?.items?.length) { + return { kind: 'rejected', status: 0, code: 'items_required', reason: '没有可推送的明细', payload: null }; + } + + const result = await callWithToken(supplierCode, (token) => + requestMainSystem({ + endpoint: 'quoteCostSync', + method: 'POST', + token, + body: input.body, + // 对方要写事务,给宽松一点的超时,但仍由统一出口控制 + timeoutMs: mainSystemTimeoutMs() + MAIN_SYSTEM_FETCH_TIMEOUT_MS, + timeoutReason: '推送报价单成本价超时(对方可能已受理,按请求号幂等重放即可)', + networkReasonPrefix: '推送报价单成本价失败:', + classify: classifyQuoteCostSync, + }) + ); + if (result.kind !== 'ok') return toFailure(result); + + const raw = result.data as any; + // **退化载荷守卫**:2xx 但没有 `data` 对象 ⇒ 不是"同步成功",而是响应不可识别(网关 HTML/字段改名)。 + // 宁可记 failed 下轮重放(对方按 client_request_id 幂等),也不能把没同步当成已同步。 + if (!raw || typeof raw !== 'object' || (raw.data !== undefined && (raw.data === null || typeof raw.data !== 'object'))) { + return { + kind: 'unavailable', + status: result.status, + code: 'invalid_main_system_response', + reason: '主系统返回的成本价同步回执不可识别(缺少 data)', + payload: result.payload, + }; + } + return { kind: 'ok', status: result.status, data: normalizeQuoteCostSyncData(raw) }; +} diff --git a/server/src/services/mainSystem/api/skuMappings.ts b/server/src/services/mainSystem/api/skuMappings.ts new file mode 100644 index 0000000..75a79fe --- /dev/null +++ b/server/src/services/mainSystem/api/skuMappings.ts @@ -0,0 +1,277 @@ +import { getMainSystemToken } from '../token'; +import { requestMainSystem, type MainSystemResult } from '../http'; +import { mainSystemSkuMappingSyncPath } from '../endpoints'; +import { + MAIN_SYSTEM_FETCH_TIMEOUT_MS, + isMainSystemIntegrationEnabled, + mainSystemTimeoutMs, +} from '../config'; + +/** + * **SKU 映射**(2026-10-18 冻结契约 `.team/sku-mapping-shared-sheet/contract.md` §2.1)出站封装。 + * + * 两个动作(映射在**配送侧维护**,我方只读): + * · **D4** `POST {path}/sync`:把我方商品字典整批推上去(≤5000/批),对方按名称完全相同做自动配对; + * · **D5** `GET {path}?main_branch_code=&status=&limit=`:只读拉映射(展示 + 方向 B 反查)。 + * + * 身份:`supplier_code` 只由 token 决定(请求体不带)。 + * 设计:docs/design/20261018-SKU映射与成本传递.md + */ + +export const SKU_MAPPING_MAX_BATCH = 5000; + +export type SkuDictionaryItemPayload = { + sku_code: string; + name: string; + unit?: string | null; +}; + +export type PushSkuDictionaryOutcome = + | { + kind: 'ok'; + status: number; + data: { matched: number; pending: number; kept: number; total: number }; + } + | { + kind: 'rejected' | 'unavailable' | 'not_configured'; + status: number; + code: string; + reason: string; + payload: unknown; + }; + +/** D5 的一行(字段名照契约表;缺省一律兜空值) */ +export type RemoteSkuMappingRow = { + supplier_sku_code: string; + supplier_sku_name: string | null; + supplier_unit: string | null; + delivery_sku_code: string | null; + delivery_sku_name: string | null; + status: string; + match_type: string | null; + updated_at: string | null; +}; + +export type PullSkuMappingsOutcome = + | { kind: 'ok'; status: number; rows: RemoteSkuMappingRow[]; nextCursor: string | null; total: number | null } + | { + 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; +} + +/** 对方错误码(`payload.error`);没带就用状态码兜一个稳定内部码 */ +export function readSkuMappingErrorCode(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, { 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' : readSkuMappingErrorCode(payload, status), + reason: result.reason || '调用主系统失败', + payload, + }; +} + +async function callWithToken( + supplierCode: string, + call: (token: string) => Promise> +): Promise> { + 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 在本端点也是语义拒绝(未绑定该分公司/无权同步),按 rejected 处理而非暂态 */ +const classifySkuMapping = (input: { status: number }) => + input.status === 403 ? ('rejected' as const) : null; + +/** 归一 D4 回执 */ +export function normalizePushResult(raw: unknown): { matched: number; pending: number; kept: number; total: number } { + const body = (raw || {}) as Record; + const data = (body.data && typeof body.data === 'object' ? body.data : body) as Record; + const num = (value: unknown) => (Number.isFinite(Number(value)) ? Number(value) : 0); + return { + matched: num(data.matched), + pending: num(data.pending), + kept: num(data.kept), + total: num(data.total), + }; +} + +/** 归一 D5 的一行 */ +export function normalizeSkuMappingRow(raw: unknown): RemoteSkuMappingRow | null { + const row = (raw || {}) as Record; + const supplierSku = toText(row.supplier_sku_code); + if (!supplierSku) return null; + return { + supplier_sku_code: supplierSku, + supplier_sku_name: toText(row.supplier_sku_name), + supplier_unit: toText(row.supplier_unit), + delivery_sku_code: toText(row.delivery_sku_code), + delivery_sku_name: toText(row.delivery_sku_name), + status: toText(row.status) || 'pending', + match_type: toText(row.match_type), + updated_at: toText(row.updated_at), + }; +} + +/** D4:整批推我方商品字典(调用方负责按 ≤5000 分批) */ +export async function pushSkuDictionary(input: { + supplierCode: string; + mainBranchCode: string; + items: SkuDictionaryItemPayload[]; +}): Promise { + 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 (!Array.isArray(input.items) || !input.items.length) { + return { kind: 'rejected', status: 0, code: 'items_required', reason: '没有可推送的商品', payload: null }; + } + if (input.items.length > SKU_MAPPING_MAX_BATCH) { + return { + kind: 'rejected', + status: 0, + code: 'too_many_items', + reason: `单批最多 ${SKU_MAPPING_MAX_BATCH} 条商品`, + payload: null, + }; + } + const mainBranchCode = String(input.mainBranchCode || '').trim(); + if (!mainBranchCode) { + return { kind: 'rejected', status: 0, code: 'main_branch_required', reason: '缺少目标分公司', payload: null }; + } + + const result = await callWithToken(supplierCode, (token) => + requestMainSystem({ + endpoint: 'skuMappings', + path: mainSystemSkuMappingSyncPath(), + method: 'POST', + token, + body: { + main_branch_code: mainBranchCode, + items: input.items.map((item) => ({ + sku_code: item.sku_code, + name: item.name, + ...(item.unit ? { unit: item.unit } : {}), + })), + }, + timeoutMs: mainSystemTimeoutMs() + MAIN_SYSTEM_FETCH_TIMEOUT_MS, + timeoutReason: '推送商品字典超时(对方可能已受理,可重试;对方按 sku_code 幂等 upsert)', + networkReasonPrefix: '推送商品字典失败:', + classify: classifySkuMapping, + }) + ); + if (result.kind !== 'ok') return toFailure(result); + return { kind: 'ok', status: result.status, data: normalizePushResult(result.data) }; +} + +/** D5:只读拉映射(分页用 `next_cursor`;调用方负责翻页) */ +export async function pullSkuMappings(input: { + supplierCode: string; + mainBranchCode: string; + status?: string | null; + limit?: number; + cursor?: string | null; +}): Promise { + 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 mainBranchCode = String(input.mainBranchCode || '').trim(); + if (!mainBranchCode) { + return { kind: 'rejected', status: 0, code: 'main_branch_required', reason: '缺少目标分公司', payload: null }; + } + const limit = Math.min(Math.max(Number(input.limit) || 200, 1), 500); + const result = await callWithToken(supplierCode, (token) => + requestMainSystem({ + endpoint: 'skuMappings', + method: 'GET', + token, + query: { + main_branch_code: mainBranchCode, + status: input.status ?? undefined, + limit, + cursor: input.cursor ?? undefined, + }, + timeoutMs: MAIN_SYSTEM_FETCH_TIMEOUT_MS, + timeoutReason: '拉取 SKU 映射超时', + networkReasonPrefix: '拉取 SKU 映射失败:', + classify: classifySkuMapping, + }) + ); + 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; + const rowsRaw = Array.isArray(data.rows) ? data.rows : []; + return { + kind: 'ok', + status: result.status, + rows: rowsRaw + .map(normalizeSkuMappingRow) + .filter((row): row is RemoteSkuMappingRow => row !== null), + nextCursor: toText(data.next_cursor) || null, + total: Number.isFinite(Number(data.total)) ? Number(data.total) : null, + }; +} diff --git a/server/src/services/mainSystem/config.ts b/server/src/services/mainSystem/config.ts index b8eaefb..5e4b71f 100644 --- a/server/src/services/mainSystem/config.ts +++ b/server/src/services/mainSystem/config.ts @@ -43,6 +43,28 @@ export const MAIN_SYSTEM_DEFAULT_PATHS = { * 设计:docs/design/20261017-主系统竞价待报价与报价提交.md */ bids: '/api/supplier/bids', + /** + * 报价单销售价 → 主系统报价单成本价(**我方推、主系统收**,2026-10-18 冻结契约): + * `POST /api/supplier/quote-sheets/cost-sync` + * 幂等由 `client_request_id` 保证(同号同 payload ⇒ 重放,同号不同 payload ⇒ 409)。 + * 设计:docs/design/20261018-报价单成本价同步推送.md + */ + quoteCostSync: '/api/supplier/quote-sheets/cost-sync', + /** + * 报价单**双向价格传递**(2026-10-18 冻结契约 §2.1): + * · `POST {path}` → D1 我方(供应商)提交整单价给配送商审(不写价) + * · `GET {path}?status=&updated_since=&limit=` → D2 A 结果轮询 + B 提议拉取 + * · `POST {path}/:id/decision` → D3 我方对 B 的回执(approved/rejected,只改状态不写价) + * 设计:docs/design/20261018-报价单双向价格传递与审批.md + */ + quotePriceProposals: '/api/supplier/quote-sheets/price-proposals', + /** + * **SKU 映射**(2026-10-18 冻结契约 `.team/sku-mapping-shared-sheet/contract.md` §2.1): + * · `POST {path}/sync` → D4 我方把**自己的商品字典**整批推给配送侧(≤5000/批); + * · `GET {path}?main_branch_code=&status=&limit=` → D5 只读拉映射(映射在配送侧维护,我方不可编辑)。 + * 设计:docs/design/20261018-SKU映射与成本传递.md + */ + skuMappings: '/api/supplier/sku-mappings', } as const; export type MainSystemEndpoint = keyof typeof MAIN_SYSTEM_DEFAULT_PATHS; diff --git a/server/src/services/mainSystem/endpoints.ts b/server/src/services/mainSystem/endpoints.ts index 8f7255f..ca01cd4 100644 --- a/server/src/services/mainSystem/endpoints.ts +++ b/server/src/services/mainSystem/endpoints.ts @@ -36,6 +36,12 @@ function pathOverride(endpoint: MainSystemEndpoint): string | undefined { return process.env.MAIN_SYSTEM_REPORT_UPLOAD_PATH; case 'qualityReportRegister': return process.env.MAIN_SYSTEM_REPORT_REGISTER_PATH; + case 'quoteCostSync': + return process.env.MAIN_SYSTEM_QUOTE_COST_SYNC_PATH; + case 'quotePriceProposals': + return process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSALS_PATH; + case 'skuMappings': + return process.env.MAIN_SYSTEM_SKU_MAPPINGS_PATH; default: return undefined; } @@ -71,6 +77,28 @@ export function mainSystemBidPath(roundId?: string | null, tail?: 'quotes' | nul return tail === 'quotes' ? `${segment}/quotes` : segment; } +/** + * D3 回执的子路径:`{quotePriceProposals}/:id/decision`。 + * + * 只走 `mainSystemPath('quotePriceProposals')`(跟着端点表与 `MAIN_SYSTEM_QUOTE_PRICE_PROPOSALS_PATH` 覆盖走), + * 本函数是唯一拼这个子路径的地方;`id` 只做路径段转义(对方按它自己的 proposal id 收)。 + */ +export function mainSystemQuotePriceProposalDecisionPath(proposalId: string): string { + const base = mainSystemPath('quotePriceProposals').replace(/\/+$/, ''); + return `${base}/${encodeURIComponent(String(proposalId || '').trim())}/decision`; +} + +/** + * D4 商品字典同步的子路径:`{skuMappings}/sync`。 + * + * 只走 `mainSystemPath('skuMappings')`(跟随端点表与 `MAIN_SYSTEM_SKU_MAPPINGS_PATH` 覆盖); + * 本函数是唯一拼这个子路径的地方。 + */ +export function mainSystemSkuMappingSyncPath(): string { + const base = mainSystemPath('skuMappings').replace(/\/+$/, ''); + return `${base}/sync`; +} + /** 组装完整 URL(含 query;空值自动省略)。**唯一**允许拼主系统 URL 的函数。 */ export function buildMainSystemUrl(endpoint: MainSystemEndpoint, query?: MainSystemQuery): string { const base = mainSystemBaseUrl(); diff --git a/server/src/services/mainSystem/index.ts b/server/src/services/mainSystem/index.ts index a371b53..a8a462a 100644 --- a/server/src/services/mainSystem/index.ts +++ b/server/src/services/mainSystem/index.ts @@ -43,3 +43,15 @@ export type { SubmitPriceQtyRequestInput, SubmitPriceQtyRequestOutcome, } from './api/priceQty'; + +export { + normalizeQuoteCostSyncData, + readQuoteCostSyncErrorCode, + submitQuoteCostSync, +} from './api/quoteCostSync'; +export type { + QuoteCostSyncItemPayload, + QuoteCostSyncOutcome, + QuoteCostSyncRequestBody, + QuoteCostSyncResultData, +} from './api/quoteCostSync'; diff --git a/server/src/services/mainSystemQuoteCostSync.ts b/server/src/services/mainSystemQuoteCostSync.ts new file mode 100644 index 0000000..febb4ba --- /dev/null +++ b/server/src/services/mainSystemQuoteCostSync.ts @@ -0,0 +1,964 @@ +import { createHash, randomUUID } from 'node:crypto'; +import { pool } from '../db'; +import { runWithTenantDbContext } from './tenantDbContext'; +import { + submitQuoteCostSync, + type QuoteCostSyncFailure, + type QuoteCostSyncItemPayload, + type QuoteCostSyncOutcome, +} from './mainSystem/api/quoteCostSync'; + +/** + * 报价单销售价 → 主系统报价单成本价:**推送端**(我方推、主系统收)。 + * + * 设计:docs/design/20261018-报价单成本价同步推送.md(冻结契约 2026-10-18) + * + * 口径(做反就要返工): + * · 触发:报价单**审批生效之后**(`approval_status→30` 且 `status→1`),且必须**事务提交之后**; + * · 目标:该单绑定的客户里 `customer_code = MAIN_<主系统分公司码>` 的那个码 ⇒ **按分公司各推一次**; + * 非 `MAIN_` 形态(真实客户 / `__INDEPENDENT_INBOUND__` / `__RETAIL__` 哨兵)一律跳过,记 `not_usage_company`; + * · 内容:该单明细 `sku_code` / `unit` / `sale_price ?? price`,只推 `sale_price > 0` 的行; + * · 幂等:台账唯一键 `(quote_sheet_code, main_branch_code)` ⇒ 一张单 × 一个分公司只推一次; + * 重试**复用同一 `client_request_id`**(对方按请求号幂等);只有对方**明确回 409** 时才换新号; + * · 改价重推(R-2):重触发时若明细指纹变了 ⇒ 复用台账行 + 换新请求号 + attempts 归零 + 立即重推; + * 指纹没变 ⇒ 仍是 `duplicate` 零出站; + * · 出站:只走 `mainSystem/http.ts` + `mainSystem/api/quoteCostSync.ts`(不新造 HTTP 客户端、不拼 URL); + * · 开关:`MAIN_SYSTEM_QUOTE_COST_SYNC`(默认关)—— 关时**不查库、不出站**; + * · 事务纪律:**出网 HTTP 永远在数据库事务之外**;任何失败都不得冒泡到审批路径。 + */ + +/** + * 客户码 → 主系统分公司码(唯一形态;`__*__` 哨兵与真实客户都不匹配)。 + * 前缀 `MAIN_` **大小写不敏感**:客户档案里的 `main_br002` / `Main_BR002` 与 `MAIN_BR002` + * 是同一个"使用公司占位客户",不能因为前缀大小写被当成"非使用公司"跳过(A2)。 + */ +export const MAIN_BRANCH_CUSTOMER_RE = /^MAIN_([0-9A-Za-z_-]{1,32})$/i; + +/** 对方 `items` 硬上限(超过整单跳过,不做截断/分批:部分成功会让对账说不清) */ +export const QUOTE_COST_SYNC_MAX_ITEMS = 2000; + +/** 台账 `attempts` 上限:到这就不再加自动重试(等人工) */ +export const QUOTE_COST_SYNC_MAX_ATTEMPTS = 5; + +/** 整单级跳过用的伪分公司码(不是真实 MAIN_ 码,不会与真实行冲突) */ +const SHEET_LEVEL_BRANCH = '*'; + +function text(value: unknown): string { + return value === null || value === undefined ? '' : String(value).trim(); +} + +/** + * 总开关。默认关;`1` / `true` / `on`(大小写不敏感)为开。 + * + * ⚠️ 与 `mainSystemReportPushService.isReportPushEnabled()` 同款:直接读 `process.env`, + * 不经 `config.mainSystemIntegration` —— 这样"关"就是逐字节回到改造前。 + */ +export function isQuoteCostSyncEnabled(): boolean { + const raw = text(process.env.MAIN_SYSTEM_QUOTE_COST_SYNC).toLowerCase(); + return raw === '1' || raw === 'true' || raw === 'on'; +} + +/** + * 客户码 → 主系统分公司码(`MAIN_BR002` ⇒ `BR002`);非该形态返回 null。 + * 前缀大小写归一在 `MAIN_BRANCH_CUSTOMER_RE` 的 `i` 上,捕获组再 UPPER(对方分公司码是 `BRxxx`)。 + */ +export function parseMainBranchCode(customerCode: unknown): string | null { + const code = text(customerCode); + const match = MAIN_BRANCH_CUSTOMER_RE.exec(code); + return match ? match[1].toUpperCase() : null; +} + +/** 单位归一:trim 后 1~20 字符才带;否则带 null(对方按 `skus.unit` 比) */ +export function normalizeQuoteCostSyncUnit(unit: unknown): string | null { + const value = text(unit); + return value && value.length <= 20 ? value : null; +} + +/** 明细行售价:`sale_price ?? price`,只认有限且 > 0 的值;其余返回 null(记 `source_price_missing`) */ +export function readQuoteCostSyncSalePrice(row: { + sale_price?: unknown; + price?: unknown; +}): number | null { + const raw = row?.sale_price ?? row?.price; + if (raw === null || raw === undefined || raw === '') return null; + const value = Number(raw); + if (!Number.isFinite(value) || value <= 0) return null; + // 落库是 DECIMAL(10,2) ⇒ 这里按 2 位小数归一,保证同一份输入得到同一份 payload + return Math.round(value * 100) / 100; +} + +function isoOrNull(value: unknown): string | null { + if (value === null || value === undefined || value === '') return null; + const date = value instanceof Date ? value : new Date(String(value)); + return Number.isFinite(date.getTime()) ? date.toISOString() : null; +} + +export type QuoteCostSyncSkip = { + reason: string; + customer_code?: string; + sku_code?: string; + detail?: string; +}; + +export type QuoteCostSyncPlan = { + branchCode: string; + quoteSheetCode: string; + /** 报价单是否存在(不存在 ⇒ 整单跳过 `quote_sheet_not_found`) */ + sheetExists: boolean; + /** 是否是"生效中"的单(`approval_status=30 && status=1 && 未过期`) */ + isActive: boolean; + /** 仅溯源:`effective_at ?? approved_at` */ + activatedAt: string | null; + /** 该单绑定的全部客户码(原样) */ + customerCodes: string[]; + /** `MAIN_` 解析出的主系统分公司码(去重、升序) */ + mainBranchCodes: string[]; + supplierCode: string | null; + /** 要推的明细(已过滤 `sale_price > 0`) */ + items: QuoteCostSyncItemPayload[]; + /** 本地跳过明细(审计/排障用;对方回执里的 skipped 另存) */ + skipped: QuoteCostSyncSkip[]; + /** 过滤前的明细行数(超限判断与留痕) */ + itemRowCount: number; +}; + +export type QuoteCostSyncPushRowResult = { + mainBranchCode: string; + /** duplicate = 台账已有行(一张单一个分公司只推一次,重试交给定时任务) */ + status: 'sent' | 'failed' | 'forbidden' | 'skipped' | 'duplicate'; + clientRequestId?: string; + error?: string; + replayed?: boolean; +}; + +export type QuoteCostSyncPushSummary = { + branchCode: string; + quoteSheetCode: string; + /** 本次**首次**落台账并出站的分公司数 */ + attempted: number; + sent: number; + failed: number; + forbidden: number; + skipped: number; + /** 台账已有行而未出站的数(幂等命中) */ + duplicates: number; + /** 明细变了 ⇒ 复用台账行换新请求号后**重推**的数(R-2) */ + rearmed: number; + /** 一张单多个客户同名分公司时的明细条数(排障用) */ + itemCount: number; + results: QuoteCostSyncPushRowResult[]; + error?: string; +}; + +function emptySummary(branchCode = '', quoteSheetCode = ''): QuoteCostSyncPushSummary { + return { + branchCode, + quoteSheetCode, + attempted: 0, + sent: 0, + failed: 0, + forbidden: 0, + skipped: 0, + duplicates: 0, + rearmed: 0, + itemCount: 0, + results: [], + }; +} + +/** + * 该分公司在主系统的**供应商编码**(换 token 用): + * ① `public.main_supplier_bindings`(active,权威在主系统侧,镜像在此)优先; + * ② 退到 `public.branches.main_supplier_code`(超管手工登记 / 历史回填)。 + * 两者都空 ⇒ `null`(调用方记 failed,等人工补绑定)。 + */ +export async function resolveMainSupplierCode(branchCode: string): Promise { + const result = await pool.query<{ code: string | null }>( + `SELECT COALESCE( + (SELECT NULLIF(TRIM(main_supplier_code), '') + FROM public.main_supplier_bindings + WHERE branch_code = $1 AND status = 'active' + AND NULLIF(TRIM(main_supplier_code), '') IS NOT NULL + ORDER BY bound_at DESC + LIMIT 1), + (SELECT NULLIF(TRIM(main_supplier_code), '') + FROM public.branches + WHERE branch_code = $1), + NULL + ) AS code`, + [branchCode] + ); + return text(result.rows[0]?.code) || null; +} + +/** + * 采集"该推什么":报价单(必须生效中)→ 绑定客户 → `MAIN_` 分公司 → 明细。 + * + * ⚠️ 只读;必须在**租户上下文**内调用(报价单三张表在租户 schema 里)。 + */ +export async function collectQuoteCostSyncPlan(input: { + branchCode: string; + quoteSheetCode: string; +}): Promise { + const branchCode = text(input.branchCode); + const quoteSheetCode = text(input.quoteSheetCode); + const plan: QuoteCostSyncPlan = { + branchCode, + quoteSheetCode, + sheetExists: false, + isActive: false, + activatedAt: null, + customerCodes: [], + mainBranchCodes: [], + supplierCode: null, + items: [], + skipped: [], + itemRowCount: 0, + }; + if (!branchCode || !quoteSheetCode) return plan; + + const sheetResult = await pool.query<{ + quote_sheet_code: string; + branch_code: string | null; + status: number; + approval_status: number; + approved_at: Date | null; + effective_at: Date | null; + expires_at: Date | null; + }>( + `SELECT quote_sheet_code, branch_code, status, approval_status, approved_at, effective_at, expires_at + FROM customer_quote_sheets + WHERE quote_sheet_code = $1`, + [quoteSheetCode] + ); + const sheet = sheetResult.rows[0]; + if (!sheet) return plan; + plan.sheetExists = true; + plan.activatedAt = isoOrNull(sheet.effective_at ?? sheet.approved_at); + plan.isActive = + Number(sheet.approval_status) === 30 && + Number(sheet.status) === 1 && + (!sheet.expires_at || new Date(sheet.expires_at).getTime() > Date.now()); + + const [customersResult, itemsResult, supplierCode] = await Promise.all([ + pool.query<{ customer_code: string }>( + `SELECT customer_code FROM customer_quote_sheet_customers + WHERE quote_sheet_code = $1 + ORDER BY customer_code ASC`, + [quoteSheetCode] + ), + pool.query<{ sku_code: string; unit: string | null; sale_price: string | null; price: string | null }>( + `SELECT sku_code, unit, sale_price, price + FROM customer_quote_sheet_items + WHERE quote_sheet_code = $1 + ORDER BY sort_order ASC, sku_code ASC`, + [quoteSheetCode] + ), + resolveMainSupplierCode(branchCode), + ]); + plan.supplierCode = supplierCode; + + const mainBranchCodes = new Set(); + for (const row of customersResult.rows) { + const customerCode = text(row.customer_code); + if (!customerCode) continue; + plan.customerCodes.push(customerCode); + const mainBranchCode = parseMainBranchCode(customerCode); + if (mainBranchCode) mainBranchCodes.add(mainBranchCode); + else plan.skipped.push({ reason: 'not_usage_company', customer_code: customerCode }); + } + plan.mainBranchCodes = [...mainBranchCodes].sort(); + + for (const row of itemsResult.rows) { + const skuCode = text(row.sku_code); + if (!skuCode) continue; + plan.itemRowCount += 1; + const salePrice = readQuoteCostSyncSalePrice(row); + if (salePrice === null) { + plan.skipped.push({ reason: 'source_price_missing', sku_code: skuCode }); + continue; + } + plan.items.push({ + sku_code: skuCode, + unit: normalizeQuoteCostSyncUnit(row.unit), + sale_price: salePrice, + }); + } + return plan; +} + +/** 写一条台账(唯一键命中则忽略;返回是否真的插入) */ +async function insertLedger(input: { + branchCode: string; + quoteSheetCode: string; + mainBranchCode: string; + clientRequestId: string; + status: 'pending' | 'failed' | 'skipped'; + lastError?: string | null; + response?: unknown; +}): Promise<{ id: string; clientRequestId: string } | null> { + const result = await pool.query<{ id: string; client_request_id: string }>( + `INSERT INTO public.main_system_quote_cost_pushes + (branch_code, quote_sheet_code, main_branch_code, client_request_id, status, last_error, response) + VALUES ($1, $2, $3, $4::uuid, $5::varchar, $6::text, $7::jsonb) + ON CONFLICT (quote_sheet_code, main_branch_code) DO NOTHING + RETURNING id::text AS id, client_request_id::text AS client_request_id`, + [ + input.branchCode, + input.quoteSheetCode, + input.mainBranchCode, + input.clientRequestId, + input.status, + input.lastError ?? null, + input.response === undefined || input.response === null ? null : JSON.stringify(input.response), + ] + ); + const row = result.rows[0]; + if (!row) return null; + return { id: String(row.id), clientRequestId: String(row.client_request_id) }; +} + +/** 回写台账结果(attempts 每次出站都 +1,成功也计数) */ +async function markLedger( + id: string, + patch: { + status: 'sent' | 'failed' | 'forbidden' | 'skipped'; + lastError?: string | null; + response?: unknown; + } +): Promise { + await pool.query( + `UPDATE public.main_system_quote_cost_pushes + SET status = $2::varchar, + attempts = attempts + 1, + last_error = $3::text, + response = $4::jsonb, + updated_at = NOW() + WHERE id = $1::uuid`, + [ + id, + patch.status, + patch.lastError ?? null, + patch.response === undefined || patch.response === null ? null : JSON.stringify(patch.response), + ] + ); +} + +/** + * 明细指纹:只跟"会发出去的内容"有关(`sku_code` / `unit` / `sale_price`,按 sku+unit 排序后 sha256)。 + * + * 用途(R-2):重触发时拿它跟台账里**最近一次推送的指纹**比对 —— 变了才换号重推,没变仍然零出站。 + * 排序是为了让"只是明细顺序变了"不算改价(payload 语义与顺序无关)。 + */ +export function quoteCostSyncItemsFingerprint(items: QuoteCostSyncItemPayload[]): string { + const canonical = (items || []) + .map((item) => [ + String(item?.sku_code || ''), + item?.unit === null || item?.unit === undefined ? '' : String(item.unit), + (Number(item?.sale_price) || 0).toFixed(2), + ]) + .sort((a, b) => { + if (a[0] !== b[0]) return a[0] < b[0] ? -1 : 1; + if (a[1] !== b[1]) return a[1] < b[1] ? -1 : 1; + return a[2] < b[2] ? -1 : a[2] > b[2] ? 1 : 0; + }); + return createHash('sha256').update(JSON.stringify(canonical)).digest('hex'); +} + +/** 本地跳过明细(截断,避免 2000 行零价把回执撑大;计数另给)+ 明细指纹 */ +function localTrace( + plan: QuoteCostSyncPlan, + extra?: Record +): Record { + const counts: Record = {}; + for (const row of plan.skipped) counts[row.reason] = (counts[row.reason] || 0) + 1; + return { + skipped_counts: counts, + skipped: plan.skipped.slice(0, 50), + item_row_count: plan.itemRowCount, + pushed_item_count: plan.items.length, + items_fingerprint: quoteCostSyncItemsFingerprint(plan.items), + ...(extra || {}), + }; +} + +/** 台账里"一张单 × 一个分公司"的当前快照(判重 / 改价重推都以它为准) */ +type LedgerSnapshot = { + id: string; + status: string; + attempts: number; + clientRequestId: string; + response: unknown; +}; + +async function readLedgerRow( + quoteSheetCode: string, + mainBranchCode: string +): Promise { + const result = await pool.query<{ + id: string; + status: string; + attempts: number; + client_request_id: string; + response: unknown; + }>( + `SELECT id::text AS id, + status, + attempts, + client_request_id::text AS client_request_id, + response + FROM public.main_system_quote_cost_pushes + WHERE quote_sheet_code = $1 AND main_branch_code = $2`, + [quoteSheetCode, mainBranchCode] + ); + const row = result.rows[0]; + if (!row) return null; + return { + id: String(row.id), + status: String(row.status), + attempts: Number(row.attempts) || 0, + clientRequestId: String(row.client_request_id), + response: row.response, + }; +} + +/** 台账里**最近一次推送**的明细指纹(没有记录 ⇒ null:老行/未推送过,按"不确定"处理,不动它) */ +export function readPushedFingerprint(response: unknown): string | null { + const local = (response as { local?: unknown } | null)?.local; + if (!local || typeof local !== 'object') return null; + const value = (local as Record).items_fingerprint; + return typeof value === 'string' && value ? value : null; +} + +/** 对方是否**明确回 409** 幂等冲突(只有这一条路径允许换请求号) */ +function isPayloadConflict(outcome: QuoteCostSyncOutcome): outcome is QuoteCostSyncFailure { + return outcome.kind === 'rejected' && Number(outcome.status) === 409; +} + +/** + * R-2 ①:对方明确回 409 ⇒ 该台账行**换新请求号**、`attempts=0`、`status='failed'`,下一轮重试用新号。 + * + * 为什么只在这一条路径换号:换号会让对方"全新的请求",若在超时/5xx/网络故障时也换号, + * 就可能把"对方其实已受理的旧请求"再写一次(重复写成本价)。409 则相反:对方明确说这个号已用于**别的内容**, + * 不换号就永远推不出去。 + */ +async function rotateLedgerRequestId(id: string, detail: string): Promise { + const result = await pool.query<{ client_request_id: string }>( + `UPDATE public.main_system_quote_cost_pushes + SET client_request_id = $2::uuid, + attempts = 0, + status = 'failed', + last_error = 'payload_changed_rotate_id', + response = COALESCE(response, '{}'::jsonb) + || jsonb_build_object('last_conflict_409', $3::text), + updated_at = NOW() + WHERE id = $1::uuid + RETURNING client_request_id::text AS client_request_id`, + [id, randomUUID(), detail] + ); + const row = result.rows[0]; + return row ? String(row.client_request_id) : null; +} + +/** + * R-2 ②:明细变了 ⇒ 复用现有台账行、**换新请求号**、`attempts` 归零、重新入队(`status='pending'`), + * 并打上 `response.local.sheet_reason='rearmed_after_change'`。 + * + * 为什么必须换号:旧号在对方那儿已经绑定了旧 payload,继续用同一号重放只会一直 409。 + */ +async function rearmLedger( + id: string, + fingerprint: string +): Promise<{ id: string; clientRequestId: string } | null> { + const result = await pool.query<{ id: string; client_request_id: string }>( + `UPDATE public.main_system_quote_cost_pushes + SET client_request_id = $2::uuid, + attempts = 0, + status = 'pending', + last_error = 'rearmed_after_change', + response = COALESCE(response, '{}'::jsonb) + || jsonb_build_object( + 'local', + COALESCE(response->'local', '{}'::jsonb) + || jsonb_build_object( + 'sheet_reason', 'rearmed_after_change', + 'items_fingerprint', $3::text + ) + ), + updated_at = NOW() + WHERE id = $1::uuid + RETURNING id::text AS id, client_request_id::text AS client_request_id`, + [id, randomUUID(), fingerprint] + ); + const row = result.rows[0]; + if (!row) return null; + return { id: String(row.id), clientRequestId: String(row.client_request_id) }; +} + +/** 出站结果 → 台账状态 */ +function mapOutcome(outcome: QuoteCostSyncOutcome): { + status: 'sent' | 'failed' | 'forbidden'; + lastError: string | null; + response?: unknown; +} { + if (outcome.kind === 'ok') { + return { status: 'sent', lastError: null, response: { data: outcome.data } }; + } + const detail = `${outcome.code}: ${outcome.reason}`.trim(); + if (outcome.kind === 'rejected' && Number(outcome.status) === 403) { + return { status: 'forbidden', lastError: detail }; + } + return { status: 'failed', lastError: detail }; +} + +function countByStatus(summary: QuoteCostSyncPushSummary, row: QuoteCostSyncPushRowResult): void { + summary.results.push(row); + if (row.status === 'duplicate') summary.duplicates += 1; + else summary.attempted += 1; + if (row.status === 'sent') summary.sent += 1; + else if (row.status === 'failed') summary.failed += 1; + else if (row.status === 'forbidden') summary.forbidden += 1; + else if (row.status === 'skipped') summary.skipped += 1; +} + +/** + * 单分公司:判重 → (必要时换号重推)→ 落 pending → 出站 → 回写。 + * + * 判重口径(R-2 ②): + * · 台账无行 ⇒ 正常首推; + * · 台账有行且**明细指纹与最近一次推送一致** ⇒ `duplicate`(幂等,零出站); + * · 台账有行但**指纹变了**(改价后再触发)⇒ 复用该行 + 换新请求号 + attempts 归零 + 立即重推; + * · 台账有行但**没有指纹记录**(理论上只有升级前的行/从未推送过的行)⇒ 按 `duplicate` 保守处理, + * 交给定时重试(`failed && attempts<5` / 卡住的 `pending`)去收口。 + */ +async function pushOneBranch(input: { + plan: QuoteCostSyncPlan; + mainBranchCode: string; + existing: LedgerSnapshot | null; +}): Promise<{ row: QuoteCostSyncPushRowResult; rearmed: boolean }> { + const { plan, mainBranchCode, existing } = input; + const fingerprint = quoteCostSyncItemsFingerprint(plan.items); + let ledger: { id: string; clientRequestId: string }; + let rearmed = false; + + if (existing) { + const previousFingerprint = readPushedFingerprint(existing.response); + if (!previousFingerprint || previousFingerprint === fingerprint) { + // 一张单 × 一个分公司只推一次(失败重试由 scheduledJobs 负责,不在这里推) + return { row: { mainBranchCode, status: 'duplicate' }, rearmed: false }; + } + const rearmedRow = await rearmLedger(existing.id, fingerprint); + if (!rearmedRow) return { row: { mainBranchCode, status: 'duplicate' }, rearmed: false }; + ledger = rearmedRow; + rearmed = true; + } else { + const clientRequestId = randomUUID(); + const inserted = await insertLedger({ + branchCode: plan.branchCode, + quoteSheetCode: plan.quoteSheetCode, + mainBranchCode, + clientRequestId, + status: 'pending', + response: { local: localTrace(plan) }, + }); + if (!inserted) { + // 并发下被别人抢先插入(唯一键命中)⇒ 按幂等命中处理 + return { row: { mainBranchCode, status: 'duplicate' }, rearmed: false }; + } + ledger = inserted; + } + + const local = localTrace(plan, rearmed ? { sheet_reason: 'rearmed_after_change' } : undefined); + + let outcome: QuoteCostSyncOutcome; + try { + outcome = await submitQuoteCostSync({ + supplierCode: String(plan.supplierCode || ''), + body: { + client_request_id: ledger.clientRequestId, + supplier_quote_sheet_code: plan.quoteSheetCode, + main_branch_code: mainBranchCode, + ...(plan.activatedAt ? { activated_at: plan.activatedAt } : {}), + items: plan.items, + }, + }); + } catch (error: any) { + // 出站层抛了未预期异常:也必须把 pending 收口成 failed(否则这行永远停在 pending、不会重试) + const message = `exception: ${String(error?.message || error)}`; + await markLedger(ledger.id, { status: 'failed', lastError: message, response: { local } }); + return { + row: { mainBranchCode, status: 'failed', clientRequestId: ledger.clientRequestId, error: message }, + rearmed, + }; + } + + if (isPayloadConflict(outcome)) { + // 对方明确说"这个请求号已用于别的内容" ⇒ 换号交给下一轮(换号后重放安全:全新请求) + await rotateLedgerRequestId(ledger.id, `${outcome.code}: ${outcome.reason}`.trim()); + return { + row: { + mainBranchCode, + status: 'failed', + clientRequestId: ledger.clientRequestId, + error: 'payload_changed_rotate_id', + }, + rearmed, + }; + } + + const mapped = mapOutcome(outcome); + const response = + mapped.response && typeof mapped.response === 'object' + ? { ...(mapped.response as Record), local } + : { local }; + await markLedger(ledger.id, { ...mapped, response }); + return { + row: { + mainBranchCode, + status: mapped.status, + clientRequestId: ledger.clientRequestId, + error: mapped.lastError ?? undefined, + replayed: outcome.kind === 'ok' ? outcome.data.replayed : undefined, + }, + rearmed, + }; +} + +/** 整单级跳过:写一行 `main_branch_code = '*'` 的台账(唯一键保证只写一次) */ +async function recordSheetSkip(plan: QuoteCostSyncPlan, reason: string, detail?: string): Promise { + const inserted = await insertLedger({ + branchCode: plan.branchCode, + quoteSheetCode: plan.quoteSheetCode, + mainBranchCode: SHEET_LEVEL_BRANCH, + clientRequestId: randomUUID(), + status: 'skipped', + lastError: detail ? `${reason}: ${detail}` : reason, + response: { local: { ...localTrace(plan), sheet_reason: reason } }, + }); + return Boolean(inserted); +} + +/** + * 推送一张报价单(**事务提交之后**调用;内部自带租户上下文 + 全量吞异常)。 + * + * `isolate + requestClient:false`:不复用调用方(请求)的数据库连接 —— + * 本函数是**旁路异步**的,请求结束后请求级连接会被归还,再借到它就是踩已释放连接。 + */ +export async function pushQuoteCostSyncForSheet(input: { + branchCode?: string | null; + quoteSheetCode?: string | null; +}): Promise { + const branchCode = text(input?.branchCode); + const quoteSheetCode = text(input?.quoteSheetCode); + const summary = emptySummary(branchCode, quoteSheetCode); + if (!isQuoteCostSyncEnabled()) return summary; + if (!branchCode || !quoteSheetCode) return summary; + + try { + return await runWithTenantDbContext( + branchCode, + async () => { + const plan = await collectQuoteCostSyncPlan({ branchCode, quoteSheetCode }); + summary.itemCount = plan.items.length; + if (!plan.sheetExists) { + summary.skipped += 1; + summary.results.push({ mainBranchCode: SHEET_LEVEL_BRANCH, status: 'skipped', error: 'quote_sheet_not_found' }); + return summary; + } + if (!plan.isActive) { + // 已驳回/已停用/已被新版取代/已过期:不推(成本价不该由一张失效单决定) + const inserted = await recordSheetSkip(plan, 'quote_sheet_not_active'); + if (inserted) { + summary.skipped += 1; + summary.results.push({ + mainBranchCode: SHEET_LEVEL_BRANCH, + status: 'skipped', + error: 'quote_sheet_not_active', + }); + } + return summary; + } + if (!plan.mainBranchCodes.length) { + // 全单没有 MAIN_ 客户(真实客户/哨兵)⇒ 记 skipped,零出站 + const inserted = await recordSheetSkip(plan, 'not_usage_company'); + if (inserted) { + summary.skipped += 1; + summary.results.push({ + mainBranchCode: SHEET_LEVEL_BRANCH, + status: 'skipped', + error: 'not_usage_company', + }); + } + return summary; + } + if (!plan.items.length) { + const inserted = await recordSheetSkip(plan, 'no_pushable_items'); + if (inserted) { + summary.skipped += 1; + summary.results.push({ + mainBranchCode: SHEET_LEVEL_BRANCH, + status: 'skipped', + error: 'no_pushable_items', + }); + } + return summary; + } + if (plan.items.length > QUOTE_COST_SYNC_MAX_ITEMS) { + // 对方硬限 2000:整单跳过,绝不截断成"部分同步" + const inserted = await recordSheetSkip( + plan, + 'too_many_items', + `可推行 ${plan.items.length} > 对方上限 ${QUOTE_COST_SYNC_MAX_ITEMS}` + ); + if (inserted) { + summary.skipped += 1; + summary.results.push({ + mainBranchCode: SHEET_LEVEL_BRANCH, + status: 'skipped', + error: 'too_many_items', + }); + } + return summary; + } + + for (const mainBranchCode of plan.mainBranchCodes) { + if (!plan.supplierCode) { + // 没有供应商编码 ⇒ 换不到 token,落 failed 等人工补绑定(不在这里瞎猜编码) + const ledger = await insertLedger({ + branchCode: plan.branchCode, + quoteSheetCode: plan.quoteSheetCode, + mainBranchCode, + clientRequestId: randomUUID(), + status: 'failed', + lastError: 'main_supplier_code_missing: 该分公司在主系统没有可用供应商编码', + response: { local: localTrace(plan) }, + }); + if (ledger) { + countByStatus(summary, { + mainBranchCode, + status: 'failed', + error: 'main_supplier_code_missing', + }); + } else { + countByStatus(summary, { mainBranchCode, status: 'duplicate' }); + } + continue; + } + try { + // 判重 / 改价重推都以台账里"该单 × 该分公司"那一行为准(R-2 ②) + const existing = await readLedgerRow(plan.quoteSheetCode, mainBranchCode); + const result = await pushOneBranch({ plan, mainBranchCode, existing }); + if (result.rearmed) summary.rearmed += 1; + countByStatus(summary, result.row); + } catch (error: any) { + // 单分公司异常不得中断其它分公司 + summary.failed += 1; + summary.attempted += 1; + summary.results.push({ + mainBranchCode, + status: 'failed', + error: String(error?.message || error), + }); + console.warn( + `[quote-cost-sync] 推送异常(${plan.quoteSheetCode} → ${mainBranchCode}):`, + error?.message || error + ); + } + } + return summary; + }, + { isolate: true, requestClient: false } + ); + } catch (error: any) { + // 绝不能冒泡:审批路径不因推送失败而失败 + summary.error = String(error?.message || error); + console.warn('[quote-cost-sync] 推送整体失败(已吞,不影响审批):', error?.message || error); + return summary; + } +} + +/** + * 触发点入口(旁路异步,绝不阻塞调用方):报价单审批生效(`COMMIT` 之后)调它。 + * 关闭开关 / 空参数 ⇒ 立即返回(零出站、零查库)。 + */ +export function triggerQuoteCostSync(input: { + branchCode?: string | null; + quoteSheetCode?: string | null; +}): void { + try { + if (!isQuoteCostSyncEnabled()) return; + const branchCode = text(input?.branchCode); + const quoteSheetCode = text(input?.quoteSheetCode); + if (!branchCode || !quoteSheetCode) return; + void pushQuoteCostSyncForSheet({ branchCode, quoteSheetCode }).catch((error: any) => { + console.warn('[quote-cost-sync] 触发推送失败(已吞,不影响主流程):', error?.message || error); + }); + } catch (error: any) { + console.warn('[quote-cost-sync] 触发入口异常(已吞,不影响主流程):', error?.message || error); + } +} + +export type QuoteCostSyncRetryRow = { + id: string; + branch_code: string; + quote_sheet_code: string; + main_branch_code: string; + client_request_id: string; + attempts: number; + /** 选中时的状态:failed(可重试失败)或 pending(卡住超过 10 分钟) */ + status?: string; +}; + +export type QuoteCostSyncRetrySummary = { + /** 本轮选中的台账行数 */ + rows: number; + attempted: number; + sent: number; + failed: number; + forbidden: number; + skipped: number; + /** 单行处理抛错(不影响其它行) */ + errors: number; +}; + +/** + * 一条待重试行:重建 payload(可能已变)→ 用**原 `client_request_id`** 重放。 + * 唯一例外:对方明确回 409(同号不同内容)⇒ 换新号、attempts 归零,下一轮用新号(R-2 ①)。 + */ +async function retryOneRow(row: QuoteCostSyncRetryRow): Promise< + 'sent' | 'failed' | 'forbidden' | 'skipped' +> { + return runWithTenantDbContext( + row.branch_code, + async () => { + const plan = await collectQuoteCostSyncPlan({ + branchCode: row.branch_code, + quoteSheetCode: row.quote_sheet_code, + }); + const finish = async ( + status: 'sent' | 'failed' | 'forbidden' | 'skipped', + lastError: string | null, + response?: unknown + ): Promise<'sent' | 'failed' | 'forbidden' | 'skipped'> => { + await markLedger(row.id, { status, lastError, response }); + return status; + }; + + if (!plan.sheetExists) return finish('skipped', 'quote_sheet_not_found'); + if (!plan.isActive) return finish('skipped', 'quote_sheet_not_active'); + if (!plan.mainBranchCodes.includes(text(row.main_branch_code).toUpperCase())) { + // 客户绑定被撤掉(或改绑到别的分公司)⇒ 这条永远推不出去了 + return finish('skipped', 'main_branch_customer_removed'); + } + if (!plan.items.length) return finish('skipped', 'no_pushable_items'); + if (plan.items.length > QUOTE_COST_SYNC_MAX_ITEMS) { + return finish('skipped', 'too_many_items'); + } + if (!plan.supplierCode) { + return finish('failed', 'main_supplier_code_missing: 该分公司在主系统没有可用供应商编码'); + } + + const outcome = await submitQuoteCostSync({ + supplierCode: plan.supplierCode, + body: { + client_request_id: row.client_request_id, + supplier_quote_sheet_code: row.quote_sheet_code, + main_branch_code: row.main_branch_code, + ...(plan.activatedAt ? { activated_at: plan.activatedAt } : {}), + items: plan.items, + }, + }); + if (isPayloadConflict(outcome)) { + // 同号不同内容 ⇒ 换号(不消耗 attempts:归零后下一轮用新号重试) + await rotateLedgerRequestId(row.id, `${outcome.code}: ${outcome.reason}`.trim()); + return 'failed'; + } + const mapped = mapOutcome(outcome); + const response = + mapped.response && typeof mapped.response === 'object' + ? { ...(mapped.response as Record), local: localTrace(plan), retried: true } + : { local: localTrace(plan), retried: true }; + return finish(mapped.status, mapped.lastError, response); + }, + { isolate: true, requestClient: false } + ); +} + +/** + * 定时重试:**两类**待收口台账行,都**复用原 `client_request_id`** 重放。 + * + * ① `status='failed' AND attempts < 5`(普通失败); + * ② `status='pending' AND updated_at < NOW() - INTERVAL '10 minutes'`(R-1:进程在 + * "台账已落、结果未回写"之间被杀会留下永久 pending,唯一键还会挡住以后所有推送; + * 重放是安全的 —— 若对方其实已受理,会按请求号回放;没受理则正常执行)。 + * + * - 开关关 ⇒ 立即返回(连台账都不查); + * - `forbidden` / `sent` / `skipped` 永不选中(绑定不成立的单重试也不会成立); + * - 单行失败只记日志(`errors`),不中断其它行(失败重试不得阻塞其它任务)。 + */ +export async function retryQuoteCostSyncPushes(options?: { + limit?: number; +}): Promise { + const summary: QuoteCostSyncRetrySummary = { + rows: 0, + attempted: 0, + sent: 0, + failed: 0, + forbidden: 0, + skipped: 0, + errors: 0, + }; + if (!isQuoteCostSyncEnabled()) return summary; + + const limit = Math.min(Math.max(Number(options?.limit) || 20, 1), 100); + const result = await pool.query( + `SELECT id::text AS id, + branch_code, + quote_sheet_code, + main_branch_code, + client_request_id::text AS client_request_id, + attempts, + status + FROM public.main_system_quote_cost_pushes + WHERE (status = 'failed' AND attempts < $1::int) + OR (status = 'pending' AND updated_at < NOW() - INTERVAL '10 minutes') + ORDER BY updated_at ASC + LIMIT $2::int`, + [QUOTE_COST_SYNC_MAX_ATTEMPTS, limit] + ); + + for (const row of result.rows) { + summary.rows += 1; + summary.attempted += 1; + try { + const status = await retryOneRow(row); + if (status === 'sent') summary.sent += 1; + else if (status === 'failed') summary.failed += 1; + else if (status === 'forbidden') summary.forbidden += 1; + else summary.skipped += 1; + } catch (error: any) { + summary.errors += 1; + console.warn( + `[quote-cost-sync] 重试异常(${row.quote_sheet_code} → ${row.main_branch_code}):`, + error?.message || error + ); + // 异常也要消耗一次尝试次数,否则同一行会在每轮里无限重试(attempts 不涨 ⇒ 永远选中) + try { + await pool.query( + // pending 行重试时抛错 ⇒ 一并收口成 failed,让它回到 `attempts<5` 的闸门内 + // (pending 的选中条件只看"卡住多久",不收口会被无限重试下去) + `UPDATE public.main_system_quote_cost_pushes + SET attempts = attempts + 1, + status = CASE WHEN status = 'pending' THEN 'failed' ELSE status END, + last_error = $2::text, + updated_at = NOW() + WHERE id = $1::uuid`, + [row.id, `retry_exception: ${String(error?.message || error)}`] + ); + } catch { + /* 记账失败只能下轮再说,不得影响其它行 */ + } + } + } + return summary; +} diff --git a/server/src/services/quotePriceProposalService.ts b/server/src/services/quotePriceProposalService.ts new file mode 100644 index 0000000..93a03f9 --- /dev/null +++ b/server/src/services/quotePriceProposalService.ts @@ -0,0 +1,1397 @@ +import { createHash, randomUUID } from 'node:crypto'; +import { pool } from '../db'; +import { runWithTenantDbContext } from './tenantDbContext'; +import { getEffectiveBranchCode, type TenantContext } from './tenantScope'; +import { + applyQuoteSheetUpdate, + loadQuoteSheetForUpdate, + type QuoteSheetItemInput, +} from './quoteSheetService'; +import { + quoteCostSyncItemsFingerprint, + resolveMainSupplierCode, +} from './mainSystemQuoteCostSync'; +import { + decideQuotePriceProposal, + listQuotePriceProposals, + submitQuotePriceProposal, + type QuotePriceProposalItemPayload, + type RemoteQuotePriceProposalRow, +} from './mainSystem/api/quotePriceProposals'; +import { writeAuditLog } from './auditService'; +import { getMappingByDeliverySku, getSheetMappingStats } from './skuMappingService'; + +/** + * 报价单**双向价格传递**(2026-10-18 冻结契约)。 + * + * 两个方向(同一个数 V = 我方 `sale_price` = 配送商 `cost_price`): + * · **A `to_delivery`**:我方把整张单的价交配送商审 —— 走 D1 建对方 pending(**不写价**); + * 结果用 D2 轮询回写本地状态; + * · **B `from_delivery`**:配送商发起的成本价提议 —— 用 D2 拉回(本地建 pending),我方审: + * 通过 ⇒ 写本单 `sale_price`(复用 `applyQuoteSheetUpdate`,整单一次、缺 SKU 跳过并记录) + * ⇒ **D3 回执 `approved`(带 applied)由配送侧用配送 SKU 落地写价**(不再走旧成本同步推送); + * 驳回 ⇒ D3 回执 `rejected` + 理由,**不写价**。 + * + * 纪律(前几轮踩过): + * · 出站 HTTP **永远在事务之外**;B 审批路径**不调** `triggerQuoteCostSync`(由配送侧按 D3 落地); + * · 台账 `main_system_quote_cost_pushes` 的唯一键/rearm 已存在 —— 本层**不重造推送、不直接写台账**; + * · `quote_sheet_change_requests`(内部改价审核)与 `quote_price_proposals`(对外传递)是**两层**,不合并; + * A 发起只检查"内部是否有在途 pending"; + * · 开关 `MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL` 默认关 ⇒ 零出站、零写库(路由 503)。 + * + * 设计:docs/design/20261018-报价单双向价格传递与审批.md + */ + +export const MAX_PROPOSAL_ITEMS = 2000; +export const MAX_PROPOSAL_PRICE = 9_999_999.99; + +/** 开关:默认关;`1` / `true` / `on`(大小写不敏感)才开 */ +export function isQuotePriceProposalEnabled(): boolean { + const raw = String(process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL ?? '').trim().toLowerCase(); + return raw === '1' || raw === 'true' || raw === 'on'; +} + +function httpError(status: number, code: string, message: string) { + return Object.assign(new Error(message), { status, code }); +} + +function toText(value: unknown): string { + return value === null || value === undefined ? '' : String(value).trim(); +} + +function roundPrice(value: unknown): number { + const num = Number(value); + if (!Number.isFinite(num)) return 0; + return Math.round(num * 100) / 100; +} + +/** 我方明细行的价(`sale_price ?? price`),按 2 位小数归一 */ +function readSheetPrice(row: Record): number { + return roundPrice(row.sale_price ?? row.price); +} + +/** 明细指纹(复用成本价同步同一算法,便于排障比对) */ +function proposalPayloadHash(input: { + quoteSheetCode: string; + mainBranchCode: string; + note: string | null; + items: QuotePriceProposalItemPayload[]; +}): string { + const items = [...input.items] + .map((item) => [item.sku_code, item.unit || '', Number(item.price).toFixed(2)]) + .sort((a, b) => (a[0] === b[0] ? (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0) : a[0] < b[0] ? -1 : 1)); + return createHash('sha256') + .update( + JSON.stringify({ + sheet: input.quoteSheetCode, + branch: input.mainBranchCode, + note: input.note || '', + items, + }) + ) + .digest('hex'); +} + +function assertProposalItems(items: QuotePriceProposalItemPayload[]): void { + if (!Array.isArray(items) || !items.length) { + throw httpError(400, 'items_required', '没有可提交的商品行'); + } + if (items.length > MAX_PROPOSAL_ITEMS) { + throw httpError(400, 'too_many_items', `商品行超过上限 ${MAX_PROPOSAL_ITEMS}`); + } + const seen = new Set(); + for (const item of items) { + const code = toText(item.sku_code); + if (!code) throw httpError(400, 'invalid_item', '商品行缺少 sku_code'); + if (seen.has(code)) throw httpError(400, 'duplicate_sku', `同一商品重复出现:${code}`); + seen.add(code); + if (!(Number(item.price) > 0) || Number(item.price) > MAX_PROPOSAL_PRICE) { + throw httpError(400, 'invalid_price', `商品 ${code} 的价格不合法`); + } + } +} + +/** 客户绑定的主系统分公司码(`MAIN_`) */ +export function parseMainBranchCodes(customerCodes: string[]): string[] { + const codes = new Set(); + for (const raw of customerCodes || []) { + const match = /^MAIN_([0-9A-Za-z_-]{1,32})$/i.exec(toText(raw)); + if (match) codes.add(match[1].toUpperCase()); + } + return [...codes].sort(); +} + +/* ── 本地台账读取 ───────────────────────────────────────────────────────── */ + +export type QuotePriceProposalDto = { + id: string; + branch_code: string; + quote_sheet_code: string; + main_branch_code: string; + direction: 'to_delivery' | 'from_delivery'; + items: QuotePriceProposalItemPayload[]; + payload_hash: string | null; + status: 'pending' | 'approved' | 'rejected' | 'cancelled' | 'superseded'; + reject_reason: string | null; + client_request_id: string | null; + remote_proposal_id: string | null; + requested_by: string | null; + requested_by_name: string | null; + requested_at: string | null; + reviewed_by: string | null; + reviewed_by_name: string | null; + reviewed_at: string | null; + applied_at: string | null; + updated_at: string | null; + /** 列表附加:与当前报价单明细的「改前 → 改后」(仅 pending 的 B 方向) */ + lines?: Array<{ + sku_code: string; + sku_name: string | null; + unit: string | null; + before_sale_price: number | null; + after_sale_price: number | null; + /** unmapped = 该配送 SKU 在本地映射表里还没有 active 映射(审批时会 skip sku_unmapped) */ + change: 'updated' | 'added' | 'unmapped'; + /** 反查到的我方 SKU(未映射时为空) */ + supplier_sku_code?: string | null; + }>; + /** 列表附加:该行最近一次 D2 回执里的 applied 摘要(若本轮拉到了) */ + applied?: { updated: number; skipped: unknown } | null; + note?: string | null; + /** pending 行已等待天数(T7:pending 不自动过期,仅展示) */ + waited_days?: number | null; +}; + +type LocalRow = Record; + +function waitedDays(requestedAt: unknown): number | null { + if (!requestedAt) return null; + const time = new Date(String(requestedAt)).getTime(); + if (!Number.isFinite(time)) return null; + return Math.max(0, Math.floor((Date.now() - time) / 86400000)); +} + +function toDto(row: LocalRow): QuotePriceProposalDto { + return { + id: String(row.id), + branch_code: String(row.branch_code), + quote_sheet_code: String(row.quote_sheet_code), + main_branch_code: String(row.main_branch_code), + direction: row.direction, + items: Array.isArray(row.items) ? (row.items as QuotePriceProposalItemPayload[]) : [], + payload_hash: row.payload_hash ? String(row.payload_hash) : null, + status: row.status, + reject_reason: row.reject_reason ? String(row.reject_reason) : null, + client_request_id: row.client_request_id ? String(row.client_request_id) : null, + remote_proposal_id: row.remote_proposal_id ? String(row.remote_proposal_id) : null, + requested_by: row.requested_by ? String(row.requested_by) : null, + requested_by_name: row.requested_by_name ? String(row.requested_by_name) : null, + requested_at: row.requested_at ?? null, + reviewed_by: row.reviewed_by ? String(row.reviewed_by) : null, + reviewed_by_name: row.reviewed_by_name ? String(row.reviewed_by_name) : null, + reviewed_at: row.reviewed_at ?? null, + applied_at: row.applied_at ?? null, + updated_at: row.updated_at ?? null, + waited_days: row.status === 'pending' ? waitedDays(row.requested_at) : null, + }; +} + +/** 读本报价单的报价明细(价沿用 sale_price ?? price) */ +async function loadSheetItemRows(quoteSheetCode: string): Promise { + const result = await pool.query( + `SELECT sku_code, sku_name, unit, sale_price, price, cost_price, markup_ratio + FROM customer_quote_sheet_items + WHERE quote_sheet_code = $1 + ORDER BY sort_order ASC, sku_code ASC`, + [quoteSheetCode] + ); + return result.rows; +} + +/** 内部改价审核是否仍有在途 pending(A 发起的前置条件) */ +async function hasInternalReviewPending(branchCode: string, quoteSheetCode: string): Promise { + const result = await pool.query<{ status: string }>( + `SELECT status FROM quote_sheet_change_requests + WHERE branch_code = $1 AND quote_sheet_code = $2 + ORDER BY requested_at DESC + LIMIT 1`, + [branchCode, quoteSheetCode] + ); + const latest = result.rows[0]; + if (!latest) return false; + // 有在途 ⇒ 必须等内部审完;历史上只有被覆盖(superseded)而没有后继的行也视为未收口 + return latest.status === 'pending' || latest.status === 'superseded'; +} + +async function findLocalByRemoteId( + remoteProposalId: string +): Promise { + const result = await pool.query( + `SELECT * FROM quote_price_proposals WHERE remote_proposal_id = $1 LIMIT 1`, + [remoteProposalId] + ); + return result.rows[0] || null; +} + +async function findPendingLocal( + branchCode: string, + quoteSheetCode: string, + direction: 'to_delivery' | 'from_delivery' +): Promise { + const result = await pool.query( + `SELECT * FROM quote_price_proposals + WHERE branch_code = $1 AND quote_sheet_code = $2 AND direction = $3 AND status = 'pending' + LIMIT 1`, + [branchCode, quoteSheetCode, direction] + ); + return result.rows[0] || null; +} + +function auditProposal(input: { + operatorId?: string | null; + operatorRole?: string | null; + action: 'submit' | 'approve' | 'reject' | 'sync'; + branchCode: string; + proposalId: string; + quoteSheetCode: string; + direction: string; + status: string; + reason?: string | null; +}): void { + // best-effort:审计失败只记日志(与上一轮口径一致) + void writeAuditLog({ + operatorId: input.operatorId || null, + operatorRole: input.operatorRole || null, + operationType: `quote_price_proposal_${input.action}`, + targetTable: 'quote_price_proposals', + targetId: input.proposalId, + oldValue: { proposal_id: input.proposalId, quote_sheet_code: input.quoteSheetCode, direction: input.direction }, + newValue: { + proposal_id: input.proposalId, + quote_sheet_code: input.quoteSheetCode, + direction: input.direction, + action: input.action, + status: input.status, + reason: input.reason ?? null, + }, + branchCode: input.branchCode, + actionCategory: 'quote_price_proposal', + }).catch((error: any) => { + console.warn('[quote-price-proposal] 审计写入失败(best-effort):', error?.message || error); + }); +} + +/* ── 方向 A:提交给配送商审 ─────────────────────────────────────────────── */ + +export type SubmitResult = { + applied: false; + proposal: QuotePriceProposalDto; + replayed: boolean; + /** + * 提交时本单的映射统计(契约 §5):「本单 N 个商品,已映射 X / 未映射 Y」。 + * 未映射**不阻止**提交(配送侧写价时会 skip `sku_unmapped`),但用户要能看到。 + */ + mapping: { + quote_sheet_code: string; + total: number; + mapped: number; + unmapped: number; + unmapped_skus: Array<{ sku_code: string; sku_name: string | null }>; + }; +}; + +/** + * 方向 A 发起(整单一次): + * ① 报价单必须生效中;② **内部改价审核无在途 pending**;③ 本方向无在途 pending; + * ④ 从绑定客户解析**唯一**主系统分公司(`MAIN_`);⑤ 调 D1(**事务外**)建对方 pending; + * ⑥ 本地建 `to_delivery` pending —— **不写价**(价只在对方通过后由对方自己写成本价)。 + */ +export async function submitPriceProposal(input: { + quoteSheetCode: string; + note?: string | null; + ctx?: TenantContext | null; + operatingBranchCode?: string | null; + requestedBy?: string | null; +}): Promise { + if (!isQuotePriceProposalEnabled()) { + throw httpError(503, 'feature_disabled', '报价单价格传递未开启(MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL)'); + } + const branchCode = getEffectiveBranchCode(input.ctx || null, input.operatingBranchCode); + if (!branchCode) throw httpError(400, 'branch_required', '请选择当前操作分公司'); + + const sheet = await loadQuoteSheetForUpdate(input.quoteSheetCode, input.ctx, input.operatingBranchCode); + const quoteSheetCode = String(sheet.quote_sheet_code); + + if (await hasInternalReviewPending(branchCode, quoteSheetCode)) { + throw httpError(409, 'internal_review_pending', '该报价单还有未完成的内部改价审核,请先审完再提交配送商审核'); + } + const existingPending = await findPendingLocal(branchCode, quoteSheetCode, 'to_delivery'); + + const customerRows = await pool.query<{ customer_code: string }>( + `SELECT customer_code FROM customer_quote_sheet_customers WHERE quote_sheet_code = $1 ORDER BY customer_code ASC`, + [quoteSheetCode] + ); + const mainBranchCodes = parseMainBranchCodes(customerRows.rows.map((row) => String(row.customer_code))); + if (!mainBranchCodes.length) { + throw httpError(400, 'not_usage_company', '该报价单没有绑定主系统分公司客户(MAIN_*),无需提交'); + } + if (mainBranchCodes.length > 1) { + throw httpError( + 400, + 'ambiguous_main_branch', + `该报价单绑定了多个主系统分公司(${mainBranchCodes.join('、')}),请拆单后再提交` + ); + } + const mainBranchCode = mainBranchCodes[0]; + + const supplierCode = await resolveMainSupplierCode(branchCode); + if (!supplierCode) { + throw httpError(409, 'main_supplier_code_missing', '该分公司在主系统没有可用供应商编码,无法提交'); + } + + const itemRows = await loadSheetItemRows(quoteSheetCode); + const items: QuotePriceProposalItemPayload[] = itemRows + .map((row) => ({ + sku_code: toText(row.sku_code), + unit: toText(row.unit) || null, + price: readSheetPrice(row), + })) + .filter((item) => item.sku_code && item.price > 0); + assertProposalItems(items); + + const note = toText(input.note) || null; + const payloadHash = proposalPayloadHash({ quoteSheetCode, mainBranchCode, note, items }); + + // T6:同方向重复提交 —— **同 payload 同 hash ⇒ 回放**(不重复出站),否则**覆盖旧 pending**(旧的置 superseded) + const mapping = await getSheetMappingStats(quoteSheetCode); + if (existingPending && String(existingPending.payload_hash || '') === payloadHash) { + return { applied: false, proposal: toDto(existingPending), replayed: true, mapping }; + } + const clientRequestId = randomUUID(); + + // 出站 HTTP 必须在事务之外(这里没有任何打开的事务) + const submitted = await submitQuotePriceProposal({ + supplierCode, + clientRequestId, + supplierQuoteSheetCode: quoteSheetCode, + mainBranchCode, + note, + items, + }); + if (submitted.kind !== 'ok') { + throw httpError( + submitted.kind === 'rejected' ? submitted.status || 409 : 502, + submitted.code, + submitted.reason + ); + } + + // 旧 pending 必须置 `superseded`(T6)+ 插新行,同一事务;冲突(并发提交)时回读判断 + const tx = await pool.connect(); + let row: LocalRow; + try { + await tx.query('BEGIN'); + await tx.query( + `UPDATE quote_price_proposals + SET status = 'superseded', updated_at = NOW() + WHERE branch_code = $1 AND quote_sheet_code = $2 AND direction = 'to_delivery' AND status = 'pending'`, + [branchCode, quoteSheetCode] + ); + const inserted = await tx.query( + `INSERT INTO quote_price_proposals + (branch_code, quote_sheet_code, main_branch_code, direction, items, payload_hash, + status, client_request_id, remote_proposal_id, requested_by, requested_at, updated_at) + VALUES ($1, $2, $3, 'to_delivery', $4::jsonb, $5, 'pending', $6::uuid, $7, $8::uuid, NOW(), NOW()) + ON CONFLICT (branch_code, quote_sheet_code, direction) WHERE status = 'pending' DO NOTHING + RETURNING *`, + [ + branchCode, + quoteSheetCode, + mainBranchCode, + JSON.stringify(items), + payloadHash, + clientRequestId, + submitted.data.proposal_id, + input.requestedBy ?? null, + ] + ); + await tx.query('COMMIT'); + row = inserted.rows[0]; + } catch (error) { + try { + await tx.query('ROLLBACK'); + } catch { + /* ignore */ + } + throw error; + } finally { + tx.release(); + } + if (!row) { + // 并发:另一请求刚插了 pending ⇒ 同 hash 视为回放,不同 hash 明确冲突(不静默吞掉) + const pending = await findPendingLocal(branchCode, quoteSheetCode, 'to_delivery'); + if (!pending) throw httpError(409, 'already_pending', '该报价单已有一条等待配送商审核的提议'); + if (String(pending.payload_hash || '') !== payloadHash) { + throw httpError(409, 'concurrent_pending', '该报价单刚被另一请求提交了不同价格,请刷新后重试'); + } + row = pending; + } + + auditProposal({ + operatorId: input.ctx?.userId || input.requestedBy || null, + operatorRole: input.ctx?.roles?.join(',') || null, + action: 'submit', + branchCode, + proposalId: String(row.id), + quoteSheetCode, + direction: 'to_delivery', + status: 'pending', + }); + + return { applied: false, proposal: toDto(row), replayed: submitted.data.replayed, mapping }; +} + +/* ── 同步(D2):A 结果回写 + B 提议拉回 + D3 回执重试 ──────────────────── */ + +export type SyncSummary = { + suppliers: number; + pulled: number; + synced: number; + receipts: number; + skipped: number; + errors: number; +}; + +const DELIVERY_DIRECTION_MAP: Record = { + // 配送侧视角:from_supplier = 我方 A 提交的;to_supplier = 配送商发起的 B + from_supplier: 'to_delivery', + to_supplier: 'from_delivery', +}; + +function isTerminalProposalStatus(status: string): boolean { + // `superseded` 必须算终态:配送侧重复发起 B 时会先把旧 pending 置 superseded 再插新 pending + // (T6 覆盖语义)。若这里不认,旧本地 pending 永远收不了口,新 pending 还会撞本地 partial unique。 + return ( + status === 'approved' || + status === 'rejected' || + status === 'cancelled' || + status === 'superseded' + ); +} + +async function deliverDecisionReceipt(input: { + supplierCode: string; + proposalId: string; + decision: 'approved' | 'rejected'; + reason?: string | null; + /** approve 时把写价统计一并回执(配送侧只记录、不写价);A20 要求 `applied` 不能恒为 null */ + applied?: { updated: number; skipped: unknown } | null; +}): Promise { + const outcome = await decideQuotePriceProposal(input); + return outcome.kind === 'ok'; +} + +/** + * 回执补发时用的 `applied` 快照(T8:第一次回执失败后重发没有原统计): + * 与报价单**当前**明细比对 —— 价已等于提议价算 `updated`,行不存在算 `sku_not_in_sheet`。 + * best-effort(重发场景),不写库。 + */ +async function computeAppliedSnapshot( + quoteSheetCode: string, + items: Array<{ sku_code?: unknown; price?: unknown }> +): Promise<{ updated: number; skipped: Array<{ sku_code: string; reason: string }> }> { + const rows = await pool.query<{ sku_code: string; sale_price: string | null; price: string | null }>( + `SELECT sku_code, sale_price, price FROM customer_quote_sheet_items WHERE quote_sheet_code = $1`, + [quoteSheetCode] + ); + const bySku = new Map(rows.rows.map((row) => [String(row.sku_code), row])); + let updated = 0; + const skipped: Array<{ sku_code: string; reason: string }> = []; + for (const item of items || []) { + const code = toText(item.sku_code); + const price = roundPrice(item.price); + if (!code) continue; + const row = bySku.get(code); + if (!row) { + skipped.push({ sku_code: code, reason: 'sku_not_in_sheet' }); + continue; + } + if (Math.abs(readSheetPrice(row as unknown as Record) - price) <= 1e-6) updated += 1; + else skipped.push({ sku_code: code, reason: 'price_not_applied' }); + } + return { updated, skipped }; +} + +/** + * 把 D2 的一行落到本地台账(在**目标分公司的租户上下文**里执行): + * · A(`from_supplier`)已有本地行:远端终态 ⇒ 回写本地状态;本地终态但远端仍 pending ⇒ 重发 D3; + * · B(`to_supplier`):本地没有 ⇒ 建 `from_delivery` pending(**不写价**);已有 ⇒ 只补状态。 + */ +async function applyRemoteRow(input: { + branchCode: string; + supplierCode: string; + remote: RemoteQuotePriceProposalRow; +}): Promise<'pulled' | 'synced' | 'receipt' | 'skipped'> { + const localDirection = DELIVERY_DIRECTION_MAP[input.remote.direction]; + if (!localDirection) return 'skipped'; + const remoteStatus = toText(input.remote.status) || 'pending'; + + /** + * A16/T6 交叉(verifier 阻断项):配送侧重复发起 B 时,会先把旧 pending 置 **`superseded`** 再插新 pending。 + * 因此: + * · 远端 `superseded` 必须当**终态**(本地同 remote id 的 pending 收口成 superseded); + * · 新的远端 pending 落本地若撞 partial unique,**不能 DO NOTHING 静默跳过** —— 先把本地旧 pending + * 置 superseded,再插新行;否则新提议永远落不了本地,用户还会对旧 id 通过 → 把已撤回价写进报价单。 + */ + return runWithTenantDbContext( + input.branchCode, + async () => { + const existingByRemote = await findLocalByRemoteId(input.remote.proposal_id); + + if (existingByRemote) { + const localStatus = String(existingByRemote.status); + const isFromDelivery = String(existingByRemote.direction) === 'from_delivery'; + + // 远端已撤回/被替代 ⇒ 本地同 remote id 的 pending 直接收口(不写价、不推送) + if (remoteStatus === 'superseded') { + if (localStatus === 'pending') { + await pool.query( + `UPDATE quote_price_proposals + SET status = 'superseded', + reject_reason = 'remote_superseded', + remote_proposal_id = COALESCE(remote_proposal_id, $2), + updated_at = NOW() + WHERE id = $1::uuid AND status = 'pending'`, + [String(existingByRemote.id), input.remote.proposal_id] + ); + return 'synced'; + } + return 'skipped'; + } + + // 本地已终态但远端还没收到回执 ⇒ 重发 D3(幂等重试,只对 B 方向有意义) + if (isTerminalProposalStatus(localStatus) && remoteStatus === 'pending' && isFromDelivery) { + const applied = + localStatus === 'approved' + ? await computeAppliedSnapshot( + String(existingByRemote.quote_sheet_code), + (Array.isArray(existingByRemote.items) ? existingByRemote.items : []) as any[] + ) + : null; + const ok = await deliverDecisionReceipt({ + supplierCode: input.supplierCode, + proposalId: input.remote.proposal_id, + decision: localStatus === 'approved' ? 'approved' : 'rejected', + reason: existingByRemote.reject_reason ? String(existingByRemote.reject_reason) : null, + applied, + }); + return ok ? 'receipt' : 'skipped'; + } + + if (localStatus === 'pending' && isTerminalProposalStatus(remoteStatus)) { + await pool.query( + `UPDATE quote_price_proposals + SET status = $2::varchar, + reject_reason = COALESCE($3::text, reject_reason), + reviewed_at = COALESCE($4::timestamptz, reviewed_at), + applied_at = CASE WHEN $2::text = 'approved' THEN NOW() ELSE applied_at END, + updated_at = NOW() + WHERE id = $1::uuid`, + [ + String(existingByRemote.id), + remoteStatus === 'cancelled' ? 'cancelled' : remoteStatus, + input.remote.reject_reason, + input.remote.reviewed_at, + ] + ); + return 'synced'; + } + return 'skipped'; + } + + // 本地没有:只拉"待我方审"的 B 提议(A 的行由我们提交时自己建) + if (localDirection !== 'from_delivery') return 'skipped'; + if (remoteStatus !== 'pending') return 'skipped'; + + /** + * T2:方向 B 的目标单在**我方**按 `MAIN_` 解析**唯一生效单**。 + * 优先用对方带过来的单号(且校验仍生效),否则按 MAIN_ 解析;0/多张都不猜(跳过并告警, + * 审批时仍会以 409 `no_quote_sheet`/`ambiguous_sheet` 兜底)。 + */ + let quoteSheetCode = toText(input.remote.supplier_quote_sheet_code); + if (quoteSheetCode) { + const alive = await pool.query( + `SELECT 1 FROM customer_quote_sheets + WHERE quote_sheet_code = $1 AND status = 1 AND approval_status = 30 + AND (expires_at IS NULL OR expires_at > NOW()) + LIMIT 1`, + [quoteSheetCode] + ); + if (!alive.rows.length) quoteSheetCode = ''; + } + if (!quoteSheetCode) { + const { candidates } = await resolveActiveSheetCodeForMainBranch(input.remote.branch_code); + if (candidates.length === 1) quoteSheetCode = candidates[0]; + else { + console.warn( + `[quote-price-proposal] 方向 B 目标单无法唯一解析(main_branch=${input.remote.branch_code}, ` + + `候选 ${candidates.length} 张,proposal=${input.remote.proposal_id})⇒ 本轮跳过` + ); + return 'skipped'; + } + } + + const items = (input.remote.items || []) + .map((item) => ({ + sku_code: toText(item.sku_code), + unit: toText(item.unit) || null, + price: roundPrice(item.price), + })) + .filter((item) => item.sku_code && item.price > 0 && item.price <= MAX_PROPOSAL_PRICE) + .slice(0, MAX_PROPOSAL_ITEMS); + if (!items.length) return 'skipped'; + + const payloadHash = proposalPayloadHash({ + quoteSheetCode, + mainBranchCode: input.remote.branch_code, + note: input.remote.note, + items, + }); + + const insertNew = () => + pool.query( + `INSERT INTO quote_price_proposals + (branch_code, quote_sheet_code, main_branch_code, direction, items, payload_hash, + status, client_request_id, remote_proposal_id, requested_by, requested_at, updated_at) + VALUES ($1, $2, $3, 'from_delivery', $4::jsonb, $5, 'pending', $6::uuid, $7, NULL, NOW(), NOW()) + ON CONFLICT (branch_code, quote_sheet_code, direction) WHERE status = 'pending' DO NOTHING + RETURNING id::text AS id`, + [ + input.branchCode, + quoteSheetCode, + input.remote.branch_code, + JSON.stringify(items), + payloadHash, + randomUUID(), + input.remote.proposal_id, + ] + ); + + /** + * 先直接插;撞唯一键时**显式接管**:旧的(不同 remote id)置 superseded 后再插。 + * 极端并发(第二次仍撞到另一个 pending)时最多接管 4 次;仍失败 ⇒ **抛错失败关闭** + * (sync 侧记 errors 并重置该 supplier 的游标,下一轮重拉;绝不静默丢新提议)。 + */ + const MAX_TAKEOVER_ATTEMPTS = 4; + for (let attempt = 0; attempt < MAX_TAKEOVER_ATTEMPTS; attempt += 1) { + const inserted = await insertNew(); + if (inserted.rows[0]) return 'pulled'; + + const localPending = await findPendingLocal(input.branchCode, quoteSheetCode, 'from_delivery'); + if (!localPending) continue; // 并发下对方刚好撤了:重试插入 + if (String(localPending.remote_proposal_id || '') === input.remote.proposal_id) { + return 'skipped'; // 同一远端提议 ⇒ 幂等跳过(不清数据) + } + await pool.query( + `UPDATE quote_price_proposals + SET status = 'superseded', + reject_reason = $2, + updated_at = NOW() + WHERE id = $1::uuid AND status = 'pending'`, + [String(localPending.id), `replaced_by_remote:${input.remote.proposal_id}`] + ); + } + throw new Error( + `quote_price_proposal_takeover_failed: ${input.remote.proposal_id} on ${input.branchCode}/${quoteSheetCode}` + ); + }, + { isolate: true, requestClient: false } + ); +} + +/** + * 定时/手动对账:按「有 active 绑定的供应商编码」逐个调 D2,把行落到**各自分公司**的租户表。 + * 供应商编码 → 我方分公司:优先 `main_supplier_bindings` 的 `main_branch_code` 精确匹配, + * 否则仅在**唯一候选**分公司时回退(多候选不猜)。 + */ +/** T10 游标记忆(按 supplier_code)。进程重启后退化为全量拉取,安全。 */ +const syncCursors = new Map(); + +export function resetQuotePriceProposalSyncCursor(supplierCode?: string): void { + if (supplierCode) syncCursors.delete(String(supplierCode)); + else syncCursors.clear(); +} + +export async function syncQuotePriceProposals(options?: { + limit?: number; + /** 显式指定/覆盖游标(排障或手动全量:传 null) */ + cursor?: string | null; + resetCursor?: boolean; +}): Promise { + const summary: SyncSummary = { suppliers: 0, pulled: 0, synced: 0, receipts: 0, skipped: 0, errors: 0 }; + if (!isQuotePriceProposalEnabled()) return summary; + + const bindings = await pool.query<{ branch_code: string; main_branch_code: string; main_supplier_code: string }>( + `SELECT branch_code, main_branch_code, main_supplier_code + FROM public.main_supplier_bindings + WHERE status = 'active' AND NULLIF(TRIM(main_supplier_code), '') IS NOT NULL` + ); + const bySupplier = new Map>(); + for (const row of bindings.rows) { + const code = String(row.main_supplier_code).trim(); + if (!bySupplier.has(code)) bySupplier.set(code, []); + bySupplier.get(code)!.push({ + branch_code: String(row.branch_code), + main_branch_code: String(row.main_branch_code), + }); + } + + const limit = Math.min(Math.max(Number(options?.limit) || 100, 1), 200); + if (options?.resetCursor) syncCursors.clear(); + for (const [supplierCode, branches] of bySupplier) { + summary.suppliers += 1; + const cursor = + options?.cursor !== undefined ? options.cursor : syncCursors.get(supplierCode) ?? null; + const listed = await listQuotePriceProposals({ supplierCode, limit, cursor }); + if (listed.kind !== 'ok') { + summary.errors += 1; + continue; + } + // T10:带上服务端返回的复合游标 `(updated_at, id)`,下一轮增量拉取 + syncCursors.set(supplierCode, listed.nextCursor); + for (const remote of listed.rows) { + const exact = branches.find((row) => row.main_branch_code === remote.branch_code); + const branchCode = exact + ? exact.branch_code + : branches.length === 1 + ? branches[0].branch_code + : ''; + if (!branchCode) { + summary.skipped += 1; + continue; + } + try { + const outcome = await applyRemoteRow({ branchCode, supplierCode, remote }); + if (outcome === 'pulled') summary.pulled += 1; + else if (outcome === 'synced') summary.synced += 1; + else if (outcome === 'receipt') summary.receipts += 1; + else summary.skipped += 1; + } catch (error: any) { + summary.errors += 1; + // 接管失败/其它异常 ⇒ 重置该供应商游标,下一轮从头发(新提议不会被"游标已过"静默丢掉) + syncCursors.delete(supplierCode); + console.warn( + `[quote-price-proposal] 同步单行失败(${remote.proposal_id}),已重置游标待下轮重拉:`, + error?.message || error + ); + } + } + } + return summary; +} + +/* ── 列表 ───────────────────────────────────────────────────────────────── */ + +/** 本地提议列表(pending 的 B 方向附带与当前明细的「改前 → 改后」) */ +export async function listPriceProposals(input: { + branchCode: string; + direction?: string | null; + status?: string | null; + limit?: number; + refresh?: boolean; +}): Promise<{ rows: QuotePriceProposalDto[]; sync: SyncSummary | null }> { + const branchCode = toText(input.branchCode); + if (!branchCode) return { rows: [], sync: null }; + const sync = input.refresh && isQuotePriceProposalEnabled() ? await syncQuotePriceProposals() : null; + + const direction = ['to_delivery', 'from_delivery'].includes(toText(input.direction)) + ? toText(input.direction) + : null; + const status = ['pending', 'approved', 'rejected', 'cancelled', 'superseded'].includes(toText(input.status)) + ? toText(input.status) + : null; + const limit = Math.min(Math.max(Number(input.limit) || 50, 1), 200); + const params: unknown[] = [branchCode]; + let where = `WHERE p.branch_code = $1`; + if (direction) { + params.push(direction); + where += ` AND p.direction = $${params.length}`; + } + if (status) { + params.push(status); + where += ` AND p.status = $${params.length}`; + } + params.push(limit); + + const result = await pool.query( + // ⚠️ 展示名在 public.profiles(auth.users 没有 full_name/username)—— 上一轮踩过 + `SELECT p.*, + COALESCE(NULLIF(TRIM(ru.full_name), ''), NULLIF(TRIM(ru.username), ''), '') AS requested_by_name, + COALESCE(NULLIF(TRIM(vu.full_name), ''), NULLIF(TRIM(vu.username), ''), '') AS reviewed_by_name + FROM quote_price_proposals p + LEFT JOIN public.profiles ru ON ru.id = p.requested_by + LEFT JOIN public.profiles vu ON vu.id = p.reviewed_by + ${where} + ORDER BY p.requested_at DESC + LIMIT $${params.length}`, + params + ); + const rows = result.rows.map((row) => toDto(row)); + + // pending 的 B 方向:附「改前 → 改后」(当前单明细 vs 提议价),供审批人直接看差 + const pendingFromDelivery = rows.filter( + (row) => row.status === 'pending' && row.direction === 'from_delivery' + ); + if (pendingFromDelivery.length) { + const codes = [...new Set(pendingFromDelivery.map((row) => row.quote_sheet_code))]; + const items = await pool.query( + `SELECT quote_sheet_code, sku_code, sku_name, unit, sale_price, price + FROM customer_quote_sheet_items WHERE quote_sheet_code = ANY($1)`, + [codes] + ); + const bySheet = new Map>(); + for (const row of items.rows) { + const sheet = String(row.quote_sheet_code); + if (!bySheet.has(sheet)) bySheet.set(sheet, new Map()); + bySheet.get(sheet)!.set(String(row.sku_code), row); + } + // 提议 items 是**配送 SKU** ⇒ 批量反查本地映射(只认 active + delivery_sku_code 非空) + const deliverySkus = [ + ...new Set(pendingFromDelivery.flatMap((row) => row.items.map((item) => toText(item.sku_code))).filter(Boolean)), + ]; + const deliveryToSupplier = new Map(); + if (deliverySkus.length) { + const mappings = await pool.query<{ supplier_sku_code: string; delivery_sku_code: string }>( + `SELECT supplier_sku_code, delivery_sku_code + FROM main_system_sku_mappings + WHERE delivery_sku_code = ANY($1) AND status = 'active'`, + [deliverySkus] + ); + for (const mapping of mappings.rows) { + deliveryToSupplier.set(String(mapping.delivery_sku_code), String(mapping.supplier_sku_code)); + } + } + for (const row of pendingFromDelivery) { + const current = bySheet.get(row.quote_sheet_code) || new Map(); + row.lines = row.items.map((item) => { + const supplierSku = deliveryToSupplier.get(toText(item.sku_code)) || null; + const before = supplierSku ? current.get(supplierSku) : undefined; + return { + sku_code: item.sku_code, + supplier_sku_code: supplierSku, + sku_name: before?.sku_name + ? String(before.sku_name) + : supplierSku + ? null + : null, + unit: item.unit || (before?.unit ? String(before.unit) : null), + before_sale_price: before ? readSheetPrice(before) : null, + after_sale_price: roundPrice(item.price), + change: !supplierSku ? ('unmapped' as const) : before ? ('updated' as const) : ('added' as const), + }; + }); + } + } + return { rows, sync }; +} + +/* ── 方向 B:审批(按行写 sale_price → rearm 推对方 cost_price → D3 回执)────── */ + +/** 锁并校验本地提议(方向 B 专用):存在 / 本分公司 / 方向对 / 仍 pending */ +async function loadLocalProposalForDecision( + client: import('pg').PoolClient, + input: { id: string; branchCode: string; expectedDirection: 'from_delivery' } +): Promise { + const locked = await client.query( + `SELECT * FROM quote_price_proposals WHERE id = $1::uuid FOR UPDATE`, + [input.id] + ); + if (!locked.rows.length) throw httpError(404, 'proposal_not_found', '价格提议不存在'); + const row = locked.rows[0]; + if (String(row.branch_code) !== input.branchCode) { + throw httpError(403, 'branch_mismatch', '无权操作其它分公司的价格提议'); + } + if (String(row.direction) !== input.expectedDirection) { + throw httpError(400, 'wrong_direction', '只有「配送商成本价确认」的提议可在此审批'); + } + if (String(row.status) !== 'pending') { + throw httpError(409, 'already_decided', '该价格提议已处理'); + } + return row; +} + +/** + * A16(verifier 阻断项):审批前**向配送侧确认该提议仍是 pending**。 + * + * 为什么必须查:配送侧重复发起 B 时会把旧 pending 置 `superseded` 再插新 pending;若本地同步还没跑到, + * 用户对**旧 id** 点通过就会把**已撤回的价**写进报价单并推给配送侧(D3 才 409,为时已晚)。 + * + * verifier 第二轮指出**原实现 fail-open + 只看第一页**:D2 是 `ORDER BY updated_at ASC LIMIT 200`(最旧 200 行), + * 被 supersede 的旧行 `updated_at` 很新 ⇒ 不在第一页;旧实现"找不到就放行" ⇒ 仍会写已撤回价。 + * + * 现在的口径(失败关闭): + * ① 先带 `proposal_id` 精确查(配送侧新增 `?proposal_id=`); + * ② 不支持精确查/没命中 ⇒ 用 `next_cursor` **翻页直到找到或耗尽**(上限 20 页); + * ③ **找不到 ⇒ 409 `remote_status_unverified`**(绝不放行);D2 不可用同样 409。 + * 事务外调用(出网不得在事务里)。 + */ +const REMOTE_STATUS_MAX_PAGES = 20; + +async function assertRemoteProposalStillPending(input: { + supplierCode: string; + proposalId: string; +}): Promise { + let cursor: string | null = null; + for (let page = 0; page < REMOTE_STATUS_MAX_PAGES; page += 1) { + const listed = await listQuotePriceProposals({ + supplierCode: input.supplierCode, + proposalId: input.proposalId, + cursor, + limit: 200, + }); + if (listed.kind !== 'ok') { + // 无法确认状态时**失败关闭**:宁可不批,也不把可能已撤回的价写下去 + throw httpError(409, 'remote_status_unverified', '无法确认该提议在配送侧的最新状态,请稍后重试'); + } + const remote = listed.rows.find((row) => row.proposal_id === input.proposalId); + if (remote) { + if (remote.status !== 'pending') { + const label = + remote.status === 'superseded' + ? '已被新的提议替代' + : remote.status === 'approved' + ? '已通过' + : remote.status === 'rejected' + ? '已驳回' + : '已撤回'; + throw httpError(409, 'proposal_not_pending', `该提议在配送侧${label},不能按旧价审批,请刷新列表`); + } + return; + } + if (!listed.nextCursor || listed.nextCursor === cursor) break; // 耗尽(或游标不前进) + cursor = listed.nextCursor; + } + // 翻页耗尽仍未找到 ⇒ **失败关闭**(旧实现这里会放行,是 verifier 抓到的阻断项) + throw httpError( + 409, + 'remote_status_unverified', + '无法在配送侧确认该提议的状态(已翻页查找),请刷新后重试' + ); +} + + +/** 目标单不可用(编辑路径的普通 Error)⇒ 审批路径 409 `target_unavailable` */ +function mapSheetUnavailable(error: any): Error | null { + const message = String(error?.message || ''); + if ( + message === '报价单不存在' || + message === '仅执行中的报价单可修改' || + message === '报价单已过期,无法修改' + ) { + return httpError(409, 'target_unavailable', message); + } + return null; +} + +/** + * T2:按 `MAIN_` 解析**唯一生效单**(`status=1 & approval_status=30 & 未过期`)。 + * + * 0 张 ⇒ 调用方 409 `no_quote_sheet`;多张 ⇒ 409 `ambiguous_sheet`(**不做"全写"扇出**)。 + * 真库 BR002 存在"同一客户多张生效单"的历史数据,所以这个闸门必须显式。 + */ +export async function resolveActiveSheetCodeForMainBranch( + mainBranchCode: string +): Promise<{ candidates: string[] }> { + const customerCode = `MAIN_${toText(mainBranchCode).toUpperCase()}`; + const result = await pool.query<{ quote_sheet_code: string }>( + `SELECT qs.quote_sheet_code + FROM customer_quote_sheets qs + WHERE qs.status = 1 + AND qs.approval_status = 30 + AND (qs.expires_at IS NULL OR qs.expires_at > NOW()) + AND EXISTS ( + SELECT 1 FROM customer_quote_sheet_customers qc + WHERE qc.quote_sheet_code = qs.quote_sheet_code + AND UPPER(TRIM(qc.customer_code)) = UPPER($1) + ) + ORDER BY qs.version_no DESC NULLS LAST, qs.updated_at DESC NULLS LAST, qs.created_at DESC NULLS LAST`, + [customerCode] + ); + return { candidates: result.rows.map((row) => String(row.quote_sheet_code)) }; +} + +async function resolveUniqueTargetSheet( + mainBranchCode: string +): Promise { + const { candidates } = await resolveActiveSheetCodeForMainBranch(mainBranchCode); + if (!candidates.length) { + throw httpError(409, 'no_quote_sheet', `没有找到 MAIN_${toText(mainBranchCode)} 对应且生效中的报价单`); + } + if (candidates.length > 1) { + throw httpError( + 409, + 'ambiguous_sheet', + `MAIN_${toText(mainBranchCode)} 对应多张生效报价单(${candidates.join('、')}),请先收敛后再审批` + ); + } + return candidates[0]; +} + +/** 逐行审计:每个真正变更的 (报价单, SKU) 一条(best-effort,提交后写) */ +function auditAppliedPriceRows(input: { + operatorId?: string | null; + operatorRole?: string | null; + branchCode: string; + quoteSheetCode: string; + proposalId: string; + rows: Array<{ itemId: string; skuCode: string; unit: string | null; oldPrice: number; newPrice: number }>; +}): void { + for (const row of input.rows) { + void writeAuditLog({ + operatorId: input.operatorId || null, + operatorRole: input.operatorRole || null, + operationType: 'quote_price_proposal_apply', + targetTable: 'customer_quote_sheet_items', + targetId: row.itemId, + oldValue: { + quote_sheet_code: input.quoteSheetCode, + sku_code: row.skuCode, + unit: row.unit, + sale_price: row.oldPrice, + source: 'delivery_price_proposal', + proposal_id: input.proposalId, + }, + newValue: { + quote_sheet_code: input.quoteSheetCode, + sku_code: row.skuCode, + unit: row.unit, + sale_price: row.newPrice, + source: 'delivery_price_proposal', + proposal_id: input.proposalId, + }, + branchCode: input.branchCode, + actionCategory: 'quote_price_proposal', + }).catch((error: any) => { + console.warn('[quote-price-proposal] 行审计写入失败(best-effort):', error?.message || error); + }); + } +} + +export type ApproveResult = { + proposal: QuotePriceProposalDto; + applied: { + updated: number; + unchanged: number; + skipped: Array<{ sku_code: string; reason: string; detail?: string }>; + }; + receiptSent: boolean; +}; + +/** + * 方向 B 通过(T3:**只按行 UPDATE**,绝不整表替换): + * + * 单事务内对 payload 里出现的 `sku_code` 逐行: + * `UPDATE customer_quote_sheet_items SET sale_price = $3, price = $3 + * WHERE quote_sheet_code = $1 AND sku_code = $2` + * —— 只改已有行、**不 INSERT / 不 DELETE / 不改单结构 / 不动其它 SKU**; + * 缺行 ⇒ `sku_not_in_sheet`;单位不一致(双方都非空且不等)⇒ `unit_mismatch`; + * 金额不合法(≤0 或 >9,999,999.99)⇒ `invalid_price`;值未变 ⇒ 不写(计入 unchanged)。 + * COMMIT 之后:每行审计(best-effort)→ D3 回执 `approved`(带 applied;配送侧据此用配送 SKU 写自己的 cost_price)。 + */ +export async function approvePriceProposal(input: { + id: string; + ctx?: TenantContext | null; + operatingBranchCode?: string | null; + reviewedBy?: string | null; +}): Promise { + if (!isQuotePriceProposalEnabled()) { + throw httpError(503, 'feature_disabled', '报价单价格传递未开启(MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL)'); + } + const branchCode = getEffectiveBranchCode(input.ctx || null, input.operatingBranchCode); + if (!branchCode) throw httpError(400, 'branch_required', '请选择当前操作分公司'); + + /** + * 事务外预检(出网不得在事务里): + * ① 本地行存在/本分公司/方向对/仍 pending; + * ② 远端仍是 pending(A16:防"旧 id 把已撤回价写下去")。事务内会再锁行复验一次。 + */ + const preloaded = await pool.query( + `SELECT * FROM quote_price_proposals WHERE id = $1::uuid`, + [input.id] + ); + if (!preloaded.rows.length) throw httpError(404, 'proposal_not_found', '价格提议不存在'); + const preRow = preloaded.rows[0]; + if (String(preRow.branch_code) !== branchCode) { + throw httpError(403, 'branch_mismatch', '无权操作其它分公司的价格提议'); + } + if (String(preRow.direction) !== 'from_delivery') { + throw httpError(400, 'wrong_direction', '只有「配送商成本价确认」的提议可在此审批'); + } + if (String(preRow.status) !== 'pending') { + throw httpError(409, 'already_decided', '该价格提议已处理'); + } + const preSupplierCode = await resolveMainSupplierCode(branchCode); + if (preRow.remote_proposal_id) { + if (!preSupplierCode) { + throw httpError(409, 'main_supplier_code_missing', '该分公司在主系统没有可用供应商编码,无法核对/回执提议'); + } + await assertRemoteProposalStillPending({ + supplierCode: preSupplierCode, + proposalId: String(preRow.remote_proposal_id), + }); + } + + const client = await pool.connect(); + let committed = false; + let row: LocalRow; + let quoteSheetCode = ''; + const changedRows: Array<{ itemId: string; skuCode: string; unit: string | null; oldPrice: number; newPrice: number }> = []; + const applied: ApproveResult['applied'] = { updated: 0, unchanged: 0, skipped: [] }; + try { + await client.query('BEGIN'); + row = await loadLocalProposalForDecision(client, { + id: input.id, + branchCode, + expectedDirection: 'from_delivery', + }); + + // T2:目标单按 MAIN_<主系统分公司> 唯一解析(0 ⇒ no_quote_sheet;多 ⇒ ambiguous_sheet) + quoteSheetCode = await resolveUniqueTargetSheet(String(row.main_branch_code)); + try { + await loadQuoteSheetForUpdate(quoteSheetCode, input.ctx, input.operatingBranchCode); + } catch (error: any) { + throw mapSheetUnavailable(error) || error; + } + + const current = await client.query( + `SELECT id::text AS id, sku_code, unit, sale_price, price + FROM customer_quote_sheet_items + WHERE quote_sheet_code = $1`, + [quoteSheetCode] + ); + const currentBySku = new Map(current.rows.map((item) => [String(item.sku_code), item])); + + const proposalItems = Array.isArray(row.items) ? (row.items as QuotePriceProposalItemPayload[]) : []; + if (!proposalItems.length) throw httpError(400, 'items_required', '该提议没有可应用的商品行'); + + /** + * ⭐ 提议 items 里的 `sku_code` 是**配送 SKU**(契约 §5):必须先反查本地映射得到**我方 SKU**, + * 查不到 ⇒ skip `sku_unmapped`(**绝不按 sku_code 直接猜** —— 两个系统的 SKU 本来就不一致)。 + */ + const resolvedSupplierSkus = new Set(); + for (const item of proposalItems) { + const deliverySku = toText(item.sku_code); + const price = roundPrice(item.price); + if (!deliverySku) { + applied.skipped.push({ sku_code: '', reason: 'invalid_item' }); + continue; + } + if (!(price > 0) || price > MAX_PROPOSAL_PRICE) { + applied.skipped.push({ sku_code: deliverySku, reason: 'invalid_price' }); + continue; + } + const mapping = await getMappingByDeliverySku(branchCode, deliverySku); + if (!mapping) { + applied.skipped.push({ sku_code: deliverySku, reason: 'sku_unmapped' }); + continue; + } + const skuCode = mapping.supplier_sku_code; + if (resolvedSupplierSkus.has(skuCode)) { + // 多个配送 SKU 映射到同一我方 SKU:只按第一个处理,避免重复计数/重复审计 + applied.skipped.push({ sku_code: deliverySku, reason: 'duplicate_supplier_sku', detail: skuCode }); + continue; + } + const target = currentBySku.get(skuCode); + if (!target) { + applied.skipped.push({ sku_code: deliverySku, reason: 'sku_not_in_sheet', detail: skuCode }); + continue; + } + // 单位闸门照旧:payload 单位(配送侧)与报价单行单位归一比较,不等就跳过并标注(契约决策 3) + const proposalUnit = toText(item.unit); + const rowUnit = toText(target.unit); + if (proposalUnit && rowUnit && proposalUnit.toLowerCase() !== rowUnit.toLowerCase()) { + applied.skipped.push({ + sku_code: deliverySku, + reason: 'unit_mismatch', + detail: `${proposalUnit} vs ${rowUnit}`, + }); + continue; + } + resolvedSupplierSkus.add(skuCode); + const oldPrice = roundPrice(target.sale_price ?? target.price); + if (Math.abs(oldPrice - price) <= 1e-6) { + applied.unchanged += 1; + continue; + } + // ⭐ T3 唯一写价语句:按 (quote_sheet_code, sku_code) 定点 UPDATE,只改 sale_price/price 两列 + const updatedRow = await client.query<{ id: string }>( + `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`, + [quoteSheetCode, skuCode, price] + ); + if (!updatedRow.rows.length) { + applied.skipped.push({ sku_code: deliverySku, reason: 'sku_not_in_sheet', detail: skuCode }); + continue; + } + applied.updated += 1; + changedRows.push({ + itemId: String(updatedRow.rows[0].id), + skuCode, + unit: rowUnit || null, + oldPrice, + newPrice: price, + }); + } + + const updatedRow = await client.query( + `UPDATE quote_price_proposals + SET status = 'approved', quote_sheet_code = $2, reviewed_by = $3::uuid, + reviewed_at = NOW(), applied_at = NOW(), reject_reason = NULL, updated_at = NOW() + WHERE id = $1::uuid AND status = 'pending' + RETURNING *`, + [row.id, quoteSheetCode, input.reviewedBy ?? null] + ); + if (!updatedRow.rows.length) throw httpError(409, 'already_decided', '该价格提议已处理'); + row = updatedRow.rows[0]; + await client.query('COMMIT'); + committed = true; + } catch (error) { + if (!committed) { + try { + await client.query('ROLLBACK'); + } catch { + /* ignore */ + } + } + throw error; + } finally { + client.release(); + } + + // 提交之后:① 每行审计(best-effort)② 既有 rearm 推对方 cost_price(本层不重造推送、不写台账) + auditAppliedPriceRows({ + operatorId: input.ctx?.userId || input.reviewedBy || null, + operatorRole: input.ctx?.roles?.join(',') || null, + branchCode, + quoteSheetCode, + proposalId: String(row.id), + rows: changedRows, + }); + /** + * ⛔ **B 审批不再走旧的成本同步推送**(2026-10-18 verifier 阻断项修正): + * 旧通道按 `sku_code` 直猜、还跳过共享单;两个系统 SKU 本就不一致 ⇒ 推过去配送 `cost_price` 静默不变。 + * 现在由**配送侧在 D3 `decision='approved'` 时**用提议里的**配送 SKU** 落地写价(共享单同样按映射写)。 + * `triggerQuoteCostSync` 只保留在**报价单生效自动推**那条链路(`quoteSheetService`),本函数不再调用。 + */ + auditProposal({ + operatorId: input.ctx?.userId || input.reviewedBy || null, + operatorRole: input.ctx?.roles?.join(',') || null, + action: 'approve', + branchCode, + proposalId: String(row.id), + quoteSheetCode, + direction: 'from_delivery', + status: 'approved', + }); + + // D3 回执(事务外;失败只记 warning,下次 D2 轮询按「本地终态 + 远端 pending」自动重发 —— T8) + let receiptSent = false; + const supplierCode = await resolveMainSupplierCode(branchCode); + if (supplierCode && row.remote_proposal_id) { + receiptSent = await deliverDecisionReceipt({ + supplierCode, + proposalId: String(row.remote_proposal_id), + decision: 'approved', + // A20:回执必须带写价统计(配送侧只记录、不写价),否则对方 proposal 的 applied 恒为 null + applied: { updated: applied.updated, skipped: applied.skipped }, + }); + if (!receiptSent) { + console.warn(`[quote-price-proposal] D3 回执失败(approved ${row.remote_proposal_id}),等待下轮自动重发`); + } + } + return { proposal: toDto(row), applied, receiptSent }; +} + +export type RejectResult = { proposal: QuotePriceProposalDto; receiptSent: boolean }; + +/** 方向 B 驳回:只记状态 + 理由,**不写价、不推送**,D3 回执 `rejected`。 */ +export async function rejectPriceProposal(input: { + id: string; + reason: string; + ctx?: TenantContext | null; + operatingBranchCode?: string | null; + reviewedBy?: string | null; +}): Promise { + if (!isQuotePriceProposalEnabled()) { + throw httpError(503, 'feature_disabled', '报价单价格传递未开启(MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL)'); + } + const branchCode = getEffectiveBranchCode(input.ctx || null, input.operatingBranchCode); + if (!branchCode) throw httpError(400, 'branch_required', '请选择当前操作分公司'); + const reason = toText(input.reason); + if (!reason) throw httpError(400, 'reject_reason_required', '请填写驳回理由'); + + const client = await pool.connect(); + let row: LocalRow; + try { + await client.query('BEGIN'); + row = await loadLocalProposalForDecision(client, { + id: input.id, + branchCode, + expectedDirection: 'from_delivery', + }); + const updatedRow = await client.query( + `UPDATE quote_price_proposals + SET status = 'rejected', reject_reason = $2, reviewed_by = $3::uuid, + reviewed_at = NOW(), updated_at = NOW() + WHERE id = $1::uuid AND status = 'pending' + RETURNING *`, + [row.id, reason, input.reviewedBy ?? null] + ); + if (!updatedRow.rows.length) throw httpError(409, 'already_decided', '该价格提议已处理'); + row = updatedRow.rows[0]; + await client.query('COMMIT'); + } catch (error) { + try { + await client.query('ROLLBACK'); + } catch { + /* ignore */ + } + throw error; + } finally { + client.release(); + } + + auditProposal({ + operatorId: input.ctx?.userId || input.reviewedBy || null, + operatorRole: input.ctx?.roles?.join(',') || null, + action: 'reject', + branchCode, + proposalId: String(row.id), + quoteSheetCode: String(row.quote_sheet_code), + direction: 'from_delivery', + status: 'rejected', + reason, + }); + + let receiptSent = false; + const supplierCode = await resolveMainSupplierCode(branchCode); + if (supplierCode && row.remote_proposal_id) { + receiptSent = await deliverDecisionReceipt({ + supplierCode, + proposalId: String(row.remote_proposal_id), + decision: 'rejected', + reason, + }); + if (!receiptSent) { + console.warn(`[quote-price-proposal] D3 回执失败(rejected ${row.remote_proposal_id}),等待下轮自动重发`); + } + } + return { proposal: toDto(row), receiptSent }; +} + +export const __testables = { + proposalPayloadHash, + quoteCostSyncItemsFingerprint, +}; diff --git a/server/src/services/quoteSheetChangeRequestService.ts b/server/src/services/quoteSheetChangeRequestService.ts new file mode 100644 index 0000000..3feb83e --- /dev/null +++ b/server/src/services/quoteSheetChangeRequestService.ts @@ -0,0 +1,858 @@ +import { pool } from '../db'; +import { getEffectiveBranchCode, type TenantContext } from './tenantScope'; +import { + applyQuoteSheetUpdate, + assertCustomersInBranch, + getQuoteSheet, + loadQuoteSheetForUpdate, + normalizeQuoteSheetUpdatePayload, + updateQuoteSheet, + type QuoteSheetItemInput, + type QuoteSheetUpdateInput, +} from './quoteSheetService'; +import { quoteCostSyncItemsFingerprint, triggerQuoteCostSync } from './mainSystemQuoteCostSync'; +import { writeAuditLog } from './auditService'; + +/** + * 编辑**生效中**报价单的「待审变更」(2026-10-18 增量需求): + * 用户原话「编辑生效单改价需要有同步审核,审核通过就同步」。 + * + * 口径(brief §3 + Lead 2026-10-18 裁定,逐条照做): + * · **只审价格相关变化**(D5):入参含 `items`(增删改明细)或 `auto_sale_price_by_cost` 真的变了 ⇒ 待审; + * 只改标题/周期/生效日/客户 ⇒ 维持现有直接保存; + * · **整单一次审核**(D2):保存时整单入参作为一条变更单; + * · 一张单只留一条 `pending`(D4):新提交把旧的置 `superseded`; + * · **未审期间零副作用**:报价单三张表与配送系统都不动; + * · 审核通过:**单事务**内应用(复用抽出的 `applyQuoteSheetUpdate(..., { client })`)→ 提交后 + * 调既有 `triggerQuoteCostSync`(走 rearm:指纹变了会换号重推);**绝不**走 + * `approveQuoteSheet`/`activateQuoteSheet`(后者会把同分公司共享客户的其它生效单置 `status=3`); + * · 驳回:只改变更单状态,报价单不变、**零推送**; + * · 重复决策 ⇒ `409 already_decided`(幂等,不重复应用); + * · 开关 `QUOTE_EDIT_APPROVAL` **默认开**;`0/false/off` 回滚成"直接保存"且**不写**变更单表。 + * + * 设计:docs/design/20261018-报价单改价审核与成本同步.md + */ + +/** 开关:默认开;只有显式 `0/false/off` 才关(回滚成改造前的「直接保存」) */ +export function isQuoteEditApprovalEnabled(): boolean { + const raw = String(process.env.QUOTE_EDIT_APPROVAL ?? '').trim().toLowerCase(); + return !(raw === '0' || raw === 'false' || raw === 'off'); +} + +/** + * 变更单业务审计(A26):提交 / 通过 / 驳回三条路径各写一条 `operation_logs` + * (`operationType = quote_sheet_change_request_`,四要素:变更单 id、报价单 code、 + * 旧状态→新状态、理由/操作人)。 + * + * ⚠️ **best-effort**:审计在**事务提交之后**调用(避免审计失败把主事务带进 aborted 状态), + * 任何异常只记日志,绝不影响提交/审批结果。 + */ +async function auditChangeRequest(input: { + operatorId?: string | null; + operatorRole?: string | null; + action: 'submit' | 'approve' | 'reject'; + branchCode: string; + changeRequestId: string; + quoteSheetCode: string; + oldStatus: string; + newStatus: string; + reason?: string | null; +}): Promise { + try { + await writeAuditLog({ + operatorId: input.operatorId || null, + operatorRole: input.operatorRole || null, + operationType: `quote_sheet_change_request_${input.action}`, + targetTable: 'quote_sheet_change_requests', + targetId: input.changeRequestId, + oldValue: { + change_request_id: input.changeRequestId, + quote_sheet_code: input.quoteSheetCode, + status: input.oldStatus, + }, + newValue: { + change_request_id: input.changeRequestId, + quote_sheet_code: input.quoteSheetCode, + status: input.newStatus, + action: input.action, + reason: input.reason ?? null, + }, + branchCode: input.branchCode, + actionCategory: 'quote_edit_approval', + }); + } catch (error: any) { + console.warn( + '[quote-change-request] 审计写入失败(best-effort,不影响主流程):', + error?.message || error + ); + } +} + +function httpError(status: number, code: string, message: string) { + return Object.assign(new Error(message), { status, code }); +} + +/** + * 审批路径专用:把「目标单不可用」的普通 Error 映射成 409 `target_unavailable`(A12 修订)。 + * + * 只认这三句既有文案(来源 `quoteSheetService` 的三连守卫 / `assertQuoteSheetAccessible`)—— + * 其它错误(数据库/网络)原样返回,仍按 500 处理。**不改编辑路径的抛错语义**: + * `updateQuoteSheet` 仍抛普通 Error(= 改造前行为),只有这里做映射。 + */ +function mapTargetUnavailable(error: any): Error | null { + const message = String(error?.message || ''); + if ( + message === '报价单不存在' || + message === '仅执行中的报价单可修改' || + message === '报价单已过期,无法修改' + ) { + return httpError(409, 'target_unavailable', message); + } + return null; +} + +/** 变更单里存的整单编辑入参(D2:整单一次审核) */ +export type QuoteChangePayload = { + title?: string; + customer_codes?: string[]; + items?: QuoteSheetItemInput[]; + auto_sale_price_by_cost?: boolean; + quote_cycle?: string; + effective_at?: string; +}; + +export type QuoteChangeLine = { + sku_code: string; + sku_name: string | null; + unit: string | null; + before_sale_price: number | null; + after_sale_price: number | null; + before_cost_price: number | null; + after_cost_price: number | null; + change: 'added' | 'removed' | 'updated'; +}; + +export type QuoteChangeSummary = { + title: string | null; + quote_cycle: string | null; + effective_at: string | null; + auto_sale_price_by_cost: boolean | null; + customer_codes: string[] | null; + items_provided: boolean; + item_count: number; + added: number; + removed: number; + updated: number; + lines: QuoteChangeLine[]; + truncated: boolean; +}; + +export type QuoteChangeRequestDto = { + id: string; + branch_code: string; + quote_sheet_code: string; + payload: QuoteChangePayload; + base_version_no: number | null; + base_items_fingerprint: string | null; + status: 'pending' | 'approved' | 'rejected' | 'superseded'; + requested_by: string | null; + requested_by_name: string | null; + requested_at: string | Date | null; + reviewed_by: string | null; + reviewed_by_name: string | null; + reviewed_at: string | Date | null; + reject_reason: string | null; + applied_at: string | Date | null; + updated_at: string | Date | null; + summary?: QuoteChangeSummary; +}; + +type ItemLike = { + sku_code?: unknown; + sku_name?: unknown; + unit?: unknown; + sale_price?: unknown; + price?: unknown; + cost_price?: unknown; +}; + +function toText(value: unknown): string { + return value === null || value === undefined ? '' : String(value).trim(); +} + +function readItemSale(row: ItemLike): number { + const raw = row?.sale_price ?? row?.price; + const value = Number(raw); + return Number.isFinite(value) ? Math.round(value * 100) / 100 : 0; +} + +function readItemCost(row: ItemLike): number { + const value = Number(row?.cost_price); + return Number.isFinite(value) ? Math.round(value * 100) / 100 : 0; +} + +/** + * 提交时的**同一 SKU 重复**闸门(Lead 裁定 #2):不去重、不落库,直接 400 `duplicate_sku`。 + * 只按非空 `sku_code` 判;空行本来就会被 `normalizeQuoteSheetUpdatePayload` 过滤掉。 + */ +export function assertNoDuplicateSku(items: QuoteSheetItemInput[] | undefined): void { + if (!Array.isArray(items) || !items.length) return; + const seen = new Set(); + const duplicates = new Set(); + for (const item of items) { + const code = toText(item?.sku_code); + if (!code) continue; + if (seen.has(code)) duplicates.add(code); + seen.add(code); + } + if (duplicates.size) { + throw httpError(400, 'duplicate_sku', `同一商品重复出现:${[...duplicates].slice(0, 5).join('、')}`); + } +} + +/** + * 「这次编辑是否价格相关」(D5):入参含 `items`(增删改明细)⇒ 是; + * `auto_sale_price_by_cost` **真的变了** ⇒ 是;只改标题/周期/生效日/客户 ⇒ 否。 + */ +export function isPriceRelatedQuoteEdit( + input: { items?: unknown; autoSalePriceByCost?: unknown }, + existing: { auto_sale_price_by_cost?: unknown } +): boolean { + if (input.items !== undefined) return true; + if (input.autoSalePriceByCost !== undefined) { + return Boolean(input.autoSalePriceByCost) !== Boolean(existing?.auto_sale_price_by_cost); + } + return false; +} + +/** + * 报价单明细指纹:**复用成本价同步的同一套算法**(`sku_code` / `unit` / `sale_price` 排序后 sha256, + * 见 `quoteCostSyncItemsFingerprint`)。用于"提交后目标单是否被改过"(`base_changed`)判据。 + * + * ⚠️ `base_version_no` 只留痕、不作判据:`version_no` 编辑时不涨,`setQuoteSheetAutoSalePriceByCost` + * 连 `updated_at` 都不更新 ⇒ 用版本号判"变没变"会永远判不出变化(Lead 裁定 #4)。 + */ +export function quoteSheetItemsFingerprint(rows: ItemLike[]): string { + return quoteCostSyncItemsFingerprint( + (rows || []) + .map((row) => ({ + sku_code: toText(row?.sku_code), + unit: toText(row?.unit) || null, + sale_price: readItemSale(row), + })) + .filter((row) => Boolean(row.sku_code)) + ); +} + +function changeLine(before: ItemLike | null, after: ItemLike | null, change: QuoteChangeLine['change']): QuoteChangeLine { + const source = after || before || {}; + return { + sku_code: toText(source.sku_code), + sku_name: toText(source.sku_name) || null, + unit: toText(source.unit) || null, + before_sale_price: before ? readItemSale(before) : null, + after_sale_price: after ? readItemSale(after) : null, + before_cost_price: before ? readItemCost(before) : null, + after_cost_price: after ? readItemCost(after) : null, + change, + }; +} + +/** 明细前后比对(纯函数,供审核摘要与单测) */ +export function diffQuoteSheetItems( + before: ItemLike[], + after: ItemLike[] +): Pick { + const index = (rows: ItemLike[]) => { + const map = new Map(); + for (const row of rows || []) { + const code = toText(row?.sku_code); + if (code) map.set(code, row); + } + return map; + }; + const beforeMap = index(before); + const afterMap = index(after); + const keys = [...new Set([...beforeMap.keys(), ...afterMap.keys()])].sort(); + const lines: QuoteChangeLine[] = []; + let added = 0; + let removed = 0; + let updated = 0; + for (const key of keys) { + const oldRow = beforeMap.get(key) || null; + const newRow = afterMap.get(key) || null; + if (!oldRow && newRow) { + added += 1; + lines.push(changeLine(null, newRow, 'added')); + continue; + } + if (oldRow && !newRow) { + removed += 1; + lines.push(changeLine(oldRow, null, 'removed')); + continue; + } + const changed = + Math.abs(readItemSale(oldRow!) - readItemSale(newRow!)) > 1e-6 || + Math.abs(readItemCost(oldRow!) - readItemCost(newRow!)) > 1e-6 || + toText(oldRow!.unit).toLowerCase() !== toText(newRow!.unit).toLowerCase(); + if (changed) { + updated += 1; + lines.push(changeLine(oldRow, newRow, 'updated')); + } + } + return { + item_count: afterMap.size, + added, + removed, + updated, + lines: lines.slice(0, 30), + truncated: lines.length > 30, + }; +} + +/** 从「当前报价单明细 + 变更 payload」生成审核摘要 */ +export function buildChangeSummaryFromItems( + payload: QuoteChangePayload | null | undefined, + beforeRows: ItemLike[] +): QuoteChangeSummary { + const body = (payload || {}) as QuoteChangePayload; + const itemsProvided = Array.isArray(body.items); + const diff = itemsProvided + ? diffQuoteSheetItems(beforeRows, body.items as ItemLike[]) + : { item_count: 0, added: 0, removed: 0, updated: 0, lines: [], truncated: false }; + return { + title: typeof body.title === 'string' ? body.title : null, + quote_cycle: typeof body.quote_cycle === 'string' ? body.quote_cycle : null, + effective_at: typeof body.effective_at === 'string' ? body.effective_at : null, + auto_sale_price_by_cost: + typeof body.auto_sale_price_by_cost === 'boolean' ? body.auto_sale_price_by_cost : null, + customer_codes: Array.isArray(body.customer_codes) ? body.customer_codes.map(String) : null, + items_provided: itemsProvided, + ...diff, + }; +} + +async function loadSheetItems(quoteSheetCode: string): Promise { + const result = await pool.query( + `SELECT sku_code, sku_name, unit, sale_price, price, cost_price + FROM customer_quote_sheet_items + WHERE quote_sheet_code = $1 + ORDER BY sort_order ASC, sku_code ASC`, + [quoteSheetCode] + ); + return result.rows; +} + +/** 审核摘要(查当前明细后生成;提交响应与列表都用它) */ +export async function buildQuoteChangeSummary( + quoteSheetCode: string, + payload: QuoteChangePayload | null | undefined +): Promise { + return buildChangeSummaryFromItems(payload, await loadSheetItems(quoteSheetCode)); +} + +function toDto(row: Record): QuoteChangeRequestDto { + return { + id: String(row.id), + branch_code: String(row.branch_code), + quote_sheet_code: String(row.quote_sheet_code), + payload: (row.payload || {}) as QuoteChangePayload, + base_version_no: row.base_version_no === null || row.base_version_no === undefined ? null : Number(row.base_version_no), + base_items_fingerprint: row.base_items_fingerprint ? String(row.base_items_fingerprint) : null, + status: row.status, + requested_by: row.requested_by ? String(row.requested_by) : null, + requested_by_name: row.requested_by_name ? String(row.requested_by_name) : null, + requested_at: row.requested_at ?? null, + reviewed_by: row.reviewed_by ? String(row.reviewed_by) : null, + reviewed_by_name: row.reviewed_by_name ? String(row.reviewed_by_name) : null, + reviewed_at: row.reviewed_at ?? null, + reject_reason: row.reject_reason ? String(row.reject_reason) : null, + applied_at: row.applied_at ?? null, + updated_at: row.updated_at ?? null, + }; +} + +function buildChangePayload( + input: QuoteSheetUpdateInput, + normalized: { customerCodes: string[] | null; items: QuoteSheetItemInput[] | null } +): QuoteChangePayload { + const payload: QuoteChangePayload = {}; + if (input.title !== undefined) payload.title = String(input.title ?? ''); + if (normalized.customerCodes) payload.customer_codes = normalized.customerCodes; + if (normalized.items) payload.items = normalized.items; + if (input.autoSalePriceByCost !== undefined) payload.auto_sale_price_by_cost = Boolean(input.autoSalePriceByCost); + if (input.quoteCycle !== undefined) payload.quote_cycle = String(input.quoteCycle ?? ''); + if (input.effectiveAt !== undefined) payload.effective_at = String(input.effectiveAt); + return payload; +} + +/** + * 落一条 pending 变更单(D4):先把该单旧的 pending 置 `superseded`,再插入新的。 + * + * 并发两次提交会撞 partial unique index(23505)⇒ 回滚后**重跑一次**(重跑时旧 pending 已可见可覆盖)。 + */ +async function supersedeAndInsertPending(input: { + branchCode: string; + quoteSheetCode: string; + payload: QuoteChangePayload; + baseVersionNo: number | null; + baseItemsFingerprint: string; + requestedBy: string | null; +}): Promise<{ changeRequest: QuoteChangeRequestDto; supersededId: string | null }> { + let lastError: any = null; + for (let attempt = 0; attempt < 2; attempt += 1) { + const client = await pool.connect(); + try { + await client.query('BEGIN'); + // 先取旧 pending 的 id(D4 覆盖留痕 + 审计要记"旧状态→新状态") + const previous = await client.query<{ id: string }>( + `SELECT id::text AS id FROM quote_sheet_change_requests + WHERE branch_code = $1 AND quote_sheet_code = $2 AND status = 'pending' + FOR UPDATE`, + [input.branchCode, input.quoteSheetCode] + ); + const supersededId = previous.rows[0] ? String(previous.rows[0].id) : null; + await client.query( + `UPDATE quote_sheet_change_requests + SET status = 'superseded', updated_at = NOW() + WHERE branch_code = $1 AND quote_sheet_code = $2 AND status = 'pending'`, + [input.branchCode, input.quoteSheetCode] + ); + const inserted = await client.query( + `INSERT INTO quote_sheet_change_requests + (branch_code, quote_sheet_code, payload, base_version_no, base_items_fingerprint, + status, requested_by, requested_at, updated_at) + VALUES ($1, $2, $3::jsonb, $4, $5, 'pending', $6::uuid, NOW(), NOW()) + RETURNING *`, + [ + input.branchCode, + input.quoteSheetCode, + JSON.stringify(input.payload), + input.baseVersionNo, + input.baseItemsFingerprint, + input.requestedBy, + ] + ); + await client.query('COMMIT'); + return { changeRequest: toDto(inserted.rows[0] as Record), supersededId }; + } catch (error: any) { + try { + await client.query('ROLLBACK'); + } catch { + /* ignore */ + } + lastError = error; + if (error?.code === '23505' && attempt === 0) continue; + throw error; + } finally { + client.release(); + } + } + throw lastError || httpError(500, 'change_request_conflict', '提交待审变更失败'); +} + + +export type SaveQuoteSheetEditResult = + | { applied: true; data: unknown } + | { applied: false; data: unknown; changeRequest: QuoteChangeRequestDto }; + +/** + * 编辑保存入口(`PUT /quote/sheets/:code` 的唯一分流点): + * 价格相关 + 开关开 ⇒ 写/覆盖 pending 变更单,**不落报价单**,`applied:false`; + * 非价格 或 开关关 ⇒ 走现有 `updateQuoteSheet`(逐字不变),`applied:true`。 + */ +export async function saveQuoteSheetEdit( + input: QuoteSheetUpdateInput & { requestedBy?: string | null } +): Promise { + const existing = await loadQuoteSheetForUpdate( + input.quoteSheetCode, + input.ctx, + input.operatingBranchCode + ); + const priceRelated = isPriceRelatedQuoteEdit(input, existing as { auto_sale_price_by_cost?: unknown }); + const branchCode = String(existing.branch_code || '').trim(); + + if (!isQuoteEditApprovalEnabled() || !priceRelated) { + const data = await updateQuoteSheet(input); + // Lead 裁定 #6:非价格编辑若新增了 MAIN_<分公司> 客户,也要触发一次成本价同步。 + // 触发入口自带「指纹判重 + (单,分公司) 唯一键」⇒ 明细没变就是 duplicate 零出站;目标分公司集合变了则自然补推。 + if (!priceRelated) { + triggerQuoteCostSync({ branchCode, quoteSheetCode: input.quoteSheetCode }); + } + return { applied: true, data }; + } + + // 价格相关:先做提交期校验(失败即 400,一条变更单都不写、报价单也不动) + assertNoDuplicateSku(input.items); + const normalized = normalizeQuoteSheetUpdatePayload({ + customerCodes: input.customerCodes, + items: input.items, + }); + if (normalized.customerCodes) await assertCustomersInBranch(normalized.customerCodes, branchCode); + + const baseItemsFingerprint = quoteSheetItemsFingerprint(await loadSheetItems(input.quoteSheetCode)); + const { changeRequest, supersededId } = await supersedeAndInsertPending({ + branchCode, + quoteSheetCode: input.quoteSheetCode, + payload: buildChangePayload(input, normalized), + baseVersionNo: Number(existing.version_no) || null, + baseItemsFingerprint, + requestedBy: input.requestedBy ?? null, + }); + // 审计(A26):提交/覆盖都记一条;事务**提交之后**写,best-effort,失败只记日志 + await auditChangeRequest({ + operatorId: input.ctx?.userId || input.requestedBy || null, + operatorRole: input.ctx?.roles?.join(',') || null, + action: 'submit', + branchCode, + changeRequestId: changeRequest.id, + quoteSheetCode: input.quoteSheetCode, + oldStatus: supersededId ? 'pending' : '(none)', + newStatus: 'pending', + reason: supersededId ? `superseded:${supersededId}` : null, + }); + const data = await getQuoteSheet(input.quoteSheetCode, input.ctx, input.operatingBranchCode); + return { + applied: false, + data, + changeRequest: { + ...changeRequest, + summary: buildChangeSummaryFromItems(changeRequest.payload, await loadSheetItems(input.quoteSheetCode)), + }, + }; +} + +export type ListQuoteChangeRequestsInput = { + branchCode: string; + status?: string; + limit?: number; +}; + +/** 待审/历史列表(按分公司;`pending` 行带审核摘要) */ +export async function listQuoteSheetChangeRequests( + input: ListQuoteChangeRequestsInput +): Promise { + const branchCode = String(input.branchCode || '').trim(); + if (!branchCode) return []; + const status = ['pending', 'approved', 'rejected', 'superseded'].includes(String(input.status || '')) + ? String(input.status) + : 'pending'; + const limit = Math.min(Math.max(Number(input.limit) || 50, 1), 200); + const result = await pool.query( + // ⚠️ 展示名在 **public.profiles**(`full_name`/`username`),不在 `auth.users` + // (auth.users 是 Supabase 兼容表的子集,没有这两列;写错会让列表 GET 直接 500 —— 真库复现过)。 + // 仓库既有惯例见 `server/src/middleware/auth.ts` 的 `LEFT JOIN public.profiles p ON p.id = u.id`。 + `SELECT cr.*, + COALESCE(NULLIF(TRIM(ru.full_name), ''), NULLIF(TRIM(ru.username), ''), '') AS requested_by_name, + COALESCE(NULLIF(TRIM(vu.full_name), ''), NULLIF(TRIM(vu.username), ''), '') AS reviewed_by_name + FROM quote_sheet_change_requests cr + LEFT JOIN public.profiles ru ON ru.id = cr.requested_by + LEFT JOIN public.profiles vu ON vu.id = cr.reviewed_by + WHERE cr.branch_code = $1 AND cr.status = $2 + ORDER BY cr.requested_at DESC + LIMIT $3`, + [branchCode, status, limit] + ); + const rows = result.rows.map((row) => toDto(row as Record)); + const pendingCodes = [...new Set(rows.filter((row) => row.status === 'pending').map((row) => row.quote_sheet_code))]; + if (pendingCodes.length) { + const items = await pool.query( + `SELECT quote_sheet_code, sku_code, sku_name, unit, sale_price, price, cost_price + FROM customer_quote_sheet_items + WHERE quote_sheet_code = ANY($1)`, + [pendingCodes] + ); + const bySheet = new Map(); + for (const row of items.rows) { + const code = String((row as any).quote_sheet_code); + if (!bySheet.has(code)) bySheet.set(code, []); + bySheet.get(code)!.push(row); + } + for (const dto of rows) { + if (dto.status !== 'pending') continue; + dto.summary = buildChangeSummaryFromItems(dto.payload, bySheet.get(dto.quote_sheet_code) || []); + } + } + return rows; +} + +/** payload → `applyQuoteSheetUpdate` 入参(审批通过时使用;只认存下来的字段) */ +export function payloadToUpdateInput( + row: { quote_sheet_code: string; payload: QuoteChangePayload | null }, + options?: { ctx?: TenantContext | null; operatingBranchCode?: string | null } +): QuoteSheetUpdateInput { + const payload = (row.payload || {}) as QuoteChangePayload; + return { + quoteSheetCode: String(row.quote_sheet_code), + ctx: options?.ctx, + operatingBranchCode: options?.operatingBranchCode, + title: typeof payload.title === 'string' ? payload.title : undefined, + customerCodes: Array.isArray(payload.customer_codes) ? payload.customer_codes.map(String) : undefined, + items: Array.isArray(payload.items) ? payload.items.map(normalizeStoredItem) : undefined, + autoSalePriceByCost: + typeof payload.auto_sale_price_by_cost === 'boolean' ? payload.auto_sale_price_by_cost : undefined, + quoteCycle: typeof payload.quote_cycle === 'string' ? payload.quote_cycle : undefined, + effectiveAt: typeof payload.effective_at === 'string' ? payload.effective_at : undefined, + }; +} + +function normalizeStoredItem(raw: unknown): QuoteSheetItemInput { + const item = (raw || {}) as Record; + const sale = Number(item.sale_price ?? item.price); + return { + sku_code: toText(item.sku_code), + unit: item.unit === null || item.unit === undefined ? undefined : String(item.unit), + price: Number.isFinite(sale) ? sale : 0, + sale_price: Number.isFinite(sale) ? sale : 0, + cost_price: Number(item.cost_price) || 0, + markup_ratio: item.markup_ratio === null || item.markup_ratio === undefined ? null : Number(item.markup_ratio), + sku_name: item.sku_name === null || item.sku_name === undefined ? undefined : String(item.sku_name), + }; +} + +/** + * 应用前校验:SKU 必须仍存活(`skus.status = 1`)、客户必须仍属该分公司。 + * + * 为什么非查不可:真库 `customer_quote_sheet_items` **零外键**(只有 `legacy_public` 有), + * 直接 INSERT 会造出孤儿行且**没有任何报错**。校验失败 ⇒ 409,变更单保持 pending(不悄悄丢掉), + * 由审核人决定驳回。 + */ +async function assertPayloadStillApplicable( + client: import('pg').PoolClient, + row: { quote_sheet_code: string; payload: QuoteChangePayload | null; branch_code: string } +): Promise { + const payload = (row.payload || {}) as QuoteChangePayload; + const skuCodes = [ + ...new Set((payload.items || []).map((item) => toText(item?.sku_code)).filter(Boolean)), + ]; + if (skuCodes.length) { + const alive = await client.query<{ sku_code: string }>( + `SELECT sku_code FROM skus WHERE sku_code = ANY($1) AND status = 1`, + [skuCodes] + ); + const aliveSet = new Set(alive.rows.map((item) => String(item.sku_code))); + const missing = skuCodes.filter((code) => !aliveSet.has(code)); + if (missing.length) { + throw httpError(409, 'sku_unavailable', `商品已停用或不存在:${missing.slice(0, 5).join('、')}`); + } + } + const customerCodes = Array.isArray(payload.customer_codes) ? payload.customer_codes.map(String) : []; + if (customerCodes.length) { + const found = await client.query<{ customer_code: string }>( + `SELECT customer_code FROM customers WHERE customer_code = ANY($1) AND branch_code = $2`, + [customerCodes, row.branch_code] + ); + const foundSet = new Set(found.rows.map((item) => String(item.customer_code))); + const missing = customerCodes.filter((code) => !foundSet.has(code)); + if (missing.length) { + throw httpError(409, 'invalid_customer', `客户不属于本分公司或已不存在:${missing.slice(0, 5).join('、')}`); + } + } +} + +export type ApproveQuoteChangeRequestInput = { + id: string; + ctx?: TenantContext | null; + operatingBranchCode?: string | null; + reviewedBy?: string | null; +}; + +/** + * 审核通过:**单事务**内应用变更 + 记审批 → 提交后再触发成本价同步(rearm 路径)。 + * + * ⚠️ 绝不走 `approveQuoteSheet`/`activateQuoteSheet`:那会把**同分公司共享客户的其它生效单**置 `status=3` + * 并重写审批字段;本路径只复用 `applyQuoteSheetUpdate`,报价单的 4 个审批字段一个都不碰。 + */ +export async function approveQuoteSheetChangeRequest( + input: ApproveQuoteChangeRequestInput +): Promise<{ data: unknown; changeRequest: QuoteChangeRequestDto }> { + const branchCode = getEffectiveBranchCode(input.ctx || null, input.operatingBranchCode); + if (!branchCode) throw httpError(400, 'branch_required', '请选择当前操作分公司'); + + const client = await pool.connect(); + let committed = false; + let row: Record; + try { + await client.query('BEGIN'); + const locked = await client.query( + `SELECT * FROM quote_sheet_change_requests WHERE id = $1::uuid FOR UPDATE`, + [input.id] + ); + if (!locked.rows.length) throw httpError(404, 'change_request_not_found', '变更单不存在'); + row = locked.rows[0] as Record; + if (String(row.branch_code) !== branchCode) { + throw httpError(403, 'branch_mismatch', '无权操作其它分公司的变更单'); + } + if (String(row.status) !== 'pending') { + throw httpError(409, 'already_decided', '该变更单已处理'); + } + + /** + * **校验顺序(P3-1,红队第三轮)**:目标单**可用性**必须排在**指纹**之前。 + * + * 为什么:目标报价单被**硬删除**时,`customer_quote_sheet_items` 查出来是空集 + * ⇒ 指纹必然"不一致" ⇒ 会走 `base_changed` 的**自动 rejected** 分支; + * 而 A12③ 修订版要求这种情况是 **409 `target_unavailable` + 变更单保持 pending**(人工可驳回)。 + * + * ⚠️ 只动顺序,不动语义: + * · 目标不存在/非执行中/已过期 ⇒ `loadQuoteSheetForUpdate` 抛既有普通 Error ⇒ `mapTargetUnavailable` + * 映射成 409 `target_unavailable`(变更单保持 pending,零应用、零推送); + * · 目标**仍可用但指纹变了** ⇒ 仍然 409 `base_changed` + 自动 `rejected`(下一段,不回退)。 + */ + try { + await loadQuoteSheetForUpdate(row.quote_sheet_code, input.ctx, input.operatingBranchCode); + } catch (error: any) { + throw mapTargetUnavailable(error) || error; + } + + // 目标单在提交后是否被改过(base_changed):指纹不一致 ⇒ 整单拒绝,零应用、零推送 + const currentItems = await client.query( + `SELECT sku_code, unit, sale_price, price FROM customer_quote_sheet_items + WHERE quote_sheet_code = $1`, + [row.quote_sheet_code] + ); + if (quoteSheetItemsFingerprint(currentItems.rows as ItemLike[]) !== String(row.base_items_fingerprint || '')) { + const rejected = await client.query( + `UPDATE quote_sheet_change_requests + SET status = 'rejected', reviewed_by = $2::uuid, reviewed_at = NOW(), + reject_reason = 'base_changed', updated_at = NOW() + WHERE id = $1::uuid AND status = 'pending' + RETURNING *`, + [row.id, input.reviewedBy ?? null] + ); + await client.query('COMMIT'); + committed = true; + if (rejected.rows.length) row = rejected.rows[0] as Record; + // 系统自动驳回也留审计(A26) + await auditChangeRequest({ + operatorId: input.ctx?.userId || input.reviewedBy || null, + operatorRole: input.ctx?.roles?.join(',') || null, + action: 'reject', + branchCode, + changeRequestId: String(row.id), + quoteSheetCode: String(row.quote_sheet_code), + oldStatus: 'pending', + newStatus: 'rejected', + reason: 'base_changed', + }); + throw httpError(409, 'base_changed', '报价单在提交后被修改,本条变更已整单拒绝(未应用、未同步)'); + } + + // 应用前守卫:SKU 存活 + 客户归属(零外键 ⇒ 必须自己查);目标可用性已在上方校验过 + await assertPayloadStillApplicable(client, row as any); + + let data: unknown; + try { + data = await applyQuoteSheetUpdate(payloadToUpdateInput(row as any, { + ctx: input.ctx, + operatingBranchCode: input.operatingBranchCode, + }), { client }); + } catch (error: any) { + // 同上:apply 内部的三连守卫也是普通 Error(并发下目标单状态可能在这一刻变化) + throw mapTargetUnavailable(error) || error; + } + + const approved = await client.query( + `UPDATE quote_sheet_change_requests + SET status = 'approved', reviewed_by = $2::uuid, reviewed_at = NOW(), + applied_at = NOW(), reject_reason = NULL, updated_at = NOW() + WHERE id = $1::uuid AND status = 'pending' + RETURNING *`, + [row.id, input.reviewedBy ?? null] + ); + if (!approved.rows.length) throw httpError(409, 'already_decided', '该变更单已处理'); + row = approved.rows[0] as Record; + await client.query('COMMIT'); + committed = true; + + // 事务提交之后:先留审计(A26),再触发成本价同步(既有 rearm 路径) + await auditChangeRequest({ + operatorId: input.ctx?.userId || input.reviewedBy || null, + operatorRole: input.ctx?.roles?.join(',') || null, + action: 'approve', + branchCode, + changeRequestId: String(row.id), + quoteSheetCode: String(row.quote_sheet_code), + oldStatus: 'pending', + newStatus: 'approved', + }); + triggerQuoteCostSync({ + branchCode: String(row.branch_code), + quoteSheetCode: String(row.quote_sheet_code), + }); + + const detail = await getQuoteSheet( + String(row.quote_sheet_code), + input.ctx, + input.operatingBranchCode + ); + return { + data: detail, + changeRequest: { + ...toDto(row), + summary: buildChangeSummaryFromItems(row.payload as QuoteChangePayload, await loadSheetItems(String(row.quote_sheet_code))), + }, + }; + } catch (error) { + if (!committed) { + try { + await client.query('ROLLBACK'); + } catch { + /* ignore */ + } + } + throw error; + } finally { + client.release(); + } +} + +export type RejectQuoteChangeRequestInput = { + id: string; + reason: string; + ctx?: TenantContext | null; + operatingBranchCode?: string | null; + reviewedBy?: string | null; +}; + +/** 审核驳回:只改变更单状态(`rejected` + 理由),报价单不变、**零推送**。 */ +export async function rejectQuoteSheetChangeRequest( + input: RejectQuoteChangeRequestInput +): Promise<{ changeRequest: QuoteChangeRequestDto }> { + const branchCode = getEffectiveBranchCode(input.ctx || null, input.operatingBranchCode); + if (!branchCode) throw httpError(400, 'branch_required', '请选择当前操作分公司'); + const reason = toText(input.reason); + if (!reason) throw httpError(400, 'reject_reason_required', '请填写驳回理由'); + + const found = await pool.query( + `SELECT id, branch_code, status FROM quote_sheet_change_requests WHERE id = $1::uuid`, + [input.id] + ); + if (!found.rows.length) throw httpError(404, 'change_request_not_found', '变更单不存在'); + if (String(found.rows[0].branch_code) !== branchCode) { + throw httpError(403, 'branch_mismatch', '无权操作其它分公司的变更单'); + } + const updated = await pool.query( + `UPDATE quote_sheet_change_requests + SET status = 'rejected', reviewed_by = $2::uuid, reviewed_at = NOW(), + reject_reason = $3, updated_at = NOW() + WHERE id = $1::uuid AND status = 'pending' + RETURNING *`, + [input.id, input.reviewedBy ?? null, reason] + ); + if (!updated.rows.length) throw httpError(409, 'already_decided', '该变更单已处理'); + const changeRequest = toDto(updated.rows[0] as Record); + // 审计(A26):驳回路径,best-effort + await auditChangeRequest({ + operatorId: input.ctx?.userId || input.reviewedBy || null, + operatorRole: input.ctx?.roles?.join(',') || null, + action: 'reject', + branchCode, + changeRequestId: changeRequest.id, + quoteSheetCode: changeRequest.quote_sheet_code, + oldStatus: 'pending', + newStatus: 'rejected', + reason, + }); + return { changeRequest }; +} diff --git a/server/src/services/quoteSheetService.ts b/server/src/services/quoteSheetService.ts index aefce04..b34383b 100644 --- a/server/src/services/quoteSheetService.ts +++ b/server/src/services/quoteSheetService.ts @@ -1,6 +1,7 @@ import { pool } from '../db'; import { getEffectiveBranchCode, type TenantContext } from './tenantScope'; import { notifyRoleUsers } from './notificationService'; +import { triggerQuoteCostSync } from './mainSystemQuoteCostSync'; export const QUOTE_CYCLE_OPTIONS = { week: { label: '周', days: 7 }, @@ -54,7 +55,7 @@ function branchFilter( return ` AND ${alias}.branch_code = $${params.length}`; } -async function assertCustomersInBranch(customerCodes: string[], branchCode: string) { +export async function assertCustomersInBranch(customerCodes: string[], branchCode: string) { const result = await pool.query( `SELECT customer_code FROM customers WHERE customer_code = ANY($1) AND branch_code = $2`, [customerCodes, branchCode] @@ -246,7 +247,14 @@ export async function createQuoteSheet(input: { client.release(); } - return loadSheetDetail(quoteSheetCode); + const detail = await loadSheetDetail(quoteSheetCode); + /** + * 报价单已生效 ⇒ **事务提交之后**把销售价推给主系统(成本价同步,开关默认关)。 + * 旁路异步 + 内部吞异常:任何推送失败都不得让建单失败;出网也绝不在事务内。 + * 设计:docs/design/20261018-报价单成本价同步推送.md §3 + */ + triggerQuoteCostSync({ branchCode: detail?.branch_code, quoteSheetCode }); + return detail; } /** 列表:默认当前执行中的报价单 */ @@ -347,7 +355,10 @@ export async function submitQuoteSheetForApproval(input: { client.release(); } - return loadSheetDetail(input.quoteSheetCode); + const detail = await loadSheetDetail(input.quoteSheetCode); + // 提交报价单(旧接口:提交即生效)⇒ 事务提交之后再推送销售价(旁路,失败不影响审批) + triggerQuoteCostSync({ branchCode: detail?.branch_code, quoteSheetCode: input.quoteSheetCode }); + return detail; } async function activateQuoteSheet( @@ -479,8 +490,8 @@ async function assertQuoteSheetAccessible( return result.rows[0]; } -/** 修改执行中的报价单(仅影响后续下单取价,历史订单明细不变) */ -export async function updateQuoteSheet(input: { +/** 修改执行中的报价单的入参(PUT /quote/sheets/:code 与「待审变更」共用) */ +export type QuoteSheetUpdateInput = { quoteSheetCode: string; title?: string; customerCodes?: string[]; @@ -490,19 +501,41 @@ export async function updateQuoteSheet(input: { effectiveAt?: string | null; ctx?: TenantContext | null; operatingBranchCode?: string | null; -}) { - const existing = await assertQuoteSheetAccessible( - input.quoteSheetCode, - input.ctx, - input.operatingBranchCode - ); +}; + +/** 「仅执行中的报价单可修改」三连守卫(改价审核提交与审核通过应用共用,口径只此一份) */ +export function assertQuoteSheetEditableForUpdate(existing: { + status: unknown; + approval_status: unknown; + expires_at?: Date | string | null; +}): void { if (Number(existing.status) !== 1 || Number(existing.approval_status) !== 30) { throw new Error('仅执行中的报价单可修改'); } if (existing.expires_at && new Date(existing.expires_at) <= new Date()) { throw new Error('报价单已过期,无法修改'); } +} +/** + * 读「可修改的生效单」并过三连守卫(改价审核提交用;**只读**,不写库)。 + * 返回原始 sheet 行(含 branch_code / version_no / auto_sale_price_by_cost)。 + */ +export async function loadQuoteSheetForUpdate( + quoteSheetCode: string, + ctx?: TenantContext | null, + operatingBranchCode?: string | null +) { + const existing = await assertQuoteSheetAccessible(quoteSheetCode, ctx, operatingBranchCode); + assertQuoteSheetEditableForUpdate(existing as { status: unknown; approval_status: unknown; expires_at?: Date | null }); + return existing; +} + +/** 入参归一(客户去重、明细过滤空行/零价行 + 非空校验):apply 与待审提交共用 */ +export function normalizeQuoteSheetUpdatePayload(input: { + customerCodes?: string[]; + items?: QuoteSheetItemInput[]; +}): { customerCodes: string[] | null; items: QuoteSheetItemInput[] | null } { const customerCodes = input.customerCodes ? [...new Set(input.customerCodes.map((c) => c.trim()).filter(Boolean))] : null; @@ -511,12 +544,33 @@ export async function updateQuoteSheet(input: { : null; if (customerCodes && !customerCodes.length) throw new Error('请至少选择一个客户'); if (items && !items.length) throw new Error('请至少添加一个商品'); + return { customerCodes, items }; +} +/** + * **应用**一次报价单修改(原 `updateQuoteSheet` 的全部动作,行为逐字不变)。 + * + * @param options.client 传入时**在调用方事务内**执行(审核通过「单事务应用」用); + * 不传时自己 BEGIN/COMMIT/ROLLBACK(= 改造前行为,`updateQuoteSheet` 走这条)。 + */ +export async function applyQuoteSheetUpdate( + input: QuoteSheetUpdateInput, + options?: { client?: import('pg').PoolClient } +) { + const existing = await assertQuoteSheetAccessible( + input.quoteSheetCode, + input.ctx, + input.operatingBranchCode + ); + assertQuoteSheetEditableForUpdate(existing as { status: unknown; approval_status: unknown; expires_at?: Date | null }); + + const { customerCodes, items } = normalizeQuoteSheetUpdatePayload(input); const { quoteCycle, effectiveAt, expiresAt } = resolveQuoteSheetUpdateDates(existing, input); - const client = await pool.connect(); + const client = options?.client ?? (await pool.connect()); + const ownsClient = !options?.client; try { - await client.query('BEGIN'); + if (ownsClient) await client.query('BEGIN'); await client.query( `UPDATE customer_quote_sheets @@ -583,17 +637,27 @@ export async function updateQuoteSheet(input: { const sheet = sheetResult.rows[0]; await materializeQuoteVersions(client, sheet, { expireSheetVersionsFirst: true }); - await client.query('COMMIT'); + if (ownsClient) await client.query('COMMIT'); } catch (error) { - await client.query('ROLLBACK'); + if (ownsClient) await client.query('ROLLBACK'); throw error; } finally { - client.release(); + if (ownsClient) client.release(); } return loadSheetDetail(input.quoteSheetCode); } +/** + * 修改执行中的报价单(仅影响后续下单取价,历史订单明细不变)。 + * + * ⚠️ 行为与改造前**逐字一致**:本函数就是 `applyQuoteSheetUpdate` 的薄封装。 + * 「价格相关改动需审核」的分流在路由/变更单服务里,不在这里(回滚开关时仍走本函数)。 + */ +export async function updateQuoteSheet(input: QuoteSheetUpdateInput) { + return applyQuoteSheetUpdate(input); +} + export async function setQuoteSheetAutoSalePriceByCost(input: { quoteSheetCode: string; enabled: boolean; @@ -951,7 +1015,10 @@ export async function approveQuoteSheet(input: { } finally { client.release(); } - return loadSheetDetail(input.quoteSheetCode); + const detail = await loadSheetDetail(input.quoteSheetCode); + // 审批通过 ⇒ 事务提交之后再推送销售价(旁路,失败不影响审批结论) + triggerQuoteCostSync({ branchCode: detail?.branch_code, quoteSheetCode: input.quoteSheetCode }); + return detail; } const nextStatus = 40; diff --git a/server/src/services/scheduledJobs.ts b/server/src/services/scheduledJobs.ts index cead868..24f5883 100644 --- a/server/src/services/scheduledJobs.ts +++ b/server/src/services/scheduledJobs.ts @@ -509,6 +509,77 @@ async function runReportPushReconcile() { } } +/** + * 报价单**双向价格传递**定时对账(2026-10-18 冻结契约): + * · 调配送系统 D2 增量拉取(T10 游标):回写方向 A 的结果、拉回方向 B 的提议(建本地 pending); + * · 顺带补发 D3 回执(T8:本地已终态、远端仍 pending 的行重发一次,幂等); + * · 开关 `MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL` 默认关 ⇒ 函数内部直接返回(零出站)。 + */ +async function runQuotePriceProposalSync() { + try { + const { syncQuotePriceProposals } = await import('./quotePriceProposalService'); + const summary = await syncQuotePriceProposals({ limit: 100 }); + if (summary.pulled || summary.synced || summary.receipts || summary.errors) { + console.log( + `[scheduler] 报价单价格传递对账:供应商 ${summary.suppliers} 个,拉回 ${summary.pulled}、` + + `回写 ${summary.synced}、补回执 ${summary.receipts}、跳过 ${summary.skipped}、异常 ${summary.errors}` + ); + } + } catch (error) { + console.error('[scheduler] 报价单价格传递对账失败:', error); + } +} + +/** + * **SKU 映射**:每天一次 **D4 推字典 + D5 拉映射**(2026-10-18 冻结契约 §5)。 + * + * 口径:映射在配送侧维护、我方只读同步;**每天一次**即可(进程内按本地日期去重,重启会多跑一次,安全)。 + * 开关 `MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL` 关闭 ⇒ 零出站。 + * 失败只记日志,不抛(不得阻塞同轮其它跨系统任务)。 + */ +let lastSkuMappingSyncDate = ''; +async function runSkuMappingSync() { + const today = new Date().toISOString().slice(0, 10); + if (lastSkuMappingSyncDate === today) return; + try { + const { syncDictionaryAndMappingsForAllBranches } = await import('./skuMappingService'); + const summary = await syncDictionaryAndMappingsForAllBranches(); + if (summary.skipped) return; + lastSkuMappingSyncDate = today; + console.log( + `[scheduler] SKU 映射同步:分公司 ${summary.branches} 个,` + + `推送字典 ${summary.pushedSkus} 条(${summary.pushBatches} 批)、` + + `写入映射 ${summary.pulled} 行、异常 ${summary.errors}` + ); + } catch (error) { + console.error('[scheduler] SKU 映射同步失败:', error); + } +} + +/** + * 报价单销售价 → 主系统成本价:**失败行定时重试**(2026-10-18)。 + * + * 口径(冻结):只重试 `status='failed'` 且 `attempts < 5` 的台账行;**复用原 `client_request_id`** + * (对方按请求号幂等);`forbidden` / `sent` / `skipped` 永不重试。 + * 开关 `MAIN_SYSTEM_QUOTE_COST_SYNC` 默认关 ⇒ 函数内部直接返回(零查库、零出站)。 + * 单行失败只记日志,不中断其它行;本函数自己不抛(不得阻塞同轮其它跨系统任务)。 + */ +async function runQuoteCostSyncReconcile() { + try { + const { retryQuoteCostSyncPushes } = await import('./mainSystemQuoteCostSync'); + const summary = await retryQuoteCostSyncPushes({ limit: 20 }); + if (summary.rows) { + console.log( + `[scheduler] 报价单成本价同步重试:选中 ${summary.rows} 行,成功 ${summary.sent}、` + + `仍失败 ${summary.failed}、对方拒绝(forbidden) ${summary.forbidden}、转跳过 ${summary.skipped}` + + `${summary.errors ? `、异常 ${summary.errors}` : ''}` + ); + } + } catch (error) { + console.error('[scheduler] 报价单成本价同步重试失败:', error); + } +} + /** * 库存抵扣 ⇒ 批次计划兜底(2026-10-12):给"已抵扣但还没有批次计划"的订单补 FIFO 批次。 * @@ -1027,6 +1098,12 @@ export function startScheduledJobs() { runDeferredUnitResendSweep(), // 批次报告推送对账(开关默认关 ⇒ 直接返回) runReportPushReconcile(), + // 报价单销售价 → 主系统成本价:失败行重试(开关默认关 ⇒ 直接返回) + runQuoteCostSyncReconcile(), + // 报价单双向价格传递:D2 对账 + B 提议拉取 + D3 回执补发(开关默认关 ⇒ 直接返回) + runQuotePriceProposalSync(), + // SKU 映射:每天拉一次 D5(开关默认关 ⇒ 直接返回;进程内按日期去重) + runSkuMappingSync(), // 主系统镜像空单收口兜底(纯本地) runEmptyMirrorOrderClosure(), ]); diff --git a/server/src/services/skuMappingService.ts b/server/src/services/skuMappingService.ts new file mode 100644 index 0000000..7c2b2eb --- /dev/null +++ b/server/src/services/skuMappingService.ts @@ -0,0 +1,492 @@ +import { pool } from '../db'; +import { runWithTenantDbContext } from './tenantDbContext'; +import { getEffectiveBranchCode, type TenantContext } from './tenantScope'; +import { resolveMainSupplierCode } from './mainSystemQuoteCostSync'; +import { + SKU_MAPPING_MAX_BATCH, + pullSkuMappings, + pushSkuDictionary, + type RemoteSkuMappingRow, +} from './mainSystem/api/skuMappings'; + +/** + * **SKU 映射**(2026-10-18 冻结契约 `.team/sku-mapping-shared-sheet/contract.md` §5)。 + * + * 关键口径(用户当轮):两个系统的 SKU **不一致**,同一个商品也不能按 sku_code 直接猜; + * 映射在**配送侧维护**,我方**只读同步**: + * · **D4 推字典**:把我方 `skus` 里 `status` 有效的商品(sku_code/name/unit)整批推上去(≤5000/批); + * · **D5 拉映射**:只读拉回写本分公司 `main_system_sku_mappings`(幂等 upsert + 删除远端已不存在的行); + * · **方向 B 反查**:提议 items 是配送 SKU ⇒ 用本表反查我方 SKU;查不到 ⇒ 审批时 skip `sku_unmapped`。 + * + * 开关沿用 `MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL`(默认关 ⇒ 零出站、零写库)。 + * 设计:docs/design/20261018-SKU映射与成本传递.md + */ + +export const SKU_MAPPING_PULL_PAGE_SIZE = 200; +export const SKU_MAPPING_PULL_MAX_PAGES = 50; + +function httpError(status: number, code: string, message: string) { + return Object.assign(new Error(message), { status, code }); +} + +/** 开关:与报价单价格传递同一个(默认关;`1` / `true` / `on` 才开) */ +export function isSkuMappingEnabled(): boolean { + const raw = String(process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL ?? '').trim().toLowerCase(); + return raw === '1' || raw === 'true' || raw === 'on'; +} + +function toText(value: unknown): string { + return value === null || value === undefined ? '' : String(value).trim(); +} + +export type SkuDictionaryPushSummary = { + skus: number; + batches: number; + matched: number; + pending: number; + kept: number; + total: number; +}; + +/** + * D4:把我方商品字典整批推给配送侧(≤5000/批)。 + * + * 只推 `status` 有效的商品(`status IS NULL OR status = 1`,与本仓库 `skus` 口径一致)。 + * 出站全部在事务之外;每批失败即中止并抛错(已推的批次可由对方幂等 upsert 覆盖,重试安全)。 + */ +export async function pushSkuDictionaryForBranch(input: { + branchCode?: string | null; + ctx?: TenantContext | null; + operatingBranchCode?: string | null; +}): Promise { + if (!isSkuMappingEnabled()) { + throw httpError(503, 'feature_disabled', '报价单价格传递未开启(MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL)'); + } + // 显式 branchCode 优先(定时/后台调用没有请求 ctx),其次按 ctx + 超管操作分公司解析 + const branchCode = + toText(input.branchCode) || getEffectiveBranchCode(input.ctx || null, input.operatingBranchCode || null); + if (!branchCode) throw httpError(400, 'branch_required', '请选择当前操作分公司'); + const supplierCode = await resolveMainSupplierCode(branchCode); + if (!supplierCode) { + throw httpError(409, 'main_supplier_code_missing', '该分公司在主系统没有可用供应商编码,无法推送商品字典'); + } + + // 读 skus 必须在**该分公司的租户上下文**里(定时任务/后台脚本没有请求级 ctx,必须显式 isolate) + const skus = await runWithTenantDbContext( + branchCode, + () => + pool.query<{ sku_code: string; sku_name: string | null; unit: string | null }>( + `SELECT sku_code, sku_name, unit FROM skus + WHERE status IS NULL OR status = 1 + ORDER BY sku_code ASC` + ), + { isolate: true, requestClient: false } + ); + const items = skus.rows + .map((row) => ({ + sku_code: toText(row.sku_code), + name: toText(row.sku_name) || toText(row.sku_code), + unit: toText(row.unit) || null, + })) + .filter((item) => item.sku_code); + if (!items.length) { + throw httpError(400, 'skus_empty', '本分公司没有可推送的商品(skus 为空)'); + } + + const summary: SkuDictionaryPushSummary = { + skus: items.length, + batches: 0, + matched: 0, + pending: 0, + kept: 0, + total: 0, + }; + for (let offset = 0; offset < items.length; offset += SKU_MAPPING_MAX_BATCH) { + const batch = items.slice(offset, offset + SKU_MAPPING_MAX_BATCH); + const pushed = await pushSkuDictionary({ + supplierCode, + mainBranchCode: branchCode, + items: batch, + }); + if (pushed.kind !== 'ok') { + throw httpError( + pushed.kind === 'rejected' ? pushed.status || 400 : 502, + pushed.code, + pushed.reason + ); + } + summary.batches += 1; + summary.matched += pushed.data.matched; + summary.pending += pushed.data.pending; + summary.kept += pushed.data.kept; + summary.total += pushed.data.total || batch.length; + } + return summary; +} + +export type SkuMappingPullSummary = { + total: number; + upserted: number; + deleted: number; + conflicts: number; + truncated: boolean; + pages: number; +}; + +/** + * D5:只读拉映射 → 幂等 upsert 本地表;**完整拉取**(未截断)时删除远端已不存在的行。 + * + * 用 `runWithTenantDbContext(..., {isolate:true})`:定时任务与请求内都走同一条路径, + * 不必区分"当前有没有请求级连接"。 + */ +export async function pullMappingsFromMainSystem(input: { + branchCode?: string | null; +}): Promise { + const branchCode = toText(input.branchCode); + if (!branchCode) throw httpError(400, 'branch_required', '缺少分公司'); + if (!isSkuMappingEnabled()) { + return { total: 0, upserted: 0, deleted: 0, conflicts: 0, truncated: false, pages: 0 }; + } + const supplierCode = await resolveMainSupplierCode(branchCode); + if (!supplierCode) { + throw httpError(409, 'main_supplier_code_missing', '该分公司在主系统没有可用供应商编码,无法拉取 SKU 映射'); + } + + // D5 翻页(出站,全程无事务) + const collected = new Map(); + let cursor: string | null = null; + let pages = 0; + let remoteTotal: number | null = null; + /** + * ⛔ verifier 阻断项(>200 行数据丢失):**只有证明"拉全了"才允许删除本地多余行**。 + * 旧实现只拉第一页、且把"没有 next_cursor"当成完整 ⇒ 商品超过 200 条时本地映射被误删。 + * 现在: + * · 按 `next_cursor` 翻页直到 null(上限 `SKU_MAPPING_PULL_MAX_PAGES`); + * · 完整性判据 = 到达 `total`,或**最后一页是短页**(rows < limit); + * · 任一页失败/翻页超上限/无法证明完整 ⇒ `truncated=true`、**本次不删**,并记日志。 + */ + let complete = false; + let truncated = false; + for (let page = 0; page < SKU_MAPPING_PULL_MAX_PAGES; page += 1) { + const listed = await pullSkuMappings({ + supplierCode, + mainBranchCode: branchCode, + limit: SKU_MAPPING_PULL_PAGE_SIZE, + cursor, + }); + if (listed.kind !== 'ok') { + truncated = true; + console.warn( + `[sku-mapping] D5 第 ${page + 1} 页失败(branch=${branchCode}),本次只做部分刷新、**不删除**本地多余行:`, + listed.reason + ); + break; + } + pages += 1; + if (remoteTotal === null && listed.total !== null && listed.total !== undefined) { + remoteTotal = Number(listed.total); + } + const pageRows = listed.rows.length; + for (const row of listed.rows) collected.set(row.supplier_sku_code, row); + if (!listed.nextCursor || listed.nextCursor === cursor) { + complete = + (remoteTotal !== null && collected.size >= remoteTotal) || + pageRows < SKU_MAPPING_PULL_PAGE_SIZE; + if (!complete) { + console.warn( + `[sku-mapping] D5 无法证明拉全(branch=${branchCode},已收 ${collected.size} 行` + + `${remoteTotal === null ? ',对方未给 total' : `,对方 total=${remoteTotal}`})⇒ 本次不删除本地多余行` + ); + } + break; + } + cursor = listed.nextCursor; + if (page === SKU_MAPPING_PULL_MAX_PAGES - 1) { + truncated = true; + console.warn( + `[sku-mapping] D5 翻页超过上限 ${SKU_MAPPING_PULL_MAX_PAGES} 页(branch=${branchCode}),本次不删除本地多余行` + ); + } + } + if (!complete) truncated = true; + + const rows = [...collected.values()]; + const summary: SkuMappingPullSummary = { + total: rows.length, + upserted: 0, + deleted: 0, + conflicts: 0, + truncated, + pages, + }; + if (!rows.length && truncated) return summary; + + await runWithTenantDbContext( + branchCode, + async () => { + for (const row of rows) { + const status = ['active', 'disabled', 'pending'].includes(row.status) ? row.status : 'pending'; + const deliverySku = toText(row.delivery_sku_code) || null; + try { + await pool.query( + `INSERT INTO main_system_sku_mappings + (supplier_sku_code, supplier_sku_name, supplier_unit, delivery_sku_code, delivery_sku_name, + status, synced_at, updated_at) + VALUES ($1, $2, $3, $4, $5, $6, NOW(), NOW()) + ON CONFLICT (supplier_sku_code) DO UPDATE SET + supplier_sku_name = EXCLUDED.supplier_sku_name, + supplier_unit = EXCLUDED.supplier_unit, + delivery_sku_code = EXCLUDED.delivery_sku_code, + delivery_sku_name = EXCLUDED.delivery_sku_name, + status = EXCLUDED.status, + synced_at = NOW(), + updated_at = NOW()`, + [ + row.supplier_sku_code, + row.supplier_sku_name, + row.supplier_unit, + deliverySku, + row.delivery_sku_name, + status, + ] + ); + summary.upserted += 1; + } catch (error: any) { + // 配送侧保证 active 的 delivery_sku 唯一;真撞了就跳过该行(不破坏已有映射),记 conflict 供排障 + summary.conflicts += 1; + console.warn( + `[sku-mapping] upsert 失败(branch=${branchCode}, supplier_sku=${row.supplier_sku_code}):`, + error?.message || error + ); + } + } + // **只有完整拉取成功**才删除远端已不存在的行(截断/失败一律不动,避免误删) + if (complete && !truncated) { + const deleted = await pool.query<{ id: string }>( + `DELETE FROM main_system_sku_mappings + WHERE supplier_sku_code <> ALL($1::text[]) + RETURNING id::text AS id`, + [rows.map((row) => row.supplier_sku_code)] + ); + summary.deleted = deleted.rowCount || 0; + } + }, + { isolate: true, requestClient: false } + ); + return summary; +} + +/** 方向 B 反查:配送 SKU → 我方 SKU(只认 active + delivery_sku_code 非空) */ +export async function getMappingByDeliverySku( + branchCode: string, + deliverySkuCode: string +): Promise<{ supplier_sku_code: string; supplier_sku_name: string | null; supplier_unit: string | null } | null> { + const delivery = toText(deliverySkuCode); + if (!branchCode || !delivery) return null; + const result = await pool.query<{ supplier_sku_code: string; supplier_sku_name: string | null; supplier_unit: string | null }>( + `SELECT supplier_sku_code, supplier_sku_name, supplier_unit + FROM main_system_sku_mappings + WHERE delivery_sku_code = $1 AND status = 'active' + LIMIT 1`, + [delivery] + ); + const row = result.rows[0]; + if (!row) return null; + return { + supplier_sku_code: String(row.supplier_sku_code), + supplier_sku_name: row.supplier_sku_name ? String(row.supplier_sku_name) : null, + supplier_unit: row.supplier_unit ? String(row.supplier_unit) : null, + }; +} + +export type SheetMappingStats = { + quote_sheet_code: string; + total: number; + mapped: number; + unmapped: number; + /** 未映射/待处理的我方 SKU(前端提示用) */ + unmapped_skus: Array<{ sku_code: string; sku_name: string | null }>; +}; + +/** + * 提交前映射统计:「本单 N 个商品,已映射 X / 未映射 Y」。 + * + * "已映射" = 本地映射表里该我方 SKU 行 `status='active'` 且 `delivery_sku_code` 非空。 + * **不按名称猜**(本侧只认配送侧下发的映射)。 + */ +export async function getSheetMappingStats(quoteSheetCode: string): Promise { + const items = await pool.query<{ sku_code: string; sku_name: string | null }>( + `SELECT sku_code, sku_name FROM customer_quote_sheet_items WHERE quote_sheet_code = $1 ORDER BY sku_code ASC`, + [quoteSheetCode] + ); + const skuCodes = items.rows.map((row) => String(row.sku_code)); + if (!skuCodes.length) { + return { quote_sheet_code: quoteSheetCode, total: 0, mapped: 0, unmapped: 0, unmapped_skus: [] }; + } + const mappings = await pool.query<{ supplier_sku_code: string; delivery_sku_code: string | null; status: string }>( + `SELECT supplier_sku_code, delivery_sku_code, status + FROM main_system_sku_mappings + WHERE supplier_sku_code = ANY($1)`, + [skuCodes] + ); + const mappedSet = new Set( + mappings.rows + .filter((row) => row.status === 'active' && toText(row.delivery_sku_code)) + .map((row) => String(row.supplier_sku_code)) + ); + const unmapped_skus = items.rows + .filter((row) => !mappedSet.has(String(row.sku_code))) + .map((row) => ({ sku_code: String(row.sku_code), sku_name: row.sku_name ? String(row.sku_name) : null })); + return { + quote_sheet_code: quoteSheetCode, + total: skuCodes.length, + mapped: mappedSet.size, + unmapped: unmapped_skus.length, + unmapped_skus, + }; +} + +export type LocalSkuMappingDto = { + supplier_sku_code: string; + supplier_sku_name: string | null; + supplier_unit: string | null; + delivery_sku_code: string | null; + delivery_sku_name: string | null; + status: string; + synced_at: string | null; +}; + +export type LocalSkuMappingList = { + rows: LocalSkuMappingDto[]; + summary: { total: number; mapped: number; unmapped: number }; +}; + +/** 只读映射列表(供应商侧不可编辑) */ +export async function listLocalSkuMappings(input: { + branchCode?: string | null; + ctx?: TenantContext | null; + operatingBranchCode?: string | null; + status?: string | null; + keyword?: string | null; + limit?: number; +}): Promise { + const branchCode = + toText(input.branchCode) || getEffectiveBranchCode(input.ctx || null, input.operatingBranchCode || null); + if (!branchCode) return { rows: [], summary: { total: 0, mapped: 0, unmapped: 0 } }; + const status = ['active', 'disabled', 'pending'].includes(toText(input.status)) ? toText(input.status) : null; + const keyword = toText(input.keyword); + const limit = Math.min(Math.max(Number(input.limit) || 200, 1), 500); + const params: unknown[] = []; + const where: string[] = []; + if (status) { + params.push(status); + where.push(`status = $${params.length}`); + } + if (keyword) { + params.push(`%${keyword}%`); + where.push(`(supplier_sku_code ILIKE $${params.length} OR supplier_sku_name ILIKE $${params.length} OR delivery_sku_code ILIKE $${params.length} OR delivery_sku_name ILIKE $${params.length})`); + } + params.push(limit); + const result = await pool.query( + `SELECT supplier_sku_code, supplier_sku_name, supplier_unit, delivery_sku_code, delivery_sku_name, + status, synced_at + FROM main_system_sku_mappings + ${where.length ? `WHERE ${where.join(' AND ')}` : ''} + ORDER BY (delivery_sku_code IS NULL) ASC, supplier_sku_code ASC + LIMIT $${params.length}`, + params + ); + const counts = await pool.query<{ total: number; mapped: number }>( + `SELECT count(*)::int AS total, + count(*) FILTER (WHERE status = 'active' AND delivery_sku_code IS NOT NULL)::int AS mapped + FROM main_system_sku_mappings` + ); + const total = Number(counts.rows[0]?.total) || 0; + const mapped = Number(counts.rows[0]?.mapped) || 0; + return { + rows: result.rows.map((row) => ({ + supplier_sku_code: String(row.supplier_sku_code), + supplier_sku_name: row.supplier_sku_name ? String(row.supplier_sku_name) : null, + supplier_unit: row.supplier_unit ? String(row.supplier_unit) : null, + delivery_sku_code: row.delivery_sku_code ? String(row.delivery_sku_code) : null, + delivery_sku_name: row.delivery_sku_name ? String(row.delivery_sku_name) : null, + status: String(row.status), + synced_at: row.synced_at ?? null, + })), + summary: { total, mapped, unmapped: Math.max(0, total - mapped) }, + }; +} + +/** + * 定时任务用:所有 active 绑定分公司的 **D4 推字典 + D5 拉映射**(开关关闭时零出站)。 + * + * 契约 §5 要求字典推送每天也跑一次(手动按钮之外);这里把两个计数分开返回,日志里能同时看到 push/pull。 + * 单个分公司失败只记 errors,不中断其它分公司,也不影响同轮其它跨系统任务。 + */ +export async function syncDictionaryAndMappingsForAllBranches(): Promise<{ + branches: number; + pushedSkus: number; + pushBatches: number; + pulled: number; + errors: number; + skipped: boolean; +}> { + if (!isSkuMappingEnabled()) { + return { branches: 0, pushedSkus: 0, pushBatches: 0, pulled: 0, errors: 0, skipped: true }; + } + const bindings = await pool.query<{ branch_code: string }>( + `SELECT DISTINCT branch_code FROM public.main_supplier_bindings + WHERE status = 'active' AND NULLIF(TRIM(main_supplier_code), '') IS NOT NULL` + ); + let pushedSkus = 0; + let pushBatches = 0; + let pulled = 0; + let errors = 0; + for (const row of bindings.rows) { + const branchCode = String(row.branch_code); + try { + const pushed = await pushSkuDictionaryForBranch({ branchCode }); + pushedSkus += pushed.skus; + pushBatches += pushed.batches; + } catch (error: any) { + errors += 1; + console.warn(`[sku-mapping] 定时推字典失败(${branchCode}):`, error?.message || error); + } + try { + const summary = await pullMappingsFromMainSystem({ branchCode }); + pulled += summary.upserted; + if (summary.truncated) errors += 1; // 部分刷新(未证明拉全)⇒ 记一次异常,便于发现对方 D5 异常 + } catch (error: any) { + errors += 1; + console.warn(`[sku-mapping] 定时拉映射失败(${branchCode}):`, error?.message || error); + } + } + return { branches: bindings.rows.length, pushedSkus, pushBatches, pulled, errors, skipped: false }; +} + +/** 定时任务用:所有 active 绑定分公司的 D5 拉取(开关关闭时零出站) */ +export async function pullMappingsForAllBranches(): Promise<{ + branches: number; + pulled: number; + errors: number; + skipped: boolean; +}> { + if (!isSkuMappingEnabled()) return { branches: 0, pulled: 0, errors: 0, skipped: true }; + const bindings = await pool.query<{ branch_code: string }>( + `SELECT DISTINCT branch_code FROM public.main_supplier_bindings + WHERE status = 'active' AND NULLIF(TRIM(main_supplier_code), '') IS NOT NULL` + ); + let pulled = 0; + let errors = 0; + for (const row of bindings.rows) { + try { + const summary = await pullMappingsFromMainSystem({ branchCode: String(row.branch_code) }); + pulled += summary.upserted; + if (summary.truncated) errors += 1; // 未证明拉全 ⇒ 记一次异常(部分刷新,本地不删) + } catch (error: any) { + errors += 1; + console.warn(`[sku-mapping] 定时拉取失败(${row.branch_code}):`, error?.message || error); + } + } + return { branches: bindings.rows.length, pulled, errors, skipped: false }; +} diff --git a/server/tests/mainSystemQuoteCostSync.test.ts b/server/tests/mainSystemQuoteCostSync.test.ts new file mode 100644 index 0000000..6554bab --- /dev/null +++ b/server/tests/mainSystemQuoteCostSync.test.ts @@ -0,0 +1,1022 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +/** + * 报价单销售价 → 主系统报价单成本价(**推送端**)—— 契约守卫。 + * + * 冻结契约 2026-10-18(详见 docs/design/20261018-报价单成本价同步推送.md)。 + * 这个文件钉住七类**做反就要返工**的行为: + * ① 默认关 ⇒ 零查库、零出站(审批/建单行为逐字节不变); + * ② 客户码闸门:只有 `MAIN_<码>` 才推;真实客户与 `__*__` 哨兵记 `not_usage_company`; + * ③ 一单多分公司各推一次,台账唯一键保证"一张单 × 一个分公司只推一次"; + * ④ 明细口径:只推 `sale_price ?? price > 0`,单位超长/缺失带 null,金额按 2 位小数归一; + * ⑤ 台账状态机:2xx→sent、403→forbidden(不重试)、其它失败→failed; + * ⑥ 重试:只选 `failed && attempts<5`,**复用原 client_request_id**; + * ⑦ 旁路纪律:tenant 上下文 `isolate + requestClient:false`(不踩请求归还后的连接)。 + */ + +/* ── mock:DB(脚本化)────────────────────────────────────────────────────── */ + +const poolQuery = vi.hoisted(() => vi.fn()); +vi.mock('../src/db', () => ({ + pool: { query: (...args: unknown[]) => poolQuery(...args) }, + getRawPoolQuery: () => poolQuery, +})); + +const tenantCtx = vi.hoisted(() => vi.fn()); +vi.mock('../src/services/tenantDbContext', () => ({ + runWithTenantDbContext: (...args: unknown[]) => tenantCtx(...args), +})); + +const submit = vi.hoisted(() => vi.fn()); +vi.mock('../src/services/mainSystem/api/quoteCostSync', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, submitQuoteCostSync: (...args: unknown[]) => submit(...args) }; +}); + +import { + MAIN_BRANCH_CUSTOMER_RE, + QUOTE_COST_SYNC_MAX_ATTEMPTS, + QUOTE_COST_SYNC_MAX_ITEMS, + collectQuoteCostSyncPlan, + isQuoteCostSyncEnabled, + normalizeQuoteCostSyncUnit, + parseMainBranchCode, + pushQuoteCostSyncForSheet, + quoteCostSyncItemsFingerprint, + readQuoteCostSyncSalePrice, + retryQuoteCostSyncPushes, + triggerQuoteCostSync, +} from '../src/services/mainSystemQuoteCostSync'; + +/* ── 脚本化 DB(含一条内存台账:唯一键 / attempts / response 都按真库语义走)─────────── */ + +type LedgerInsert = { sql: string; params: unknown[]; row: Record | null }; +type LedgerUpdate = { sql: string; params: unknown[] }; + +/** 内存台账行(模拟 `public.main_system_quote_cost_pushes`) */ +type MockLedgerRow = { + id: string; + branch_code: string; + quote_sheet_code: string; + main_branch_code: string; + client_request_id: string; + status: string; + attempts: number; + last_error: string | null; + response: any; + /** 毫秒时间戳(模拟 updated_at;R-1 的"卡住超过 10 分钟"靠它) */ + updated_at: number; +}; + +type DbState = { + sheet: Record | null; + customers: string[]; + items: Array>; + supplierCode: string | null; + /** 内存台账:键 = `quote_sheet_code::main_branch_code` */ + ledger: Record; + /** 显式指定重试扫描结果(不给则按内存台账推导,见 installDb) */ + retryRows: Array>; + inserts: LedgerInsert[]; + updates: LedgerUpdate[]; +}; + +function makeState(overrides: Partial = {}): DbState { + return { + sheet: { + quote_sheet_code: 'QS1', + branch_code: 'BR002', + status: 1, + approval_status: 30, + approved_at: '2026-10-18T01:00:00.000Z', + effective_at: '2026-10-18T01:00:00.000Z', + expires_at: new Date(Date.now() + 86400_000).toISOString(), + }, + customers: ['MAIN_BR002'], + items: [{ sku_code: 'SKU1', unit: '斤', sale_price: '12.34', price: '12.34' }], + supplierCode: 'SUP37831443', + ledger: {}, + retryRows: [], + inserts: [], + updates: [], + ...overrides, + }; +} + +/** 预置一行台账(模拟"上一次推送留下的行") */ +function seedLedger( + state: DbState, + patch: Partial = {} +): MockLedgerRow { + const row: MockLedgerRow = { + id: patch.id ?? 'lid-seed', + branch_code: patch.branch_code ?? 'BR002', + quote_sheet_code: patch.quote_sheet_code ?? 'QS1', + main_branch_code: patch.main_branch_code ?? 'BR002', + client_request_id: patch.client_request_id ?? 'cr-seed', + status: patch.status ?? 'sent', + attempts: patch.attempts ?? 1, + last_error: patch.last_error ?? null, + response: patch.response ?? null, + updated_at: patch.updated_at ?? Date.now(), + }; + state.ledger[`${row.quote_sheet_code}::${row.main_branch_code}`] = row; + return row; +} + +const LEDGER_TABLE = 'FROM public.main_system_quote_cost_pushes'; + +function installDb(state: DbState): void { + const findById = (id: unknown) => Object.values(state.ledger).find((row) => row.id === String(id)); + + poolQuery.mockImplementation(async (sql: string, params: unknown[] = []) => { + // ① 重试扫描:failed && attempts<5 **或** 卡住 >10 分钟的 pending(R-1) + if (sql.includes("status = 'failed' AND attempts <")) { + if (state.retryRows.length) return { rows: state.retryRows }; + const now = Date.now(); + const rows = Object.values(state.ledger).filter( + (row) => + (row.status === 'failed' && row.attempts < Number(params[0])) || + (row.status === 'pending' && row.updated_at < now - 10 * 60 * 1000) + ); + return { + rows: rows.map((row) => ({ + id: row.id, + branch_code: row.branch_code, + quote_sheet_code: row.quote_sheet_code, + main_branch_code: row.main_branch_code, + client_request_id: row.client_request_id, + attempts: row.attempts, + status: row.status, + })), + }; + } + // ② 读一行台账(判重 / 改价重推用) + if (sql.includes(LEDGER_TABLE) && sql.includes('WHERE quote_sheet_code = $1 AND main_branch_code = $2')) { + const row = state.ledger[`${params[0]}::${params[1]}`]; + if (!row) return { rows: [], rowCount: 0 }; + return { + rows: [ + { + id: row.id, + status: row.status, + attempts: row.attempts, + client_request_id: row.client_request_id, + response: row.response, + }, + ], + rowCount: 1, + }; + } + // ③ 台账 INSERT ... ON CONFLICT DO NOTHING + if (sql.includes('INSERT INTO public.main_system_quote_cost_pushes')) { + const key = `${params[1]}::${params[2]}`; + if (state.ledger[key]) { + state.inserts.push({ sql, params, row: null }); + return { rows: [], rowCount: 0 }; + } + const row: MockLedgerRow = { + id: `lid-${Object.keys(state.ledger).length + 1}`, + branch_code: String(params[0]), + quote_sheet_code: String(params[1]), + main_branch_code: String(params[2]), + client_request_id: String(params[3]), + status: String(params[4]), + attempts: 0, + last_error: (params[5] as string | null) ?? null, + response: params[6] ? JSON.parse(String(params[6])) : null, + updated_at: Date.now(), + }; + state.ledger[key] = row; + state.inserts.push({ sql, params, row: { id: row.id, client_request_id: row.client_request_id } }); + return { rows: [{ id: row.id, client_request_id: row.client_request_id }], rowCount: 1 }; + } + // ④ 台账 UPDATE(普通回写 / 409 换号 / 改价重推) + if (sql.includes('UPDATE public.main_system_quote_cost_pushes')) { + state.updates.push({ sql, params }); + const row = findById(params[0]); + if (sql.includes('payload_changed_rotate_id')) { + // $1=id, $2=新请求号, $3=409 明细 + if (row) { + row.client_request_id = String(params[1]); + row.attempts = 0; + row.status = 'failed'; + row.last_error = 'payload_changed_rotate_id'; + row.response = { ...(row.response || {}), last_conflict_409: params[2] }; + row.updated_at = Date.now(); + } + return { rows: [{ client_request_id: params[1] }], rowCount: 1 }; + } + if (sql.includes('rearmed_after_change')) { + // $1=id, $2=新请求号, $3=当前指纹 + if (row) { + row.client_request_id = String(params[1]); + row.attempts = 0; + row.status = 'pending'; + row.last_error = 'rearmed_after_change'; + row.response = { + ...(row.response || {}), + local: { + ...((row.response || {}).local || {}), + sheet_reason: 'rearmed_after_change', + items_fingerprint: params[2], + }, + }; + row.updated_at = Date.now(); + } + return { rows: [{ id: params[0], client_request_id: params[1] }], rowCount: 1 }; + } + // 重试异常兜底:`attempts+1` + 把 pending 收口成 failed($1=id, $2=last_error) + if (sql.includes('status = CASE WHEN status =')) { + if (row) { + row.attempts += 1; + if (row.status === 'pending') row.status = 'failed'; + row.last_error = String(params[1]); + row.updated_at = Date.now(); + } + return { rows: [], rowCount: 1 }; + } + // 普通 markLedger:$1=id, $2=status, $3=last_error, $4=response + if (row) { + row.status = String(params[1]); + row.attempts += 1; + row.last_error = (params[2] as string | null) ?? null; + row.response = params[3] ? JSON.parse(String(params[3])) : null; + row.updated_at = Date.now(); + } + return { rows: [], rowCount: 1 }; + } + if (sql.includes('AS code')) { + return { rows: [{ code: state.supplierCode }] }; + } + if (sql.includes('FROM customer_quote_sheets')) { + return { rows: state.sheet ? [state.sheet] : [] }; + } + if (sql.includes('FROM customer_quote_sheet_customers')) { + return { rows: state.customers.map((customer_code) => ({ customer_code })) }; + } + if (sql.includes('FROM customer_quote_sheet_items')) { + return { rows: state.items }; + } + return { rows: [] }; + }); +} + +const okResult = () => ({ + kind: 'ok' as const, + status: 200, + data: { + client_request_id: 'cr', + replayed: false, + main_branch_code: 'BR002', + updated: 1, + sheets: ['QS-THEIR'], + skipped: [], + warnings: [], + }, +}); + +beforeEach(() => { + poolQuery.mockReset(); + submit.mockReset(); + tenantCtx.mockReset(); + tenantCtx.mockImplementation(async (_code: string, fn: () => Promise) => fn()); + submit.mockResolvedValue(okResult()); + delete process.env.MAIN_SYSTEM_QUOTE_COST_SYNC; +}); + +/* ── ① 开关与纯函数 ──────────────────────────────────────────────────────── */ + +describe('开关(默认关)', () => { + it('未设置 / 0 / 其它值 ⇒ 关;1 / true / on(大小写不敏感)⇒ 开', () => { + expect(isQuoteCostSyncEnabled()).toBe(false); + for (const value of ['0', '', 'false', 'off', 'yes']) { + process.env.MAIN_SYSTEM_QUOTE_COST_SYNC = value; + expect(isQuoteCostSyncEnabled(), value).toBe(false); + } + for (const value of ['1', 'true', 'TRUE', 'on', 'On']) { + process.env.MAIN_SYSTEM_QUOTE_COST_SYNC = value; + expect(isQuoteCostSyncEnabled(), value).toBe(true); + } + }); +}); + +describe('客户码闸门 parseMainBranchCode', () => { + it('只认 ^MAIN_([0-9A-Za-z_-]{1,32})$(前缀大小写不敏感),且结果 UPPER', () => { + expect(MAIN_BRANCH_CUSTOMER_RE.test('MAIN_BR002')).toBe(true); + expect(parseMainBranchCode('MAIN_BR002')).toBe('BR002'); + expect(parseMainBranchCode(' MAIN_br002 ')).toBe('BR002'); + expect(parseMainBranchCode('MAIN_BR-002_A')).toBe('BR-002_A'); + // 超长(33 字符)与空码都不成立 + expect(parseMainBranchCode(`MAIN_${'A'.repeat(33)}`)).toBeNull(); + expect(parseMainBranchCode('MAIN_')).toBeNull(); + }); + + it('前缀大小写归一(A2):main_br002 / Main_BR002 与 MAIN_BR002 等价', () => { + for (const code of ['main_br002', 'Main_BR002', 'main_BR002', 'MaIn_br002', ' main_br002 ']) { + expect(parseMainBranchCode(code), code).toBe('BR002'); + } + // X 段本身也归一成大写(对方分公司码是 BRxxx) + expect(parseMainBranchCode('main_br-002_a')).toBe('BR-002_A'); + }); + + it('真实客户与哨兵客户一律不匹配(不写、不猜)', () => { + for (const code of [ + 'CUS98392383347', + 'real_customer', + '__INDEPENDENT_INBOUND__', + '__RETAIL__', + 'MAINBR002', + '', + ]) { + expect(parseMainBranchCode(code), code).toBeNull(); + } + }); +}); + +describe('明细口径(单位 / 售价)', () => { + it('单位:trim 后 1~20 字符才带,否则 null(对方按 skus.unit 比)', () => { + expect(normalizeQuoteCostSyncUnit(' 斤 ')).toBe('斤'); + expect(normalizeQuoteCostSyncUnit('袋装(500g)')).toBe('袋装(500g)'); + expect(normalizeQuoteCostSyncUnit('')).toBeNull(); + expect(normalizeQuoteCostSyncUnit(null)).toBeNull(); + expect(normalizeQuoteCostSyncUnit('A'.repeat(21))).toBeNull(); + }); + + it('售价:sale_price ?? price,只认 >0 的有限数,按 2 位小数归一', () => { + expect(readQuoteCostSyncSalePrice({ sale_price: '12.34', price: '9' })).toBe(12.34); + expect(readQuoteCostSyncSalePrice({ sale_price: null, price: '9.00' })).toBe(9); + expect(readQuoteCostSyncSalePrice({ sale_price: '12.345' })).toBe(12.35); + for (const bad of [null, undefined, '', '0', 0, -1, 'abc', 'NaN']) { + expect(readQuoteCostSyncSalePrice({ sale_price: bad as unknown }), String(bad)).toBeNull(); + } + }); +}); + +/* ── ② 门禁:零出站 ─────────────────────────────────────────────────────── */ + +describe('默认关 ⇒ 零查库、零出站', () => { + it('pushQuoteCostSyncForSheet 关时直接返回(不查库、不出站)', async () => { + const summary = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' }); + expect(summary.attempted).toBe(0); + expect(poolQuery).not.toHaveBeenCalled(); + expect(submit).not.toHaveBeenCalled(); + expect(tenantCtx).not.toHaveBeenCalled(); + }); + + it('retryQuoteCostSyncPushes 关时直接返回(连台账都不查)', async () => { + const summary = await retryQuoteCostSyncPushes({ limit: 10 }); + expect(summary).toEqual({ rows: 0, attempted: 0, sent: 0, failed: 0, forbidden: 0, skipped: 0, errors: 0 }); + expect(poolQuery).not.toHaveBeenCalled(); + expect(submit).not.toHaveBeenCalled(); + }); + + it('triggerQuoteCostSync 关时零动作(含参数缺失)', () => { + triggerQuoteCostSync({ branchCode: 'BR002', quoteSheetCode: 'QS1' }); + expect(poolQuery).not.toHaveBeenCalled(); + process.env.MAIN_SYSTEM_QUOTE_COST_SYNC = '1'; + triggerQuoteCostSync({ branchCode: '', quoteSheetCode: 'QS1' }); + triggerQuoteCostSync({ quoteSheetCode: 'QS1' }); + expect(poolQuery).not.toHaveBeenCalled(); + expect(submit).not.toHaveBeenCalled(); + }); + + it('租户上下文按 isolate + requestClient:false 打开(不复用请求连接)', async () => { + process.env.MAIN_SYSTEM_QUOTE_COST_SYNC = '1'; + installDb(makeState()); + await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' }); + expect(tenantCtx).toHaveBeenCalledTimes(1); + expect(tenantCtx.mock.calls[0][0]).toBe('BR002'); + expect(tenantCtx.mock.calls[0][2]).toEqual({ isolate: true, requestClient: false }); + }); +}); + +/* ── ③ 推送主链路 ───────────────────────────────────────────────────────── */ + +describe('推送:单分公司', () => { + beforeEach(() => { + process.env.MAIN_SYSTEM_QUOTE_COST_SYNC = '1'; + }); + + it('生效单 + MAIN_BR002 ⇒ 1 条台账 + 1 次出站(字段名照契约、请求号取自台账)', async () => { + const state = makeState(); + installDb(state); + const summary = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' }); + + expect(summary.sent).toBe(1); + expect(summary.attempted).toBe(1); + expect(state.inserts).toHaveLength(1); + const insertParams = state.inserts[0].params; + expect(insertParams[0]).toBe('BR002'); + expect(insertParams[1]).toBe('QS1'); + expect(insertParams[2]).toBe('BR002'); + expect(insertParams[4]).toBe('pending'); + + expect(submit).toHaveBeenCalledTimes(1); + const call = submit.mock.calls[0][0] as any; + expect(call.supplierCode).toBe('SUP37831443'); + expect(call.body).toEqual({ + client_request_id: insertParams[3], + supplier_quote_sheet_code: 'QS1', + main_branch_code: 'BR002', + activated_at: '2026-10-18T01:00:00.000Z', + items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 12.34 }], + }); + + expect(state.updates).toHaveLength(1); + expect(state.updates[0].params[1]).toBe('sent'); + expect(state.updates[0].params[2]).toBeNull(); + // 回执与本地口径都留在台账里 + expect(String(state.updates[0].params[3])).toContain('QS-THEIR'); + }); + + it('一单绑两个 MAIN 客户 ⇒ 按分公司各推一次(items 相同、分公司不同)', async () => { + const state = makeState({ customers: ['MAIN_BR003', 'MAIN_BR002', '__RETAIL__'] }); + installDb(state); + const summary = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' }); + + expect(summary.sent).toBe(2); + expect(state.inserts.map((i) => i.params[2])).toEqual(['BR002', 'BR003']); + const branches = submit.mock.calls.map((c) => (c[0] as any).body.main_branch_code); + expect(branches).toEqual(['BR002', 'BR003']); + // 两个分公司各自独立的請求号 + const ids = submit.mock.calls.map((c) => (c[0] as any).body.client_request_id); + expect(new Set(ids).size).toBe(2); + }); + + it('台账已有行且明细未变 ⇒ 不再出站(一张单 × 一个分公司只推一次)', async () => { + const state = makeState(); + seedLedger(state, { + status: 'sent', + client_request_id: 'cr-old', + response: { + local: { items_fingerprint: quoteCostSyncItemsFingerprint([{ sku_code: 'SKU1', unit: '斤', sale_price: 12.34 }]) }, + }, + }); + installDb(state); + const summary = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' }); + expect(summary.duplicates).toBe(1); + expect(summary.attempted).toBe(0); + expect(summary.rearmed).toBe(0); + expect(submit).not.toHaveBeenCalled(); + expect(state.updates).toHaveLength(0); + }); + + it('非 MAIN_ 客户(真实客户 + 两个哨兵)⇒ 整单记 skipped,零出站', async () => { + const state = makeState({ customers: ['CUS98392383347', '__INDEPENDENT_INBOUND__', '__RETAIL__'] }); + installDb(state); + const summary = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' }); + + expect(summary.skipped).toBe(1); + expect(submit).not.toHaveBeenCalled(); + expect(state.inserts).toHaveLength(1); + expect(state.inserts[0].params[2]).toBe('*'); // 整单级台账行 + expect(state.inserts[0].params[4]).toBe('skipped'); + expect(String(state.inserts[0].params[5])).toContain('not_usage_company'); + }); + + it('全部明细 sale_price<=0(或缺失)⇒ 整单 skipped,零出站', async () => { + const state = makeState({ + items: [ + { sku_code: 'SKU1', unit: '斤', sale_price: '0', price: '0' }, + { sku_code: 'SKU2', unit: '斤', sale_price: null, price: null }, + ], + }); + installDb(state); + const summary = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' }); + expect(summary.skipped).toBe(1); + expect(submit).not.toHaveBeenCalled(); + expect(String(state.inserts[0].params[5])).toContain('no_pushable_items'); + }); + + it('只推 >0 的行:零价行被过滤,但正价行照推', async () => { + const state = makeState({ + items: [ + { sku_code: 'SKU1', unit: '斤', sale_price: '9', price: '9' }, + { sku_code: 'SKU2', unit: '斤', sale_price: '0', price: '0' }, + ], + }); + installDb(state); + await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' }); + const body = (submit.mock.calls[0][0] as any).body; + expect(body.items).toEqual([{ sku_code: 'SKU1', unit: '斤', sale_price: 9 }]); + }); + + it(`可推行超过 ${QUOTE_COST_SYNC_MAX_ITEMS} 条 ⇒ 整单 skipped(不做截断/分批)`, async () => { + const items = Array.from({ length: QUOTE_COST_SYNC_MAX_ITEMS + 1 }, (_, i) => ({ + sku_code: `SKU${i}`, + unit: '斤', + sale_price: '1.00', + price: '1.00', + })); + const state = makeState({ items }); + installDb(state); + const summary = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' }); + expect(summary.skipped).toBe(1); + expect(submit).not.toHaveBeenCalled(); + expect(String(state.inserts[0].params[5])).toContain('too_many_items'); + }); + + it('报价单不存在 ⇒ skipped(不写台账)', async () => { + const state = makeState({ sheet: null }); + installDb(state); + const summary = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' }); + expect(summary.skipped).toBe(1); + expect(state.inserts).toHaveLength(0); + expect(submit).not.toHaveBeenCalled(); + }); + + it('非生效单(已驳回 approval_status=40)⇒ skipped,零出站', async () => { + const state = makeState({ + sheet: { + quote_sheet_code: 'QS1', + branch_code: 'BR002', + status: 0, + approval_status: 40, + approved_at: null, + effective_at: null, + expires_at: null, + }, + }); + installDb(state); + const summary = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' }); + expect(summary.skipped).toBe(1); + expect(submit).not.toHaveBeenCalled(); + expect(String(state.inserts[0].params[5])).toContain('quote_sheet_not_active'); + }); + + it('没有主系统供应商编码 ⇒ 落 failed 等人工(不猜编码、不出站)', async () => { + const state = makeState({ supplierCode: null }); + installDb(state); + const summary = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' }); + expect(summary.failed).toBe(1); + expect(submit).not.toHaveBeenCalled(); + expect(state.inserts[0].params[4]).toBe('failed'); + expect(String(state.inserts[0].params[5])).toContain('main_supplier_code_missing'); + }); +}); + +/* ── ④ 回执 → 台账状态 ───────────────────────────────────────────────────── */ + +describe('出站结果映射', () => { + beforeEach(() => { + process.env.MAIN_SYSTEM_QUOTE_COST_SYNC = '1'; + }); + + function lastUpdateStatus(state: DbState): string { + return String(state.updates[state.updates.length - 1]?.params[1]); + } + + it('200 + replayed:true ⇒ sent(对方幂等命中也是同步成功)', async () => { + installDb(makeState()); + submit.mockResolvedValue({ + ...okResult(), + data: { ...okResult().data, replayed: true, updated: 0 }, + }); + const summary = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' }); + expect(summary.sent).toBe(1); + expect(summary.results[0].replayed).toBe(true); + }); + + it('403 branch_not_bound ⇒ forbidden(终态,不重试)', async () => { + const state = makeState(); + installDb(state); + submit.mockResolvedValue({ + kind: 'rejected', + status: 403, + code: 'branch_not_bound', + reason: '该供应商未绑定此分公司', + payload: { error: 'branch_not_bound' }, + }); + const summary = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' }); + expect(summary.forbidden).toBe(1); + expect(lastUpdateStatus(state)).toBe('forbidden'); + expect(String(state.updates[0].params[2])).toContain('branch_not_bound'); + }); + + it('503 feature_disabled / 5xx / 网络 ⇒ failed(可重试)', async () => { + for (const outcome of [ + { kind: 'unavailable', status: 503, code: 'feature_disabled', reason: '对方开关未开', payload: null }, + { kind: 'unavailable', status: 500, code: 'main_system_error', reason: 'HTTP 500', payload: null }, + { kind: 'unavailable', status: 0, code: 'request_failed', reason: '调用主系统超时', payload: null }, + ]) { + const state = makeState(); + installDb(state); + submit.mockResolvedValueOnce(outcome); + const summary = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' }); + expect(summary.failed, JSON.stringify(outcome)).toBe(1); + expect(lastUpdateStatus(state)).toBe('failed'); + expect(String(state.updates[0].params[2])).toContain(String((outcome as any).code)); + } + }); + + it('出站层抛异常 ⇒ 台账收口成 failed(不留 pending)+ 不影响其它分公司', async () => { + const state = makeState({ customers: ['MAIN_BR002', 'MAIN_BR003'] }); + installDb(state); + submit + .mockRejectedValueOnce(new Error('boom')) + .mockResolvedValueOnce(okResult()); + const summary = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' }); + expect(summary.failed).toBe(1); + expect(summary.sent).toBe(1); + expect(lastUpdateStatus(state)).toBe('sent'); + // 第一行也必须被收口(不能停在 pending) + expect(state.updates[0].params[1]).toBe('failed'); + expect(String(state.updates[0].params[2])).toContain('exception'); + }); +}); + +/* ── ⑤ 采集(plan)──────────────────────────────────────────────────────── */ + +describe('collectQuoteCostSyncPlan', () => { + beforeEach(() => { + process.env.MAIN_SYSTEM_QUOTE_COST_SYNC = '1'; + }); + + it('跳过明细带 reason,主系统分公司去重升序', async () => { + installDb( + makeState({ + customers: ['MAIN_BR003', 'MAIN_BR002', 'MAIN_BR002', 'CUS1', '__RETAIL__'], + items: [ + { sku_code: 'SKU1', unit: '斤', sale_price: '4.5', price: '4.5' }, + { sku_code: 'SKU2', unit: '斤', sale_price: '0', price: '0' }, + { sku_code: '', unit: '斤', sale_price: '5', price: '5' }, + ], + }) + ); + const plan = await collectQuoteCostSyncPlan({ branchCode: 'BR002', quoteSheetCode: 'QS1' }); + expect(plan.mainBranchCodes).toEqual(['BR002', 'BR003']); + expect(plan.items).toEqual([{ sku_code: 'SKU1', unit: '斤', sale_price: 4.5 }]); + expect(plan.skipped).toEqual([ + { reason: 'not_usage_company', customer_code: 'CUS1' }, + { reason: 'not_usage_company', customer_code: '__RETAIL__' }, + { reason: 'source_price_missing', sku_code: 'SKU2' }, + ]); + expect(plan.itemRowCount).toBe(2); // 空 sku_code 不计入 + expect(plan.isActive).toBe(true); + }); +}); + +/* ── ⑥ 重试 ─────────────────────────────────────────────────────────────── */ + +describe('定时重试', () => { + beforeEach(() => { + process.env.MAIN_SYSTEM_QUOTE_COST_SYNC = '1'; + }); + + it('只选 failed && attempts<5,复用原 client_request_id 重放', async () => { + const state = makeState({ + retryRows: [ + { + id: 'lid-9', + branch_code: 'BR002', + quote_sheet_code: 'QS1', + main_branch_code: 'BR002', + client_request_id: 'cr-original', + attempts: 2, + }, + ], + }); + installDb(state); + const summary = await retryQuoteCostSyncPushes({ limit: 10 }); + + // SELECT 的 where/limit 就是重试口径(不是"所有历史行") + const selectSql = String(poolQuery.mock.calls[0][0]); + expect(selectSql).toContain("status = 'failed' AND attempts <"); + expect(poolQuery.mock.calls[0][1]).toEqual([QUOTE_COST_SYNC_MAX_ATTEMPTS, 10]); + + expect(summary.rows).toBe(1); + expect(summary.sent).toBe(1); + expect((submit.mock.calls[0][0] as any).body.client_request_id).toBe('cr-original'); + expect((submit.mock.calls[0][0] as any).body.main_branch_code).toBe('BR002'); + expect(String(state.updates[0].params[1])).toBe('sent'); + expect(String(state.updates[0].params[3])).toContain('retried'); + }); + + it('客户绑定被撤掉(目标分公司已不在 MAIN_ 里)⇒ skipped,零出站', async () => { + const state = makeState({ + customers: ['MAIN_BR003'], + retryRows: [ + { + id: 'lid-9', + branch_code: 'BR002', + quote_sheet_code: 'QS1', + main_branch_code: 'BR002', + client_request_id: 'cr-original', + attempts: 1, + }, + ], + }); + installDb(state); + const summary = await retryQuoteCostSyncPushes(); + expect(summary.skipped).toBe(1); + expect(submit).not.toHaveBeenCalled(); + expect(String(state.updates[0].params[2])).toContain('main_branch_customer_removed'); + }); + + it('重试遇 403 ⇒ forbidden(此后不再被选中)', async () => { + const state = makeState({ + retryRows: [ + { + id: 'lid-9', + branch_code: 'BR002', + quote_sheet_code: 'QS1', + main_branch_code: 'BR002', + client_request_id: 'cr-original', + attempts: 1, + }, + ], + }); + installDb(state); + submit.mockResolvedValue({ kind: 'rejected', status: 403, code: 'branch_not_bound', reason: 'x', payload: null }); + const summary = await retryQuoteCostSyncPushes(); + expect(summary.forbidden).toBe(1); + expect(String(state.updates[0].params[1])).toBe('forbidden'); + }); + + it('单行异常不影响其它行,且异常行 attempts 也 +1(防止无限重试)', async () => { + const state = makeState({ + retryRows: [ + { + id: 'lid-1', + branch_code: 'BR002', + quote_sheet_code: 'QS1', + main_branch_code: 'BR002', + client_request_id: 'cr-1', + attempts: 1, + }, + { + id: 'lid-2', + branch_code: 'BR002', + quote_sheet_code: 'QS1', + main_branch_code: 'BR002', + client_request_id: 'cr-2', + attempts: 1, + }, + ], + }); + installDb(state); + submit.mockRejectedValueOnce(new Error('boom')).mockResolvedValueOnce(okResult()); + const summary = await retryQuoteCostSyncPushes(); + expect(summary.errors).toBe(1); + expect(summary.sent).toBe(1); + const bump = state.updates.find((u) => String(u.params[1] ?? '').includes('retry_exception')); + expect(bump).toBeTruthy(); + }); +}); + +/* ── ⑥ tester 补充(2026-10-18):验收边界里原本没被钉住的形态 ─────────────────── */ + +describe('tester 补充:client 的 MAIN_BR007 不在 S(对方授权集合)', () => { + beforeEach(() => { + process.env.MAIN_SYSTEM_QUOTE_COST_SYNC = '1'; + }); + + it('一单混绑 MAIN_BR002(已授权)+ MAIN_BR007(未授权)⇒ BR002 sent、BR007 forbidden,且 forbidden 不再重试', async () => { + const state = makeState({ customers: ['MAIN_BR002', 'MAIN_BR007'] }); + installDb(state); + submit.mockImplementation(async (input: any) => { + if (input.body.main_branch_code === 'BR007') { + // 对方验收 A3/§1.3:该供应商未绑定 BR007 ⇒ 403 branch_not_bound(NOT `not_bound` skip) + return { + kind: 'rejected', + status: 403, + code: 'branch_not_bound', + reason: '供应商未绑定分公司 BR007', + payload: { error: 'branch_not_bound' }, + }; + } + return okResult(); + }); + + const summary = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' }); + + expect(summary.sent).toBe(1); + expect(summary.forbidden).toBe(1); + expect(summary.failed).toBe(0); + // 两个分公司各自一行台账(唯一键是 (单号, 分公司),不是整单一行) + expect(state.inserts.map((i) => i.params[2])).toEqual(['BR002', 'BR007']); + // markLedger 的参数顺序是 (id, status, last_error, response) ⇒ 按出站顺序是 sent 然后 forbidden + expect(state.updates.map((u) => String(u.params[1]))).toEqual(['sent', 'forbidden']); + expect(String(state.updates[1].params[2])).toContain('branch_not_bound'); + // 终态语义:`forbidden` 是终态,重试只选 `status='failed'`(重试口径由「定时重试」组钉住) + expect(summary.results.map((r) => r.status)).toEqual(['sent', 'forbidden']); + }); + + it('全部客户都非 MAIN_(含 `MAIN_*` 这种伪形态)⇒ 一条台账 skipped、零出站、零主系统分公司', async () => { + const state = makeState({ customers: ['MAIN_*', 'MAIN_BR 002', 'MAIN_A'.padEnd(40, 'A')] }); + installDb(state); + const plan = await collectQuoteCostSyncPlan({ branchCode: 'BR002', quoteSheetCode: 'QS1' }); + expect(plan.mainBranchCodes).toEqual([]); + expect(plan.skipped.filter((s) => s.reason === 'not_usage_company')).toHaveLength(3); + + const summary = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' }); + expect(summary.skipped).toBe(1); + expect(summary.attempted).toBe(0); + expect(submit).not.toHaveBeenCalled(); + expect(state.inserts[0].params[2]).toBe('*'); + }); +}); + +describe('tester 补充:源金额口径(上限由接收端判)', () => { + beforeEach(() => { + process.env.MAIN_SYSTEM_QUOTE_COST_SYNC = '1'; + }); + + it('超过 9,999,999.99 的源价**不在发送端丢弃**(对方按行记 invalid_price,口径单点维护)', async () => { + const state = makeState({ + items: [ + { sku_code: 'SKU_BIG', unit: '斤', sale_price: '10000000', price: '10000000' }, + { sku_code: 'SKU_OK', unit: '斤', sale_price: '9.99', price: '9.99' }, + ], + }); + installDb(state); + await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' }); + const body = (submit.mock.calls[0][0] as any).body; + expect(body.items.map((i: any) => i.sku_code)).toEqual(['SKU_BIG', 'SKU_OK']); + expect(body.items[0].sale_price).toBe(10000000); + }); + + it('0 / 负数 / 非数字的源价行一律 source_price_missing(不兜底成 0 推送)', async () => { + const state = makeState({ + items: [ + { sku_code: 'SKU_ZERO', unit: '斤', sale_price: '0', price: '0' }, + { sku_code: 'SKU_NEG', unit: '斤', sale_price: '-3', price: '-3' }, + { sku_code: 'SKU_NAN', unit: '斤', sale_price: 'abc', price: 'abc' }, + ], + }); + installDb(state); + const plan = await collectQuoteCostSyncPlan({ branchCode: 'BR002', quoteSheetCode: 'QS1' }); + expect(plan.items).toHaveLength(0); + expect(plan.skipped.filter((s) => s.reason === 'source_price_missing')).toHaveLength(3); + expect(submit).not.toHaveBeenCalled(); + }); + + it('对方 409 idempotency_conflict ⇒(R-2 修正)轮换 client_request_id、attempts 归零,下一轮用新号', async () => { + const state = makeState(); + installDb(state); + submit.mockResolvedValue({ + kind: 'rejected', + status: 409, + code: 'idempotency_conflict', + reason: '同一 client_request_id 已用于不同内容', + payload: { error: 'idempotency_conflict' }, + }); + const summary = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' }); + expect(summary.failed).toBe(1); + const row = state.ledger['QS1::BR002']; + expect(row.status).toBe('failed'); + expect(row.attempts).toBe(0); + expect(row.last_error).toBe('payload_changed_rotate_id'); + expect(row.client_request_id).not.toBe(state.inserts[0].params[3]); // 已换成新号 + // 换号的 UPDATE 也把 409 原始原因留在台账里(排障) + expect(JSON.stringify(row.response)).toContain('idempotency_conflict'); + }); +}); + +/* ── ⑦ 红队 R-1 / R-2 修复(contract.md §7.3 / §7.4)──────────────────────────── */ + +describe('R-1:pending 卡死(进程在"台账已落、结果未回写"之间被杀)', () => { + beforeEach(() => { + process.env.MAIN_SYSTEM_QUOTE_COST_SYNC = '1'; + }); + + it('卡住超过 10 分钟的 pending ⇒ 本轮扫描到,用**原 client_request_id** 重放并收口成 sent', async () => { + const state = makeState(); + seedLedger(state, { + status: 'pending', + attempts: 0, + client_request_id: 'cr-pending-old', + response: null, + updated_at: Date.now() - 11 * 60 * 1000, + }); + installDb(state); + submit.mockResolvedValueOnce(okResult()); + + const summary = await retryQuoteCostSyncPushes(); + expect(summary.rows).toBe(1); + expect(summary.sent).toBe(1); + expect((submit.mock.calls[0][0] as any).body.client_request_id).toBe('cr-pending-old'); + const row = state.ledger['QS1::BR002']; + expect(row.status).toBe('sent'); + expect(row.attempts).toBe(1); + }); + + it('刚落下的 pending(未超 10 分钟)不抢跑(避免和正在飞的出站重复写)', async () => { + const state = makeState(); + seedLedger(state, { status: 'pending', attempts: 0, client_request_id: 'cr-pending-fresh', updated_at: Date.now() }); + installDb(state); + const summary = await retryQuoteCostSyncPushes(); + expect(summary.rows).toBe(0); + expect(submit).not.toHaveBeenCalled(); + }); + + it('重试 SQL 同时覆盖两类行(failed<5 / 卡住的 pending)', async () => { + const state = makeState(); + installDb(state); + await retryQuoteCostSyncPushes(); + const sql = String(poolQuery.mock.calls[0][0]); + expect(sql).toContain("status = 'failed' AND attempts <"); + expect(sql).toContain("status = 'pending' AND updated_at < NOW() - INTERVAL '10 minutes'"); + }); +}); + +describe('R-2:改价后新价必须能同步过去', () => { + beforeEach(() => { + process.env.MAIN_SYSTEM_QUOTE_COST_SYNC = '1'; + }); + + it('① 重试遇 409 ⇒ 换新号 + attempts 归零;下一轮用新号成功', async () => { + const state = makeState(); + seedLedger(state, { + status: 'failed', + attempts: 2, + client_request_id: 'cr-old', + response: { local: { items_fingerprint: 'stale-fingerprint' } }, + }); + installDb(state); + submit.mockResolvedValueOnce({ + kind: 'rejected', + status: 409, + code: 'idempotency_conflict', + reason: '同一 client_request_id 已用于不同内容', + payload: { error: 'idempotency_conflict' }, + }); + + const first = await retryQuoteCostSyncPushes(); + expect(first.failed).toBe(1); + const row = state.ledger['QS1::BR002']; + expect(row.status).toBe('failed'); + expect(row.attempts).toBe(0); + expect(row.last_error).toBe('payload_changed_rotate_id'); + expect(row.client_request_id).not.toBe('cr-old'); + const newId = row.client_request_id; + + // 下一轮:同一台账行已换成新号 ⇒ 成功 + submit.mockResolvedValueOnce(okResult()); + const second = await retryQuoteCostSyncPushes(); + expect(second.sent).toBe(1); + expect((submit.mock.calls[1][0] as any).body.client_request_id).toBe(newId); + expect(state.ledger['QS1::BR002'].status).toBe('sent'); + }); + + it('② 首推成功后改价 ⇒ 再触发真推出去(换新号,不是 duplicate)', async () => { + const state = makeState(); + installDb(state); + const first = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' }); + expect(first.sent).toBe(1); + const firstId = state.ledger['QS1::BR002'].client_request_id; + + // 运营改了销售价(举例 12.34 → 99) + state.items = [{ sku_code: 'SKU1', unit: '斤', sale_price: '99.00', price: '99.00' }]; + submit.mockClear(); + submit.mockResolvedValueOnce(okResult()); + const second = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' }); + + expect(second.duplicates).toBe(0); + expect(second.rearmed).toBe(1); + expect(second.sent).toBe(1); + const body = (submit.mock.calls[0][0] as any).body; + expect(body.items).toEqual([{ sku_code: 'SKU1', unit: '斤', sale_price: 99 }]); + expect(body.client_request_id).not.toBe(firstId); + const row = state.ledger['QS1::BR002']; + expect(row.response.local.sheet_reason).toBe('rearmed_after_change'); + expect(row.status).toBe('sent'); + expect(row.attempts).toBe(1); + }); + + it('③ 未改价 ⇒ 仍 duplicate、零出站、请求号不变', async () => { + const state = makeState(); + installDb(state); + await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' }); + const firstId = state.ledger['QS1::BR002'].client_request_id; + + submit.mockClear(); + const second = await pushQuoteCostSyncForSheet({ branchCode: 'BR002', quoteSheetCode: 'QS1' }); + expect(second.duplicates).toBe(1); + expect(second.rearmed).toBe(0); + expect(second.attempted).toBe(0); + expect(submit).not.toHaveBeenCalled(); + expect(state.ledger['QS1::BR002'].client_request_id).toBe(firstId); + }); + + it('非 409 的失败(5xx / 超时 / 网络)**仍复用同一请求号**(不得换号)', async () => { + const state = makeState(); + seedLedger(state, { status: 'failed', attempts: 1, client_request_id: 'cr-keep' }); + installDb(state); + submit.mockResolvedValueOnce({ + kind: 'unavailable', + status: 500, + code: 'main_system_error', + reason: 'HTTP 500', + payload: null, + }); + const summary = await retryQuoteCostSyncPushes(); + expect(summary.failed).toBe(1); + expect((submit.mock.calls[0][0] as any).body.client_request_id).toBe('cr-keep'); + const row = state.ledger['QS1::BR002']; + expect(row.client_request_id).toBe('cr-keep'); + expect(row.status).toBe('failed'); + expect(row.attempts).toBe(2); + }); +}); diff --git a/server/tests/mainSystemQuoteCostSyncApi.test.ts b/server/tests/mainSystemQuoteCostSyncApi.test.ts new file mode 100644 index 0000000..85d2f2b --- /dev/null +++ b/server/tests/mainSystemQuoteCostSyncApi.test.ts @@ -0,0 +1,215 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +/** + * 报价单成本价同步 —— **接口封装层**契约守卫(`server/src/services/mainSystem/api/quoteCostSync.ts`)。 + * + * 钉住四类做反就返工的行为: + * ① URL 只在端点表里拼(含 `MAIN_SYSTEM_QUOTE_COST_SYNC_PATH` 覆盖),业务层不硬编码; + * ② 字段名照契约(snake_case),`supplier_code` **不进 body**(只由 token 决定); + * ③ 403 判成**语义拒绝**(不是网络故障),503/5xx 判成"对方不可用"(可重试); + * ④ 2xx 但回执不可识别 ⇒ 失败(绝不把"没同步"当"已同步")。 + */ + +const enabled = vi.hoisted(() => ({ value: true })); +vi.mock('../src/services/mainSystem/config', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + isMainSystemIntegrationEnabled: () => enabled.value, + mainSystemBaseUrl: () => 'http://main-system.example', + }; +}); + +const getMainSystemToken = vi.hoisted(() => vi.fn()); +vi.mock('../src/services/mainSystem/token', () => ({ + getMainSystemToken: (...args: unknown[]) => getMainSystemToken(...args), +})); + +const fetchMock = vi.hoisted(() => vi.fn()); +vi.stubGlobal('fetch', fetchMock); + +import { + normalizeQuoteCostSyncData, + readQuoteCostSyncErrorCode, + submitQuoteCostSync, +} from '../src/services/mainSystem/api/quoteCostSync'; + +function jsonResponse(status: number, body: unknown) { + return { + ok: status >= 200 && status < 300, + status, + json: async () => body, + }; +} + +const BODY = { + client_request_id: '11111111-1111-1111-1111-111111111111', + supplier_quote_sheet_code: 'QS1792200796033LUTV', + main_branch_code: 'BR002', + activated_at: '2026-10-18T02:00:00.000Z', + items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 12.34 }], +}; + +const OK_PAYLOAD = { + success: true, + data: { + client_request_id: BODY.client_request_id, + replayed: false, + main_branch_code: 'BR002', + updated: 2, + sheets: ['QS-A', 'QS-B'], + skipped: [{ reason: 'unit_mismatch', sku_code: 'SKU9', detail: '斤 vs 袋' }], + warnings: [], + }, +}; + +beforeEach(() => { + fetchMock.mockReset(); + getMainSystemToken.mockReset(); + enabled.value = true; + delete process.env.MAIN_SYSTEM_QUOTE_COST_SYNC_PATH; + getMainSystemToken.mockResolvedValue({ + kind: 'ok', + token: 'tok-1', + branchCode: 'BR002', + expiresAt: Date.now() + 60_000, + }); +}); + +describe('URL 与请求(端点表唯一拼装)', () => { + it('默认路径 = /api/supplier/quote-sheets/cost-sync,POST + Bearer + JSON', async () => { + fetchMock.mockResolvedValue(jsonResponse(200, OK_PAYLOAD)); + const outcome = await submitQuoteCostSync({ supplierCode: 'SUP37831443', body: BODY }); + expect(outcome.kind).toBe('ok'); + + const [url, init] = fetchMock.mock.calls[0] as [string, any]; + expect(url).toBe('http://main-system.example/api/supplier/quote-sheets/cost-sync'); + expect(init.method).toBe('POST'); + expect(init.headers.Authorization).toBe('Bearer tok-1'); + expect(init.headers['Content-Type']).toBe('application/json'); + const sent = JSON.parse(init.body); + expect(sent).toEqual(BODY); + // supplier_code 只由 token 决定,**不得**出现在请求体里 + expect(Object.keys(sent)).not.toContain('supplier_code'); + }); + + it('`MAIN_SYSTEM_QUOTE_COST_SYNC_PATH` 可覆盖端点路径', async () => { + process.env.MAIN_SYSTEM_QUOTE_COST_SYNC_PATH = '/custom/cost-sync'; + fetchMock.mockResolvedValue(jsonResponse(200, OK_PAYLOAD)); + await submitQuoteCostSync({ supplierCode: 'SUP1', body: BODY }); + expect((fetchMock.mock.calls[0] as [string])[0]).toBe('http://main-system.example/custom/cost-sync'); + }); +}); + +describe('回执归一', () => { + it('200 ⇒ ok + 字段归一(replayed / updated / sheets / skipped)', async () => { + fetchMock.mockResolvedValue(jsonResponse(200, OK_PAYLOAD)); + const outcome = await submitQuoteCostSync({ supplierCode: 'SUP1', body: BODY }); + expect(outcome.kind).toBe('ok'); + if (outcome.kind !== 'ok') return; + expect(outcome.data.replayed).toBe(false); + expect(outcome.data.updated).toBe(2); + expect(outcome.data.sheets).toEqual(['QS-A', 'QS-B']); + expect(outcome.data.skipped).toEqual([{ reason: 'unit_mismatch', sku_code: 'SKU9', detail: '斤 vs 袋' }]); + }); + + it('回执缺字段不炸(一律兜空值)', () => { + expect(normalizeQuoteCostSyncData({})).toEqual({ + client_request_id: '', + replayed: false, + main_branch_code: '', + updated: 0, + sheets: [], + skipped: [], + warnings: [], + }); + }); + + it('2xx 但回执不可识别(data 非对象)⇒ unavailable,绝不判成功', async () => { + fetchMock.mockResolvedValue(jsonResponse(200, { success: true, data: null })); + const outcome = await submitQuoteCostSync({ supplierCode: 'SUP1', body: BODY }); + expect(outcome.kind).toBe('unavailable'); + expect((outcome as any).code).toBe('invalid_main_system_response'); + }); + + it('非 JSON(网关 HTML)⇒ unavailable,不判成功', async () => { + fetchMock.mockResolvedValue({ + ok: true, + status: 200, + json: async () => { + throw new Error('Unexpected token < in JSON'); + }, + }); + const outcome = await submitQuoteCostSync({ supplierCode: 'SUP1', body: BODY }); + expect(outcome.kind).toBe('unavailable'); + }); +}); + +describe('错误归类(决定台账状态与是否重试)', () => { + it('403 branch_not_bound ⇒ rejected(语义拒绝,不是网络故障)', async () => { + fetchMock.mockResolvedValue(jsonResponse(403, { error: 'branch_not_bound', error_description: '未绑定该分公司' })); + const outcome = await submitQuoteCostSync({ supplierCode: 'SUP1', body: BODY }); + expect(outcome.kind).toBe('rejected'); + expect((outcome as any).status).toBe(403); + expect((outcome as any).code).toBe('branch_not_bound'); + }); + + it('409 幂等冲突 ⇒ rejected(默认 4xx 口径)', async () => { + fetchMock.mockResolvedValue(jsonResponse(409, { error: 'idempotency_conflict' })); + const outcome = await submitQuoteCostSync({ supplierCode: 'SUP1', body: BODY }); + expect(outcome.kind).toBe('rejected'); + expect((outcome as any).code).toBe('idempotency_conflict'); + }); + + it('503 feature_disabled / 500 ⇒ unavailable(可重试)', async () => { + for (const status of [503, 500]) { + fetchMock.mockResolvedValueOnce(jsonResponse(status, { error: status === 503 ? 'feature_disabled' : 'server_error' })); + const outcome = await submitQuoteCostSync({ supplierCode: 'SUP1', body: BODY }); + expect(outcome.kind, String(status)).toBe('unavailable'); + } + }); + + it('网络抛错 ⇒ unavailable(不抛给业务层)', async () => { + fetchMock.mockRejectedValue(new Error('ECONNREFUSED')); + const outcome = await submitQuoteCostSync({ supplierCode: 'SUP1', body: BODY }); + expect(outcome.kind).toBe('unavailable'); + }); + + it('401 ⇒ 强制刷新 token 后重试一次', async () => { + fetchMock + .mockResolvedValueOnce(jsonResponse(401, { error: 'unauthorized' })) + .mockResolvedValueOnce(jsonResponse(200, OK_PAYLOAD)); + const outcome = await submitQuoteCostSync({ supplierCode: 'SUP1', body: BODY }); + expect(outcome.kind).toBe('ok'); + expect(getMainSystemToken).toHaveBeenCalledTimes(2); + expect((getMainSystemToken.mock.calls[1] as unknown[])[1]).toEqual({ forceRefresh: true }); + expect(fetchMock).toHaveBeenCalledTimes(2); + }); + + it('token 换不到 ⇒ unavailable,一个业务请求都不发', async () => { + getMainSystemToken.mockResolvedValue({ kind: 'unavailable', reason: '被撤权' }); + const outcome = await submitQuoteCostSync({ supplierCode: 'SUP1', body: BODY }); + expect(outcome.kind).toBe('unavailable'); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('未配置对接 / 缺 supplier_code / 空 items ⇒ 本地直接判失败,零出站', async () => { + enabled.value = false; + expect((await submitQuoteCostSync({ supplierCode: 'SUP1', body: BODY })).kind).toBe('not_configured'); + enabled.value = true; + expect((await submitQuoteCostSync({ supplierCode: '', body: BODY })).kind).toBe('not_configured'); + const empty = await submitQuoteCostSync({ supplierCode: 'SUP1', body: { ...BODY, items: [] } }); + expect(empty.kind).toBe('rejected'); + expect((empty as any).code).toBe('items_required'); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('错误码兜底(没带 error 时按状态码)', () => { + expect(readQuoteCostSyncErrorCode({ error: 'branch_not_bound' }, 403)).toBe('branch_not_bound'); + expect(readQuoteCostSyncErrorCode(null, 401)).toBe('unauthorized'); + expect(readQuoteCostSyncErrorCode(null, 403)).toBe('forbidden'); + expect(readQuoteCostSyncErrorCode(null, 409)).toBe('idempotency_conflict'); + expect(readQuoteCostSyncErrorCode(null, 503)).toBe('feature_disabled'); + expect(readQuoteCostSyncErrorCode(null, 500)).toBe('main_system_error'); + }); +}); diff --git a/server/tests/mainSystemQuoteCostSyncDb.integration.test.ts b/server/tests/mainSystemQuoteCostSyncDb.integration.test.ts new file mode 100644 index 0000000..95b643b --- /dev/null +++ b/server/tests/mainSystemQuoteCostSyncDb.integration.test.ts @@ -0,0 +1,118 @@ +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +/** + * 报价单成本价同步台账**真库**验证(默认跳过;`QUOTE_COST_SYNC_DB_TEST=1` 才跑)。 + * + * 为什么需要这一份:单测里的 DB 是脚本化 mock(等于我写的第二份 SQL 语义), + * 这一份连真 Postgres(本地 `supplier_delivery`),只验证**不依赖对方系统**的那一半: + * + * · 迁移真的落库(表 / 唯一索引 / `status` CHECK 都存在,不是只写在文件里); + * · 唯一键 `(quote_sheet_code, main_branch_code)` 真的会让 `ON CONFLICT DO NOTHING` 命中 + * ⇒ "一张单 × 一个分公司只推一次" 有硬约束兜底(并发下也不会出两行); + * · `status` CHECK 真的拦住非法取值。 + * + * 纪律:只碰 `public.main_system_quote_cost_pushes`,且只碰 `branch_code` 以 `BR_TESTQCS` 开头的临时行,跑完删干净。 + * + * 跑法(本地): + * cd server && QUOTE_COST_SYNC_DB_TEST=1 npx vitest run tests/mainSystemQuoteCostSyncDb.integration.test.ts + */ + +const RUN = process.env.QUOTE_COST_SYNC_DB_TEST === '1'; +const TEST_BRANCH = `BR_TESTQCS_${Date.now()}`; +const SHEET = `QS_TESTQCS_${Date.now()}`; + +// 默认(未设开关)连 src/db 都不加载,保证常规套件不受影响 +const db = RUN ? await import('../src/db') : null; +const pool = () => db!.pool; + +async function cleanup() { + await pool().query(`DELETE FROM public.main_system_quote_cost_pushes WHERE branch_code LIKE 'BR_TESTQCS%'`); +} + +async function insertLedger(mainBranchCode: string, status = 'pending') { + return pool().query<{ id: string }>( + `INSERT INTO public.main_system_quote_cost_pushes + (branch_code, quote_sheet_code, main_branch_code, client_request_id, status) + VALUES ($1, $2, $3, gen_random_uuid(), $4::varchar) + ON CONFLICT (quote_sheet_code, main_branch_code) DO NOTHING + RETURNING id::text AS id`, + [TEST_BRANCH, SHEET, mainBranchCode, status] + ); +} + +describe.skipIf(!RUN)('报价单成本价同步台账 · 真库(迁移约束 + 幂等键)', () => { + beforeAll(async () => { + await cleanup(); + }); + + afterAll(async () => { + await cleanup(); + await pool().end(); + }); + + it('迁移已落库:表 / 唯一索引 / status CHECK 都在 public', async () => { + const table = await pool().query( + `SELECT table_name FROM information_schema.tables + WHERE table_schema = 'public' AND table_name = 'main_system_quote_cost_pushes'` + ); + expect(table.rows).toHaveLength(1); + + const index = await pool().query( + `SELECT indexname FROM pg_indexes + WHERE schemaname = 'public' AND tablename = 'main_system_quote_cost_pushes' + AND indexname = 'uq_main_system_quote_cost_pushes'` + ); + expect(index.rows).toHaveLength(1); + + const check = await pool().query( + `SELECT conname FROM pg_constraint + WHERE conrelid = 'public.main_system_quote_cost_pushes'::regclass + AND conname = 'main_system_quote_cost_pushes_status_chk'` + ); + expect(check.rows).toHaveLength(1); + }); + + it('唯一键生效:同一 (报价单, 分公司) 第二次插入被 ON CONFLICT 吃掉(0 行)', async () => { + const first = await insertLedger('BR_QC_A'); + expect(first.rowCount).toBe(1); + const second = await insertLedger('BR_QC_A'); + expect(second.rowCount).toBe(0); + const count = await pool().query<{ n: number }>( + `SELECT count(*)::int AS n FROM public.main_system_quote_cost_pushes + WHERE quote_sheet_code = $1 AND main_branch_code = 'BR_QC_A'`, + [SHEET] + ); + expect(Number(count.rows[0]?.n)).toBe(1); + }); + + it('不同分公司各自一行(一单多分公司各推一次)', async () => { + const a = await insertLedger('BR_QC_B'); + const b = await insertLedger('BR_QC_C'); + expect(a.rowCount).toBe(1); + expect(b.rowCount).toBe(1); + }); + + it('status CHECK 拦住非法取值(拼错的终态不会静默入库)', async () => { + await expect(insertLedger('BR_QC_BAD', 'synced')).rejects.toThrow(); + }); + + it('整单级跳过用 * 也受唯一键约束(重复触发只写一次)', async () => { + const first = await insertLedger('*', 'skipped'); + const second = await insertLedger('*', 'skipped'); + expect(first.rowCount).toBe(1); + expect(second.rowCount).toBe(0); + }); + + // tester 补充(2026-10-18):并发不是「连续插两次」的同义词 —— 并发下真正兜底的是唯一索引本身 + it('并发 10 次同 (报价单, 分公司) 插入 ⇒ 恰好 1 行(唯一键在并发下收敛,不是靠应用层先查后写)', async () => { + const results = await Promise.all(Array.from({ length: 10 }, () => insertLedger('BR_QC_RACE'))); + const inserted = results.filter((r) => r.rowCount === 1).length; + expect(inserted, '只允许 1 次插入成功').toBe(1); + const count = await pool().query<{ n: number }>( + `SELECT count(*)::int AS n FROM public.main_system_quote_cost_pushes + WHERE quote_sheet_code = $1 AND main_branch_code = 'BR_QC_RACE'`, + [SHEET] + ); + expect(Number(count.rows[0]?.n)).toBe(1); + }, 30000); +}); diff --git a/server/tests/quotePriceProposal.test.ts b/server/tests/quotePriceProposal.test.ts new file mode 100644 index 0000000..98c6410 --- /dev/null +++ b/server/tests/quotePriceProposal.test.ts @@ -0,0 +1,1459 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +/** + * 报价单**双向价格传递**(2026-10-18 冻结契约 + Lead 7 条 T 裁定)—— 服务层契约守卫。 + * + * 钉住(做反就要返工): + * · 开关默认关 ⇒ 零出站、零写库(三个入口一律 503); + * · 方向 A:内部审核无在途 pending 才允许;整单提交调用 D1(出站),本地建 pending,**不写价**; + * T6:同 payload 同 hash ⇒ 回放;不同 hash ⇒ 旧 pending 置 `superseded`; + * · 方向 B:T2 按 `MAIN_<主系统分公司>` 解析**唯一生效单**(0 ⇒ no_quote_sheet,多 ⇒ ambiguous_sheet); + * **T3 只按行 UPDATE**(绝不整表 DELETE+INSERT,payload 只含 2 个 SKU 时其余 SKU 行必须原样保留); + * 缺行/单位不一致/金额非法 ⇒ 跳过并记录;值未变不写; + * · approve 后:**不再调用 `triggerQuoteCostSync`**(verifier 阻断项修正:由配送侧按 D3 `approved` 落地写价),只发 D3 回执; + * · 重复决策 ⇒ already_decided;驳回 ⇒ 不写价、零推送、D3 回执带理由; + * · T8:本地已终态、远端仍 pending ⇒ 下次 D2 轮询补发 D3; + * · T10:D2 带游标,用返回的 `next_cursor` 增量拉。 + */ + +/* ── mock:DB(脚本化,内存台账)──────────────────────────────────────────── */ + +const poolQuery = vi.hoisted(() => vi.fn()); +const clientQuery = vi.hoisted(() => vi.fn()); +const clientRelease = vi.hoisted(() => vi.fn()); +vi.mock('../src/db', () => ({ + pool: { + query: (...args: unknown[]) => poolQuery(...args), + connect: async () => ({ + query: (...args: unknown[]) => clientQuery(...args), + release: () => clientRelease(), + }), + }, + getRawPoolQuery: () => poolQuery, +})); + +const tenantCtx = vi.hoisted(() => vi.fn()); +vi.mock('../src/services/tenantDbContext', () => ({ + runWithTenantDbContext: (...args: unknown[]) => tenantCtx(...args), +})); + +// 报价单服务:方向 B 不再走 applyQuoteSheetUpdate(T3),只 mock 读取守卫;改为断言它从未被调用 +const applyQuoteSheetUpdate = vi.hoisted(() => vi.fn()); +const loadQuoteSheetForUpdate = vi.hoisted(() => vi.fn()); +vi.mock('../src/services/quoteSheetService', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + applyQuoteSheetUpdate: (...args: unknown[]) => applyQuoteSheetUpdate(...args), + loadQuoteSheetForUpdate: (...args: unknown[]) => loadQuoteSheetForUpdate(...args), + }; +}); + +// 成本价同步:触发入口 + 供应商编码解析 mock;指纹算法用真实现 +const triggerQuoteCostSync = vi.hoisted(() => vi.fn()); +const resolveMainSupplierCode = vi.hoisted(() => vi.fn()); +vi.mock('../src/services/mainSystemQuoteCostSync', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + triggerQuoteCostSync: (...args: unknown[]) => triggerQuoteCostSync(...args), + resolveMainSupplierCode: (...args: unknown[]) => resolveMainSupplierCode(...args), + }; +}); + +// 出站封装:D1/D2/D3 全 mock(零真网络) +const submitRemote = vi.hoisted(() => vi.fn()); +const listRemote = vi.hoisted(() => vi.fn()); +const decideRemote = vi.hoisted(() => vi.fn()); +vi.mock('../src/services/mainSystem/api/quotePriceProposals', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + submitQuotePriceProposal: (...args: unknown[]) => submitRemote(...args), + listQuotePriceProposals: (...args: unknown[]) => listRemote(...args), + decideQuotePriceProposal: (...args: unknown[]) => decideRemote(...args), + }; +}); + +const writeAuditLog = vi.hoisted(() => vi.fn()); +vi.mock('../src/services/auditService', () => ({ + writeAuditLog: (...args: unknown[]) => writeAuditLog(...args), +})); + +import { + approvePriceProposal, + isQuotePriceProposalEnabled, + listPriceProposals, + rejectPriceProposal, + submitPriceProposal, + syncQuotePriceProposals, + resetQuotePriceProposalSyncCursor, +} from '../src/services/quotePriceProposalService'; + +/* ── 脚本化 DB ──────────────────────────────────────────────────────────── */ + +type LocalProposal = Record; + +type DbState = { + sheet: Record; + sheetCustomers: string[]; + items: Array>; + proposals: LocalProposal[]; + changeRequests: Array<{ status: string }>; + activeSheets: string[]; + bindings: Array<{ branch_code: string; main_branch_code: string; main_supplier_code: string }>; + sql: string[]; + events: string[]; + /** 模拟极端并发:INSERT 永远撞唯一键 */ + forceInsertConflict?: boolean; + /** 模拟极端并发:查不到本地 pending(旧行刚被别的请求接管) */ + forceNoPending?: boolean; + /** 本地 SKU 映射副本(默认恒等映射:配送 SKU = 我方 SKU,保证既有用例语义不变) */ + mappings?: Array<{ + supplier_sku_code: string; + supplier_sku_name: string | null; + supplier_unit: string | null; + delivery_sku_code: string | null; + delivery_sku_name: string | null; + status: string; + }>; +}; + +const SHEET = 'QS1'; +const BRANCH = 'BR002'; +const MAIN_BRANCH = 'BR002'; + +function makeState(overrides: Partial = {}): DbState { + return { + sheet: { + quote_sheet_code: SHEET, + branch_code: BRANCH, + title: '报价单 V1', + version_no: 1, + status: 1, + approval_status: 30, + expires_at: new Date(Date.now() + 86400_000).toISOString(), + auto_sale_price_by_cost: false, + }, + sheetCustomers: ['MAIN_BR002'], + items: [ + { id: 'item-1', sku_code: 'SKU1', sku_name: '草鱼', unit: '斤', sale_price: '10.00', price: '10.00', cost_price: '5.00', markup_ratio: null, sort_order: 0 }, + { id: 'item-2', sku_code: 'SKU2', sku_name: '鲤鱼', unit: '袋', sale_price: '20.00', price: '20.00', cost_price: '9.00', markup_ratio: null, sort_order: 1 }, + { id: 'item-3', sku_code: 'SKU3', sku_name: '鲫鱼', unit: '斤', sale_price: '30.00', price: '30.00', cost_price: '12.00', markup_ratio: null, sort_order: 2 }, + ], + proposals: [], + changeRequests: [], + activeSheets: [SHEET], + bindings: [{ branch_code: BRANCH, main_branch_code: MAIN_BRANCH, main_supplier_code: 'SUP1' }], + sql: [], + events: [], + mappings: [ + { supplier_sku_code: 'SKU1', supplier_sku_name: '草鱼', supplier_unit: '斤', delivery_sku_code: 'SKU1', delivery_sku_name: '草鱼', status: 'active' }, + { supplier_sku_code: 'SKU2', supplier_sku_name: '鲤鱼', supplier_unit: '袋', delivery_sku_code: 'SKU2', delivery_sku_name: '鲤鱼', status: 'active' }, + { supplier_sku_code: 'SKU3', supplier_sku_name: '鲫鱼', supplier_unit: '斤', delivery_sku_code: 'SKU3', delivery_sku_name: '鲫鱼', status: 'active' }, + ], + ...overrides, + }; +} + +function seedLocalProposal(state: DbState, patch: LocalProposal = {}): LocalProposal { + const row: LocalProposal = { + id: patch.id ?? '11111111-1111-4111-8111-111111111111', + branch_code: patch.branch_code ?? BRANCH, + quote_sheet_code: patch.quote_sheet_code ?? SHEET, + main_branch_code: patch.main_branch_code ?? MAIN_BRANCH, + direction: patch.direction ?? 'from_delivery', + items: patch.items ?? [{ sku_code: 'SKU1', unit: '斤', price: 11 }], + payload_hash: patch.payload_hash ?? 'fp', + status: patch.status ?? 'pending', + reject_reason: patch.reject_reason ?? null, + client_request_id: patch.client_request_id ?? 'cr-local', + remote_proposal_id: patch.remote_proposal_id ?? 'remote-1', + requested_by: patch.requested_by ?? 'u1', + requested_by_name: patch.requested_by_name ?? '甲', + requested_at: patch.requested_at ?? '2026-10-18T01:00:00.000Z', + reviewed_by: patch.reviewed_by ?? null, + reviewed_by_name: patch.reviewed_by_name ?? null, + reviewed_at: patch.reviewed_at ?? null, + applied_at: patch.applied_at ?? null, + updated_at: patch.updated_at ?? '2026-10-18T01:00:00.000Z', + }; + state.proposals.push(row); + return row; +} + +function installDb(state: DbState): void { + const handler = async (sql: string, params: unknown[] = [], fromClient: boolean) => { + const text = String(sql); + state.sql.push(text); + if (/^\s*(BEGIN|COMMIT|ROLLBACK)\s*;?\s*$/i.test(text)) { + if (fromClient) state.events.push(text.trim().toUpperCase()); + return { rows: [], rowCount: 0 }; + } + // 生效单解析(T2) + if (text.includes('FROM customer_quote_sheets qs') && text.includes('EXISTS')) { + return { rows: state.activeSheets.map((quote_sheet_code) => ({ quote_sheet_code })) }; + } + if (text.includes('FROM quote_price_proposals') && text.includes('WHERE id = $1::uuid')) { + const row = state.proposals.find((item) => item.id === String(params[0])); + return { rows: row ? [row] : [], rowCount: row ? 1 : 0 }; + } + if (text.includes('FROM quote_price_proposals') && text.includes('FOR UPDATE')) { + state.events.push('PROPOSAL_LOCK'); + const row = state.proposals.find((item) => item.id === String(params[0])); + return { rows: row ? [row] : [], rowCount: row ? 1 : 0 }; + } + if (text.includes('FROM quote_price_proposals') && text.includes('remote_proposal_id = $1')) { + const row = state.proposals.find((item) => item.remote_proposal_id === String(params[0])); + return { rows: row ? [row] : [], rowCount: row ? 1 : 0 }; + } + if (text.includes('FROM quote_price_proposals') && text.includes("status = 'pending'")) { + if (state.forceNoPending) return { rows: [], rowCount: 0 }; + const row = state.proposals.find( + (item) => + item.branch_code === params[0] && + item.quote_sheet_code === params[1] && + item.direction === params[2] && + item.status === 'pending' + ); + return { rows: row ? [row] : [], rowCount: row ? 1 : 0 }; + } + if (text.includes('INSERT INTO quote_price_proposals')) { + state.events.push('PROPOSAL_INSERT'); + if (text.includes('ON CONFLICT')) { + const direction = text.includes("'from_delivery'") ? 'from_delivery' : 'to_delivery'; + if (state.forceInsertConflict) return { rows: [], rowCount: 0 }; + const conflict = state.proposals.some( + (item) => + item.branch_code === params[0] && + item.quote_sheet_code === params[1] && + item.direction === direction && + item.status === 'pending' + ); + if (conflict) return { rows: [], rowCount: 0 }; + } + const row: LocalProposal = { + id: `local-${state.proposals.length + 1}`, + branch_code: params[0], + quote_sheet_code: params[1], + main_branch_code: params[2], + direction: text.includes("'from_delivery'") ? 'from_delivery' : 'to_delivery', + items: JSON.parse(String(params[3])), + payload_hash: params[4], + status: 'pending', + reject_reason: null, + client_request_id: params[5], + remote_proposal_id: params[6], + requested_by: params[7] ?? null, + requested_at: new Date().toISOString(), + reviewed_by: null, + reviewed_at: null, + applied_at: null, + updated_at: new Date().toISOString(), + }; + state.proposals.push(row); + return { rows: [row], rowCount: 1 }; + } + if (text.includes('UPDATE quote_price_proposals') && text.includes("SET status = 'superseded'")) { + state.events.push('PROPOSAL_SUPERSEDE'); + if (text.includes('WHERE id = $1::uuid')) { + // 收口单行(sync:remote_superseded 是 SQL 字面量;replaced_by_remote 是参数 $2) + const row = state.proposals.find((item) => item.id === String(params[0])); + if (row) { + row.status = 'superseded'; + if (text.includes("reject_reason = 'remote_superseded'")) row.reject_reason = 'remote_superseded'; + else if (params[1]) row.reject_reason = params[1]; + } + return { rows: [], rowCount: row ? 1 : 0 }; + } + for (const row of state.proposals) { + if ( + row.branch_code === params[0] && + row.quote_sheet_code === params[1] && + row.direction === 'to_delivery' && + row.status === 'pending' + ) { + row.status = 'superseded'; + } + } + return { rows: [], rowCount: 1 }; + } + if (text.includes('UPDATE quote_price_proposals') && text.includes("SET status = 'approved'")) { + state.events.push('PROPOSAL_APPROVED'); + const row = state.proposals.find((item) => item.id === String(params[0]) && item.status === 'pending'); + if (!row) return { rows: [], rowCount: 0 }; + row.status = 'approved'; + row.quote_sheet_code = params[1]; + row.reviewed_by = params[2] ?? null; + row.applied_at = new Date().toISOString(); + return { rows: [row], rowCount: 1 }; + } + if (text.includes('UPDATE quote_price_proposals') && text.includes("SET status = 'rejected'")) { + state.events.push('PROPOSAL_REJECTED'); + const row = state.proposals.find((item) => item.id === String(params[0]) && item.status === 'pending'); + if (!row) return { rows: [], rowCount: 0 }; + row.status = 'rejected'; + row.reject_reason = params[1]; + return { rows: [row], rowCount: 1 }; + } + if (text.includes('UPDATE quote_price_proposals') && text.includes('SET status = $2::varchar')) { + state.events.push('PROPOSAL_SYNC_STATUS'); + const row = state.proposals.find((item) => item.id === String(params[0])); + if (row) { + row.status = params[1]; + if (params[2]) row.reject_reason = params[2]; + } + return { rows: [], rowCount: row ? 1 : 0 }; + } + if (text.includes('FROM main_system_sku_mappings') && text.includes('delivery_sku_code = $1')) { + const row = (state.mappings || []).find( + (item) => item.delivery_sku_code === String(params[0]) && item.status === 'active' + ); + return { rows: row ? [row] : [], rowCount: row ? 1 : 0 }; + } + if (text.includes('FROM main_system_sku_mappings') && text.includes('delivery_sku_code = ANY')) { + const list = new Set((params[0] as string[]) || []); + return { rows: (state.mappings || []).filter((item) => item.delivery_sku_code && list.has(item.delivery_sku_code)) }; + } + if (text.includes('FROM main_system_sku_mappings') && text.includes('supplier_sku_code = ANY')) { + const list = new Set((params[0] as string[]) || []); + return { rows: (state.mappings || []).filter((item) => list.has(item.supplier_sku_code)) }; + } + if (text.includes('FROM quote_price_proposals p')) { + return { + rows: state.proposals.map((row) => ({ + ...row, + requested_by_name: row.requested_by_name ?? '甲', + reviewed_by_name: row.reviewed_by_name ?? '', + })), + }; + } + if (text.includes('FROM quote_sheet_change_requests')) { + return { rows: state.changeRequests, rowCount: state.changeRequests.length }; + } + if (text.includes('FROM customer_quote_sheet_customers') && text.includes('ORDER BY customer_code')) { + return { rows: state.sheetCustomers.map((customer_code) => ({ customer_code })) }; + } + if (text.includes('FROM customer_quote_sheet_customers')) { + return { rows: state.sheetCustomers.map((customer_code) => ({ customer_code, company_name: '客户' })) }; + } + // T3:唯一写价语句 + if (text.includes('UPDATE customer_quote_sheet_items') && text.includes('SET sale_price = $3, price = $3')) { + state.events.push('ITEM_UPDATE'); + const row = state.items.find( + (item) => item.quote_sheet_code === params[0] || item.sku_code === params[1] + ); + const target = state.items.find((item) => item.sku_code === String(params[1])); + if (!target) return { rows: [], rowCount: 0 }; + target.sale_price = String(params[2]); + target.price = String(params[2]); + return { rows: [{ id: target.id }], rowCount: 1 }; + } + if (text.includes('FROM customer_quote_sheet_items')) { + return { + rows: state.items.map((item) => ({ ...item, quote_sheet_code: item.quote_sheet_code ?? SHEET })), + rowCount: state.items.length, + }; + } + if (text.includes('SELECT 1 FROM customer_quote_sheets')) { + return { rows: state.activeSheets.includes(String(params[0])) ? [{ 1: 1 }] : [] }; + } + if (text.includes('FROM customer_quote_sheets')) { + return { rows: [state.sheet], rowCount: 1 }; + } + if (text.includes('FROM public.main_supplier_bindings')) { + return { rows: state.bindings, rowCount: state.bindings.length }; + } + return { rows: [], rowCount: 0 }; + }; + poolQuery.mockImplementation((sql: string, params?: unknown[]) => handler(sql, params || [], false)); + clientQuery.mockImplementation((sql: string, params?: unknown[]) => handler(sql, params || [], true)); +} + +const okSubmit = (proposalId = 'remote-1') => ({ + kind: 'ok' as const, + status: 200, + data: { proposal_id: proposalId, status: 'pending', replayed: false }, +}); + +beforeEach(() => { + poolQuery.mockReset(); + clientQuery.mockReset(); + clientRelease.mockReset(); + applyQuoteSheetUpdate.mockReset(); + loadQuoteSheetForUpdate.mockReset(); + triggerQuoteCostSync.mockReset(); + resolveMainSupplierCode.mockReset(); + submitRemote.mockReset(); + listRemote.mockReset(); + decideRemote.mockReset(); + writeAuditLog.mockReset(); + tenantCtx.mockReset(); + tenantCtx.mockImplementation(async (_code: string, fn: () => Promise) => fn()); + resetQuotePriceProposalSyncCursor(); + + delete process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL; + loadQuoteSheetForUpdate.mockResolvedValue({ + quote_sheet_code: SHEET, + branch_code: BRANCH, + version_no: 1, + status: 1, + approval_status: 30, + auto_sale_price_by_cost: false, + }); + resolveMainSupplierCode.mockResolvedValue('SUP1'); + submitRemote.mockResolvedValue(okSubmit()); + // 默认:D2 精确查(带 proposalId)返回"该提议仍 pending";不带 id 的批量拉取返回空 + listRemote.mockImplementation(async (input: any) => ({ + kind: 'ok' as const, + status: 200, + rows: input?.proposalId + ? [ + { + proposal_id: String(input.proposalId), + direction: 'to_supplier', + status: 'pending', + supplier_quote_sheet_code: SHEET, + branch_code: MAIN_BRANCH, + items: [], + note: null, + reject_reason: null, + applied: null, + created_at: null, + reviewed_at: null, + }, + ] + : [], + summary: null, + nextCursor: null, + })); + decideRemote.mockResolvedValue({ kind: 'ok', status: 200 }); + writeAuditLog.mockResolvedValue(undefined); +}); + +/* ── 开关 ───────────────────────────────────────────────────────────────── */ + +describe('开关(默认关)', () => { + it('未设置 / 0 / false ⇒ 关;1 / true / on ⇒ 开', () => { + expect(isQuotePriceProposalEnabled()).toBe(false); + for (const value of ['1', 'true', 'on', 'TRUE']) { + process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = value; + expect(isQuotePriceProposalEnabled(), value).toBe(true); + } + for (const value of ['0', 'false', 'off']) { + process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = value; + expect(isQuotePriceProposalEnabled(), value).toBe(false); + } + }); + + it('关 ⇒ 三个入口 503 feature_disabled,且零出站 / 零查库', async () => { + installDb(makeState()); + await expect(submitPriceProposal({ quoteSheetCode: SHEET, ctx: { branchCode: BRANCH } as any })).rejects.toMatchObject({ + status: 503, + code: 'feature_disabled', + }); + await expect( + approvePriceProposal({ id: '11111111-1111-4111-8111-111111111111' }) + ).rejects.toMatchObject({ status: 503, code: 'feature_disabled' }); + await expect( + rejectPriceProposal({ id: '11111111-1111-4111-8111-111111111111', reason: 'x' }) + ).rejects.toMatchObject({ status: 503, code: 'feature_disabled' }); + const sync = await syncQuotePriceProposals(); + expect(sync.pulled + sync.synced + sync.receipts + sync.errors).toBe(0); + expect(poolQuery).not.toHaveBeenCalled(); + expect(submitRemote).not.toHaveBeenCalled(); + expect(listRemote).not.toHaveBeenCalled(); + }); +}); + +/* ── 方向 A:发起 ───────────────────────────────────────────────────────── */ + +describe('方向 A:提交配送商审核(不写价)', () => { + beforeEach(() => { + process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1'; + }); + + it('整单 items 调 D1、本地建 pending,**不写价**(applyQuoteSheetUpdate 从未被调用)', async () => { + const state = makeState(); + installDb(state); + // 记录 D1 出站事件,用于断言"出站先于任何 BEGIN"(HTTP 必须在事务之外) + submitRemote.mockImplementationOnce(async () => { + state.events.push('D1_OUTBOUND'); + return okSubmit(); + }); + const result = await submitPriceProposal({ + quoteSheetCode: SHEET, + note: '请审核', + requestedBy: 'u1', + ctx: { branchCode: BRANCH, userId: 'u1', roles: ['operator'] } as any, + }); + + expect(result.applied).toBe(false); + expect(submitRemote).toHaveBeenCalledTimes(1); + const call = submitRemote.mock.calls[0][0] as any; + expect(call).toMatchObject({ + supplierCode: 'SUP1', + supplierQuoteSheetCode: SHEET, + mainBranchCode: MAIN_BRANCH, + note: '请审核', + }); + expect(call.items).toEqual([ + { sku_code: 'SKU1', unit: '斤', price: 10 }, + { sku_code: 'SKU2', unit: '袋', price: 20 }, + { sku_code: 'SKU3', unit: '斤', price: 30 }, + ]); + expect(state.proposals).toHaveLength(1); + expect(state.proposals[0]).toMatchObject({ + direction: 'to_delivery', + status: 'pending', + remote_proposal_id: 'remote-1', + }); + expect(applyQuoteSheetUpdate).not.toHaveBeenCalled(); + expect(triggerQuoteCostSync).not.toHaveBeenCalled(); + // 出站必须发生在落库事务之前(HTTP 永远在事务之外) + expect(state.events.indexOf('D1_OUTBOUND')).toBeGreaterThan(-1); + expect(state.events.indexOf('D1_OUTBOUND')).toBeLessThan(state.events.indexOf('BEGIN')); + }); + + it('内部改价审核仍有在途 pending ⇒ 409 internal_review_pending,零出站', async () => { + const state = makeState({ changeRequests: [{ status: 'pending' }] }); + installDb(state); + await expect(submitPriceProposal({ quoteSheetCode: SHEET, ctx: { branchCode: BRANCH } as any })).rejects.toMatchObject({ + status: 409, + code: 'internal_review_pending', + }); + expect(submitRemote).not.toHaveBeenCalled(); + expect(state.proposals).toHaveLength(0); + }); + + it('没有 MAIN_ 客户 / 多个主系统分公司 ⇒ 400(不猜、不扇出)', async () => { + const none = makeState({ sheetCustomers: ['CUS1', '__RETAIL__'] }); + installDb(none); + await expect(submitPriceProposal({ quoteSheetCode: SHEET, ctx: { branchCode: BRANCH } as any })).rejects.toMatchObject({ + status: 400, + code: 'not_usage_company', + }); + + const many = makeState({ sheetCustomers: ['MAIN_BR002', 'MAIN_BR007'] }); + installDb(many); + await expect(submitPriceProposal({ quoteSheetCode: SHEET, ctx: { branchCode: BRANCH } as any })).rejects.toMatchObject({ + status: 400, + code: 'ambiguous_main_branch', + }); + expect(submitRemote).not.toHaveBeenCalled(); + }); + + it('T6:同 payload 再提交 ⇒ 回放(不重复出站),不同 payload ⇒ 旧 pending 置 superseded 再建新行', async () => { + const state = makeState(); + installDb(state); + const first = await submitPriceProposal({ quoteSheetCode: SHEET, ctx: { branchCode: BRANCH } as any }); + expect(first.replayed).toBe(false); + expect(submitRemote).toHaveBeenCalledTimes(1); + + // 同 payload ⇒ 回放 + const replay = await submitPriceProposal({ quoteSheetCode: SHEET, ctx: { branchCode: BRANCH } as any }); + expect(replay.replayed).toBe(true); + expect(submitRemote).toHaveBeenCalledTimes(1); + expect(state.proposals).toHaveLength(1); + + // 改价后再提交 ⇒ 旧行 superseded、新行 pending + state.items = state.items.map((item) => + item.sku_code === 'SKU1' ? { ...item, sale_price: '11.00', price: '11.00' } : item + ); + submitRemote.mockResolvedValueOnce(okSubmit('remote-2')); + const second = await submitPriceProposal({ quoteSheetCode: SHEET, ctx: { branchCode: BRANCH } as any }); + expect(second.replayed).toBe(false); + expect(state.events).toContain('PROPOSAL_SUPERSEDE'); + expect(state.proposals.filter((row) => row.status === 'superseded')).toHaveLength(1); + expect(state.proposals.filter((row) => row.status === 'pending')).toHaveLength(1); + expect(state.proposals.find((row) => row.status === 'pending')!.remote_proposal_id).toBe('remote-2'); + }); + + it('D1 失败 ⇒ 抛错且不落本地行(旧 pending 不动)', async () => { + const state = makeState(); + installDb(state); + submitRemote.mockResolvedValueOnce({ + kind: 'unavailable', + status: 502, + code: 'main_system_error', + reason: '对方不可用', + payload: null, + }); + await expect(submitPriceProposal({ quoteSheetCode: SHEET, ctx: { branchCode: BRANCH } as any })).rejects.toMatchObject({ + status: 502, + code: 'main_system_error', + }); + expect(state.proposals).toHaveLength(0); + }); +}); + +/* ── 同步(D2):A 结果 + B 拉取 + T8 回执重试 + T10 游标 ─────────────── */ + +describe('同步 D2', () => { + beforeEach(() => { + process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1'; + }); + + it('方向 A 的结果(from_supplier approved)⇒ 回写本地状态', async () => { + const state = makeState(); + seedLocalProposal(state, { + id: 'local-a', + direction: 'to_delivery', + status: 'pending', + remote_proposal_id: 'remote-a', + }); + installDb(state); + listRemote.mockResolvedValueOnce({ + kind: 'ok', + status: 200, + rows: [ + { + proposal_id: 'remote-a', + direction: 'from_supplier', + status: 'approved', + supplier_quote_sheet_code: SHEET, + branch_code: MAIN_BRANCH, + items: [], + note: null, + reject_reason: null, + applied: { updated: 0, skipped: [] }, + created_at: null, + reviewed_at: '2026-10-18T02:00:00.000Z', + }, + ], + summary: null, + nextCursor: 'cursor-1', + }); + const summary = await syncQuotePriceProposals(); + expect(summary.synced).toBe(1); + expect(state.proposals[0].status).toBe('approved'); + }); + + it('T2:方向 B(to_supplier pending)拉回时按 MAIN_ 解析生效单并建本地 pending', async () => { + const state = makeState(); + installDb(state); + listRemote.mockResolvedValueOnce({ + kind: 'ok', + status: 200, + rows: [ + { + proposal_id: 'remote-b', + direction: 'to_supplier', + status: 'pending', + supplier_quote_sheet_code: '', + branch_code: MAIN_BRANCH, + items: [ + { sku_code: 'SKU1', unit: '斤', price: 12 }, + { sku_code: 'SKU9', unit: '斤', price: 8 }, + ], + note: '成本上调', + reject_reason: null, + applied: null, + created_at: null, + reviewed_at: null, + }, + ], + summary: null, + nextCursor: null, + }); + const summary = await syncQuotePriceProposals(); + expect(summary.pulled).toBe(1); + const row = state.proposals.find((item) => item.direction === 'from_delivery')!; + expect(row).toMatchObject({ quote_sheet_code: SHEET, status: 'pending', remote_proposal_id: 'remote-b' }); + expect(row.items).toEqual([ + { sku_code: 'SKU1', unit: '斤', price: 12 }, + { sku_code: 'SKU9', unit: '斤', price: 8 }, + ]); + }); + + it('T2:MAIN_ 对应多张生效单 ⇒ 不猜、不落行(跳过并告警)', async () => { + const state = makeState({ activeSheets: ['QS1', 'QS2'] }); + installDb(state); + listRemote.mockResolvedValueOnce({ + kind: 'ok', + status: 200, + rows: [ + { + proposal_id: 'remote-b2', + direction: 'to_supplier', + status: 'pending', + supplier_quote_sheet_code: '', + branch_code: MAIN_BRANCH, + items: [{ sku_code: 'SKU1', unit: '斤', price: 12 }], + note: null, + reject_reason: null, + applied: null, + created_at: null, + reviewed_at: null, + }, + ], + summary: null, + nextCursor: null, + }); + const summary = await syncQuotePriceProposals(); + expect(summary.pulled).toBe(0); + expect(state.proposals).toHaveLength(0); + expect(summary.skipped).toBe(1); + }); + + it('T8:本地已终态、远端仍 pending ⇒ 补发 D3(幂等)', async () => { + const state = makeState(); + seedLocalProposal(state, { + direction: 'from_delivery', + status: 'approved', + remote_proposal_id: 'remote-c', + }); + installDb(state); + listRemote.mockResolvedValueOnce({ + kind: 'ok', + status: 200, + rows: [ + { + proposal_id: 'remote-c', + direction: 'to_supplier', + status: 'pending', + supplier_quote_sheet_code: SHEET, + branch_code: MAIN_BRANCH, + items: [], + note: null, + reject_reason: null, + applied: null, + created_at: null, + reviewed_at: null, + }, + ], + summary: null, + nextCursor: null, + }); + const summary = await syncQuotePriceProposals(); + expect(summary.receipts).toBe(1); + expect(decideRemote).toHaveBeenCalledWith( + expect.objectContaining({ proposalId: 'remote-c', decision: 'approved' }) + ); + }); + + it('T10:第二轮带上服务端返回的 next_cursor 增量拉取', async () => { + const state = makeState(); + installDb(state); + listRemote + .mockResolvedValueOnce({ kind: 'ok', status: 200, rows: [], summary: null, nextCursor: 'c1' }) + .mockResolvedValueOnce({ kind: 'ok', status: 200, rows: [], summary: null, nextCursor: 'c2' }); + await syncQuotePriceProposals(); + await syncQuotePriceProposals(); + expect((listRemote.mock.calls[0][0] as any).cursor).toBeNull(); + expect((listRemote.mock.calls[1][0] as any).cursor).toBe('c1'); + }); +}); + +/* ── 方向 B:审批(T3 按行 UPDATE)──────────────────────────────────────── */ + +describe('方向 B:approve 只按行 UPDATE(T3)', () => { + beforeEach(() => { + process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1'; + }); + + it('payload 只含 2 个 SKU ⇒ 只更新这 2 行,第三行原样保留(无 DELETE / 无 INSERT / 不整表替换)', async () => { + const state = makeState(); + seedLocalProposal(state, { + items: [ + { sku_code: 'SKU1', unit: '斤', price: 11 }, + { sku_code: 'SKU2', unit: '袋', price: 21 }, + ], + }); + installDb(state); + + const result = await approvePriceProposal({ + id: '11111111-1111-4111-8111-111111111111', + ctx: { branchCode: BRANCH, userId: 'u2', roles: ['admin'] } as any, + reviewedBy: 'u2', + }); + + expect(result.applied.updated).toBe(2); + expect(result.applied.skipped).toEqual([]); + // 只对 payload 的 SKU 发 UPDATE(2 条),第 3 个 SKU 没被碰 + const itemUpdates = state.sql.filter((sql) => sql.includes('SET sale_price = $3, price = $3')); + expect(itemUpdates).toHaveLength(2); + expect(state.events.filter((event) => event === 'ITEM_UPDATE')).toHaveLength(2); + // 绝不整表替换 + expect(state.sql.some((sql) => /DELETE\s+FROM\s+customer_quote_sheet_items/i.test(sql))).toBe(false); + expect(state.sql.some((sql) => /INSERT\s+INTO\s+customer_quote_sheet_items/i.test(sql))).toBe(false); + expect(applyQuoteSheetUpdate).not.toHaveBeenCalled(); + // 第三行未被修改 + expect(state.items.find((item) => item.sku_code === 'SKU3')!.sale_price).toBe('30.00'); + expect(state.items.find((item) => item.sku_code === 'SKU1')!.sale_price).toBe('11'); + }); + + it('写价后:COMMIT 早于 D3 回执;**不再出站旧成本同步通道**;本地置 approved', async () => { + const state = makeState(); + seedLocalProposal(state, { items: [{ sku_code: 'SKU1', unit: '斤', price: 11 }] }); + installDb(state); + const order: string[] = []; + triggerQuoteCostSync.mockImplementation(() => order.push('trigger')); + decideRemote.mockImplementation(async () => { + order.push('d3'); + return { kind: 'ok', status: 200 }; + }); + + const result = await approvePriceProposal({ + id: '11111111-1111-4111-8111-111111111111', + ctx: { branchCode: BRANCH, userId: 'u2', roles: ['admin'] } as any, + reviewedBy: 'u2', + }); + + expect(state.events.indexOf('COMMIT')).toBeGreaterThan(-1); + // verifier 阻断项:B 审批不再走旧通道(旧通道按 sku_code 直猜且跳过共享单,配送 cost_price 会静默不变) + expect(order).toEqual(['d3']); + expect(triggerQuoteCostSync).not.toHaveBeenCalled(); + expect(result.receiptSent).toBe(true); + expect(state.proposals[0].status).toBe('approved'); + expect(decideRemote).toHaveBeenCalledWith( + expect.objectContaining({ proposalId: 'remote-1', decision: 'approved' }) + ); + // 每行一条审计(best-effort,提交后写) + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(writeAuditLog).toHaveBeenCalled(); + expect((writeAuditLog.mock.calls[0][0] as any).operationType).toBe('quote_price_proposal_apply'); + }); + + it('未映射 ⇒ sku_unmapped;单位不一致 ⇒ unit_mismatch;金额非法 ⇒ invalid_price', async () => { + const state = makeState(); + seedLocalProposal(state, { + items: [ + { sku_code: 'SKU1', unit: '袋', price: 11 }, // 单里 SKU1 是「斤」⇒ unit_mismatch + { sku_code: 'SKU9', unit: '斤', price: 9 }, // 单里没有 ⇒ sku_not_in_sheet + { sku_code: 'SKU3', unit: '斤', price: 0 }, // 金额非法 ⇒ invalid_price + ], + }); + installDb(state); + const result = await approvePriceProposal({ + id: '11111111-1111-4111-8111-111111111111', + ctx: { branchCode: BRANCH } as any, + }); + expect(result.applied.updated).toBe(0); + expect(result.applied.skipped).toEqual( + expect.arrayContaining([ + { sku_code: 'SKU1', reason: 'unit_mismatch', detail: '袋 vs 斤' }, + { sku_code: 'SKU9', reason: 'sku_unmapped' }, + { sku_code: 'SKU3', reason: 'invalid_price' }, + ]) + ); + expect(state.events).not.toContain('ITEM_UPDATE'); + }); + + it('值未变 ⇒ 不写 UPDATE(计入 unchanged)', async () => { + const state = makeState(); + seedLocalProposal(state, { items: [{ sku_code: 'SKU1', unit: '斤', price: 10 }] }); + installDb(state); + const result = await approvePriceProposal({ + id: '11111111-1111-4111-8111-111111111111', + ctx: { branchCode: BRANCH } as any, + }); + expect(result.applied.updated).toBe(0); + expect(result.applied.unchanged).toBe(1); + expect(state.events).not.toContain('ITEM_UPDATE'); + // 状态仍要推进(T9:零写入也是 approved);但**不**再触发旧成本同步通道 + expect(state.proposals[0].status).toBe('approved'); + expect(triggerQuoteCostSync).not.toHaveBeenCalled(); + }); + + it('T2:目标单 0 张 ⇒ 409 no_quote_sheet;多张 ⇒ 409 ambiguous_sheet', async () => { + const none = makeState({ activeSheets: [] }); + seedLocalProposal(none, {}); + installDb(none); + await expect( + approvePriceProposal({ id: '11111111-1111-4111-8111-111111111111', ctx: { branchCode: BRANCH } as any }) + ).rejects.toMatchObject({ status: 409, code: 'no_quote_sheet' }); + + const many = makeState({ activeSheets: ['QS1', 'QS2'] }); + seedLocalProposal(many, {}); + installDb(many); + await expect( + approvePriceProposal({ id: '11111111-1111-4111-8111-111111111111', ctx: { branchCode: BRANCH } as any }) + ).rejects.toMatchObject({ status: 409, code: 'ambiguous_sheet' }); + }); + + it('重复决策 ⇒ 409 already_decided;错误方向 ⇒ 400 wrong_direction', async () => { + const decided = makeState(); + seedLocalProposal(decided, { status: 'approved' }); + installDb(decided); + await expect( + approvePriceProposal({ id: '11111111-1111-4111-8111-111111111111', ctx: { branchCode: BRANCH } as any }) + ).rejects.toMatchObject({ status: 409, code: 'already_decided' }); + + const toDelivery = makeState(); + seedLocalProposal(toDelivery, { direction: 'to_delivery' }); + installDb(toDelivery); + await expect( + approvePriceProposal({ id: '11111111-1111-4111-8111-111111111111', ctx: { branchCode: BRANCH } as any }) + ).rejects.toMatchObject({ status: 400, code: 'wrong_direction' }); + }); +}); + +describe('方向 B:reject', () => { + beforeEach(() => { + process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1'; + }); + + it('驳回 ⇒ 不写价、零推送、D3 回执 rejected + 理由', async () => { + const state = makeState(); + seedLocalProposal(state, {}); + installDb(state); + const result = await rejectPriceProposal({ + id: '11111111-1111-4111-8111-111111111111', + reason: '成本谈不拢', + ctx: { branchCode: BRANCH, userId: 'u2', roles: ['admin'] } as any, + reviewedBy: 'u2', + }); + expect(result.proposal.status).toBe('rejected'); + expect(state.events).not.toContain('ITEM_UPDATE'); + expect(applyQuoteSheetUpdate).not.toHaveBeenCalled(); + expect(triggerQuoteCostSync).not.toHaveBeenCalled(); + expect(decideRemote).toHaveBeenCalledWith( + expect.objectContaining({ decision: 'rejected', reason: '成本谈不拢' }) + ); + }); + + it('驳回必须给理由(400 reject_reason_required)', async () => { + installDb(makeState()); + await expect( + rejectPriceProposal({ id: '11111111-1111-4111-8111-111111111111', reason: ' ', ctx: { branchCode: BRANCH } as any }) + ).rejects.toMatchObject({ status: 400, code: 'reject_reason_required' }); + }); +}); + +/* ── 列表 ──────────────────────────────────────────────────────────────── */ + +describe('列表', () => { + beforeEach(() => { + process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1'; + }); + + it('返回本地行 + 提交人;pending 的 B 行带「改前 → 改后」与等待天数', async () => { + const state = makeState(); + seedLocalProposal(state, { + direction: 'from_delivery', + items: [{ sku_code: 'SKU1', unit: '斤', price: 11 }], + requested_at: new Date(Date.now() - 3 * 86400000).toISOString(), + }); + installDb(state); + const { rows } = await listPriceProposals({ branchCode: BRANCH, status: 'pending' }); + expect(rows).toHaveLength(1); + expect(rows[0].requested_by_name).toBe('甲'); + expect(rows[0].waited_days).toBe(3); + expect(rows[0].lines?.[0]).toMatchObject({ + sku_code: 'SKU1', + before_sale_price: 10, + after_sale_price: 11, + change: 'updated', + }); + }); +}); + +/* ── ⑩ verifier 阻断项(A16/T6 交叉):远端 superseded / 旧 id / 冲突接管 / D3 带 applied ─── */ + +describe('A16/T6 交叉:远端 superseded 必须收口本地 pending', () => { + beforeEach(() => { + process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1'; + }); + + const remoteRow = (over: Record) => ({ + proposal_id: 'remote-old', + direction: 'to_supplier', + status: 'superseded', + supplier_quote_sheet_code: SHEET, + branch_code: MAIN_BRANCH, + items: [{ sku_code: 'SKU1', unit: '斤', price: 11 }], + note: null, + reject_reason: null, + applied: null, + created_at: null, + reviewed_at: null, + ...over, + }); + + it('一轮内「旧 id=superseded + 新 id=pending」⇒ 本地旧 pending 变 superseded、新 pending 落库', async () => { + const state = makeState(); + seedLocalProposal(state, { + id: 'local-old', + direction: 'from_delivery', + status: 'pending', + remote_proposal_id: 'remote-old', + items: [{ sku_code: 'SKU1', unit: '斤', price: 11 }], + }); + installDb(state); + listRemote.mockResolvedValueOnce({ + kind: 'ok', + status: 200, + rows: [ + remoteRow({ proposal_id: 'remote-old', status: 'superseded' }), + remoteRow({ proposal_id: 'remote-new', status: 'pending', supplier_quote_sheet_code: '', items: [{ sku_code: 'SKU1', unit: '斤', price: 13 }] }), + ], + summary: null, + nextCursor: null, + }); + + const summary = await syncQuotePriceProposals(); + + const oldRow = state.proposals.find((row) => row.id === 'local-old')!; + expect(oldRow.status).toBe('superseded'); // 不再卡在 pending + expect(oldRow.reject_reason).toBe('remote_superseded'); + const newRow = state.proposals.find((row) => row.remote_proposal_id === 'remote-new'); + expect(newRow, '新远端 pending 必须落本地(不能 DO NOTHING 静默丢)').toBeTruthy(); + expect(newRow!.status).toBe('pending'); + expect(newRow!.remote_proposal_id).toBe('remote-new'); + expect(summary.pulled).toBe(1); + expect(summary.synced).toBe(1); + }); + + it('旧 id 已 superseded + 新 pending 撞本地部分唯一键 ⇒ 旧行被接管(reason=replaced_by_remote)后新行插入', async () => { + const state = makeState(); + // 旧本地 pending 的 remote id 与远端新提议不同,但远端本轮只返回新 pending(旧行还没收到 superseded 通知) + seedLocalProposal(state, { + id: 'local-old', + direction: 'from_delivery', + status: 'pending', + remote_proposal_id: 'remote-old', + }); + installDb(state); + listRemote.mockResolvedValueOnce({ + kind: 'ok', + status: 200, + rows: [remoteRow({ proposal_id: 'remote-new', status: 'pending', supplier_quote_sheet_code: '' })], + summary: null, + nextCursor: null, + }); + + await syncQuotePriceProposals(); + + const oldRow = state.proposals.find((row) => row.id === 'local-old')!; + expect(oldRow.status).toBe('superseded'); + expect(oldRow.reject_reason).toBe('replaced_by_remote:remote-new'); + expect(state.proposals.find((row) => row.remote_proposal_id === 'remote-new')!.status).toBe('pending'); + }); + + it('同一远端 id 再拉一次 ⇒ 幂等跳过(不重复插、不动已有行)', async () => { + const state = makeState(); + seedLocalProposal(state, { id: 'local-old', direction: 'from_delivery', remote_proposal_id: 'remote-old' }); + installDb(state); + listRemote.mockResolvedValue({ + kind: 'ok', + status: 200, + rows: [remoteRow({ proposal_id: 'remote-old', status: 'pending' })], + summary: null, + nextCursor: null, + }); + await syncQuotePriceProposals(); + await syncQuotePriceProposals(); + expect(state.proposals.filter((row) => row.direction === 'from_delivery')).toHaveLength(1); + expect(state.proposals[0].status).toBe('pending'); + }); +}); + +describe('A16:旧 id approve 必须被拒(不能写已撤回的价)', () => { + beforeEach(() => { + process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1'; + }); + + it('本地仍 pending 但远端已 superseded ⇒ 409 proposal_not_pending,零写价、零推送、零回执', async () => { + const state = makeState(); + seedLocalProposal(state, { + direction: 'from_delivery', + status: 'pending', + remote_proposal_id: 'remote-old', + items: [{ sku_code: 'SKU1', unit: '斤', price: 11 }], + }); + installDb(state); + listRemote.mockResolvedValueOnce({ + kind: 'ok', + status: 200, + rows: [ + { + proposal_id: 'remote-old', + direction: 'to_supplier', + status: 'superseded', + supplier_quote_sheet_code: SHEET, + branch_code: MAIN_BRANCH, + items: [], + note: null, + reject_reason: null, + applied: null, + created_at: null, + reviewed_at: null, + }, + ], + summary: null, + nextCursor: null, + }); + + await expect( + approvePriceProposal({ + id: '11111111-1111-4111-8111-111111111111', + ctx: { branchCode: BRANCH, userId: 'u2', roles: ['admin'] } as any, + }) + ).rejects.toMatchObject({ status: 409, code: 'proposal_not_pending' }); + + expect(state.events).not.toContain('ITEM_UPDATE'); + expect(applyQuoteSheetUpdate).not.toHaveBeenCalled(); + expect(triggerQuoteCostSync).not.toHaveBeenCalled(); + expect(decideRemote).not.toHaveBeenCalled(); + expect(state.proposals[0].status).toBe('pending'); // 本地行未变(留给下一轮同步收口) + }); + + it('无法确认远端状态(D2 不可用)⇒ 409 remote_status_unverified(失败关闭,不写价)', async () => { + const state = makeState(); + seedLocalProposal(state, { direction: 'from_delivery', status: 'pending', remote_proposal_id: 'remote-old' }); + installDb(state); + listRemote.mockResolvedValueOnce({ + kind: 'unavailable', + status: 502, + code: 'main_system_error', + reason: '对方不可用', + payload: null, + }); + await expect( + approvePriceProposal({ id: '11111111-1111-4111-8111-111111111111', ctx: { branchCode: BRANCH } as any }) + ).rejects.toMatchObject({ status: 409, code: 'remote_status_unverified' }); + expect(state.events).not.toContain('ITEM_UPDATE'); + expect(triggerQuoteCostSync).not.toHaveBeenCalled(); + }); +}); + +describe('A20:D3 回执必须带 applied(写价统计)', () => { + beforeEach(() => { + process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1'; + }); + + it('新 id approve 正常写价 + rearm 推送,且 D3 body 带 applied', async () => { + const state = makeState(); + seedLocalProposal(state, { + direction: 'from_delivery', + status: 'pending', + remote_proposal_id: 'remote-new', + items: [ + { sku_code: 'SKU1', unit: '斤', price: 11 }, + { sku_code: 'SKU9', unit: '斤', price: 9 }, + ], + }); + installDb(state); + // 远端仍是 pending ⇒ 预检通过 + listRemote.mockResolvedValueOnce({ + kind: 'ok', + status: 200, + rows: [ + { + proposal_id: 'remote-new', + direction: 'to_supplier', + status: 'pending', + supplier_quote_sheet_code: SHEET, + branch_code: MAIN_BRANCH, + items: [], + note: null, + reject_reason: null, + applied: null, + created_at: null, + reviewed_at: null, + }, + ], + summary: null, + nextCursor: null, + }); + + const result = await approvePriceProposal({ + id: '11111111-1111-4111-8111-111111111111', + ctx: { branchCode: BRANCH, userId: 'u2', roles: ['admin'] } as any, + reviewedBy: 'u2', + }); + + expect(result.applied.updated).toBe(1); + expect(result.applied.skipped).toEqual([ + { sku_code: 'SKU9', reason: 'sku_unmapped' }, + ]); + const d3 = decideRemote.mock.calls.find(([arg]) => (arg as any).decision === 'approved'); + expect(d3, '通过必须回执').toBeTruthy(); + expect((d3![0] as any).applied).toEqual({ + updated: 1, + skipped: [{ sku_code: 'SKU9', reason: 'sku_unmapped' }], + }); + // 配送侧按 D3 落地写价;本侧不再推旧通道 + expect(triggerQuoteCostSync).not.toHaveBeenCalled(); + }); +}); + +/* ── ⑪ verifier 第二轮:预检精确查 + 翻页兜底 + 失败关闭 + 接管不丢数据 ──────────── */ + +describe('A16 残余:旧 id 预检必须精确查 / 翻页兜底 / 失败关闭', () => { + beforeEach(() => { + process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1'; + }); + + const decidedRemote = (id: string, status: string) => ({ + proposal_id: id, + direction: 'to_supplier', + status, + supplier_quote_sheet_code: SHEET, + branch_code: MAIN_BRANCH, + items: [], + note: null, + reject_reason: null, + applied: null, + created_at: null, + reviewed_at: null, + }); + + it('先按 proposal_id 精确查(一次命中即通过,不多拉 200 行)', async () => { + const state = makeState(); + seedLocalProposal(state, { direction: 'from_delivery', status: 'pending', remote_proposal_id: 'remote-xyz' }); + installDb(state); + listRemote.mockClear(); + + await approvePriceProposal({ + id: '11111111-1111-4111-8111-111111111111', + ctx: { branchCode: BRANCH, userId: 'u2', roles: ['admin'] } as any, + }); + + expect(listRemote).toHaveBeenCalledTimes(1); + expect((listRemote.mock.calls[0][0] as any).proposalId).toBe('remote-xyz'); + expect(state.items.find((item) => item.sku_code === 'SKU1')!.sale_price).toBe('11'); + }); + + it('>200 行(旧行不在第一页)⇒ 翻页找到 superseded 后 409 proposal_not_pending,零写价零推送', async () => { + const state = makeState(); + seedLocalProposal(state, { + direction: 'from_delivery', + status: 'pending', + remote_proposal_id: 'remote-old', + items: [{ sku_code: 'SKU1', unit: '斤', price: 11 }], + }); + installDb(state); + const filler = (n: number) => Array.from({ length: n }, (_, i) => decidedRemote(`filler-${i}`, 'approved')); + // 精确查不支持/未命中 ⇒ 返回最旧 200 行 + 下一页游标;目标行在第 2 页(superseded) + listRemote + .mockResolvedValueOnce({ kind: 'ok', status: 200, rows: filler(200), summary: null, nextCursor: 'p2' }) + .mockResolvedValueOnce({ + kind: 'ok', + status: 200, + rows: [decidedRemote('remote-old', 'superseded')], + summary: null, + nextCursor: null, + }); + + await expect( + approvePriceProposal({ id: '11111111-1111-4111-8111-111111111111', ctx: { branchCode: BRANCH } as any }) + ).rejects.toMatchObject({ status: 409, code: 'proposal_not_pending' }); + + expect(listRemote).toHaveBeenCalledTimes(2); + expect((listRemote.mock.calls[1][0] as any).cursor).toBe('p2'); + expect(state.events).not.toContain('ITEM_UPDATE'); + expect(applyQuoteSheetUpdate).not.toHaveBeenCalled(); + expect(triggerQuoteCostSync).not.toHaveBeenCalled(); + expect(decideRemote).not.toHaveBeenCalled(); + expect(state.proposals[0].status).toBe('pending'); // 本地行留给下一轮 D2 收口 + }); + + it('翻页耗尽仍找不到该提议 ⇒ 409 remote_status_unverified(失败关闭,绝不放行)', async () => { + const state = makeState(); + seedLocalProposal(state, { direction: 'from_delivery', status: 'pending', remote_proposal_id: 'remote-old' }); + installDb(state); + listRemote + .mockResolvedValueOnce({ + kind: 'ok', + status: 200, + rows: [decidedRemote('other-1', 'pending')], + summary: null, + nextCursor: 'p2', + }) + .mockResolvedValueOnce({ + kind: 'ok', + status: 200, + rows: [decidedRemote('other-2', 'pending')], + summary: null, + nextCursor: null, + }); + + await expect( + approvePriceProposal({ id: '11111111-1111-4111-8111-111111111111', ctx: { branchCode: BRANCH } as any }) + ).rejects.toMatchObject({ status: 409, code: 'remote_status_unverified' }); + + expect(state.events).not.toContain('ITEM_UPDATE'); + expect(triggerQuoteCostSync).not.toHaveBeenCalled(); + }); +}); + +describe('A16 残余:接管循环不再静默丢新提议', () => { + beforeEach(() => { + process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1'; + }); + + it('极端并发:接管耗尽 ⇒ 记 errors + 重置游标(下轮全量重拉),不返回 skipped 吞掉', async () => { + const state = makeState({ forceInsertConflict: true, forceNoPending: true }); + installDb(state); + listRemote.mockResolvedValue({ + kind: 'ok', + status: 200, + rows: [ + { + proposal_id: 'remote-new', + direction: 'to_supplier', + status: 'pending', + supplier_quote_sheet_code: '', + branch_code: MAIN_BRANCH, + items: [{ sku_code: 'SKU1', unit: '斤', price: 12 }], + note: null, + reject_reason: null, + applied: null, + created_at: null, + reviewed_at: null, + }, + ], + summary: null, + nextCursor: 'c1', + }); + + const summary = await syncQuotePriceProposals(); + expect(summary.errors).toBe(1); + expect(summary.pulled).toBe(0); + + // 游标应已重置 ⇒ 下一轮从 cursor=null 全量重拉(新提议不会因"游标已过"而丢) + listRemote.mockClear(); + await syncQuotePriceProposals(); + expect((listRemote.mock.calls[0][0] as any).cursor).toBeNull(); + }); +}); + +/* ── ⑫ SKU 映射(2026-10-18 增量):方向 B 必须经映射反查,不按 sku_code 猜 ─────────── */ + +describe('SKU 映射:方向 B 用配送 SKU 反查我方 SKU', () => { + beforeEach(() => { + process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1'; + }); + + it('配送 SKU 与我方 SKU 不同 ⇒ 通过映射写到我方行(不按 sku_code 猜)', async () => { + const state = makeState({ + mappings: [ + { supplier_sku_code: 'SKU1', supplier_sku_name: '草鱼', supplier_unit: '斤', delivery_sku_code: 'D-001', delivery_sku_name: '草鱼(配送)', status: 'active' }, + ], + }); + seedLocalProposal(state, { + direction: 'from_delivery', + status: 'pending', + remote_proposal_id: 'remote-map', + items: [{ sku_code: 'D-001', unit: '斤', price: 11 }], + }); + installDb(state); + listRemote.mockResolvedValueOnce({ + kind: 'ok', + status: 200, + rows: [ + { + proposal_id: 'remote-map', + direction: 'to_supplier', + status: 'pending', + supplier_quote_sheet_code: SHEET, + branch_code: MAIN_BRANCH, + items: [], + note: null, + reject_reason: null, + applied: null, + created_at: null, + reviewed_at: null, + }, + ], + summary: null, + nextCursor: null, + }); + + const result = await approvePriceProposal({ + id: '11111111-1111-4111-8111-111111111111', + ctx: { branchCode: BRANCH, userId: 'u2', roles: ['admin'] } as any, + }); + + expect(result.applied.updated).toBe(1); + expect(result.applied.skipped).toEqual([]); + // 写的是我方 SKU1 行(而不是 D-001 行) + expect(state.items.find((item) => item.sku_code === 'SKU1')!.sale_price).toBe('11'); + expect(state.events.filter((event) => event === 'ITEM_UPDATE')).toHaveLength(1); + }); + + it('配送 SKU 没有 active 映射 ⇒ skipped sku_unmapped,零写价、零推送', async () => { + const state = makeState({ mappings: [] }); + seedLocalProposal(state, { + direction: 'from_delivery', + status: 'pending', + remote_proposal_id: 'remote-unmapped', + items: [{ sku_code: 'D-999', unit: '斤', price: 11 }], + }); + installDb(state); + listRemote.mockResolvedValueOnce({ + kind: 'ok', + status: 200, + rows: [ + { + proposal_id: 'remote-unmapped', + direction: 'to_supplier', + status: 'pending', + supplier_quote_sheet_code: SHEET, + branch_code: MAIN_BRANCH, + items: [], + note: null, + reject_reason: null, + applied: null, + created_at: null, + reviewed_at: null, + }, + ], + summary: null, + nextCursor: null, + }); + + const result = await approvePriceProposal({ + id: '11111111-1111-4111-8111-111111111111', + ctx: { branchCode: BRANCH } as any, + }); + expect(result.applied.updated).toBe(0); + expect(result.applied.skipped).toEqual([{ sku_code: 'D-999', reason: 'sku_unmapped' }]); + expect(state.events).not.toContain('ITEM_UPDATE'); + expect(triggerQuoteCostSync).not.toHaveBeenCalled(); // 不再走旧通道,由 D3 让配送侧落地 + }); + + it('A 提交响应带本单映射统计(未映射不阻止提交)', async () => { + const state = makeState({ + mappings: [ + { supplier_sku_code: 'SKU1', supplier_sku_name: '草鱼', supplier_unit: '斤', delivery_sku_code: 'D-001', delivery_sku_name: null, status: 'active' }, + { supplier_sku_code: 'SKU2', supplier_sku_name: '鲤鱼', supplier_unit: '袋', delivery_sku_code: null, delivery_sku_name: null, status: 'pending' }, + ], + }); + installDb(state); + const result = await submitPriceProposal({ + quoteSheetCode: SHEET, + ctx: { branchCode: BRANCH } as any, + }); + expect(result.mapping).toMatchObject({ quote_sheet_code: SHEET, total: 3, mapped: 1, unmapped: 2 }); + expect(result.mapping.unmapped_skus.map((row) => row.sku_code)).toEqual(['SKU2', 'SKU3']); + }); + + it('列表的「改前 → 改后」按映射反查我方行;未映射标 unmapped', async () => { + const state = makeState({ + mappings: [ + { supplier_sku_code: 'SKU1', supplier_sku_name: '草鱼', supplier_unit: '斤', delivery_sku_code: 'D-001', delivery_sku_name: null, status: 'active' }, + ], + }); + seedLocalProposal(state, { + direction: 'from_delivery', + items: [ + { sku_code: 'D-001', unit: '斤', price: 11 }, + { sku_code: 'D-777', unit: '斤', price: 9 }, + ], + }); + installDb(state); + const { rows } = await listPriceProposals({ branchCode: BRANCH, status: 'pending' }); + const lines = rows[0].lines || []; + expect(lines[0]).toMatchObject({ + sku_code: 'D-001', + supplier_sku_code: 'SKU1', + before_sale_price: 10, + after_sale_price: 11, + change: 'updated', + }); + expect(lines[1]).toMatchObject({ sku_code: 'D-777', supplier_sku_code: null, change: 'unmapped' }); + }); +}); diff --git a/server/tests/quotePriceProposalDb.integration.test.ts b/server/tests/quotePriceProposalDb.integration.test.ts new file mode 100644 index 0000000..19835a9 --- /dev/null +++ b/server/tests/quotePriceProposalDb.integration.test.ts @@ -0,0 +1,288 @@ +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; + +/** + * D2 出站 mock(只 mock 配送侧只读接口):本文件的核心是**真库**语义(报价单明细 / proposal 表 / 台账), + * `>200 行` 场景是"远端数据量",只能在 D2 侧造。 + */ +const remoteMock = vi.hoisted(() => ({ + pages: [] as Array<{ rows: unknown[]; nextCursor: string | null }>, + calls: [] as Array>, +})); +vi.mock('../src/services/mainSystem/api/quotePriceProposals', () => ({ + submitQuotePriceProposal: vi.fn(async () => ({ + kind: 'ok', + status: 200, + data: { proposal_id: 'remote-created', status: 'pending', replayed: false }, + })), + listQuotePriceProposals: vi.fn(async (input: Record) => { + remoteMock.calls.push(input); + const page = remoteMock.pages[remoteMock.calls.length - 1] || { rows: [], nextCursor: null }; + return { kind: 'ok', status: 200, rows: page.rows, summary: null, nextCursor: page.nextCursor }; + }), + decideQuotePriceProposal: vi.fn(async () => ({ kind: 'ok', status: 200 })), +})); + +/** + * `quote_price_proposals` **真库**约束验证(默认跳过;`QUOTE_PRICE_PROPOSAL_DB_TEST=1` 才跑)。 + * + * verifier 抓到过一个真问题:T6 裁定「同方向重复提交 ⇒ 旧 pending 置 `superseded`」, + * 但迁移最初的 CHECK 不含 `superseded` ⇒ 真库会 500。单测的 DB 是脚本化 mock,**永远发现不了枚举/约束**。 + * 这里只验证不依赖对方系统的部分: + * ① 迁移已落库(tenant_br002 + tenant_template 都有表),且 `status` CHECK **含 `superseded`**; + * ② partial unique `(branch_code, quote_sheet_code, direction) WHERE status='pending'` 确实生效 + * (同方向第二条 pending 撞唯一键 ⇒ 必须先 supersede 旧的); + * ③ `superseded` 行不与 pending 冲突(旧行改成 superseded 后可以再插新 pending)。 + * + * 跑法(本地): + * cd server && QUOTE_PRICE_PROPOSAL_DB_TEST=1 npx vitest run tests/quotePriceProposalDb.integration.test.ts + */ + +const RUN = process.env.QUOTE_PRICE_PROPOSAL_DB_TEST === '1'; +const SCHEMA = 'tenant_br002'; +const BRANCH = 'BR002'; +const SHEET = 'QS_TESTQPP_1'; + +const db = RUN ? await import('../src/db') : null; +const pool = () => db!.pool; + +async function cleanup() { + await pool().query(`DELETE FROM ${SCHEMA}.quote_price_proposals WHERE quote_sheet_code LIKE 'QS_TESTQPP_%'`); + await pool().query(`DELETE FROM ${SCHEMA}.customer_quote_sheet_items WHERE quote_sheet_code LIKE 'QS_TESTQPP_%'`); + await pool().query(`DELETE FROM ${SCHEMA}.customer_quote_sheets WHERE quote_sheet_code LIKE 'QS_TESTQPP_%'`); +} + +async function insertProposal(input: { status: string; direction?: string }): Promise { + const result = await pool().query<{ id: string }>( + `INSERT INTO ${SCHEMA}.quote_price_proposals + (branch_code, quote_sheet_code, main_branch_code, direction, items, payload_hash, status, client_request_id) + VALUES ($1, $2, 'BR002', $3, '[]'::jsonb, 'fp-test', $4, gen_random_uuid()) + RETURNING id::text AS id`, + [BRANCH, SHEET, input.direction || 'to_delivery', input.status] + ); + return String(result.rows[0].id); +} + +describe.skipIf(!RUN)('quote_price_proposals · 真库(T6 枚举 / partial unique)', () => { + beforeAll(async () => { + await cleanup(); + }); + + afterAll(async () => { + await cleanup(); + await pool().end(); + }); + + it('迁移已落库:tenant_template 与 tenant_br002 都有表,且 status CHECK 含 superseded', async () => { + const tables = await pool().query<{ table_schema: string }>( + `SELECT table_schema FROM information_schema.tables + WHERE table_name = 'quote_price_proposals' AND table_schema IN ('tenant_template', 'tenant_br002') + ORDER BY table_schema` + ); + expect(tables.rows.map((row) => row.table_schema)).toEqual(['tenant_br002', 'tenant_template']); + + const check = await pool().query<{ def: string }>( + `SELECT pg_get_constraintdef(oid) AS def FROM pg_constraint + WHERE conname = 'quote_price_proposals_status_chk' + AND conrelid = '${SCHEMA}.quote_price_proposals'::regclass` + ); + expect(check.rows[0]?.def || '').toContain('superseded'); + }); + + it('superseded 是合法状态(T6 写它不会 500)', async () => { + const id = await insertProposal({ status: 'superseded' }); + const row = await pool().query<{ status: string }>( + `SELECT status FROM ${SCHEMA}.quote_price_proposals WHERE id = $1::uuid`, + [id] + ); + expect(row.rows[0].status).toBe('superseded'); + await pool().query(`DELETE FROM ${SCHEMA}.quote_price_proposals WHERE id = $1::uuid`, [id]); + }); + + it('非法状态仍被 CHECK 拦住', async () => { + await expect(insertProposal({ status: 'bogus' })).rejects.toThrow(); + }); + + it('partial unique:同 (分支,单,方向) 第二条 pending 撞唯一键;把旧行改 superseded 后可插新 pending(T6 覆盖语义)', async () => { + const first = await insertProposal({ status: 'pending' }); + await expect(insertProposal({ status: 'pending' })).rejects.toThrow(/uq_quote_price_proposals_pending|duplicate key/); + + // T6 的正确顺序:旧 pending → superseded,再插新 pending + await pool().query( + `UPDATE ${SCHEMA}.quote_price_proposals SET status = 'superseded' WHERE id = $1::uuid`, + [first] + ); + const second = await insertProposal({ status: 'pending' }); + const rows = await pool().query<{ status: string }>( + `SELECT status FROM ${SCHEMA}.quote_price_proposals + WHERE quote_sheet_code = $1 AND direction = 'to_delivery' ORDER BY requested_at ASC`, + [SHEET] + ); + expect(rows.rows.map((row) => row.status)).toEqual(['superseded', 'pending']); + await pool().query(`DELETE FROM ${SCHEMA}.quote_price_proposals WHERE id = ANY($1::uuid[])`, [ + [first, second], + ]); + }); + + it('A16 真库:旧 pending 被「远端 superseded」收口(不写价)后,新 pending 可插入(不撞唯一键)', async () => { + const oldId = await insertProposal({ status: 'pending', direction: 'from_delivery' }); + await pool().query( + `UPDATE ${SCHEMA}.quote_price_proposals + SET status = 'superseded', reject_reason = 'remote_superseded', updated_at = NOW() + WHERE id = $1::uuid AND status = 'pending'`, + [oldId] + ); + const oldRow = await pool().query<{ status: string; reject_reason: string | null }>( + `SELECT status, reject_reason FROM ${SCHEMA}.quote_price_proposals WHERE id = $1::uuid`, + [oldId] + ); + expect(oldRow.rows[0]).toMatchObject({ status: 'superseded', reject_reason: 'remote_superseded' }); + // 收口后同 (分支,单,方向) 可以插新 pending(唯一的"在途"是新提议) + const newId = await insertProposal({ status: 'pending', direction: 'from_delivery' }); + expect(newId).not.toBe(oldId); + await pool().query( + `DELETE FROM ${SCHEMA}.quote_price_proposals WHERE id = ANY($1::uuid[])`, + [[oldId, newId]] + ); + }); + + it('A16 真库 + >200 行远端:旧 id 不在第一页(已 superseded)⇒ approve 409,零写价、零推送', async () => { + process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1'; + const code = 'QS_TESTQPP_OLD'; + const proposalId = '11111111-2222-4333-8444-555555555555'; + const service = await import('../src/services/quotePriceProposalService'); + const tenant = await import('../src/services/tenantDbContext'); + + await tenant.runWithTenantDbContext(BRANCH, async () => { + await pool().query( + `INSERT INTO customer_quote_sheets + (quote_sheet_code, title, version_no, quote_cycle, effective_at, status, approval_status, branch_code, created_at, updated_at) + VALUES ($1, '旧提议测试单', 1, 'month', NOW(), 1, 30, $2, NOW(), NOW())`, + [code, BRANCH] + ); + await pool().query( + `INSERT INTO customer_quote_sheet_items + (quote_sheet_code, sku_code, sku_name, unit, price, cost_price, sale_price, sort_order) + VALUES ($1, 'SKU_TESTQPP_1', '测试商品', '斤', 10, 5, 10, 0)`, + [code] + ); + await pool().query( + `INSERT INTO quote_price_proposals + (id, branch_code, quote_sheet_code, main_branch_code, direction, items, payload_hash, + status, client_request_id, remote_proposal_id, requested_at, updated_at) + VALUES ($1::uuid, $2, $3, 'BR002', 'from_delivery', $4::jsonb, 'fp-init', 'pending', + gen_random_uuid(), $5, NOW(), NOW())`, + [ + proposalId, + BRANCH, + code, + JSON.stringify([{ sku_code: 'SKU_TESTQPP_1', unit: '斤', price: 11 }]), + 'remote-old', + ] + ); + }); + + // 远端 >200 行:第一页 200 条(最旧,不含目标行)+ 下一页游标;第二页才有目标行且已 superseded + const filler = Array.from({ length: 200 }, (_, i) => ({ + proposal_id: `filler-${i}`, + direction: 'to_supplier', + status: 'approved', + supplier_quote_sheet_code: '', + branch_code: 'BR002', + items: [], + note: null, + reject_reason: null, + applied: null, + created_at: null, + reviewed_at: null, + })); + remoteMock.calls.length = 0; + remoteMock.pages = [ + { rows: filler, nextCursor: 'page-2' }, + { + rows: [ + { + proposal_id: 'remote-old', + direction: 'to_supplier', + status: 'superseded', + supplier_quote_sheet_code: code, + branch_code: 'BR002', + items: [], + note: null, + reject_reason: null, + applied: null, + created_at: null, + reviewed_at: null, + }, + ], + nextCursor: null, + }, + ]; + + await expect( + tenant.runWithTenantDbContext(BRANCH, () => + service.approvePriceProposal({ + id: proposalId, + ctx: { branchCode: BRANCH, userId: 'a0000000-0000-0000-0000-000000000001', roles: ['admin'] } as any, + }) + ) + ).rejects.toMatchObject({ status: 409, code: 'proposal_not_pending' }); + + // 零写价:明细售价仍是 10 + const item = await pool().query<{ sale_price: string }>( + `SELECT sale_price FROM ${SCHEMA}.customer_quote_sheet_items WHERE quote_sheet_code = $1`, + [code] + ); + expect(Number(item.rows[0].sale_price)).toBe(10); + // 零推送:台账没有该单行 + const ledger = await pool().query<{ n: number }>( + `SELECT count(*)::int AS n FROM public.main_system_quote_cost_pushes WHERE quote_sheet_code = $1`, + [code] + ); + expect(Number(ledger.rows[0].n)).toBe(0); + // 本地提议仍 pending(留给下一轮 D2 收口),且确实翻到了第二页 + const local = await pool().query<{ status: string }>( + `SELECT status FROM ${SCHEMA}.quote_price_proposals WHERE id = $1::uuid`, + [proposalId] + ); + expect(local.rows[0].status).toBe('pending'); + expect(remoteMock.calls.length).toBe(2); + expect(remoteMock.calls[1].cursor).toBe('page-2'); + + delete process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL; + }); + + it('A16 真库:冲突接管(旧 pending 打 replaced_by_remote 后新 pending 落库)', async () => { + const oldId = await insertProposal({ status: 'pending', direction: 'from_delivery' }); + await pool().query( + `UPDATE ${SCHEMA}.quote_price_proposals + SET status = 'superseded', reject_reason = $2, updated_at = NOW() + WHERE id = $1::uuid AND status = 'pending'`, + [oldId, 'replaced_by_remote:remote-new'] + ); + const newId = await insertProposal({ status: 'pending', direction: 'from_delivery' }); + const rows = await pool().query<{ status: string; reject_reason: string | null }>( + `SELECT status, reject_reason FROM ${SCHEMA}.quote_price_proposals + WHERE quote_sheet_code = $1 AND direction = 'from_delivery' ORDER BY requested_at ASC`, + [SHEET] + ); + expect(rows.rows[0]).toMatchObject({ status: 'superseded', reject_reason: 'replaced_by_remote:remote-new' }); + expect(rows.rows[1].status).toBe('pending'); + await pool().query( + `DELETE FROM ${SCHEMA}.quote_price_proposals WHERE id = ANY($1::uuid[])`, + [[oldId, newId]] + ); + }); + + it('不同方向可各有一条 pending(A/B 互不挤占)', async () => { + const a = await insertProposal({ status: 'pending', direction: 'to_delivery' }); + // 已有一条 to_delivery pending ⇒ 先清掉,再验证 from_delivery 能建 + await pool().query(`DELETE FROM ${SCHEMA}.quote_price_proposals WHERE id = $1::uuid`, [a]); + const fromDelivery = await insertProposal({ status: 'pending', direction: 'from_delivery' }); + const toDelivery = await insertProposal({ status: 'pending', direction: 'to_delivery' }); + expect(fromDelivery).not.toBe(toDelivery); + await pool().query( + `DELETE FROM ${SCHEMA}.quote_price_proposals WHERE id = ANY($1::uuid[])`, + [[fromDelivery, toDelivery]] + ); + }); +}); diff --git a/server/tests/quotePriceProposalMergeDb.integration.test.ts b/server/tests/quotePriceProposalMergeDb.integration.test.ts new file mode 100644 index 0000000..997b4e9 --- /dev/null +++ b/server/tests/quotePriceProposalMergeDb.integration.test.ts @@ -0,0 +1,488 @@ +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +/** + * 报价单双向价格传递 · **方向 B 合并语义真库 integration**(默认 skip) + * + * 跑法: + * cd server && QUOTE_PRICE_PROPOSAL_DB_TEST=1 \ + * npx vitest run tests/quotePriceProposalMergeDb.integration.test.ts + * + * 为什么必须真库(mock 覆盖不到): + * · **T3 硬判据**:`approvePriceProposal` 只对 payload 里出现的 SKU 逐行 `UPDATE`, + * **不 INSERT / 不 DELETE / 不整表替换**。脚本化 mock 只认 SQL 字符串, + * 证明不了「其余 SKU 行原样存在、`customer_quote_sheet_items` 行总数不变」; + * · **T2**:按 `MAIN_` 解析唯一生效单,0 张 ⇒ 409 `no_quote_sheet`、 + * 多张 ⇒ 409 `ambiguous_sheet`,且失败时**零写价**、提案仍 pending; + * · **并发 approve 10 次**:`SELECT ... FOR UPDATE` + `status='pending'` 条件更新必须恰好应用一次; + * · **T4**:B 通过不生成 `quote_sheet_change_requests`(不二次内部审核); + * · **A21**:驳回零写价、零推送。 + * + * 造数隔离:真库临时分公司 `BR_QPPQA`(schema `tenant_br_qppqa`),全部行 `QPP_QA*` 前缀; + * 出站/审计按契约 mock(不出站、不落 operation_logs)。跑完 DROP SCHEMA + 删 registry/branches/提案, + * 并断言 0 残留;不碰 BR001/BR002 既有业务行。 + */ + +vi.hoisted(() => { + process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = 'true'; +}); + +const triggerSpy = vi.hoisted(() => vi.fn()); +const resolveSupplierSpy = vi.hoisted(() => vi.fn(async () => null)); +vi.mock('../src/services/mainSystemQuoteCostSync', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + triggerQuoteCostSync: (...args: unknown[]) => triggerSpy(...args), + resolveMainSupplierCode: (...args: unknown[]) => resolveSupplierSpy(...args), + }; +}); + +const auditSpy = vi.hoisted(() => vi.fn(async () => undefined)); +vi.mock('../src/services/auditService', () => ({ + writeAuditLog: (...args: unknown[]) => auditSpy(...args), +})); + +const DB_TEST = process.env.QUOTE_PRICE_PROPOSAL_DB_TEST === '1'; +const BRANCH = 'BR_QPPQA'; +const SCHEMA = 'tenant_br_qppqa'; +const MERGE_SHEET = 'QPP_QA_QS_MERGE'; +const AMB_A = 'QPP_QA_QS_AMB_A'; +const AMB_B = 'QPP_QA_QS_AMB_B'; + +import { pool } from '../src/db'; +import { runWithTenantDbContext } from '../src/services/tenantDbContext'; +import { + approvePriceProposal, + rejectPriceProposal, +} from '../src/services/quotePriceProposalService'; + +const uuid = () => crypto.randomUUID(); + +async function q>(sql: string, params: unknown[] = []): Promise { + return (await pool.query(sql, params)).rows as T[]; +} + +type ItemRow = { + id: string; + quote_sheet_code: string; + sku_code: string; + unit: string | null; + price: string; + cost_price: string; + sale_price: string; + sort_order: number; +}; + +/** 本用例造的全部明细行(含 id,用于证明没有 INSERT/DELETE/整表替换) */ +async function itemRows(): Promise { + return q( + `SELECT id::text AS id, quote_sheet_code, sku_code, unit, price::text, cost_price::text, + sale_price::text, sort_order + FROM ${SCHEMA}.customer_quote_sheet_items + WHERE quote_sheet_code LIKE 'QPP_QA_%' + ORDER BY quote_sheet_code, sku_code` + ); +} + +async function priceSnapshot(): Promise<{ count: number; md5: string }> { + const [row] = await q<{ count: number; md5: string }>( + `SELECT COUNT(*)::int AS count, + COALESCE(md5(string_agg( + id::text || '|' || quote_sheet_code || '|' || sku_code || '|' || + COALESCE(unit, '') || '|' || COALESCE(price::text, '') || '|' || + COALESCE(cost_price::text, '') || '|' || COALESCE(sale_price::text, '') || '|' || + COALESCE(sort_order::text, ''), + ';' ORDER BY quote_sheet_code, sku_code, id::text + )), '') AS md5 + FROM ${SCHEMA}.customer_quote_sheet_items + WHERE quote_sheet_code LIKE 'QPP_QA_%'` + ); + return row!; +} + +async function createProposal(input: { + mainBranchCode: string; + items: Array<{ sku_code: string; unit?: string | null; price: number }>; + quoteSheetCode?: string; + branchCode?: string; +}): Promise { + const [row] = await q<{ id: string }>( + `INSERT INTO ${SCHEMA}.quote_price_proposals + (branch_code, quote_sheet_code, main_branch_code, direction, items, payload_hash, status, + client_request_id, requested_at) + VALUES ($1, $2, $3, 'from_delivery', $4::jsonb, 'qpp-qa-hash', 'pending', $5, NOW()) + RETURNING id::text AS id`, + [ + input.branchCode || BRANCH, + input.quoteSheetCode || 'QPP_QA_PLACEHOLDER', + input.mainBranchCode, + JSON.stringify(input.items), + uuid(), + ] + ); + return row!.id; +} + +async function proposalStatus(id: string): Promise { + const [row] = await q<{ status: string }>( + `SELECT status FROM ${SCHEMA}.quote_price_proposals WHERE id = $1::uuid`, + [id] + ); + return row!.status; +} + +async function resetFixtures(): Promise { + await runWithTenantDbContext(BRANCH, async () => { + await q(`DELETE FROM ${SCHEMA}.quote_price_proposals WHERE quote_sheet_code LIKE 'QPP_QA_%'`); + await q(`DELETE FROM ${SCHEMA}.quote_sheet_change_requests WHERE quote_sheet_code LIKE 'QPP_QA_%'`); + await q(`DELETE FROM ${SCHEMA}.customer_quote_sheet_customers WHERE quote_sheet_code LIKE 'QPP_QA_%'`); + await q(`DELETE FROM ${SCHEMA}.customer_quote_sheet_items WHERE quote_sheet_code LIKE 'QPP_QA_%'`); + await q(`DELETE FROM ${SCHEMA}.customer_quote_sheets WHERE quote_sheet_code LIKE 'QPP_QA_%'`); + + const sheet = async (code: string, customers: string[], itemCount: number) => { + await q( + `INSERT INTO ${SCHEMA}.customer_quote_sheets + (quote_sheet_code, title, status, approval_status, effective_at, expires_at, branch_code) + VALUES ($1, $1, 1, 30, NOW(), NOW() + interval '30 day', $2)`, + [code, BRANCH] + ); + for (const customer of customers) { + await q( + `INSERT INTO ${SCHEMA}.customer_quote_sheet_customers (quote_sheet_code, customer_code) + VALUES ($1, $2)`, + [code, customer] + ); + } + for (let i = 1; i <= itemCount; i += 1) { + await q( + `INSERT INTO ${SCHEMA}.customer_quote_sheet_items + (quote_sheet_code, sku_code, sku_name, unit, price, cost_price, sale_price, sort_order) + VALUES ($1, $2, $2, '斤', 10, 8, 10, $3)`, + [code, `QPP_QA_SKU_${i}`, i] + ); + } + }; + await sheet(MERGE_SHEET, ['MAIN_BR_QPPQA'], 5); + // 同一 MAIN_ 客户两张生效单 ⇒ T2 ambiguous_sheet + await sheet(AMB_A, ['MAIN_BR_QPPQAMB'], 1); + await sheet(AMB_B, ['MAIN_BR_QPPQAMB'], 1); + }); +} + +async function cleanup(): Promise { + await q(`DROP SCHEMA IF EXISTS ${SCHEMA} CASCADE`); + await q(`DELETE FROM public.tenant_schema_registry WHERE branch_code = $1`, [BRANCH]); + await q(`DELETE FROM public.branches WHERE branch_code = $1`, [BRANCH]); +} + +beforeAll(async () => { + if (!DB_TEST) return; + await cleanup(); + await q( + `INSERT INTO public.branches (branch_code, branch_name, status) + VALUES ($1, 'QPP QA 测试分公司', 1) ON CONFLICT (branch_code) DO NOTHING`, + [BRANCH] + ); + await q(`SELECT public.clone_tenant_schema($1, 'active')`, [BRANCH]); + await runWithTenantDbContext(BRANCH, async () => { + for (const customer of ['MAIN_BR_QPPQA', 'MAIN_BR_QPPQAMB']) { + await q( + `INSERT INTO ${SCHEMA}.customers (customer_code, company_name, branch_code, status) + VALUES ($1, $1, $2, 10) ON CONFLICT (customer_code) DO NOTHING`, + [customer, BRANCH] + ); + } + }); +}, 120_000); + +beforeEach(async () => { + if (!DB_TEST) return; + auditSpy.mockClear(); + triggerSpy.mockClear(); + await resetFixtures(); +}); + +afterAll(async () => { + if (!DB_TEST) return; + await cleanup(); + const [left] = await q<{ registry: number; branch: number; schema: number }>( + `SELECT + (SELECT COUNT(*)::int FROM public.tenant_schema_registry WHERE branch_code = $1) AS registry, + (SELECT COUNT(*)::int FROM public.branches WHERE branch_code = $1) AS branch, + (SELECT COUNT(*)::int FROM information_schema.schemata WHERE schema_name = $2) AS schema`, + [BRANCH, SCHEMA] + ); + console.log('[QPP QA 供应商侧清理后残留]', JSON.stringify(left)); + expect(left).toEqual({ registry: 0, branch: 0, schema: 0 }); + await pool.end().catch(() => undefined); +}, 120_000); + +describe.skipIf(!DB_TEST)('真库 T3 硬判据:B approve 只按行 UPDATE,其余 SKU 行原样存在', () => { + it('payload 只含 2 个 SKU ⇒ 只更新这 2 行,另外 3 行逐字段不变,行总数不变(无 INSERT/DELETE)', async () => { + const before = await itemRows(); + const mergeRows = before.filter((row) => row.quote_sheet_code === MERGE_SHEET); + expect(mergeRows).toHaveLength(5); + const untouched = mergeRows.filter((row) => !['QPP_QA_SKU_1', 'QPP_QA_SKU_2'].includes(row.sku_code)); + + const id = await createProposal({ + mainBranchCode: 'BR_QPPQA', + items: [ + { sku_code: 'QPP_QA_SKU_1', unit: '斤', price: 12.34 }, + { sku_code: 'QPP_QA_SKU_2', unit: '斤', price: 22.22 }, + ], + }); + + const result = await runWithTenantDbContext(BRANCH, () => + approvePriceProposal({ id, ctx: { branchCode: BRANCH } as never }) + ); + expect(result.applied).toMatchObject({ updated: 2, unchanged: 0, skipped: [] }); + expect(result.proposal.status).toBe('approved'); + + const after = await itemRows(); + // 行总数不变 + id 集合完全一致 ⇒ 没有 INSERT / DELETE / 整表替换 + expect(after).toHaveLength(before.length); + expect(new Set(after.map((row) => row.id))).toEqual(new Set(before.map((row) => row.id))); + + const afterMerge = after.filter((row) => row.quote_sheet_code === MERGE_SHEET); + expect(afterMerge.find((row) => row.sku_code === 'QPP_QA_SKU_1')).toMatchObject({ + price: '12.34', + sale_price: '12.34', + cost_price: '8.00', + }); + expect(afterMerge.find((row) => row.sku_code === 'QPP_QA_SKU_2')).toMatchObject({ + price: '22.22', + sale_price: '22.22', + cost_price: '8.00', + }); + // 其余 3 行逐字段原样(T3 硬判据) + for (const row of untouched) { + expect(after.find((item) => item.id === row.id)).toEqual(row); + } + // 提案落库 + 指向解析出的唯一生效单 + const [proposal] = await q<{ status: string; quote_sheet_code: string; applied_at: string | null }>( + `SELECT status, quote_sheet_code, applied_at::text + FROM ${SCHEMA}.quote_price_proposals WHERE id = $1::uuid`, + [id] + ); + expect(proposal).toMatchObject({ status: 'approved', quote_sheet_code: MERGE_SHEET }); + expect(proposal!.applied_at).toBeTruthy(); + }); + + it('缺 SKU / 单位不一致 / 金额非法 ⇒ 跳过并记录,命中行照写;T4 不生成内部变更单', async () => { + const before = await itemRows(); + const changeReqBefore = await q<{ n: number }>( + `SELECT COUNT(*)::int AS n FROM ${SCHEMA}.quote_sheet_change_requests` + ); + const id = await createProposal({ + mainBranchCode: 'BR_QPPQA', + items: [ + { sku_code: 'QPP_QA_SKU_1', unit: '斤', price: 11.11 }, + { sku_code: 'QPP_QA_SKU_3', unit: 'kg', price: 33.33 }, + { sku_code: 'QPP_QA_SKU_4', unit: '斤', price: 0 }, + { sku_code: 'QPP_QA_SKU_MISSING', unit: '斤', price: 44.44 }, + ], + }); + const result = await runWithTenantDbContext(BRANCH, () => + approvePriceProposal({ id, ctx: { branchCode: BRANCH } as never }) + ); + expect(result.applied.updated).toBe(1); + const reasons = result.applied.skipped.map((row) => `${row.sku_code}:${row.reason}`); + expect(reasons).toEqual( + expect.arrayContaining([ + 'QPP_QA_SKU_3:unit_mismatch', + 'QPP_QA_SKU_4:invalid_price', + 'QPP_QA_SKU_MISSING:sku_not_in_sheet', + ]) + ); + const after = await itemRows(); + expect(after).toHaveLength(before.length); + expect( + after.find((row) => row.quote_sheet_code === MERGE_SHEET && row.sku_code === 'QPP_QA_SKU_1')! + .sale_price + ).toBe('11.11'); + expect( + after.find((row) => row.quote_sheet_code === MERGE_SHEET && row.sku_code === 'QPP_QA_SKU_3')! + .sale_price + ).toBe('10.00'); + // T4:B 通过不再走内部审核(零新增变更单) + const changeReqAfter = await q<{ n: number }>( + `SELECT COUNT(*)::int AS n FROM ${SCHEMA}.quote_sheet_change_requests` + ); + expect(changeReqAfter[0]!.n).toBe(changeReqBefore[0]!.n); + }); + + it('每行变更一条审计 + 提交后 triggerQuoteCostSync 恰好一次;重复 approve ⇒ 409 already_decided', async () => { + const id = await createProposal({ + mainBranchCode: 'BR_QPPQA', + items: [ + { sku_code: 'QPP_QA_SKU_1', unit: '斤', price: 12.34 }, + { sku_code: 'QPP_QA_SKU_2', unit: '斤', price: 22.22 }, + ], + }); + await runWithTenantDbContext(BRANCH, () => + approvePriceProposal({ id, ctx: { branchCode: BRANCH } as never }) + ); + const rowAudits = auditSpy.mock.calls.filter( + (call) => (call[0] as { operationType?: string }).operationType === 'quote_price_proposal_apply' + ); + expect(rowAudits).toHaveLength(2); + expect(triggerSpy).toHaveBeenCalledTimes(1); + expect(triggerSpy).toHaveBeenCalledWith({ branchCode: BRANCH, quoteSheetCode: MERGE_SHEET }); + + const snapshot = await priceSnapshot(); + await expect( + runWithTenantDbContext(BRANCH, () => + approvePriceProposal({ id, ctx: { branchCode: BRANCH } as never }) + ) + ).rejects.toMatchObject({ status: 409, code: 'already_decided' }); + expect(await priceSnapshot()).toEqual(snapshot); + expect(triggerSpy).toHaveBeenCalledTimes(1); + }); +}); + +describe.skipIf(!DB_TEST)('真库 T2:目标单解析 0 张 / 多张 ⇒ 409,零写价、提案仍 pending', () => { + it('0 张生效单 ⇒ 409 no_quote_sheet;2 张 ⇒ 409 ambiguous_sheet;两者都不写价', async () => { + const before = await priceSnapshot(); + const missing = await createProposal({ + mainBranchCode: 'BR_QPPQANONE', + quoteSheetCode: 'QPP_QA_PLACEHOLDER_NONE', + items: [{ sku_code: 'QPP_QA_SKU_1', unit: '斤', price: 9.99 }], + }); + await expect( + runWithTenantDbContext(BRANCH, () => + approvePriceProposal({ id: missing, ctx: { branchCode: BRANCH } as never }) + ) + ).rejects.toMatchObject({ status: 409, code: 'no_quote_sheet' }); + + const ambiguous = await createProposal({ + mainBranchCode: 'BR_QPPQAMB', + quoteSheetCode: 'QPP_QA_PLACEHOLDER_AMB', + items: [{ sku_code: 'QPP_QA_SKU_1', unit: '斤', price: 9.99 }], + }); + await expect( + runWithTenantDbContext(BRANCH, () => + approvePriceProposal({ id: ambiguous, ctx: { branchCode: BRANCH } as never }) + ) + ).rejects.toMatchObject({ status: 409, code: 'ambiguous_sheet' }); + + expect(await priceSnapshot()).toEqual(before); + expect(await proposalStatus(missing)).toBe('pending'); + expect(await proposalStatus(ambiguous)).toBe('pending'); + expect(triggerSpy).not.toHaveBeenCalled(); + }); +}); + +describe.skipIf(!DB_TEST)('真库并发:approve 恰好应用一次', () => { + it('10 路并发 approve ⇒ 1 成功 + 9 个 409;价格只写一次、trigger 只 1 次', async () => { + const id = await createProposal({ + mainBranchCode: 'BR_QPPQA', + quoteSheetCode: 'QPP_QA_PLACEHOLDER_RACE', + items: [{ sku_code: 'QPP_QA_SKU_1', unit: '斤', price: 12.34 }], + }); + const results = await Promise.allSettled( + Array.from({ length: 10 }, () => + runWithTenantDbContext(BRANCH, () => + approvePriceProposal({ id, ctx: { branchCode: BRANCH } as never }) + ) + ) + ); + const fulfilled = results.filter( + (r): r is PromiseFulfilledResult>> => + r.status === 'fulfilled' + ); + const rejected = results.filter((r): r is PromiseRejectedResult => r.status === 'rejected'); + expect(fulfilled).toHaveLength(1); + expect(rejected).toHaveLength(9); + for (const row of rejected) { + expect(row.reason).toMatchObject({ status: 409, code: 'already_decided' }); + } + expect(fulfilled[0]!.value.applied.updated).toBe(1); + expect(triggerSpy).toHaveBeenCalledTimes(1); + const after = await itemRows(); + expect( + after.find((row) => row.quote_sheet_code === MERGE_SHEET && row.sku_code === 'QPP_QA_SKU_1')! + .sale_price + ).toBe('12.34'); + }); +}); + +describe.skipIf(!DB_TEST)('真库 B 驳回 / 跨分公司 / 跨租户 / 开关', () => { + it('驳回:只改状态 + 理由,零写价、零推送(A21)', async () => { + const before = await priceSnapshot(); + const id = await createProposal({ + mainBranchCode: 'BR_QPPQA', + quoteSheetCode: 'QPP_QA_PLACEHOLDER_REJECT', + items: [{ sku_code: 'QPP_QA_SKU_1', unit: '斤', price: 9.99 }], + }); + const result = await runWithTenantDbContext(BRANCH, () => + rejectPriceProposal({ + id, + reason: '真库:不接受该成本价', + ctx: { branchCode: BRANCH } as never, + }) + ); + expect(result.proposal.status).toBe('rejected'); + expect(await priceSnapshot()).toEqual(before); + expect(triggerSpy).not.toHaveBeenCalled(); + const [row] = await q<{ status: string; reject_reason: string }>( + `SELECT status, reject_reason FROM ${SCHEMA}.quote_price_proposals WHERE id = $1::uuid`, + [id] + ); + expect(row).toEqual({ status: 'rejected', reject_reason: '真库:不接受该成本价' }); + }); + + it('跨分公司提案(同 schema 不同 branch_code)⇒ 403 branch_mismatch,零写价', async () => { + const before = await priceSnapshot(); + const id = await createProposal({ + branchCode: 'BR001', + mainBranchCode: 'BR_QPPQA', + quoteSheetCode: 'QPP_QA_PLACEHOLDER_CROSS', + items: [{ sku_code: 'QPP_QA_SKU_1', unit: '斤', price: 9.99 }], + }); + await expect( + runWithTenantDbContext(BRANCH, () => + approvePriceProposal({ id, ctx: { branchCode: BRANCH } as never }) + ) + ).rejects.toMatchObject({ status: 403, code: 'branch_mismatch' }); + expect(await priceSnapshot()).toEqual(before); + expect(await proposalStatus(id)).toBe('pending'); + }); + + it('其它分公司上下文 ⇒ 404 proposal_not_found(跨租户不可见),零写价', async () => { + const before = await priceSnapshot(); + const id = await createProposal({ + mainBranchCode: 'BR_QPPQA', + quoteSheetCode: 'QPP_QA_PLACEHOLDER_OTHER', + items: [{ sku_code: 'QPP_QA_SKU_1', unit: '斤', price: 9.99 }], + }); + await expect( + runWithTenantDbContext('BR001', () => + approvePriceProposal({ id, ctx: { branchCode: 'BR001' } as never }) + ) + ).rejects.toMatchObject({ status: 404, code: 'proposal_not_found' }); + expect(await priceSnapshot()).toEqual(before); + }); + + it('开关关闭 ⇒ 503 feature_disabled,零写价、零推送(A39)', async () => { + const before = await priceSnapshot(); + const id = await createProposal({ + mainBranchCode: 'BR_QPPQA', + quoteSheetCode: 'QPP_QA_PLACEHOLDER_OFF', + items: [{ sku_code: 'QPP_QA_SKU_1', unit: '斤', price: 9.99 }], + }); + const saved = process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL; + process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = 'false'; + try { + await expect( + runWithTenantDbContext(BRANCH, () => + approvePriceProposal({ id, ctx: { branchCode: BRANCH } as never }) + ) + ).rejects.toMatchObject({ status: 503, code: 'feature_disabled' }); + } finally { + process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = saved; + } + expect(await priceSnapshot()).toEqual(before); + expect(triggerSpy).not.toHaveBeenCalled(); + expect(await proposalStatus(id)).toBe('pending'); + }); +}); diff --git a/server/tests/quotePriceProposalRoute.test.ts b/server/tests/quotePriceProposalRoute.test.ts new file mode 100644 index 0000000..a9a13ea --- /dev/null +++ b/server/tests/quotePriceProposalRoute.test.ts @@ -0,0 +1,301 @@ +import express from 'express'; +import request from 'supertest'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +/** + * 报价单双向价格传递 · **供应商侧路由层边界**(tester 独立补测,2026-10-18)。 + * + * 与 dev 的 `quotePriceProposal.test.ts`(服务层 + 脚本化 DB)分工:这里只钉 HTTP 面, + * 服务实现全部 mock,专注「权限矩阵 / 开关 503 / 入参不可信 / 错误码原样透出」: + * · 发起 A、approve、reject 仅 `customer_manage`;列表 `customer_manage | order_manage`; + * · 开关关:列表路由自己 503,其余端点把服务层 503 `feature_disabled` 原样透出; + * · approve/reject 只认 URL 里的 id,body 里塞 items/branch_code/sale_price 一律不采信; + * · 非法 id ⇒ 400 invalid_request 且服务零调用; + * · 服务层 403 `branch_mismatch` / 409 `already_decided` 原样透出。 + * + * 鉴权/租户上下文/服务层都 mock;数据库不参与(真库后果见 MergeDb.integration)。 + */ + +const H = vi.hoisted(() => ({ + ctx: null as Record | null, + enabled: true, + submitPriceProposal: vi.fn(), + listPriceProposals: vi.fn(), + approvePriceProposal: vi.fn(), + rejectPriceProposal: vi.fn(), +})); + +vi.mock('../src/middleware/auth', () => ({ + authMiddleware: (req: { userId?: string }, _res: unknown, next: () => void) => { + req.userId = 'user-1'; + next(); + }, +})); + +vi.mock('../src/modules/workflow/context', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, getWorkflowCtx: async () => H.ctx }; +}); + +vi.mock('../src/services/quotePriceProposalService', () => ({ + isQuotePriceProposalEnabled: () => H.enabled, + submitPriceProposal: (...args: unknown[]) => H.submitPriceProposal(...args), + listPriceProposals: (...args: unknown[]) => H.listPriceProposals(...args), + approvePriceProposal: (...args: unknown[]) => H.approvePriceProposal(...args), + rejectPriceProposal: (...args: unknown[]) => H.rejectPriceProposal(...args), +})); + +const { mountQuoteWorkflowRoutes } = await import('../src/modules/workflow/routes/quoteRoutes'); + +const ID = '11111111-1111-4111-8111-111111111111'; + +function buildApp() { + const app = express(); + app.use(express.json()); + const router = express.Router(); + mountQuoteWorkflowRoutes(router); + app.use('/api/workflow', router); + return app; +} + +const app = buildApp(); + +function ctxWith(permissions: string[], patch: Record = {}) { + return { + userId: 'user-1', + roles: ['admin'], + permissions, + branchCode: 'BR002', + supplierCode: null, + purchaserCode: null, + isSuperAdmin: false, + isBranchAdmin: false, + isInternalStaff: true, + isSupplierAccount: false, + ...patch, + }; +} + +const proposal = (patch: Record = {}) => ({ + id: ID, + status: 'pending', + direction: 'from_delivery', + quote_sheet_code: 'QS1', + items: [{ sku_code: 'SKU1', unit: '斤', price: 12.34 }], + ...patch, +}); + +beforeEach(() => { + H.ctx = ctxWith(['customer_manage', 'order_manage']); + H.enabled = true; + H.submitPriceProposal.mockReset(); + H.listPriceProposals.mockReset(); + H.approvePriceProposal.mockReset(); + H.rejectPriceProposal.mockReset(); + H.submitPriceProposal.mockResolvedValue({ + proposal: proposal({ status: 'pending' }), + applied: null, + replayed: false, + }); + H.listPriceProposals.mockResolvedValue({ rows: [proposal()], sync: null }); + H.approvePriceProposal.mockResolvedValue({ + proposal: proposal({ status: 'approved' }), + applied: { updated: 1, unchanged: 0, skipped: [] }, + receiptSent: true, + }); + H.rejectPriceProposal.mockResolvedValue({ + proposal: proposal({ status: 'rejected' }), + receiptSent: true, + }); +}); + +describe('权限矩阵(发起/审批 customer_manage;查看 customer_manage|order_manage)', () => { + it('无任何权限 ⇒ 四个端点全 403,且服务零调用', async () => { + H.ctx = ctxWith([]); + const submit = await request(app) + .post('/api/workflow/quote/sheets/QS1/price-proposals') + .send({ note: 'x' }); + const list = await request(app).get('/api/workflow/quote/price-proposals'); + const approve = await request(app).post(`/api/workflow/quote/price-proposals/${ID}/approve`).send({}); + const reject = await request(app) + .post(`/api/workflow/quote/price-proposals/${ID}/reject`) + .send({ reason: 'x' }); + for (const [name, res] of Object.entries({ submit, list, approve, reject })) { + expect(res.status, name).toBe(403); + } + expect(H.submitPriceProposal).not.toHaveBeenCalled(); + expect(H.listPriceProposals).not.toHaveBeenCalled(); + expect(H.approvePriceProposal).not.toHaveBeenCalled(); + expect(H.rejectPriceProposal).not.toHaveBeenCalled(); + }); + + it('只有 order_manage ⇒ 可查看列表,但发起/通过/驳回一律 403', async () => { + H.ctx = ctxWith(['order_manage']); + const list = await request(app).get('/api/workflow/quote/price-proposals'); + expect(list.status).toBe(200); + const submit = await request(app) + .post('/api/workflow/quote/sheets/QS1/price-proposals') + .send({}); + const approve = await request(app).post(`/api/workflow/quote/price-proposals/${ID}/approve`).send({}); + const reject = await request(app) + .post(`/api/workflow/quote/price-proposals/${ID}/reject`) + .send({ reason: 'x' }); + expect(submit.status).toBe(403); + expect(approve.status).toBe(403); + expect(reject.status).toBe(403); + expect(H.submitPriceProposal).not.toHaveBeenCalled(); + expect(H.approvePriceProposal).not.toHaveBeenCalled(); + expect(H.rejectPriceProposal).not.toHaveBeenCalled(); + }); + + it('customer_manage ⇒ 四端点放行,透传 code/note/id/reason,响应形状固定', async () => { + H.ctx = ctxWith(['customer_manage']); + const submit = await request(app) + .post('/api/workflow/quote/sheets/QS1/price-proposals') + .send({ note: '整单提交' }); + expect(submit.status).toBe(200); + expect(submit.body).toMatchObject({ replayed: false }); + expect(H.submitPriceProposal).toHaveBeenCalledWith( + expect.objectContaining({ quoteSheetCode: 'QS1', note: '整单提交', requestedBy: 'user-1' }) + ); + + const list = await request(app).get( + '/api/workflow/quote/price-proposals?direction=from_delivery&status=pending&limit=20&refresh=1' + ); + expect(list.status).toBe(200); + expect(H.listPriceProposals).toHaveBeenCalledWith( + expect.objectContaining({ + branchCode: 'BR002', + direction: 'from_delivery', + status: 'pending', + limit: 20, + refresh: true, + }) + ); + + const approve = await request(app) + .post(`/api/workflow/quote/price-proposals/${ID}/approve`) + .send({}); + expect(approve.status).toBe(200); + expect(approve.body).toMatchObject({ receipt_sent: true, applied: { updated: 1 } }); + expect(H.approvePriceProposal).toHaveBeenCalledWith( + expect.objectContaining({ id: ID, reviewedBy: 'user-1' }) + ); + + const reject = await request(app) + .post(`/api/workflow/quote/price-proposals/${ID}/reject`) + .send({ reason: ' 成本价不成立 ' }); + expect(reject.status).toBe(200); + expect(H.rejectPriceProposal).toHaveBeenCalledWith( + expect.objectContaining({ id: ID, reason: ' 成本价不成立 ' }) + ); + }); +}); + +describe('开关关闭 ⇒ 503 feature_disabled(A39)', () => { + it('列表路由自己 503;发起/通过/驳回把服务层 503 原样透出', async () => { + H.enabled = false; + const featureDisabled = Object.assign(new Error('报价单价格传递未开启'), { + status: 503, + code: 'feature_disabled', + }); + H.submitPriceProposal.mockRejectedValue(featureDisabled); + H.approvePriceProposal.mockRejectedValue(featureDisabled); + H.rejectPriceProposal.mockRejectedValue(featureDisabled); + + const list = await request(app).get('/api/workflow/quote/price-proposals'); + expect(list.status).toBe(503); + expect(list.body.error).toBe('feature_disabled'); + + const submit = await request(app) + .post('/api/workflow/quote/sheets/QS1/price-proposals') + .send({}); + const approve = await request(app).post(`/api/workflow/quote/price-proposals/${ID}/approve`).send({}); + const reject = await request(app) + .post(`/api/workflow/quote/price-proposals/${ID}/reject`) + .send({ reason: 'x' }); + for (const [name, res] of Object.entries({ submit, approve, reject })) { + expect(res.status, name).toBe(503); + expect(res.body.error, name).toBe('feature_disabled'); + } + // 列表在服务层之前就被开关拦下,不触发出站/查询 + expect(H.listPriceProposals).not.toHaveBeenCalled(); + }); +}); + +describe('入参不可信 / 错误码透出', () => { + it('approve/reject body 里塞 items/branch_code/sale_price 不传给服务(只认 URL id)', async () => { + await request(app) + .post(`/api/workflow/quote/price-proposals/${ID}/approve`) + .send({ + items: [{ sku_code: 'SKU_EVIL', price: 0.01 }], + sale_price: 0.01, + branch_code: 'BR999', + }); + const approveArgs = H.approvePriceProposal.mock.calls[0]![0] as Record; + expect(approveArgs).toMatchObject({ id: ID, reviewedBy: 'user-1' }); + expect(approveArgs).not.toHaveProperty('items'); + expect(approveArgs).not.toHaveProperty('sale_price'); + expect(approveArgs).not.toHaveProperty('branch_code'); + + await request(app) + .post(`/api/workflow/quote/price-proposals/${ID}/reject`) + .send({ reason: '理由', items: [{ sku_code: 'SKU_EVIL', price: 0.01 }], status: 'approved' }); + const rejectArgs = H.rejectPriceProposal.mock.calls[0]![0] as Record; + expect(rejectArgs).toMatchObject({ id: ID, reason: '理由' }); + expect(rejectArgs).not.toHaveProperty('items'); + expect(rejectArgs).not.toHaveProperty('status'); + }); + + it('非法 id ⇒ 400 invalid_request 且服务零调用', async () => { + const approve = await request(app) + .post('/api/workflow/quote/price-proposals/not-a-uuid/approve') + .send({}); + const reject = await request(app) + .post('/api/workflow/quote/price-proposals/not-a-uuid/reject') + .send({ reason: 'x' }); + expect(approve.status).toBe(400); + expect(approve.body.error).toBe('invalid_request'); + expect(reject.status).toBe(400); + expect(reject.body.error).toBe('invalid_request'); + expect(H.approvePriceProposal).not.toHaveBeenCalled(); + expect(H.rejectPriceProposal).not.toHaveBeenCalled(); + }); + + it('服务层 403 branch_mismatch / 409 already_decided / 409 no_quote_sheet 原样透出', async () => { + H.approvePriceProposal.mockRejectedValueOnce( + Object.assign(new Error('无权操作其它分公司'), { status: 403, code: 'branch_mismatch' }) + ); + const forbidden = await request(app) + .post(`/api/workflow/quote/price-proposals/${ID}/approve`) + .send({}); + expect(forbidden.status).toBe(403); + expect(forbidden.body.error).toBe('branch_mismatch'); + + H.approvePriceProposal.mockRejectedValueOnce( + Object.assign(new Error('已处理'), { status: 409, code: 'already_decided' }) + ); + const decided = await request(app) + .post(`/api/workflow/quote/price-proposals/${ID}/approve`) + .send({}); + expect(decided.status).toBe(409); + expect(decided.body.error).toBe('already_decided'); + + H.approvePriceProposal.mockRejectedValueOnce( + Object.assign(new Error('没有唯一生效单'), { status: 409, code: 'no_quote_sheet' }) + ); + const noSheet = await request(app) + .post(`/api/workflow/quote/price-proposals/${ID}/approve`) + .send({}); + expect(noSheet.status).toBe(409); + expect(noSheet.body.error).toBe('no_quote_sheet'); + }); + + it('缺少分公司上下文(列表)⇒ 400 branch_required,不调服务', async () => { + H.ctx = ctxWith(['customer_manage'], { branchCode: null }); + const res = await request(app).get('/api/workflow/quote/price-proposals'); + expect(res.status).toBe(400); + expect(res.body.error).toBe('branch_required'); + expect(H.listPriceProposals).not.toHaveBeenCalled(); + }); +}); diff --git a/server/tests/quoteSheetChangeRequest.test.ts b/server/tests/quoteSheetChangeRequest.test.ts new file mode 100644 index 0000000..b48cc82 --- /dev/null +++ b/server/tests/quoteSheetChangeRequest.test.ts @@ -0,0 +1,999 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +/** + * 「编辑生效报价单改价 → 待审变更 → 审核通过才应用 + 才同步」—— 服务层契约守卫(2026-10-18 增量)。 + * + * 钉住(brief §3 + Lead 裁定): + * ① 价格相关改动**不落报价单**、只写/覆盖 pending 变更单,响应 `applied:false`; + * ② 非价格改动(只改标题/周期/生效日/客户)走现有直接保存,`applied:true`; + * ③ 开关 `QUOTE_EDIT_APPROVAL` 默认开;`0/false/off` 回滚成直接保存且**不写变更单表**; + * ④ 同一 SKU 重复 ⇒ 400 `duplicate_sku`(不去重、不落库); + * ⑤ D4:新提交把旧 pending 置 `superseded`,一张单只留一条 pending; + * ⑥ 审核通过:**单事务**(BEGIN → 应用 → 记审批 → COMMIT)→ **提交后**才 `triggerQuoteCostSync`; + * **绝不**走 `approveQuoteSheet`/`activateQuoteSheet`(不置其它共享单为 3、不动审批字段); + * ⑦ base 已变 ⇒ 409 `base_changed` + 变更单置 rejected + 零应用零推送; + * ⑧ 驳回 ⇒ 只改状态、报价单不变、零推送;重复决策 ⇒ 409 `already_decided`; + * ⑨ 应用前守卫:SKU 存活(`skus.status=1`)、客户归属分公司(真库零外键)。 + */ + +/* ── mock:DP ────────────────────────────────────────────────────────────── */ + +const poolQuery = vi.hoisted(() => vi.fn()); +const clientQuery = vi.hoisted(() => vi.fn()); +const clientRelease = vi.hoisted(() => vi.fn()); +vi.mock('../src/db', () => ({ + pool: { + query: (...args: unknown[]) => poolQuery(...args), + connect: async () => ({ + query: (...args: unknown[]) => clientQuery(...args), + release: () => clientRelease(), + }), + }, + getRawPoolQuery: () => poolQuery, +})); + +// 报价单服务:只替换「应用/读取/客户校验」,`normalizeQuoteSheetUpdatePayload` 用真实现 +const applyQuoteSheetUpdate = vi.hoisted(() => vi.fn()); +const updateQuoteSheet = vi.hoisted(() => vi.fn()); +const loadQuoteSheetForUpdate = vi.hoisted(() => vi.fn()); +const getQuoteSheet = vi.hoisted(() => vi.fn()); +const assertCustomersInBranch = vi.hoisted(() => vi.fn()); +vi.mock('../src/services/quoteSheetService', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + applyQuoteSheetUpdate: (...args: unknown[]) => applyQuoteSheetUpdate(...args), + updateQuoteSheet: (...args: unknown[]) => updateQuoteSheet(...args), + loadQuoteSheetForUpdate: (...args: unknown[]) => loadQuoteSheetForUpdate(...args), + getQuoteSheet: (...args: unknown[]) => getQuoteSheet(...args), + assertCustomersInBranch: (...args: unknown[]) => assertCustomersInBranch(...args), + }; +}); + +// 业务审计(A26):断言三条路径各写一条 +const writeAuditLog = vi.hoisted(() => vi.fn()); +vi.mock('../src/services/auditService', () => ({ + writeAuditLog: (...args: unknown[]) => writeAuditLog(...args), +})); + +// 成本价同步:指纹算法用真实现(base 判据复用同一算法),触发入口 mock +const triggerQuoteCostSync = vi.hoisted(() => vi.fn()); +vi.mock('../src/services/mainSystemQuoteCostSync', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, triggerQuoteCostSync: (...args: unknown[]) => triggerQuoteCostSync(...args) }; +}); + +import { + approveQuoteSheetChangeRequest, + assertNoDuplicateSku, + diffQuoteSheetItems, + isPriceRelatedQuoteEdit, + isQuoteEditApprovalEnabled, + listQuoteSheetChangeRequests, + payloadToUpdateInput, + quoteSheetItemsFingerprint, + rejectQuoteSheetChangeRequest, + saveQuoteSheetEdit, +} from '../src/services/quoteSheetChangeRequestService'; + +/* ── 脚本化 DB(内存台账)──────────────────────────────────────────────── */ + +type MockChangeRequest = Record; + +type DbState = { + sheet: Record; + items: Array>; + sheetCustomers: string[]; + changeRequests: Map; + aliveSkus: Set; + branchCustomers: Set; + events: string[]; +}; + +const SHEET = 'QS1'; +const BRANCH = 'BR002'; + +function seedSheet(overrides: Partial> = {}) { + return { + quote_sheet_code: SHEET, + branch_code: BRANCH, + title: '报价单 V1', + version_no: 1, + status: 1, + approval_status: 30, + approved_by: 'u-approver', + approved_at: '2026-10-17T00:00:00.000Z', + effective_at: '2026-10-17T00:00:00.000Z', + expires_at: new Date(Date.now() + 86400_000).toISOString(), + auto_sale_price_by_cost: false, + ...overrides, + }; +} + +function makeState(overrides: Partial = {}): DbState { + return { + sheet: seedSheet(), + items: [ + { sku_code: 'SKU1', sku_name: '草鱼', unit: '斤', sale_price: '10.00', price: '10.00', cost_price: '5.00' }, + { sku_code: 'SKU2', sku_name: '鲤鱼', unit: '斤', sale_price: '12.00', price: '12.00', cost_price: '6.00' }, + ], + sheetCustomers: ['MAIN_BR002'], + changeRequests: new Map(), + aliveSkus: new Set(['SKU1', 'SKU2']), + branchCustomers: new Set(['MAIN_BR002', 'CUS_A']), + events: [], + ...overrides, + }; +} + +function seedChangeRequest(state: DbState, patch: MockChangeRequest = {}): MockChangeRequest { + const row: MockChangeRequest = { + id: patch.id ?? '11111111-1111-4111-8111-111111111111', + branch_code: patch.branch_code ?? BRANCH, + quote_sheet_code: patch.quote_sheet_code ?? SHEET, + payload: patch.payload ?? { items: [] }, + base_version_no: patch.base_version_no ?? 1, + base_items_fingerprint: patch.base_items_fingerprint ?? quoteSheetItemsFingerprint(state.items), + status: patch.status ?? 'pending', + requested_by: patch.requested_by ?? 'u-requester', + requested_by_name: patch.requested_by_name ?? '提交人甲', + requested_at: patch.requested_at ?? '2026-10-18T01:00:00.000Z', + reviewed_by: patch.reviewed_by ?? null, + reviewed_by_name: patch.reviewed_by_name ?? null, + reviewed_at: patch.reviewed_at ?? null, + reject_reason: patch.reject_reason ?? null, + applied_at: patch.applied_at ?? null, + updated_at: patch.updated_at ?? '2026-10-18T01:00:00.000Z', + }; + state.changeRequests.set(row.id, row); + return row; +} + +function installDb(state: DbState): void { + const handler = async (sql: string, params: unknown[] = [], fromClient: boolean) => { + const text = String(sql); + if (/^\s*(BEGIN|COMMIT|ROLLBACK)\s*;?\s*$/i.test(text)) { + if (fromClient) state.events.push(text.trim().toUpperCase()); + return { rows: [], rowCount: 0 }; + } + // ── 变更单 ── + if (text.includes('UPDATE quote_sheet_change_requests') && text.includes("SET status = 'superseded'")) { + state.events.push('CR_SUPERSEDE'); + let count = 0; + for (const row of state.changeRequests.values()) { + if (row.branch_code === params[0] && row.quote_sheet_code === params[1] && row.status === 'pending') { + row.status = 'superseded'; + count += 1; + } + } + return { rows: [], rowCount: count }; + } + if (text.includes('INSERT INTO quote_sheet_change_requests')) { + state.events.push('CR_INSERT'); + const id = `11111111-1111-4111-8111-${String(state.changeRequests.size + 1).padStart(12, '0')}`; + const row: MockChangeRequest = { + id, + branch_code: params[0], + quote_sheet_code: params[1], + payload: JSON.parse(String(params[2])), + base_version_no: params[3], + base_items_fingerprint: params[4], + status: 'pending', + requested_by: params[5], + requested_by_name: '提交人甲', + requested_at: '2026-10-18T02:00:00.000Z', + reviewed_by: null, + reviewed_by_name: null, + reviewed_at: null, + reject_reason: null, + applied_at: null, + updated_at: '2026-10-18T02:00:00.000Z', + }; + state.changeRequests.set(id, row); + return { rows: [row], rowCount: 1 }; + } + if (text.includes('FROM quote_sheet_change_requests') && text.includes('FOR UPDATE')) { + // 两种锁:① 提交时找旧 pending(按 branch+sheet);② 审批时按 id 锁行 + if (text.includes('WHERE branch_code = $1 AND quote_sheet_code = $2')) { + state.events.push('CR_PREVIOUS_LOCK'); + const previous = [...state.changeRequests.values()].filter( + (row) => row.branch_code === params[0] && row.quote_sheet_code === params[1] && row.status === 'pending' + ); + return { rows: previous.map((row) => ({ id: row.id })), rowCount: previous.length }; + } + state.events.push('CR_LOCK'); + const row = state.changeRequests.get(String(params[0])); + return { rows: row ? [row] : [], rowCount: row ? 1 : 0 }; + } + if (text.includes('SELECT id, branch_code, status FROM quote_sheet_change_requests')) { + const row = state.changeRequests.get(String(params[0])); + return { rows: row ? [row] : [], rowCount: row ? 1 : 0 }; + } + if (text.includes('UPDATE quote_sheet_change_requests') && text.includes("SET status = 'rejected'")) { + const row = state.changeRequests.get(String(params[0])); + state.events.push('CR_REJECT'); + if (!row || row.status !== 'pending') return { rows: [], rowCount: 0 }; + row.status = 'rejected'; + row.reviewed_by = params[1] ?? null; + row.reviewed_at = '2026-10-18T03:00:00.000Z'; + row.reject_reason = text.includes("reject_reason = 'base_changed'") ? 'base_changed' : params[2]; + row.updated_at = '2026-10-18T03:00:00.000Z'; + return { rows: [row], rowCount: 1 }; + } + if (text.includes('UPDATE quote_sheet_change_requests') && text.includes("SET status = 'approved'")) { + const row = state.changeRequests.get(String(params[0])); + state.events.push('CR_APPROVED'); + if (!row || row.status !== 'pending') return { rows: [], rowCount: 0 }; + row.status = 'approved'; + row.reviewed_by = params[1] ?? null; + row.reviewed_at = '2026-10-18T03:00:00.000Z'; + row.applied_at = '2026-10-18T03:00:00.000Z'; + row.updated_at = '2026-10-18T03:00:00.000Z'; + return { rows: [row], rowCount: 1 }; + } + if (text.includes('FROM quote_sheet_change_requests cr')) { + state.events.push('CR_LIST'); + const status = params[1]; + const rows = [...state.changeRequests.values()] + .filter((row) => row.branch_code === params[0] && row.status === status) + .sort((a, b) => String(b.requested_at).localeCompare(String(a.requested_at))); + return { rows, rowCount: rows.length }; + } + // ── 报价单明细 / 客户 ── + if (text.includes('FROM customer_quote_sheet_items') && text.includes('= ANY($1)')) { + return { + rows: state.items.map((item) => ({ ...item, quote_sheet_code: SHEET })), + rowCount: state.items.length, + }; + } + if (text.includes('FROM customer_quote_sheet_items')) { + return { rows: state.items, rowCount: state.items.length }; + } + if (text.includes('FROM skus WHERE sku_code = ANY($1) AND status = 1')) { + state.events.push('CHECK_SKUS'); + const codes = (params[0] as string[]) || []; + return { rows: codes.filter((code) => state.aliveSkus.has(code)).map((sku_code) => ({ sku_code })) }; + } + if (text.includes('FROM customers WHERE customer_code = ANY($1) AND branch_code = $2')) { + state.events.push('CHECK_CUSTOMERS'); + const codes = (params[0] as string[]) || []; + return { + rows: codes + .filter((code) => state.branchCustomers.has(code)) + .map((customer_code) => ({ customer_code })), + }; + } + return { rows: [], rowCount: 0 }; + }; + + poolQuery.mockImplementation((sql: string, params?: unknown[]) => handler(sql, params || [], false)); + clientQuery.mockImplementation((sql: string, params?: unknown[]) => handler(sql, params || [], true)); +} + +const okDetail = () => ({ quote_sheet_code: SHEET, items: [], customers: [] }); + +beforeEach(() => { + poolQuery.mockReset(); + clientQuery.mockReset(); + clientRelease.mockReset(); + applyQuoteSheetUpdate.mockReset(); + updateQuoteSheet.mockReset(); + loadQuoteSheetForUpdate.mockReset(); + getQuoteSheet.mockReset(); + assertCustomersInBranch.mockReset(); + triggerQuoteCostSync.mockReset(); + writeAuditLog.mockReset(); + writeAuditLog.mockResolvedValue(undefined); + + delete process.env.QUOTE_EDIT_APPROVAL; + loadQuoteSheetForUpdate.mockResolvedValue(seedSheet()); + getQuoteSheet.mockResolvedValue(okDetail()); + updateQuoteSheet.mockResolvedValue(okDetail()); + applyQuoteSheetUpdate.mockImplementation(async () => { + // 模拟"应用成功",并记录与事务相关的事件顺序 + return okDetail(); + }); + assertCustomersInBranch.mockResolvedValue(undefined); +}); + +/* ── 纯函数 ─────────────────────────────────────────────────────────────── */ + +describe('开关(默认开)', () => { + it('未设置 / 1 / true / on ⇒ 开;0 / false / off(大小写不敏感)⇒ 关', () => { + expect(isQuoteEditApprovalEnabled()).toBe(true); + for (const value of ['1', 'true', 'on', 'TRUE']) { + process.env.QUOTE_EDIT_APPROVAL = value; + expect(isQuoteEditApprovalEnabled(), value).toBe(true); + } + for (const value of ['0', 'false', 'off', 'OFF', 'Off']) { + process.env.QUOTE_EDIT_APPROVAL = value; + expect(isQuoteEditApprovalEnabled(), value).toBe(false); + } + }); +}); + +describe('价格相关性判定(D5)', () => { + it('含 items ⇒ 价格相关;只改标题/周期/生效日/客户 ⇒ 不相关', () => { + expect(isPriceRelatedQuoteEdit({ items: [] }, { auto_sale_price_by_cost: false })).toBe(true); + expect(isPriceRelatedQuoteEdit({ items: [{ sku_code: 'SKU1' }] }, {})).toBe(true); + expect(isPriceRelatedQuoteEdit({ title: 'x', customerCodes: ['CUS_A'] }, {})).toBe(false); + expect(isPriceRelatedQuoteEdit({}, {})).toBe(false); + }); + + it('auto_sale_price_by_cost:真的变了才算价格相关', () => { + expect(isPriceRelatedQuoteEdit({ autoSalePriceByCost: true }, { auto_sale_price_by_cost: false })).toBe(true); + expect(isPriceRelatedQuoteEdit({ autoSalePriceByCost: false }, { auto_sale_price_by_cost: false })).toBe(false); + expect(isPriceRelatedQuoteEdit({ autoSalePriceByCost: true }, { auto_sale_price_by_cost: true })).toBe(false); + }); +}); + +describe('重复 SKU 闸门(Lead 裁定 #2)', () => { + it('重复(trim 后同名)⇒ 抛 400 duplicate_sku;空 sku 行不算', () => { + expect(() => + assertNoDuplicateSku([ + { sku_code: 'SKU1' }, + { sku_code: ' SKU1 ' }, + { sku_code: '' }, + { sku_code: '' }, + ]) + ).toThrowError(/同一商品重复出现/); + try { + assertNoDuplicateSku([{ sku_code: 'A' }, { sku_code: 'A' }]); + } catch (error: any) { + expect(error.status).toBe(400); + expect(error.code).toBe('duplicate_sku'); + } + expect(() => assertNoDuplicateSku([{ sku_code: 'A' }, { sku_code: 'B' }])).not.toThrow(); + }); +}); + +describe('明细指纹 / 摘要(复用成本价同步同一算法)', () => { + it('指纹按 sku_code/unit/sale_price 排序后 sha256,与顺序无关', () => { + const a = quoteSheetItemsFingerprint([ + { sku_code: 'SKU1', unit: '斤', sale_price: '10' }, + { sku_code: 'SKU2', unit: '袋', sale_price: '12.5' }, + ]); + const b = quoteSheetItemsFingerprint([ + { sku_code: 'SKU2', unit: '袋', sale_price: '12.5' }, + { sku_code: 'SKU1', unit: '斤', sale_price: '10' }, + ]); + expect(a).toBe(b); + expect(a).toMatch(/^[0-9a-f]{64}$/); + // 价格/单位变化 ⇒ 指纹变化 + expect(quoteSheetItemsFingerprint([{ sku_code: 'SKU1', unit: '斤', sale_price: '11' }])).not.toBe( + quoteSheetItemsFingerprint([{ sku_code: 'SKU1', unit: '斤', sale_price: '10' }]) + ); + }); + + it('摘要:增/删/改分桶,改前→改后都在,未变不进 lines', () => { + const summary = diffQuoteSheetItems( + [ + { sku_code: 'SKU1', unit: '斤', sale_price: '10.00', cost_price: '5.00' }, + { sku_code: 'SKU2', unit: '斤', sale_price: '12.00', cost_price: '6.00' }, + { sku_code: 'SKU3', unit: '袋', sale_price: '3.00', cost_price: '1.00' }, + ], + [ + { sku_code: 'SKU1', sku_name: '草鱼', unit: '斤', sale_price: '11.00', cost_price: '5.00' }, + { sku_code: 'SKU2', unit: '斤', sale_price: '12.00', cost_price: '6.00' }, + { sku_code: 'SKU4', unit: '盒', sale_price: '9.00', cost_price: '4.00' }, + ] + ); + expect(summary).toMatchObject({ item_count: 3, added: 1, removed: 1, updated: 1, truncated: false }); + const byChange = Object.fromEntries(summary.lines.map((line) => [line.change, line])); + expect(byChange.updated.before_sale_price).toBe(10); + expect(byChange.updated.after_sale_price).toBe(11); + expect(byChange.added.sku_code).toBe('SKU4'); + expect(byChange.removed.sku_code).toBe('SKU3'); + expect(summary.lines.some((line) => line.sku_code === 'SKU2')).toBe(false); + }); +}); + +/* ── 提交分流 ───────────────────────────────────────────────────────────── */ + +describe('PUT 分流:价格相关 ⇒ 待审;非价格 ⇒ 直接保存', () => { + it('价格相关 ⇒ 不落报价单(updateQuoteSheet 不被调用),写 pending 变更单并返回 applied:false', async () => { + const state = makeState(); + installDb(state); + + const result = await saveQuoteSheetEdit({ + quoteSheetCode: SHEET, + items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 11, price: 11, cost_price: 5 }], + requestedBy: 'u-requester', + }); + + expect(result.applied).toBe(false); + expect(updateQuoteSheet).not.toHaveBeenCalled(); + expect(state.events).toContain('CR_INSERT'); + const created = [...state.changeRequests.values()][0]; + expect(created.status).toBe('pending'); + expect(created.branch_code).toBe(BRANCH); + expect(created.payload.items).toHaveLength(1); + expect(created.payload.items[0]).toMatchObject({ sku_code: 'SKU1', sale_price: 11 }); + expect(created.base_items_fingerprint).toBe(quoteSheetItemsFingerprint(state.items)); + if (result.applied === false) { + expect(result.changeRequest.status).toBe('pending'); + expect(result.changeRequest.summary?.updated).toBe(1); + } + expect(triggerQuoteCostSync).not.toHaveBeenCalled(); + }); + + it('非价格(只改标题/客户)⇒ 直接保存 applied:true,并按 Lead #6 触发一次成本价同步(自带指纹判重)', async () => { + const state = makeState(); + installDb(state); + + const result = await saveQuoteSheetEdit({ + quoteSheetCode: SHEET, + title: '新标题', + customerCodes: ['MAIN_BR002'], + }); + + expect(result.applied).toBe(true); + expect(updateQuoteSheet).toHaveBeenCalledTimes(1); + expect(state.events).not.toContain('CR_INSERT'); + expect(triggerQuoteCostSync).toHaveBeenCalledWith({ branchCode: BRANCH, quoteSheetCode: SHEET }); + }); + + it('价格相关但开关关 ⇒ 直接保存、不写变更单表、不推送(= 改造前)', async () => { + process.env.QUOTE_EDIT_APPROVAL = '0'; + const state = makeState(); + installDb(state); + + const result = await saveQuoteSheetEdit({ + quoteSheetCode: SHEET, + items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 11, price: 11 }], + }); + + expect(result.applied).toBe(true); + expect(updateQuoteSheet).toHaveBeenCalledTimes(1); + expect(state.events).not.toContain('CR_INSERT'); + expect(state.changeRequests.size).toBe(0); + expect(triggerQuoteCostSync).not.toHaveBeenCalled(); + }); + + it('同一 SKU 重复 ⇒ 400 duplicate_sku,一条变更单都不写', async () => { + const state = makeState(); + installDb(state); + await expect( + saveQuoteSheetEdit({ + quoteSheetCode: SHEET, + items: [ + { sku_code: 'SKU1', unit: '斤', sale_price: 11 }, + { sku_code: 'SKU1', unit: '斤', sale_price: 12 }, + ], + }) + ).rejects.toMatchObject({ status: 400, code: 'duplicate_sku' }); + expect(state.changeRequests.size).toBe(0); + expect(updateQuoteSheet).not.toHaveBeenCalled(); + }); + + it('D4:二次提交把旧 pending 置 superseded,只留一条 pending', async () => { + const state = makeState(); + installDb(state); + await saveQuoteSheetEdit({ + quoteSheetCode: SHEET, + items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 11 }], + }); + await saveQuoteSheetEdit({ + quoteSheetCode: SHEET, + items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 13 }], + }); + const rows = [...state.changeRequests.values()]; + expect(rows.filter((row) => row.status === 'pending')).toHaveLength(1); + expect(rows.filter((row) => row.status === 'superseded')).toHaveLength(1); + expect(rows.find((row) => row.status === 'pending')!.payload.items[0].sale_price).toBe(13); + }); +}); + +/* ── 审核通过 ───────────────────────────────────────────────────────────── */ + +describe('审核通过:单事务应用 + 提交后才推送', () => { + const pendingPayload = { + items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 11, price: 11, cost_price: 5 }], + }; + + it('事件顺序 BEGIN → 应用 → 记审批 → COMMIT → trigger;且传入同一事务 client', async () => { + const state = makeState(); + seedChangeRequest(state, { payload: pendingPayload }); + installDb(state); + + const result = await approveQuoteSheetChangeRequest({ + id: '11111111-1111-4111-8111-111111111111', + ctx: { branchCode: BRANCH } as any, + reviewedBy: 'u-reviewer', + }); + + expect(applyQuoteSheetUpdate).toHaveBeenCalledTimes(1); + const [, options] = applyQuoteSheetUpdate.mock.calls[0] as [any, any]; + expect(options?.client).toBeTruthy(); + const applyArg = applyQuoteSheetUpdate.mock.calls[0][0] as any; + expect(applyArg.quoteSheetCode).toBe(SHEET); + expect(applyArg.items[0]).toMatchObject({ sku_code: 'SKU1', sale_price: 11 }); + + const order = state.events.filter((event) => + ['BEGIN', 'CR_LOCK', 'CHECK_SKUS', 'CHECK_CUSTOMERS', 'CR_APPROVED', 'COMMIT'].includes(event) + ); + expect(order[0]).toBe('BEGIN'); + expect(order).toContain('CR_APPROVED'); + expect(order[order.length - 1]).toBe('COMMIT'); + // 推送必须在 COMMIT 之后(trigger 在 mock 里不记事件,靠下面的调用顺序断言) + expect(triggerQuoteCostSync).toHaveBeenCalledWith({ branchCode: BRANCH, quoteSheetCode: SHEET }); + expect(state.changeRequests.get('11111111-1111-4111-8111-111111111111')!.status).toBe('approved'); + expect(result.changeRequest.status).toBe('approved'); + expect(result.changeRequest.applied_at).toBeTruthy(); + expect(result.changeRequest.reviewed_by).toBe('u-reviewer'); + }); + + it('推送发生在 COMMIT 之后(用事件顺序钉住)', async () => { + const state = makeState(); + seedChangeRequest(state, { payload: pendingPayload }); + installDb(state); + triggerQuoteCostSync.mockImplementation(() => { + state.events.push('TRIGGER'); + }); + await approveQuoteSheetChangeRequest({ + id: '11111111-1111-4111-8111-111111111111', + ctx: { branchCode: BRANCH } as any, + }); + expect(state.events.indexOf('COMMIT')).toBeLessThan(state.events.indexOf('TRIGGER')); + }); + + it('base 已变 ⇒ 409 base_changed:变更单置 rejected + 理由,零应用、零推送', async () => { + const state = makeState(); + seedChangeRequest(state, { + payload: pendingPayload, + // 提交时指纹:价格 10;随后目标单被改成 10.5 + base_items_fingerprint: quoteSheetItemsFingerprint(state.items), + }); + state.items = [ + { sku_code: 'SKU1', unit: '斤', sale_price: '10.50', price: '10.50', cost_price: '5.00' }, + ]; + installDb(state); + + await expect( + approveQuoteSheetChangeRequest({ + id: '11111111-1111-4111-8111-111111111111', + ctx: { branchCode: BRANCH } as any, + }) + ).rejects.toMatchObject({ status: 409, code: 'base_changed' }); + + expect(applyQuoteSheetUpdate).not.toHaveBeenCalled(); + expect(triggerQuoteCostSync).not.toHaveBeenCalled(); + const row = state.changeRequests.get('11111111-1111-4111-8111-111111111111')!; + expect(row.status).toBe('rejected'); + expect(row.reject_reason).toBe('base_changed'); + }); + + it('SKU 已停用 ⇒ 409 sku_unavailable:零应用、零推送、变更单仍 pending(人工决定驳回)', async () => { + const state = makeState({ aliveSkus: new Set(['SKU2']) }); + seedChangeRequest(state, { payload: pendingPayload }); + installDb(state); + await expect( + approveQuoteSheetChangeRequest({ + id: '11111111-1111-4111-8111-111111111111', + ctx: { branchCode: BRANCH } as any, + }) + ).rejects.toMatchObject({ status: 409, code: 'sku_unavailable' }); + expect(applyQuoteSheetUpdate).not.toHaveBeenCalled(); + expect(triggerQuoteCostSync).not.toHaveBeenCalled(); + expect(state.changeRequests.get('11111111-1111-4111-8111-111111111111')!.status).toBe('pending'); + }); + + it('客户不属本分公司 ⇒ 409 invalid_customer:零应用、零推送', async () => { + const state = makeState({ branchCustomers: new Set(['MAIN_BR002']) }); + seedChangeRequest(state, { + payload: { items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 11 }], customer_codes: ['CUS_OTHER'] }, + }); + installDb(state); + await expect( + approveQuoteSheetChangeRequest({ + id: '11111111-1111-4111-8111-111111111111', + ctx: { branchCode: BRANCH } as any, + }) + ).rejects.toMatchObject({ status: 409, code: 'invalid_customer' }); + expect(applyQuoteSheetUpdate).not.toHaveBeenCalled(); + }); + + it('重复决策 ⇒ 409 already_decided(不重复应用、不重复推送)', async () => { + const state = makeState(); + seedChangeRequest(state, { payload: pendingPayload, status: 'approved' }); + installDb(state); + await expect( + approveQuoteSheetChangeRequest({ + id: '11111111-1111-4111-8111-111111111111', + ctx: { branchCode: BRANCH } as any, + }) + ).rejects.toMatchObject({ status: 409, code: 'already_decided' }); + expect(applyQuoteSheetUpdate).not.toHaveBeenCalled(); + expect(triggerQuoteCostSync).not.toHaveBeenCalled(); + }); + + it('变更单所属分公司与当前 ctx 不符 ⇒ 403 branch_mismatch', async () => { + const state = makeState(); + seedChangeRequest(state, { payload: pendingPayload, branch_code: 'BR999' }); + installDb(state); + await expect( + approveQuoteSheetChangeRequest({ + id: '11111111-1111-4111-8111-111111111111', + ctx: { branchCode: BRANCH } as any, + }) + ).rejects.toMatchObject({ status: 403, code: 'branch_mismatch' }); + expect(applyQuoteSheetUpdate).not.toHaveBeenCalled(); + }); + + it('找不到变更单 ⇒ 404', async () => { + installDb(makeState()); + await expect( + approveQuoteSheetChangeRequest({ + id: '22222222-2222-4222-8222-222222222222', + ctx: { branchCode: BRANCH } as any, + }) + ).rejects.toMatchObject({ status: 404, code: 'change_request_not_found' }); + }); +}); + +/* ── 驳回 / 列表 ────────────────────────────────────────────────────────── */ + +describe('审核驳回', () => { + it('驳回 ⇒ rejected + 理由,报价单不变、零推送', async () => { + const state = makeState(); + seedChangeRequest(state, { payload: { items: [] } }); + installDb(state); + const result = await rejectQuoteSheetChangeRequest({ + id: '11111111-1111-4111-8111-111111111111', + reason: '价格谈不拢', + ctx: { branchCode: BRANCH } as any, + reviewedBy: 'u-reviewer', + }); + expect(result.changeRequest.status).toBe('rejected'); + expect(result.changeRequest.reject_reason).toBe('价格谈不拢'); + expect(applyQuoteSheetUpdate).not.toHaveBeenCalled(); + expect(updateQuoteSheet).not.toHaveBeenCalled(); + expect(triggerQuoteCostSync).not.toHaveBeenCalled(); + }); + + it('驳回必须给理由(400 reject_reason_required)', async () => { + installDb(makeState()); + await expect( + rejectQuoteSheetChangeRequest({ + id: '11111111-1111-4111-8111-111111111111', + reason: ' ', + ctx: { branchCode: BRANCH } as any, + }) + ).rejects.toMatchObject({ status: 400, code: 'reject_reason_required' }); + }); + + it('已处理的变更单再驳回 ⇒ 409 already_decided', async () => { + const state = makeState(); + seedChangeRequest(state, { status: 'rejected' }); + installDb(state); + await expect( + rejectQuoteSheetChangeRequest({ + id: '11111111-1111-4111-8111-111111111111', + reason: '再驳一次', + ctx: { branchCode: BRANCH } as any, + }) + ).rejects.toMatchObject({ status: 409, code: 'already_decided' }); + }); +}); + +describe('待审列表', () => { + it('返回 pending 行 + 提交人 + 审核摘要(改前 → 改后)', async () => { + const state = makeState(); + seedChangeRequest(state, { + payload: { items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 11, price: 11, cost_price: 5 }] }, + }); + installDb(state); + const rows = await listQuoteSheetChangeRequests({ branchCode: BRANCH, status: 'pending' }); + expect(rows).toHaveLength(1); + expect(rows[0].requested_by_name).toBe('提交人甲'); + expect(rows[0].summary?.updated).toBe(1); + expect(rows[0].summary?.lines[0]).toMatchObject({ + sku_code: 'SKU1', + before_sale_price: 10, + after_sale_price: 11, + change: 'updated', + }); + }); +}); + +/* ── payload 往返 ───────────────────────────────────────────────────────── */ + +describe('payload → apply 入参', () => { + it('只映射存下来的字段(未提供的不传给 apply)', () => { + expect( + payloadToUpdateInput({ + quote_sheet_code: SHEET, + payload: { items: [{ sku_code: 'SKU1', sale_price: 11, cost_price: 5 }] }, + }) + ).toMatchObject({ quoteSheetCode: SHEET, items: [{ sku_code: 'SKU1', sale_price: 11, cost_price: 5 }] }); + const onlyTitle = payloadToUpdateInput({ quote_sheet_code: SHEET, payload: { title: 'x' } }); + expect(onlyTitle.customerCodes).toBeUndefined(); + expect(onlyTitle.items).toBeUndefined(); + expect(onlyTitle.autoSalePriceByCost).toBeUndefined(); + }); +}); + +/* ── ⑧ verifier 复核后修复:A29 列表 SQL / A26 业务审计 / A12 目标失效映射 ────────────── */ + +describe('A29:待审列表必须用 public.profiles(auth.users 没有 full_name/username)', () => { + beforeEach(() => { + process.env.QUOTE_EDIT_APPROVAL = '1'; + }); + + it('列表 SQL 只 join public.profiles,且不出现 auth.users', async () => { + const state = makeState(); + seedChangeRequest(state, { payload: { items: [] } }); + installDb(state); + await listQuoteSheetChangeRequests({ branchCode: BRANCH, status: 'pending' }); + const call = poolQuery.mock.calls.find(([sql]) => + String(sql).includes('FROM quote_sheet_change_requests cr') + ); + expect(call).toBeTruthy(); + const sql = String(call![0]); + expect(sql).toContain('LEFT JOIN public.profiles ru ON ru.id = cr.requested_by'); + expect(sql).toContain('LEFT JOIN public.profiles vu ON vu.id = cr.reviewed_by'); + expect(sql).not.toContain('auth.users'); + }); +}); + +describe('A26:提交 / 通过 / 驳回各一条业务审计(best-effort)', () => { + beforeEach(() => { + process.env.QUOTE_EDIT_APPROVAL = '1'; + }); + + function auditCalls() { + return writeAuditLog.mock.calls.map(([arg]) => arg as any); + } + + it('提交(新 pending)⇒ quote_sheet_change_request_submit,记 id / 单号 / (none)→pending / 操作人', async () => { + const state = makeState(); + installDb(state); + const result = await saveQuoteSheetEdit({ + quoteSheetCode: SHEET, + items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 11 }], + requestedBy: 'u-requester', + ctx: { branchCode: BRANCH, userId: 'u-requester', roles: ['operator'] } as any, + }); + const calls = auditCalls(); + expect(calls).toHaveLength(1); + expect(calls[0]).toMatchObject({ + operatorId: 'u-requester', + operatorRole: 'operator', + operationType: 'quote_sheet_change_request_submit', + targetTable: 'quote_sheet_change_requests', + branchCode: BRANCH, + actionCategory: 'quote_edit_approval', + }); + expect(calls[0].targetId).toBe(result.applied === false ? result.changeRequest.id : ''); + expect(calls[0].oldValue).toMatchObject({ status: '(none)', quote_sheet_code: SHEET }); + expect(calls[0].newValue).toMatchObject({ status: 'pending', action: 'submit' }); + }); + + it('覆盖旧 pending ⇒ 审计 oldStatus=pending 且 reason 记被覆盖的变更单 id', async () => { + const state = makeState(); + installDb(state); + const first = await saveQuoteSheetEdit({ + quoteSheetCode: SHEET, + items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 11 }], + }); + writeAuditLog.mockClear(); + await saveQuoteSheetEdit({ + quoteSheetCode: SHEET, + items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 13 }], + }); + const calls = auditCalls(); + expect(calls).toHaveLength(1); + expect(calls[0].oldValue.status).toBe('pending'); + expect(String(calls[0].newValue.reason)).toBe( + `superseded:${first.applied === false ? first.changeRequest.id : ''}` + ); + }); + + it('通过 ⇒ quote_sheet_change_request_approve(pending → approved)', async () => { + const state = makeState(); + seedChangeRequest(state, { + payload: { items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 11, price: 11, cost_price: 5 }] }, + }); + installDb(state); + await approveQuoteSheetChangeRequest({ + id: '11111111-1111-4111-8111-111111111111', + ctx: { branchCode: BRANCH, userId: 'u-reviewer', roles: ['admin'] } as any, + reviewedBy: 'u-reviewer', + }); + const calls = auditCalls(); + expect(calls.some((arg) => arg.operationType === 'quote_sheet_change_request_approve')).toBe(true); + const approveAudit = calls.find((arg) => arg.operationType === 'quote_sheet_change_request_approve'); + expect(approveAudit).toMatchObject({ + operatorId: 'u-reviewer', + operatorRole: 'admin', + targetId: '11111111-1111-4111-8111-111111111111', + branchCode: BRANCH, + }); + expect(approveAudit.oldValue).toMatchObject({ status: 'pending', quote_sheet_code: SHEET }); + expect(approveAudit.newValue).toMatchObject({ status: 'approved', action: 'approve' }); + }); + + it('驳回 ⇒ quote_sheet_change_request_reject(带理由)', async () => { + const state = makeState(); + seedChangeRequest(state, { payload: { items: [] } }); + installDb(state); + await rejectQuoteSheetChangeRequest({ + id: '11111111-1111-4111-8111-111111111111', + reason: '价格谈不拢', + ctx: { branchCode: BRANCH, userId: 'u-reviewer', roles: ['admin'] } as any, + reviewedBy: 'u-reviewer', + }); + const calls = auditCalls(); + expect(calls).toHaveLength(1); + expect(calls[0]).toMatchObject({ + operationType: 'quote_sheet_change_request_reject', + targetId: '11111111-1111-4111-8111-111111111111', + }); + expect(calls[0].newValue).toMatchObject({ status: 'rejected', action: 'reject', reason: '价格谈不拢' }); + }); + + it('base_changed 自动驳回也留 reject 审计(理由 base_changed)', async () => { + const state = makeState(); + seedChangeRequest(state, { + payload: { items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 11 }] }, + base_items_fingerprint: quoteSheetItemsFingerprint(state.items), + }); + state.items = [{ sku_code: 'SKU1', unit: '斤', sale_price: '10.50', price: '10.50', cost_price: '5.00' }]; + installDb(state); + await expect( + approveQuoteSheetChangeRequest({ + id: '11111111-1111-4111-8111-111111111111', + ctx: { branchCode: BRANCH, userId: 'u-reviewer', roles: ['admin'] } as any, + }) + ).rejects.toMatchObject({ status: 409, code: 'base_changed' }); + const calls = auditCalls(); + expect(calls).toHaveLength(1); + expect(calls[0]).toMatchObject({ operationType: 'quote_sheet_change_request_reject' }); + expect(calls[0].newValue).toMatchObject({ status: 'rejected', reason: 'base_changed' }); + }); + + it('审计失败不得影响主流程(writeAuditLog 抛错时提交/通过仍成功)', async () => { + const state = makeState(); + installDb(state); + writeAuditLog.mockRejectedValueOnce(new Error('audit down')); + const submit = await saveQuoteSheetEdit({ + quoteSheetCode: SHEET, + items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 11 }], + }); + expect(submit.applied).toBe(false); + + seedChangeRequest(state, { + payload: { items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 11, price: 11, cost_price: 5 }] }, + }); + writeAuditLog.mockRejectedValueOnce(new Error('audit down')); + const approved = await approveQuoteSheetChangeRequest({ + id: '11111111-1111-4111-8111-111111111111', + ctx: { branchCode: BRANCH } as any, + }); + expect(approved.changeRequest.status).toBe('approved'); + }); +}); + +describe('A12(修订):审批时目标单不可用 ⇒ 409 target_unavailable,变更单保持 pending', () => { + beforeEach(() => { + process.env.QUOTE_EDIT_APPROVAL = '1'; + }); + + it.each([ + ['报价单不存在', '报价单不存在'], + ['仅执行中的报价单可修改', '仅执行中的报价单可修改'], + ['报价单已过期,无法修改', '报价单已过期,无法修改'], + ])('目标单「%s」⇒ 409 target_unavailable(不改编辑路径的抛错语义)', async (_label, message) => { + const state = makeState(); + seedChangeRequest(state, { + payload: { items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 11 }] }, + }); + installDb(state); + loadQuoteSheetForUpdate.mockRejectedValueOnce(new Error(message)); + + await expect( + approveQuoteSheetChangeRequest({ + id: '11111111-1111-4111-8111-111111111111', + ctx: { branchCode: BRANCH } as any, + }) + ).rejects.toMatchObject({ status: 409, code: 'target_unavailable', message }); + + expect(applyQuoteSheetUpdate).not.toHaveBeenCalled(); + expect(triggerQuoteCostSync).not.toHaveBeenCalled(); + expect(state.changeRequests.get('11111111-1111-4111-8111-111111111111')!.status).toBe('pending'); + }); + + it('目标单失效是「审批路径映射」:编辑路径仍抛普通 Error(无 status/code)', async () => { + const state = makeState(); + installDb(state); + loadQuoteSheetForUpdate.mockRejectedValueOnce(new Error('仅执行中的报价单可修改')); + await expect( + saveQuoteSheetEdit({ quoteSheetCode: SHEET, items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 11 }] }) + ).rejects.toMatchObject({ message: '仅执行中的报价单可修改' }); + }); +}); + +/* ── ⑨ 红队第三轮 P3-1:目标单硬删时的校验顺序(可用性必须先于指纹)────────────── */ + +describe('P3-1:目标单「硬删」⇒ 409 target_unavailable + 变更单保持 pending(不回退成 base_changed)', () => { + beforeEach(() => { + process.env.QUOTE_EDIT_APPROVAL = '1'; + }); + + const payload = { + items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 11, price: 11, cost_price: 5 }], + }; + + it('目标单被硬删(明细也空了 ⇒ 旧代码会误判指纹不一致)⇒ 409 target_unavailable,零应用/零推送/零台账,变更单 pending', async () => { + const state = makeState(); + seedChangeRequest(state, { + payload, + // 提交时指纹来自"当时存在的明细" + base_items_fingerprint: quoteSheetItemsFingerprint(state.items), + }); + // 硬删:报价单与明细一起消失(真库无外键 ⇒ 明细可能是空集,也可能残留孤儿行;两种都试) + state.items = []; + installDb(state); + loadQuoteSheetForUpdate.mockRejectedValueOnce(new Error('报价单不存在')); + + await expect( + approveQuoteSheetChangeRequest({ + id: '11111111-1111-4111-8111-111111111111', + ctx: { branchCode: BRANCH } as any, + }) + ).rejects.toMatchObject({ status: 409, code: 'target_unavailable', message: '报价单不存在' }); + + // 关键:**不得**走 base_changed 的自动驳回分支 + expect(state.events).not.toContain('CR_REJECT'); + expect(state.changeRequests.get('11111111-1111-4111-8111-111111111111')!.status).toBe('pending'); + expect(state.changeRequests.get('11111111-1111-4111-8111-111111111111')!.reject_reason).toBeNull(); + // 零应用 / 零推送 / 零台账(pushOneBranch 都没机会跑) + expect(applyQuoteSheetUpdate).not.toHaveBeenCalled(); + expect(triggerQuoteCostSync).not.toHaveBeenCalled(); + expect(poolQuery.mock.calls.some(([sql]) => String(sql).includes('INSERT INTO public.main_system_quote_cost_pushes'))).toBe(false); + }); + + it('防回退:目标**仍可用**但指纹变了 ⇒ 仍然 409 base_changed + 自动 rejected(不许改成 pending)', async () => { + const state = makeState(); + seedChangeRequest(state, { + payload, + base_items_fingerprint: quoteSheetItemsFingerprint(state.items), + }); + state.items = [{ sku_code: 'SKU1', unit: '斤', sale_price: '10.50', price: '10.50', cost_price: '5.00' }]; + installDb(state); + + await expect( + approveQuoteSheetChangeRequest({ + id: '11111111-1111-4111-8111-111111111111', + ctx: { branchCode: BRANCH } as any, + }) + ).rejects.toMatchObject({ status: 409, code: 'base_changed' }); + + expect(state.events).toContain('CR_REJECT'); + const row = state.changeRequests.get('11111111-1111-4111-8111-111111111111')!; + expect(row.status).toBe('rejected'); + expect(row.reject_reason).toBe('base_changed'); + expect(applyQuoteSheetUpdate).not.toHaveBeenCalled(); + expect(triggerQuoteCostSync).not.toHaveBeenCalled(); + }); + + it('顺序断言:目标不可用时连指纹查询都不该发生(先可用性、后指纹)', async () => { + const state = makeState({ items: [] }); + seedChangeRequest(state, { payload, base_items_fingerprint: 'stale-fp' }); + installDb(state); + loadQuoteSheetForUpdate.mockRejectedValueOnce(new Error('仅执行中的报价单可修改')); + + await expect( + approveQuoteSheetChangeRequest({ + id: '11111111-1111-4111-8111-111111111111', + ctx: { branchCode: BRANCH } as any, + }) + ).rejects.toMatchObject({ status: 409, code: 'target_unavailable' }); + + // 指纹查询 = `SELECT sku_code, unit, sale_price, price FROM customer_quote_sheet_items` + const fingerprintQueries = poolQuery.mock.calls + .concat(clientQuery.mock.calls) + .filter(([sql]) => String(sql).includes('SELECT sku_code, unit, sale_price, price FROM customer_quote_sheet_items')); + expect(fingerprintQueries).toHaveLength(0); + }); +}); diff --git a/server/tests/quoteSheetChangeRequestDb.integration.test.ts b/server/tests/quoteSheetChangeRequestDb.integration.test.ts new file mode 100644 index 0000000..751de95 --- /dev/null +++ b/server/tests/quoteSheetChangeRequestDb.integration.test.ts @@ -0,0 +1,341 @@ +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +/** + * 「待审改价」列��**真库**验证(默认跳过;`QUOTE_EDIT_APPROVAL_DB_TEST=1` 才跑)。 + * + * 为什么必须有这一份(verifier A29 阻断项的回归):列表 SQL 曾写成 + * `LEFT JOIN auth.users ru ... ru.full_name`,而 **`auth.users` 没有 `full_name`/`username`** + * (展示名在 `public.profiles`)⇒ 真库上 `GET /quote/change-requests` 直接 500,前端面板加载不出来。 + * 单测里 DB 是脚本化 mock,**永远发现不了这种"列不存在"** —— 所以这里连真 Postgres。 + * + * 覆盖: + * ① 前提复现:`auth.users` 确实没有那两列(旧写法必炸,防止有人改回去); + * ② 列表走 `public.profiles`:`requested_by_name` / `reviewed_by_name` **非空**; + * ③ pending 行带审核摘要(items 比对); + * ④ 按 `branch_code` 过滤(别的分公司 code 取不到这批测试行)。 + * + * 纪律:只碰本地 `supplier_delivery` 的 `tenant_br002.quote_sheet_change_requests`, + * 且只碰 `quote_sheet_code LIKE 'QS_TESTQCR_%'` 的临时行,跑完删干净。 + * + * 跑法(本地): + * cd server && QUOTE_EDIT_APPROVAL_DB_TEST=1 npx vitest run tests/quoteSheetChangeRequestDb.integration.test.ts + */ + +const RUN = process.env.QUOTE_EDIT_APPROVAL_DB_TEST === '1'; +const BRANCH = 'BR002'; +const SCHEMA = 'tenant_br002'; +const OTHER_BRANCH = 'BR_TESTQCR_OTHER'; +const SHEET_APPROVED = 'QS_TESTQCR_APPROVED'; +const SHEET_PENDING = 'QS_TESTQCR_PENDING'; +const SHEET_FALLBACK = 'QS_TESTQCR_FALLBACK'; +const SHEET_SUMMARY = 'QS_TESTQCR_SUMMARY'; + +// 默认(未设开关)连 src/db 都不加载,保证常规套件不受影响 +const real = RUN + ? { + db: await import('../src/db'), + tenant: await import('../src/services/tenantDbContext'), + service: await import('../src/services/quoteSheetChangeRequestService'), + } + : null; + +const pool = () => real!.db.pool; + +let profileA: { id: string; name: string } = { id: '', name: '' }; +let profileB: { id: string; name: string } = { id: '', name: '' }; +let realSheetCode = SHEET_FALLBACK; + +async function cleanup() { + // marker 兜住全部本次插入行(含当初误用真实单号插的那条),前缀是双保险 + await pool().query( + `DELETE FROM ${SCHEMA}.quote_sheet_change_requests + WHERE base_items_fingerprint = 'fp-test-integration' OR quote_sheet_code LIKE 'QS_TESTQCR_%'` + ); + // P3-1 临时报价单(正常用例会先删;失败时兜底) + await pool().query( + `DELETE FROM ${SCHEMA}.customer_quote_sheet_items WHERE quote_sheet_code LIKE 'QS_TESTQCR_%'` + ).catch(() => undefined); + await pool().query( + `DELETE FROM ${SCHEMA}.customer_quote_sheets WHERE quote_sheet_code LIKE 'QS_TESTQCR_%'` + ).catch(() => undefined); + // A26 审计行:本次测试的驳回审计(按 target_table + 目标单号兜底清理) + await pool().query( + `DELETE FROM ${SCHEMA}.operation_logs + WHERE target_table = 'quote_sheet_change_requests' + AND target_id IN ( + SELECT id::text FROM ${SCHEMA}.quote_sheet_change_requests WHERE quote_sheet_code LIKE 'QS_TESTQCR_%' + )` + ).catch(() => undefined); +} + +/** 在租户上下文里插临时行(未限定 schema ⇒ 命中 tenant_br002) */ +async function insertChangeRequest(input: { + sheetCode: string; + status: 'pending' | 'approved'; + requestedBy: string; + reviewedBy: string | null; + payload: Record; +}) { + return real!.tenant.runWithTenantDbContext(BRANCH, async () => { + const result = await pool().query<{ id: string }>( + `INSERT INTO quote_sheet_change_requests + (branch_code, quote_sheet_code, payload, base_version_no, base_items_fingerprint, + status, requested_by, requested_at, reviewed_by, reviewed_at, applied_at, updated_at) + VALUES ($1, $2, $3::jsonb, 1, 'fp-test-integration', $4, + $5::uuid, NOW() - INTERVAL '1 hour', $6::uuid, NOW() - INTERVAL '30 minutes', NOW(), NOW()) + RETURNING id::text AS id`, + [ + BRANCH, + input.sheetCode, + JSON.stringify(input.payload), + input.status, + input.requestedBy, + input.reviewedBy, + ] + ); + return String(result.rows[0].id); + }); +} + +describe.skipIf(!RUN)('待审改价列表 · 真库(A29 回归)', () => { + beforeAll(async () => { + await cleanup(); + const profiles = await pool().query<{ id: string; name: string }>( + `SELECT id::text AS id, + COALESCE(NULLIF(TRIM(full_name), ''), NULLIF(TRIM(username), '')) AS name + FROM public.profiles + ORDER BY id + LIMIT 2` + ); + expect(profiles.rows.length, '需要至少 2 个 public.profiles 用户').toBeGreaterThanOrEqual(2); + profileA = profiles.rows[0]; + profileB = profiles.rows[1]; + + const sheet = await pool().query<{ quote_sheet_code: string }>( + `SELECT quote_sheet_code FROM ${SCHEMA}.customer_quote_sheets + WHERE status = 1 AND approval_status = 30 + ORDER BY created_at DESC + LIMIT 1` + ); + realSheetCode = sheet.rows[0]?.quote_sheet_code || SHEET_FALLBACK; + + await insertChangeRequest({ + sheetCode: SHEET_APPROVED, + status: 'approved', + requestedBy: profileA.id, + reviewedBy: profileB.id, + payload: { title: '改标题', items: [{ sku_code: 'SKU_TESTQCR_1', unit: '斤', sale_price: 11 }] }, + }); + await insertChangeRequest({ + sheetCode: SHEET_PENDING, + status: 'pending', + requestedBy: profileA.id, + reviewedBy: null, + payload: { + items: [ + { sku_code: 'SKU_TESTQCR_1', unit: '斤', sale_price: 11, price: 11, cost_price: 5 }, + { sku_code: 'SKU_TESTQCR_2', unit: '袋', sale_price: 20, price: 20, cost_price: 9 }, + ], + }, + }); + }); + + afterAll(async () => { + await cleanup(); + await pool().end(); + }); + + it('前提复现:auth.users 没有 full_name / username(旧写法必炸 42703)', async () => { + const columns = await pool().query<{ column_name: string }>( + `SELECT column_name FROM information_schema.columns + WHERE table_schema = 'auth' AND table_name = 'users'` + ); + const names = columns.rows.map((row) => String(row.column_name)); + expect(names).not.toContain('full_name'); + expect(names).not.toContain('username'); + // 直接证伪旧 SQL:走 auth.users 取 full_name 必然报错(这就是 500 的来源) + await expect( + pool().query(`SELECT ru.full_name FROM auth.users ru LIMIT 1`) + ).rejects.toThrow(/full_name/); + }); + + it('GET 列表(approved):requested_by_name / reviewed_by_name 都非空,且带回 payload', async () => { + const rows = await real!.tenant.runWithTenantDbContext(BRANCH, () => + real!.service.listQuoteSheetChangeRequests({ branchCode: BRANCH, status: 'approved' }) + ); + const row = rows.find((item) => item.quote_sheet_code === SHEET_APPROVED); + expect(row, 'approved 临时行应出现在列表里').toBeTruthy(); + expect(row!.requested_by_name).toBe(profileA.name); + expect(row!.reviewed_by_name).toBe(profileB.name); + expect(row!.requested_by_name && row!.requested_by_name.length).toBeGreaterThan(0); + expect(row!.reviewed_by_name && row!.reviewed_by_name.length).toBeGreaterThan(0); + expect(row!.payload.title).toBe('改标题'); + expect(row!.applied_at).toBeTruthy(); + }); + + it('GET 列表(pending):提交人非空 + 审核摘要(真库行上算得出来)', async () => { + // ⚠️ 用**独立测试单号**建 pending:绝不在真实报价单号上建 pending —— + // ① 会污染真实单的待审列表;② partial unique 让重复跑第二次直接 23505(踩过)。 + await insertChangeRequest({ + sheetCode: SHEET_SUMMARY, + status: 'pending', + requestedBy: profileA.id, + reviewedBy: null, + payload: { + items: [ + { sku_code: 'SKU_TESTQCR_1', unit: '斤', sale_price: 11, price: 11, cost_price: 5 }, + { sku_code: 'SKU_TESTQCR_2', unit: '袋', sale_price: 20, price: 20, cost_price: 9 }, + ], + }, + }); + + const rows = await real!.tenant.runWithTenantDbContext(BRANCH, () => + real!.service.listQuoteSheetChangeRequests({ branchCode: BRANCH, status: 'pending' }) + ); + const row = rows.find((item) => item.quote_sheet_code === SHEET_SUMMARY); + expect(row).toBeTruthy(); + expect(row!.requested_by_name).toBe(profileA.name); + expect(row!.summary?.items_provided).toBe(true); + expect(row!.summary?.item_count).toBe(2); + expect(Array.isArray(row!.summary?.lines)).toBe(true); + expect(row!.summary!.lines.length).toBe(2); + // 该测试单号在库里没有明细 ⇒ 两行都是"新增"(改前为 null、改后有值) + for (const line of row!.summary!.lines) { + expect(line.change).toBe('added'); + expect(line.before_sale_price).toBeNull(); + expect(line.after_sale_price).not.toBeNull(); + } + }); + + it('A26 驳回路径:真库真的写入 operation_logs(四要素),失败不影响主流程', async () => { + const sheetCode = 'QS_TESTQCR_AUDIT'; + const changeRequestId = await insertChangeRequest({ + sheetCode, + status: 'pending', + requestedBy: profileA.id, + reviewedBy: null, + payload: { items: [] }, + }); + + await real!.tenant.runWithTenantDbContext(BRANCH, () => + real!.service.rejectQuoteSheetChangeRequest({ + id: changeRequestId, + reason: '集成测试驳回', + ctx: { branchCode: BRANCH, userId: profileB.id, roles: ['admin'] } as any, + reviewedBy: profileB.id, + }) + ); + + const audit = await pool().query<{ + operator_id: string; + operation_type: string; + target_table: string; + target_id: string; + branch_code: string; + new_value: any; + }>( + `SELECT operator_id::text AS operator_id, operation_type, target_table, target_id::text AS target_id, + branch_code, new_value + FROM ${SCHEMA}.operation_logs + WHERE target_table = 'quote_sheet_change_requests' AND target_id = $1 + ORDER BY created_at DESC + LIMIT 5`, + [changeRequestId] + ); + const row = audit.rows.find((item) => item.operation_type === 'quote_sheet_change_request_reject'); + expect(row, '驳回必须留下 operation_logs 业务审计').toBeTruthy(); + expect(row!.operator_id).toBe(profileB.id); + expect(row!.branch_code).toBe(BRANCH); + expect(row!.new_value).toMatchObject({ status: 'rejected', action: 'reject', reason: '集成测试驳回' }); + + // 清理本用例的审计行(不留测试噪声) + await pool().query( + `DELETE FROM ${SCHEMA}.operation_logs WHERE target_table = 'quote_sheet_change_requests' AND target_id = $1`, + [changeRequestId] + ); + }); + + /** + * 红队第三轮 P3-1 真库复现:**目标单被硬删除**(单 + 明细都不在了)。 + * 旧实现先比指纹 ⇒ 空集让指纹"必然不一致" ⇒ 误走 `base_changed` 自动驳回;正确行为是 + * 409 `target_unavailable` + 变更单保持 pending + 零应用、零推送、零台账。 + */ + it('P3-1 真库:目标单被硬删 ⇒ 409 target_unavailable + 变更单 pending + 零推送/零台账', async () => { + const code = 'QS_TESTQCR_HARDDEL'; + await real!.tenant.runWithTenantDbContext(BRANCH, async () => { + await pool().query( + `INSERT INTO customer_quote_sheets + (quote_sheet_code, title, version_no, quote_cycle, effective_at, status, approval_status, branch_code, created_at, updated_at) + VALUES ($1, '硬删测试单', 1, 'month', NOW(), 1, 30, $2, NOW(), NOW())`, + [code, BRANCH] + ); + await pool().query( + `INSERT INTO customer_quote_sheet_items + (quote_sheet_code, sku_code, sku_name, unit, price, cost_price, sale_price, sort_order) + VALUES ($1, 'SKU_TESTQCR_HARD', '硬删商品', '斤', 10, 5, 10, 0)`, + [code] + ); + }); + const changeRequestId = await insertChangeRequest({ + sheetCode: code, + status: 'pending', + requestedBy: profileA.id, + reviewedBy: null, + payload: { + items: [{ sku_code: 'SKU_TESTQCR_HARD', unit: '斤', sale_price: 11, price: 11, cost_price: 5 }], + }, + }); + // 提交时指纹 = 当时明细(硬删前) + const submittedFingerprint = real!.service.quoteSheetItemsFingerprint([ + { sku_code: 'SKU_TESTQCR_HARD', unit: '斤', sale_price: 10 }, + ]); + await pool().query( + `UPDATE ${SCHEMA}.quote_sheet_change_requests SET base_items_fingerprint = $2 WHERE id = $1::uuid`, + [changeRequestId, submittedFingerprint] + ); + + // 硬删:报价单 + 明细一起消失(不经软删) + await real!.tenant.runWithTenantDbContext(BRANCH, async () => { + await pool().query(`DELETE FROM customer_quote_sheet_items WHERE quote_sheet_code = $1`, [code]); + await pool().query(`DELETE FROM customer_quote_sheets WHERE quote_sheet_code = $1`, [code]); + }); + + await expect( + real!.tenant.runWithTenantDbContext(BRANCH, () => + real!.service.approveQuoteSheetChangeRequest({ + id: changeRequestId, + ctx: { branchCode: BRANCH, userId: profileB.id, roles: ['admin'] } as any, + reviewedBy: profileB.id, + }) + ) + ).rejects.toMatchObject({ status: 409, code: 'target_unavailable', message: '报价单不存在' }); + + const cr = await pool().query<{ status: string; reject_reason: string | null }>( + `SELECT status, reject_reason FROM ${SCHEMA}.quote_sheet_change_requests WHERE id = $1::uuid`, + [changeRequestId] + ); + expect(cr.rows[0].status, '变更单必须保持 pending(不能自动 rejected)').toBe('pending'); + expect(cr.rows[0].reject_reason).toBeNull(); + + const ledger = await pool().query<{ n: number }>( + `SELECT count(*)::int AS n FROM public.main_system_quote_cost_pushes WHERE quote_sheet_code = $1`, + [code] + ); + expect(Number(ledger.rows[0].n), '零推送(台账不得出现该单的分公司行)').toBe(0); + + const sheet = await pool().query( + `SELECT 1 FROM ${SCHEMA}.customer_quote_sheets WHERE quote_sheet_code = $1`, + [code] + ); + expect(sheet.rows).toHaveLength(0); // 报价单没被"复活" + + await pool().query(`DELETE FROM ${SCHEMA}.quote_sheet_change_requests WHERE id = $1::uuid`, [changeRequestId]); + }); + + it('按 branch_code 过滤:别的分公司 code 取不到这批测试行', async () => { + const rows = await real!.tenant.runWithTenantDbContext(BRANCH, () => + real!.service.listQuoteSheetChangeRequests({ branchCode: OTHER_BRANCH, status: 'pending' }) + ); + expect(rows).toHaveLength(0); + }); +}); diff --git a/server/tests/quoteSheetCostSyncTrigger.test.ts b/server/tests/quoteSheetCostSyncTrigger.test.ts new file mode 100644 index 0000000..8d7ffb6 --- /dev/null +++ b/server/tests/quoteSheetCostSyncTrigger.test.ts @@ -0,0 +1,282 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +/** + * 报价单**生效之后**的推送接线(`quoteSheetService.ts` 三处 `activateQuoteSheet` 调用点)。 + * + * 钉住四条纪律(做反就要返工): + * ① 出网必须在 `COMMIT` **之后**(HTTP 永远不在数据库事务里); + * ② 推送失败(对方 403 / 5xx / 网络抛错)**不得**让审批/建单失败; + * ③ 开关默认关 ⇒ 零出站、零台账写入; + * ④ 推送的 body 来自该单明细(`sku_code` / `unit` / `sale_price`),请求号取自台账那行。 + */ + +/* ── mock:DB(脚本化 fake client)────────────────────────────────────────── */ + +const poolQuery = vi.hoisted(() => vi.fn()); +const clientQuery = vi.hoisted(() => vi.fn()); +const clientRelease = vi.hoisted(() => vi.fn()); +vi.mock('../src/db', () => ({ + pool: { + query: (...args: unknown[]) => poolQuery(...args), + connect: async () => ({ + query: (...args: unknown[]) => clientQuery(...args), + release: () => clientRelease(), + }), + }, + getRawPoolQuery: () => poolQuery, +})); + +// 旁路任务自带租户上下文(本测试不需要真 schema,直接执行回调) +vi.mock('../src/services/tenantDbContext', () => ({ + runWithTenantDbContext: async (_code: string, fn: () => Promise) => fn(), +})); + +vi.mock('../src/services/mainSystem/token', () => ({ + getMainSystemToken: async () => ({ + kind: 'ok', + token: 'tok-1', + branchCode: 'BR002', + expiresAt: Date.now() + 60_000, + }), +})); + +vi.mock('../src/services/mainSystem/config', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + isMainSystemIntegrationEnabled: () => true, + mainSystemBaseUrl: () => 'http://main-system.example', + }; +}); + +const fetchMock = vi.hoisted(() => vi.fn()); +vi.stubGlobal('fetch', fetchMock); + +import { approveQuoteSheet, createQuoteSheet } from '../src/services/quoteSheetService'; + +/** 事件顺序:BEGIN / COMMIT / LEDGER_* / FETCH 都记在这里 */ +const events: string[] = []; + +function activeSheet() { + return { + quote_sheet_code: 'QS1', + branch_code: 'BR002', + title: '报价单 V1', + version_no: 1, + status: 1, + approval_status: 30, + approved_at: '2026-10-18T01:00:00.000Z', + effective_at: '2026-10-18T01:00:00.000Z', + expires_at: new Date(Date.now() + 86400_000).toISOString(), + }; +} + +function ledgerInsertParams(): unknown[] | null { + const call = poolQuery.mock.calls.find(([sql]) => String(sql).includes('RETURNING id::text AS id')); + return call ? (call[1] as unknown[]) : null; +} + +function setupDb(): void { + events.length = 0; + poolQuery.mockImplementation(async (sql: string, params: unknown[] = []) => { + if (String(sql).includes('RETURNING id::text AS id')) { + events.push('LEDGER_INSERT'); + return { rows: [{ id: 'lid-1', client_request_id: params[3] }], rowCount: 1 }; + } + if (String(sql).includes('UPDATE public.main_system_quote_cost_pushes')) { + events.push(`LEDGER_${String(params[1])}`); + return { rows: [], rowCount: 1 }; + } + if (String(sql).includes('AS code')) return { rows: [{ code: 'SUP37831443' }] }; + if (String(sql).includes('SELECT quote_sheet_code, branch_code, status, approval_status')) { + return { rows: [activeSheet()] }; + } + if (String(sql).includes('ORDER BY customer_code ASC')) { + return { rows: [{ customer_code: 'MAIN_BR002' }] }; + } + if (String(sql).includes('FROM customer_quote_sheet_items') && String(sql).includes('sale_price')) { + return { rows: [{ sku_code: 'SKU1', unit: '斤', sale_price: '8.80', price: '8.80' }] }; + } + if (String(sql).includes('SELECT * FROM customer_quote_sheets')) return { rows: [activeSheet()] }; + if (String(sql).includes('RETURNING quote_sheet_code')) { + return { rows: [{ quote_sheet_code: 'QS1' }], rowCount: 1 }; + } + if (String(sql).includes('SELECT quote_sheet_code FROM customer_quote_sheets')) { + return { rows: [{ quote_sheet_code: 'QS1' }] }; + } + if (String(sql).includes('FROM customers WHERE customer_code = ANY')) { + const codes = (params[0] as string[]) || []; + return { rows: codes.map((customer_code) => ({ customer_code })) }; + } + // loadSheetDetail 的 items/customers(带 sort_order / JOIN customers 的两种) + return { rows: [] }; + }); + + clientQuery.mockImplementation(async (sql: string) => { + const text = String(sql).trim().toUpperCase(); + if (text === 'BEGIN') { + events.push('BEGIN'); + return { rows: [] }; + } + if (text === 'COMMIT') { + events.push('COMMIT'); + return { rows: [] }; + } + if (text === 'ROLLBACK') { + events.push('ROLLBACK'); + return { rows: [] }; + } + if (String(sql).includes('UPDATE customer_quote_sheets') && String(sql).includes('RETURNING *')) { + return { rows: [activeSheet()] }; + } + return { rows: [] }; + }); +} + +function jsonResponse(status: number, body: unknown) { + return { ok: status >= 200 && status < 300, status, json: async () => body }; +} + +const OK_PAYLOAD = { + success: true, + data: { + client_request_id: 'x', + replayed: false, + main_branch_code: 'BR002', + updated: 1, + sheets: ['QS-THEIR'], + skipped: [], + warnings: [], + }, +}; + +async function waitFor(check: () => void, timeoutMs = 2000): Promise { + const started = Date.now(); + while (Date.now() - started < timeoutMs) { + try { + check(); + return; + } catch { + await new Promise((resolve) => setTimeout(resolve, 10)); + } + } + check(); +} + +beforeEach(() => { + poolQuery.mockReset(); + clientQuery.mockReset(); + clientRelease.mockReset(); + fetchMock.mockReset(); + delete process.env.MAIN_SYSTEM_QUOTE_COST_SYNC; + setupDb(); + fetchMock.mockImplementation(async () => { + events.push('FETCH'); + return jsonResponse(200, OK_PAYLOAD); + }); +}); + +describe('审批生效 ⇒ 事务提交之后才出网', () => { + beforeEach(() => { + process.env.MAIN_SYSTEM_QUOTE_COST_SYNC = '1'; + }); + + it('approveQuoteSheet:COMMIT 早于 FETCH,body 来自明细、请求号取自台账', async () => { + const detail = await approveQuoteSheet({ + quoteSheetCode: 'QS1', + approved: true, + ctx: { branchCode: 'BR002', isSuperAdmin: false } as any, + }); + // 审批本身正常返回(不被旁路推送影响) + expect(detail?.quote_sheet_code).toBe('QS1'); + + await waitFor(() => expect(events).toContain('FETCH')); + expect(events).toContain('COMMIT'); + expect(events.indexOf('COMMIT')).toBeGreaterThan(-1); + expect(events.indexOf('COMMIT')).toBeLessThan(events.indexOf('FETCH')); + expect(events).toContain('LEDGER_INSERT'); + expect(events).toContain('LEDGER_sent'); + + const [url, init] = fetchMock.mock.calls[0] as [string, any]; + expect(url).toBe('http://main-system.example/api/supplier/quote-sheets/cost-sync'); + const body = JSON.parse(init.body); + expect(body.supplier_quote_sheet_code).toBe('QS1'); + expect(body.main_branch_code).toBe('BR002'); + expect(body.items).toEqual([{ sku_code: 'SKU1', unit: '斤', sale_price: 8.8 }]); + // 请求号 = 落台账时的那个(重试复用同一个,不是每次新生成) + expect(body.client_request_id).toBe(ledgerInsertParams()?.[3]); + }); + + it('createQuoteSheet(旧接口:建单即生效)同样在 COMMIT 之后出网', async () => { + const detail = await createQuoteSheet({ + customerCodes: ['MAIN_BR002'], + items: [{ sku_code: 'SKU1', unit: '斤', sale_price: 8.8 }], + branchCode: 'BR002', + }); + expect(detail?.quote_sheet_code).toBe('QS1'); + await waitFor(() => expect(events).toContain('FETCH')); + expect(events.indexOf('COMMIT')).toBeLessThan(events.indexOf('FETCH')); + }); +}); + +describe('推送失败不得影响审批/建单', () => { + beforeEach(() => { + process.env.MAIN_SYSTEM_QUOTE_COST_SYNC = '1'; + }); + + it('对方 403 ⇒ 审批照常成功,台账记 forbidden', async () => { + events.length = 0; + fetchMock.mockImplementation(async () => { + events.push('FETCH'); + return jsonResponse(403, { error: 'branch_not_bound', error_description: '未绑定' }); + }); + const detail = await approveQuoteSheet({ + quoteSheetCode: 'QS1', + approved: true, + ctx: { branchCode: 'BR002', isSuperAdmin: false } as any, + }); + expect(detail?.quote_sheet_code).toBe('QS1'); + await waitFor(() => expect(events).toContain('LEDGER_forbidden')); + }); + + it('出站网络抛错 ⇒ 审批照常成功,台账记 failed(可重试),无未处理拒绝', async () => { + events.length = 0; + fetchMock.mockImplementation(async () => { + events.push('FETCH'); + throw new Error('ECONNRESET'); + }); + const detail = await approveQuoteSheet({ + quoteSheetCode: 'QS1', + approved: true, + ctx: { branchCode: 'BR002', isSuperAdmin: false } as any, + }); + expect(detail?.quote_sheet_code).toBe('QS1'); + await waitFor(() => expect(events).toContain('LEDGER_failed')); + }); + + it('驳回(approved:false)不推送、不写台账', async () => { + const detail = await approveQuoteSheet({ + quoteSheetCode: 'QS1', + approved: false, + ctx: { branchCode: 'BR002', isSuperAdmin: false } as any, + }); + expect(detail?.quote_sheet_code).toBe('QS1'); + await new Promise((resolve) => setTimeout(resolve, 80)); + expect(fetchMock).not.toHaveBeenCalled(); + expect(events).not.toContain('LEDGER_INSERT'); + }); +}); + +describe('开关默认关 ⇒ 零出站、零台账', () => { + it('开关未设时,审批成功但一个外部请求都不发', async () => { + const detail = await approveQuoteSheet({ + quoteSheetCode: 'QS1', + approved: true, + ctx: { branchCode: 'BR002', isSuperAdmin: false } as any, + }); + expect(detail?.quote_sheet_code).toBe('QS1'); + await new Promise((resolve) => setTimeout(resolve, 80)); + expect(fetchMock).not.toHaveBeenCalled(); + expect(events).not.toContain('LEDGER_INSERT'); + }); +}); diff --git a/server/tests/quoteSheetUpdateApply.test.ts b/server/tests/quoteSheetUpdateApply.test.ts new file mode 100644 index 0000000..f334ad2 --- /dev/null +++ b/server/tests/quoteSheetUpdateApply.test.ts @@ -0,0 +1,290 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +/** + * `applyQuoteSheetUpdate` 抽取的**行为不变**守卫(2026-10-18 增量): + * · `updateQuoteSheet` 仍是「自己开事务 → DELETE+INSERT 明细 → 刷版本 → COMMIT」, + * 与原实现逐字一致(搬动代码不得改口径); + * · **审批通过**走 `applyQuoteSheetUpdate(..., { client })`:在调用方事务内执行, + * **不得**自己 BEGIN/COMMIT; + * · 两条路径都**不碰审批字段**(`approval_status` / `approved_by` / `approved_at` / `status`), + * 也不得把同分公司共享客户的其它生效单置 `status=3`(那是 `activateQuoteSheet` 的行为,本路径禁止调用它)。 + */ + +const poolQuery = vi.hoisted(() => vi.fn()); +const clientQuery = vi.hoisted(() => vi.fn()); +const clientRelease = vi.hoisted(() => vi.fn()); +vi.mock('../src/db', () => ({ + pool: { + query: (...args: unknown[]) => poolQuery(...args), + connect: async () => ({ + query: (...args: unknown[]) => clientQuery(...args), + release: () => clientRelease(), + }), + }, + getRawPoolQuery: () => poolQuery, +})); +vi.mock('../src/services/notificationService', () => ({ notifyRoleUsers: vi.fn() })); + +import { applyQuoteSheetUpdate, updateQuoteSheet } from '../src/services/quoteSheetService'; + +const SHEET = 'QS1'; +const BRANCH = 'BR002'; + +type State = { + events: string[]; + sheet: Record; + items: Array>; + customers: string[]; +}; + +function makeState(): State { + return { + events: [], + sheet: { + quote_sheet_code: SHEET, + branch_code: BRANCH, + title: '报价单 V1', + version_no: 1, + quote_cycle: 'month', + status: 1, + approval_status: 30, + approved_by: 'u-approver', + approved_at: '2026-10-17T00:00:00.000Z', + effective_at: '2026-10-17T00:00:00.000Z', + expires_at: new Date(Date.now() + 86400_000).toISOString(), + auto_sale_price_by_cost: false, + }, + items: [ + { quote_sheet_code: SHEET, sku_code: 'SKU1', unit: '斤', sale_price: '10.00', price: '10.00', cost_price: '5.00', sort_order: 0 }, + ], + customers: ['MAIN_BR002'], + }; +} + +function installDb(state: State): void { + const handler = async (sql: string, params: unknown[] = [], fromClient: boolean) => { + const text = String(sql); + if (/^\s*(BEGIN|COMMIT|ROLLBACK)\s*;?\s*$/i.test(text)) { + if (fromClient) state.events.push(text.trim().toUpperCase()); + return { rows: [], rowCount: 0 }; + } + if (text.includes('UPDATE customer_quote_sheets') && text.includes('SET title = COALESCE')) { + state.events.push('UPDATE_SHEET'); + return { rows: [], rowCount: 1 }; + } + if (text.includes('DELETE FROM customer_quote_sheet_customers')) { + state.events.push('DELETE_CUSTOMERS'); + state.customers = []; + return { rows: [], rowCount: 1 }; + } + if (text.includes('INSERT INTO customer_quote_sheet_customers')) { + state.events.push('INSERT_CUSTOMER'); + state.customers.push(String(params[1])); + return { rows: [], rowCount: 1 }; + } + if (text.includes('DELETE FROM customer_quote_sheet_items')) { + state.events.push('DELETE_ITEMS'); + state.items = []; + return { rows: [], rowCount: 1 }; + } + if (text.includes('INSERT INTO customer_quote_sheet_items')) { + state.events.push('INSERT_ITEM'); + state.items.push({ + quote_sheet_code: String(params[0]), + sku_code: String(params[1]), + sku_name: params[2], + unit: params[3], + price: String(params[4]), + cost_price: String(params[5]), + sale_price: String(params[6]), + markup_ratio: params[7], + sort_order: params[8], + }); + return { rows: [], rowCount: 1 }; + } + if (text.includes('UPDATE customer_quote_versions') && text.includes('SET status = 0')) { + state.events.push('VERSION_EXPIRE'); + return { rows: [], rowCount: 0 }; + } + if (text.includes('INSERT INTO customer_quote_versions')) { + state.events.push('VERSION_INSERT'); + return { rows: [], rowCount: 1 }; + } + if (text.includes('SELECT COALESCE(MAX(version_no)')) { + return { rows: [{ next_version: 2 }] }; + } + if (text.includes('FROM customer_quote_sheet_items') && text.includes('ORDER BY sort_order')) { + return { rows: state.items, rowCount: state.items.length }; + } + if (text.includes('FROM customer_quote_sheet_items')) { + return { rows: state.items, rowCount: state.items.length }; + } + if (text.includes('FROM customer_quote_sheet_customers') && text.includes('JOIN customers')) { + return { rows: state.customers.map((customer_code) => ({ customer_code, company_name: '客户' })) }; + } + if (text.includes('FROM customer_quote_sheet_customers')) { + return { rows: state.customers.map((customer_code) => ({ customer_code })), rowCount: state.customers.length }; + } + if (text.includes('FROM customers WHERE customer_code = ANY($1)')) { + const codes = (params[0] as string[]) || []; + return { rows: codes.map((customer_code) => ({ customer_code })), rowCount: codes.length }; + } + if (text.includes('FROM customer_quote_sheets')) { + return { rows: [state.sheet], rowCount: 1 }; + } + return { rows: [], rowCount: 0 }; + }; + poolQuery.mockImplementation((sql: string, params?: unknown[]) => handler(sql, params || [], false)); + clientQuery.mockImplementation((sql: string, params?: unknown[]) => handler(sql, params || [], true)); +} + +const ITEMS = [ + { sku_code: 'SKU1', unit: '斤', sale_price: 11, price: 11, cost_price: 5, sku_name: '草鱼' }, + { sku_code: 'SKU2', unit: '袋', sale_price: 20, price: 20, cost_price: 9, sku_name: '鲤鱼' }, +]; + +function allSql(state: State): string[] { + return [...state.events]; +} + +beforeEach(() => { + poolQuery.mockReset(); + clientQuery.mockReset(); + clientRelease.mockReset(); + delete process.env.QUOTE_EDIT_APPROVAL; +}); + +describe('updateQuoteSheet(行为不变)', () => { + it('自己开事务:BEGIN → 改单头 → DELETE+INSERT 明细 → 刷版本 → COMMIT', async () => { + const state = makeState(); + installDb(state); + const detail = await updateQuoteSheet({ + quoteSheetCode: SHEET, + items: ITEMS, + ctx: { branchCode: BRANCH } as any, + }); + + expect(detail?.quote_sheet_code).toBe(SHEET); + const order = state.events.filter((event) => + ['BEGIN', 'UPDATE_SHEET', 'DELETE_ITEMS', 'INSERT_ITEM', 'VERSION_EXPIRE', 'VERSION_INSERT', 'COMMIT'].includes(event) + ); + expect(order[0]).toBe('BEGIN'); + expect(order[order.length - 1]).toBe('COMMIT'); + expect(order).toContain('DELETE_ITEMS'); + expect(order.filter((event) => event === 'INSERT_ITEM')).toHaveLength(2); + expect(order).toContain('VERSION_EXPIRE'); + expect(order).toContain('VERSION_INSERT'); + expect(clientRelease).toHaveBeenCalledTimes(1); + }); + + it('明细写入口径不变:price/sale_price 同值、cost_price 夹到 >=0、unit trim', async () => { + const state = makeState(); + installDb(state); + await updateQuoteSheet({ + quoteSheetCode: SHEET, + items: [{ sku_code: 'SKU9', unit: ' 盒 ', sale_price: 12.5, cost_price: -3 }], + ctx: { branchCode: BRANCH } as any, + }); + expect(state.items).toHaveLength(1); + expect(state.items[0]).toMatchObject({ + sku_code: 'SKU9', + unit: '盒', + price: '12.5', + sale_price: '12.5', + cost_price: '0', + }); + }); + + it('只改标题(不带 items/customer_codes)⇒ 不删不改明细、不删客户', async () => { + const state = makeState(); + installDb(state); + await updateQuoteSheet({ quoteSheetCode: SHEET, title: '新标题', ctx: { branchCode: BRANCH } as any }); + expect(state.events).toContain('UPDATE_SHEET'); + expect(state.events).not.toContain('DELETE_ITEMS'); + expect(state.events).not.toContain('DELETE_CUSTOMERS'); + expect(state.items).toHaveLength(1); + }); + + it('**不碰审批字段、不置其它共享单为 3**(不能走 activateQuoteSheet)', async () => { + const state = makeState(); + installDb(state); + const seen: string[] = []; + const record = (sql: unknown) => { + seen.push(String(sql)); + return undefined; + }; + poolQuery.mockImplementation(async (sql: string, params?: unknown[]) => { + record(sql); + return (await installDbAndCall(state, sql, params)) as any; + }); + clientQuery.mockImplementation(async (sql: string, params?: unknown[]) => { + record(sql); + return (await installDbAndCall(state, sql, params)) as any; + }); + await updateQuoteSheet({ quoteSheetCode: SHEET, items: ITEMS, ctx: { branchCode: BRANCH } as any }); + for (const sql of seen) { + expect(sql, sql).not.toMatch(/approval_status\s*=\s*30/); + expect(sql, sql).not.toMatch(/approved_by\s*=/); + expect(sql, sql).not.toMatch(/SET\s+status\s*=\s*3/i); + expect(sql, sql).not.toMatch(/quote_sheet_code\s*<>\s*\$1/); + } + expect(allSql(state).length).toBeGreaterThan(0); + }); +}); + +/** 在断言 SQL 文本的同时复用同一套 DB 语义 */ +async function installDbAndCall(state: State, sql: string, params?: unknown[]) { + const handlerState = state; + const text = String(sql); + if (/^\s*(BEGIN|COMMIT|ROLLBACK)\s*;?\s*$/i.test(text)) { + handlerState.events.push(text.trim().toUpperCase()); + return { rows: [], rowCount: 0 }; + } + if (text.includes('UPDATE customer_quote_sheets') && text.includes('SET title = COALESCE')) { + handlerState.events.push('UPDATE_SHEET'); + return { rows: [], rowCount: 1 }; + } + if (text.includes('DELETE FROM customer_quote_sheet_items')) { + handlerState.events.push('DELETE_ITEMS'); + handlerState.items = []; + return { rows: [], rowCount: 1 }; + } + if (text.includes('INSERT INTO customer_quote_sheet_items')) { + handlerState.events.push('INSERT_ITEM'); + handlerState.items.push({ sku_code: String(params?.[1]) }); + return { rows: [], rowCount: 1 }; + } + if (text.includes('UPDATE customer_quote_versions') && text.includes('SET status = 0')) { + handlerState.events.push('VERSION_EXPIRE'); + return { rows: [], rowCount: 0 }; + } + if (text.includes('INSERT INTO customer_quote_versions')) { + handlerState.events.push('VERSION_INSERT'); + return { rows: [], rowCount: 1 }; + } + if (text.includes('SELECT COALESCE(MAX(version_no)')) return { rows: [{ next_version: 2 }] }; + if (text.includes('FROM customer_quote_sheet_items')) return { rows: handlerState.items, rowCount: handlerState.items.length }; + if (text.includes('FROM customer_quote_sheet_customers')) { + return { rows: handlerState.customers.map((customer_code) => ({ customer_code, company_name: '客户' })) }; + } + if (text.includes('FROM customer_quote_sheets')) return { rows: [handlerState.sheet], rowCount: 1 }; + return { rows: [], rowCount: 0 }; +} + +describe('applyQuoteSheetUpdate({ client })(审核通过路径)', () => { + it('传入 client 时**不自己** BEGIN/COMMIT/ROLLBACK(事务归调用方)', async () => { + const state = makeState(); + installDb(state); + const detail = await applyQuoteSheetUpdate( + { quoteSheetCode: SHEET, items: ITEMS, ctx: { branchCode: BRANCH } as any }, + { client: { query: (...args: unknown[]) => clientQuery(...args) } as any } + ); + expect(detail?.quote_sheet_code).toBe(SHEET); + expect(state.events).not.toContain('BEGIN'); + expect(state.events).not.toContain('COMMIT'); + expect(state.events).not.toContain('ROLLBACK'); + expect(clientRelease).not.toHaveBeenCalled(); + expect(state.events).toContain('DELETE_ITEMS'); + expect(state.events.filter((event) => event === 'INSERT_ITEM')).toHaveLength(2); + }); +}); diff --git a/server/tests/skuMapping.test.ts b/server/tests/skuMapping.test.ts new file mode 100644 index 0000000..4179c43 --- /dev/null +++ b/server/tests/skuMapping.test.ts @@ -0,0 +1,491 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +/** + * **SKU 映射**(2026-10-18 冻结契约 `.team/sku-mapping-shared-sheet/contract.md` §5)服务层守卫。 + * + * 钉住: + * · 开关关闭 ⇒ **零出站**(D4/D5 一次都不发); + * · D4:只推 `status` 有效的商品,>5000 自动分批,汇总 matched/pending/kept/total; + * · D5:按 `next_cursor` 翻页;幂等 upsert;**完整拉取**才删除远端已不存在的行(截断不删); + * · 方向 B 反查:只认 `status='active'` 且 `delivery_sku_code` 非空;映射不可编辑(无写接口); + * · 提交前统计:total / mapped / unmapped(不按名称猜)。 + */ + +const poolQuery = vi.hoisted(() => vi.fn()); +const clientQuery = vi.hoisted(() => vi.fn()); +vi.mock('../src/db', () => ({ + pool: { + query: (...args: unknown[]) => poolQuery(...args), + connect: async () => ({ query: (...args: unknown[]) => clientQuery(...args), release: () => undefined }), + }, + getRawPoolQuery: () => poolQuery, +})); + +const tenantCtx = vi.hoisted(() => vi.fn()); +vi.mock('../src/services/tenantDbContext', () => ({ + runWithTenantDbContext: (...args: unknown[]) => tenantCtx(...args), +})); + +const resolveMainSupplierCode = vi.hoisted(() => vi.fn()); +vi.mock('../src/services/mainSystemQuoteCostSync', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, resolveMainSupplierCode: (...a: unknown[]) => resolveMainSupplierCode(...a) }; +}); + +const pushSkuDictionary = vi.hoisted(() => vi.fn()); +const pullSkuMappings = vi.hoisted(() => vi.fn()); +vi.mock('../src/services/mainSystem/api/skuMappings', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + pushSkuDictionary: (...a: unknown[]) => pushSkuDictionary(...a), + pullSkuMappings: (...a: unknown[]) => pullSkuMappings(...a), + }; +}); + +import { + getMappingByDeliverySku, + getSheetMappingStats, + isSkuMappingEnabled, + listLocalSkuMappings, + pullMappingsForAllBranches, + pullMappingsFromMainSystem, + pushSkuDictionaryForBranch, +} from '../src/services/skuMappingService'; + +type MappingRow = { + supplier_sku_code: string; + supplier_sku_name: string | null; + supplier_unit: string | null; + delivery_sku_code: string | null; + delivery_sku_name: string | null; + status: string; + synced_at?: string; +}; + +type State = { + skus: Array<{ sku_code: string; sku_name: string | null; unit: string | null; status?: number | null }>; + mappings: MappingRow[]; + sheetItems: Array<{ sku_code: string; sku_name: string | null }>; + bindings: string[]; + sql: string[]; +}; + +function makeState(overrides: Partial = {}): State { + return { + skus: [ + { sku_code: 'SKU1', sku_name: '草鱼', unit: '斤', status: 1 }, + { sku_code: 'SKU2', sku_name: '鲤鱼', unit: '袋', status: 1 }, + { sku_code: 'SKU9', sku_name: '停用商品', unit: '斤', status: 0 }, + ], + mappings: [ + { supplier_sku_code: 'SKU1', supplier_sku_name: '草鱼', supplier_unit: '斤', delivery_sku_code: 'D-001', delivery_sku_name: '草鱼(配送)', status: 'active' }, + { supplier_sku_code: 'SKU2', supplier_sku_name: '鲤鱼', supplier_unit: '袋', delivery_sku_code: null, delivery_sku_name: null, status: 'pending' }, + ], + sheetItems: [ + { sku_code: 'SKU1', sku_name: '草鱼' }, + { sku_code: 'SKU2', sku_name: '鲤鱼' }, + { sku_code: 'SKU3', sku_name: '鲫鱼' }, + ], + bindings: ['BR002'], + sql: [], + ...overrides, + }; +} + +function installDb(state: State): void { + const handler = async (sql: string, params: unknown[] = []) => { + const text = String(sql); + state.sql.push(text); + if (text.includes('FROM skus')) { + return { rows: state.skus.filter((row) => row.status === undefined || row.status === null || row.status === 1) }; + } + if (text.includes('INSERT INTO main_system_sku_mappings')) { + const row: MappingRow = { + supplier_sku_code: String(params[0]), + supplier_sku_name: (params[1] as string) ?? null, + supplier_unit: (params[2] as string) ?? null, + delivery_sku_code: (params[3] as string) ?? null, + delivery_sku_name: (params[4] as string) ?? null, + status: String(params[5]), + synced_at: new Date().toISOString(), + }; + const existing = state.mappings.findIndex((m) => m.supplier_sku_code === row.supplier_sku_code); + if (existing >= 0) state.mappings[existing] = row; + else state.mappings.push(row); + return { rows: [], rowCount: 1 }; + } + if (text.includes('DELETE FROM main_system_sku_mappings') && text.includes('<> ALL')) { + const keep = new Set((params[0] as string[]) || []); + const before = state.mappings.length; + state.mappings = state.mappings.filter((row) => keep.has(row.supplier_sku_code)); + return { rows: [], rowCount: before - state.mappings.length }; + } + if (text.includes('FROM main_system_sku_mappings') && text.includes('delivery_sku_code = $1')) { + const row = state.mappings.find( + (m) => m.delivery_sku_code === String(params[0]) && m.status === 'active' + ); + return { rows: row ? [row] : [], rowCount: row ? 1 : 0 }; + } + if (text.includes('FROM main_system_sku_mappings') && text.includes('delivery_sku_code = ANY')) { + const list = new Set((params[0] as string[]) || []); + return { rows: state.mappings.filter((m) => m.delivery_sku_code && list.has(m.delivery_sku_code)) }; + } + if (text.includes('FROM main_system_sku_mappings') && text.includes('supplier_sku_code = ANY')) { + const list = new Set((params[0] as string[]) || []); + return { rows: state.mappings.filter((m) => list.has(m.supplier_sku_code)) }; + } + if (text.includes('count(*)::int AS total') && text.includes('FROM main_system_sku_mappings')) { + const total = state.mappings.length; + const mapped = state.mappings.filter((m) => m.status === 'active' && m.delivery_sku_code).length; + return { rows: [{ total, mapped }], rowCount: 1 }; + } + if (text.includes('FROM main_system_sku_mappings') && text.includes('ORDER BY')) { + return { rows: state.mappings, rowCount: state.mappings.length }; + } + if (text.includes('FROM customer_quote_sheet_items')) { + return { rows: state.sheetItems, rowCount: state.sheetItems.length }; + } + if (text.includes('DISTINCT branch_code FROM public.main_supplier_bindings')) { + return { rows: state.bindings.map((branch_code) => ({ branch_code })) }; + } + return { rows: [], rowCount: 0 }; + }; + poolQuery.mockImplementation((sql: string, params?: unknown[]) => handler(sql, params || [])); + clientQuery.mockImplementation((sql: string, params?: unknown[]) => handler(sql, params || [])); +} + +beforeEach(() => { + poolQuery.mockReset(); + clientQuery.mockReset(); + resolveMainSupplierCode.mockReset(); + pushSkuDictionary.mockReset(); + pullSkuMappings.mockReset(); + tenantCtx.mockReset(); + tenantCtx.mockImplementation(async (_branch: string, fn: () => Promise) => fn()); + resolveMainSupplierCode.mockResolvedValue('SUP-37831443'); + delete process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL; +}); + +describe('开关', () => { + it('未设置 / 0 ⇒ 关闭;1/true/on ⇒ 打开', () => { + expect(isSkuMappingEnabled()).toBe(false); + process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1'; + expect(isSkuMappingEnabled()).toBe(true); + process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '0'; + expect(isSkuMappingEnabled()).toBe(false); + }); + + it('关闭 ⇒ 零出站:推字典 503、拉映射空跑、定时任务 skipped', async () => { + installDb(makeState()); + await expect(pushSkuDictionaryForBranch({ branchCode: 'BR002' })).rejects.toMatchObject({ + status: 503, + code: 'feature_disabled', + }); + const pulled = await pullMappingsFromMainSystem({ branchCode: 'BR002' }); + expect(pulled).toMatchObject({ upserted: 0, deleted: 0, truncated: false }); + const all = await pullMappingsForAllBranches(); + expect(all.skipped).toBe(true); + expect(pushSkuDictionary).not.toHaveBeenCalled(); + expect(pullSkuMappings).not.toHaveBeenCalled(); + expect(poolQuery).not.toHaveBeenCalled(); + }); +}); + +describe('D4 推送商品字典', () => { + beforeEach(() => { + process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1'; + }); + + it('只推 status 有效的商品;>5000 自动分批;汇总 matched/pending/kept/total', async () => { + const state = makeState(); + state.skus = [ + ...Array.from({ length: 5001 }, (_, i) => ({ + sku_code: `SKU${i}`, + sku_name: `商品${i}`, + unit: '斤', + status: 1, + })), + { sku_code: 'SKU_DISABLED', sku_name: '停用商品', unit: '斤', status: 0 }, + ]; + installDb(state); + pushSkuDictionary + .mockResolvedValueOnce({ kind: 'ok', status: 200, data: { matched: 3, pending: 0, kept: 0, total: 5000 } }) + .mockResolvedValueOnce({ kind: 'ok', status: 200, data: { matched: 1, pending: 0, kept: 0, total: 1 } }); + + const summary = await pushSkuDictionaryForBranch({ branchCode: 'BR002' }); + expect(pushSkuDictionary).toHaveBeenCalledTimes(2); + expect((pushSkuDictionary.mock.calls[0][0] as any).items).toHaveLength(5000); + expect((pushSkuDictionary.mock.calls[1][0] as any).items).toHaveLength(1); + expect(summary).toMatchObject({ skus: 5001, batches: 2, matched: 4, total: 5001 }); + // 停用商品没有被推 + const pushedCodes = pushSkuDictionary.mock.calls.flatMap(([arg]) => + (arg as any).items.map((item: any) => item.sku_code) + ); + expect(pushedCodes).not.toContain('SKU_DISABLED'); + }); + + it('D4 失败 ⇒ 抛错(rejected 状态码透传,unavailable 转 502)', async () => { + installDb(makeState()); + pushSkuDictionary.mockResolvedValueOnce({ + kind: 'rejected', + status: 403, + code: 'forbidden', + reason: '未绑定该分公司', + payload: null, + }); + await expect(pushSkuDictionaryForBranch({ branchCode: 'BR002' })).rejects.toMatchObject({ + status: 403, + code: 'forbidden', + }); + }); +}); + +describe('D5 拉映射', () => { + beforeEach(() => { + process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1'; + }); + + it('按 next_cursor 翻页、幂等 upsert、完整拉取后删除远端已不存在的行', async () => { + const state = makeState({ + mappings: [ + // 远端已不存在的一行(完整拉取后应被删) + { supplier_sku_code: 'GONE', supplier_sku_name: '旧', supplier_unit: '斤', delivery_sku_code: 'D-X', delivery_sku_name: null, status: 'active' }, + ], + }); + installDb(state); + pullSkuMappings + .mockResolvedValueOnce({ + kind: 'ok', + status: 200, + rows: [ + { supplier_sku_code: 'SKU1', supplier_sku_name: '草鱼', supplier_unit: '斤', delivery_sku_code: 'D-001', delivery_sku_name: '草鱼(配送)', status: 'active', match_type: 'manual', updated_at: null }, + ], + nextCursor: 'p2', + total: null, + }) + .mockResolvedValueOnce({ + kind: 'ok', + status: 200, + rows: [ + { supplier_sku_code: 'SKU2', supplier_sku_name: '鲤鱼', supplier_unit: '袋', delivery_sku_code: null, delivery_sku_name: null, status: 'pending', match_type: 'none', updated_at: null }, + ], + nextCursor: null, + total: null, + }); + + const summary = await pullMappingsFromMainSystem({ branchCode: 'BR002' }); + expect(summary).toMatchObject({ total: 2, upserted: 2, deleted: 1, truncated: false, pages: 2 }); + expect(pullSkuMappings).toHaveBeenCalledTimes(2); + expect((pullSkuMappings.mock.calls[1][0] as any).cursor).toBe('p2'); + const codes = state.mappings.map((row) => row.supplier_sku_code).sort(); + expect(codes).toEqual(['SKU1', 'SKU2']); + expect(state.mappings.find((row) => row.supplier_sku_code === 'SKU1')!.status).toBe('active'); + }); + + it('翻页截断(>最大页数)⇒ 不删本地行(避免误删)', async () => { + const state = makeState(); + installDb(state); + const rows = [{ supplier_sku_code: 'SKU1', supplier_sku_name: '草鱼', supplier_unit: '斤', delivery_sku_code: 'D-001', delivery_sku_name: null, status: 'active', match_type: 'manual', updated_at: null }]; + let page = 0; + pullSkuMappings.mockImplementation(async () => ({ + kind: 'ok', + status: 200, + rows, + nextCursor: `c${++page}`, // 每页游标都不同,避免"游标不前进"提前 break + total: null, + })); + const summary = await pullMappingsFromMainSystem({ branchCode: 'BR002' }); + expect(summary.truncated).toBe(true); + expect(summary.deleted).toBe(0); + expect(summary.pages).toBe(50); + }); + + it('D5 第一页失败 ⇒ 本次只做空刷新、**不删**本地行、truncated=true(不抛错丢上下文)', async () => { + const state = makeState(); + installDb(state); + const before = JSON.stringify(state.mappings); + pullSkuMappings.mockResolvedValueOnce({ kind: 'unavailable', status: 502, code: 'main_system_error', reason: '对方不可用', payload: null }); + const summary = await pullMappingsFromMainSystem({ branchCode: 'BR002' }); + expect(summary).toMatchObject({ upserted: 0, deleted: 0, truncated: true, pages: 0 }); + expect(JSON.stringify(state.mappings)).toBe(before); + }); +}); + +describe('方向 B 反查与提交前统计', () => { + beforeEach(() => { + process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1'; + }); + + it('只认 active 且 delivery_sku_code 非空的映射', async () => { + installDb(makeState()); + expect(await getMappingByDeliverySku('BR002', 'D-001')).toMatchObject({ supplier_sku_code: 'SKU1' }); + expect(await getMappingByDeliverySku('BR002', 'NOT-MAPPED')).toBeNull(); + expect(await getMappingByDeliverySku('BR002', '')).toBeNull(); + }); + + it('提交前统计:total / mapped / unmapped + 未映射清单(不按名称猜)', async () => { + installDb(makeState()); + const stats = await getSheetMappingStats('QS1'); + expect(stats).toMatchObject({ total: 3, mapped: 1, unmapped: 2 }); + expect(stats.unmapped_skus.map((row) => row.sku_code)).toEqual(['SKU2', 'SKU3']); + }); + + it('只读列表带汇总(total/mapped/unmapped)', async () => { + installDb(makeState()); + const listed = await listLocalSkuMappings({ branchCode: 'BR002' }); + expect(listed.summary).toEqual({ total: 2, mapped: 1, unmapped: 1 }); + expect(listed.rows).toHaveLength(2); + }); +}); + +describe('定时任务', () => { + beforeEach(() => { + process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1'; + }); + + it('按 active 绑定分公司逐个拉取;单个失败记 errors 不中断其它', async () => { + installDb(makeState({ bindings: ['BR002', 'BR007'] })); + pullSkuMappings + .mockResolvedValueOnce({ kind: 'ok', status: 200, rows: [{ supplier_sku_code: 'SKU1', supplier_sku_name: '草鱼', supplier_unit: '斤', delivery_sku_code: 'D-001', delivery_sku_name: null, status: 'active', match_type: 'manual', updated_at: null }], nextCursor: null, total: null }) + .mockResolvedValueOnce({ kind: 'unavailable', status: 502, code: 'main_system_error', reason: '对方不可用', payload: null }); + const summary = await pullMappingsForAllBranches(); + expect(summary).toMatchObject({ branches: 2, pulled: 1, errors: 1, skipped: false }); + }); +}); + +/* ── verifier 阻断项(>200 行):完整性判据 + 截断绝不删本地行 ───────────────── */ + +describe('D5 完整性判据(>200 行不再误删本地映射)', () => { + beforeEach(() => { + process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1'; + }); + + const row = (code: string) => ({ + supplier_sku_code: code, + supplier_sku_name: code, + supplier_unit: '斤', + delivery_sku_code: `D-${code}`, + delivery_sku_name: null, + status: 'active', + match_type: 'manual', + updated_at: null, + }); + + it('首屏恰好 200 行、对方没给 next_cursor 也没给 total ⇒ 无法证明拉全 ⇒ truncated=true 且**不删**本地行', async () => { + const local = Array.from({ length: 250 }, (_, i) => ({ + supplier_sku_code: `SKU${i}`, + supplier_sku_name: '本地', + supplier_unit: '斤', + delivery_sku_code: `D-SKU${i}`, + delivery_sku_name: null, + status: 'active', + })); + const state = makeState({ mappings: local }); + installDb(state); + pullSkuMappings.mockResolvedValueOnce({ + kind: 'ok', + status: 200, + rows: Array.from({ length: 200 }, (_, i) => row(`REMOTE-${i}`)), + nextCursor: null, + total: null, + }); + + const summary = await pullMappingsFromMainSystem({ branchCode: 'BR002' }); + expect(summary.truncated).toBe(true); + expect(summary.deleted).toBe(0); + // 本地 250 行必须原样保留(旧实现会在这里删掉 50 行) + expect(state.mappings.filter((item) => item.supplier_sku_code.startsWith('SKU'))).toHaveLength(250); + expect(summary.upserted).toBe(200); + }); + + it('翻页中途失败 ⇒ truncated=true、保留已拉到的部分、**不删**本地行', async () => { + const state = makeState({ + mappings: [ + { supplier_sku_code: 'OLD', supplier_sku_name: '旧', supplier_unit: '斤', delivery_sku_code: 'D-OLD', delivery_sku_name: null, status: 'active' }, + ], + }); + installDb(state); + pullSkuMappings + .mockResolvedValueOnce({ kind: 'ok', status: 200, rows: [row('NEW-1')], nextCursor: 'p2', total: 300 }) + .mockResolvedValueOnce({ kind: 'unavailable', status: 502, code: 'main_system_error', reason: '对方不可用', payload: null }); + + const summary = await pullMappingsFromMainSystem({ branchCode: 'BR002' }); + expect(summary.truncated).toBe(true); + expect(summary.deleted).toBe(0); + expect(summary.upserted).toBe(1); + expect(state.mappings.map((item) => item.supplier_sku_code).sort()).toEqual(['NEW-1', 'OLD']); + }); + + it('完整拉取(total 对得上、翻页到 null)⇒ 删除远端已不存在的行', async () => { + const state = makeState({ + mappings: [ + { supplier_sku_code: 'GONE', supplier_sku_name: '旧', supplier_unit: '斤', delivery_sku_code: 'D-GONE', delivery_sku_name: null, status: 'active' }, + ], + }); + installDb(state); + pullSkuMappings + .mockResolvedValueOnce({ kind: 'ok', status: 200, rows: [row('A')], nextCursor: 'p2', total: 2 }) + .mockResolvedValueOnce({ kind: 'ok', status: 200, rows: [row('B')], nextCursor: null, total: 2 }); + + const summary = await pullMappingsFromMainSystem({ branchCode: 'BR002' }); + expect(summary.truncated).toBe(false); + expect(summary.deleted).toBe(1); + expect(state.mappings.map((item) => item.supplier_sku_code).sort()).toEqual(['A', 'B']); + }); +}); + +/* ── 定时任务:D4 推字典 + D5 拉映射,两个计数都要有 ─────────────────────────── */ + +describe('定时任务(D4 + D5)', () => { + beforeEach(() => { + process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1'; + }); + + it('按分公司推字典 + 拉映射,返回 push/pull 计数;单点失败记 errors 不中断', async () => { + const state = makeState({ + bindings: ['BR002', 'BR007'], + skus: Array.from({ length: 10 }, (_, i) => ({ + sku_code: `SKU${i}`, + sku_name: `商品${i}`, + unit: '斤', + status: 1, + })), + }); + installDb(state); + pushSkuDictionary + .mockResolvedValueOnce({ kind: 'ok', status: 200, data: { matched: 9, pending: 1, kept: 0, total: 10 } }) + .mockResolvedValueOnce({ kind: 'unavailable', status: 502, code: 'main_system_error', reason: '对方不可用', payload: null }); + pullSkuMappings + .mockResolvedValueOnce({ + kind: 'ok', + status: 200, + rows: [{ supplier_sku_code: 'SKU1', supplier_sku_name: '草鱼', supplier_unit: '斤', delivery_sku_code: 'D-001', delivery_sku_name: null, status: 'active', match_type: 'manual', updated_at: null }], + nextCursor: null, + total: 1, + }) + .mockResolvedValueOnce({ kind: 'ok', status: 200, rows: [], nextCursor: null, total: 0 }); + + const { syncDictionaryAndMappingsForAllBranches } = await import('../src/services/skuMappingService'); + const summary = await syncDictionaryAndMappingsForAllBranches(); + expect(summary).toMatchObject({ + branches: 2, + pushedSkus: 10, // BR002 推 10 条成功;BR007 推字典失败(不计入) + pushBatches: 1, + pulled: 1, + skipped: false, + }); + expect(summary.errors).toBeGreaterThanOrEqual(1); // BR007 推字典失败 + expect(pushSkuDictionary).toHaveBeenCalledTimes(2); + }); + + it('开关关闭 ⇒ 定时任务零出站(skipped=true)', async () => { + delete process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL; + installDb(makeState()); + const { syncDictionaryAndMappingsForAllBranches } = await import('../src/services/skuMappingService'); + const summary = await syncDictionaryAndMappingsForAllBranches(); + expect(summary.skipped).toBe(true); + expect(pushSkuDictionary).not.toHaveBeenCalled(); + expect(pullSkuMappings).not.toHaveBeenCalled(); + }); +}); diff --git a/server/tests/skuMappingDb.integration.test.ts b/server/tests/skuMappingDb.integration.test.ts new file mode 100644 index 0000000..e88bdf4 --- /dev/null +++ b/server/tests/skuMappingDb.integration.test.ts @@ -0,0 +1,134 @@ +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +/** + * `main_system_sku_mappings` **真库**约束/幂等验证(默认跳过;`SKU_MAPPING_DB_TEST=1` 才跑)。 + * + * 钉住(契约 §5 + 迁移): + * ① 迁移落库:tenant_template + tenant_br002 都有表,且登记进 `public.tenant_business_tables()`; + * ② `status` CHECK 只接受 active/disabled/pending; + * ③ 一个我方 SKU 只有一行(唯一索引)⇒ D5 的 ON CONFLICT upsert 才能真正幂等; + * ④ `status='active'` 的 delivery_sku_code 唯一(一个配送商品不被两个我方 SKU 占用); + * ⑤ 完整拉取的 "删除远端已不存在的行" SQL 可执行。 + * + * 跑法:cd server && SKU_MAPPING_DB_TEST=1 npx vitest run tests/skuMappingDb.integration.test.ts + */ + +const RUN = process.env.SKU_MAPPING_DB_TEST === '1'; +const SCHEMA = 'tenant_br002'; + +const db = RUN ? await import('../src/db') : null; +const pool = () => db!.pool; + +const SUPPLIER_SKUS = ['SKU_TESTMAP_A', 'SKU_TESTMAP_B', 'SKU_TESTMAP_C']; + +async function cleanup() { + await pool().query( + `DELETE FROM ${SCHEMA}.main_system_sku_mappings WHERE supplier_sku_code LIKE 'SKU_TESTMAP_%'` + ); +} + +async function upsert(input: { + supplier_sku_code: string; + delivery_sku_code: string | null; + status: string; + name?: string; +}): Promise { + await pool().query( + `INSERT INTO ${SCHEMA}.main_system_sku_mappings + (supplier_sku_code, supplier_sku_name, supplier_unit, delivery_sku_code, delivery_sku_name, + status, synced_at, updated_at) + VALUES ($1, $2, '斤', $3, $4, $5, NOW(), NOW()) + ON CONFLICT (supplier_sku_code) DO UPDATE SET + supplier_sku_name = EXCLUDED.supplier_sku_name, + supplier_unit = EXCLUDED.supplier_unit, + delivery_sku_code = EXCLUDED.delivery_sku_code, + delivery_sku_name = EXCLUDED.delivery_sku_name, + status = EXCLUDED.status, + synced_at = NOW(), + updated_at = NOW()`, + [input.supplier_sku_code, input.name || '测试商品', input.delivery_sku_code, '配送名', input.status] + ); +} + +describe.skipIf(!RUN)('main_system_sku_mappings · 真库(迁移 / 唯一键 / upsert 幂等)', () => { + beforeAll(async () => { + await cleanup(); + }); + + afterAll(async () => { + await cleanup(); + await pool().end(); + }); + + it('迁移落库:tenant_template 与 tenant_br002 都有表,且登记进 tenant_business_tables()', async () => { + const tables = await pool().query<{ table_schema: string }>( + `SELECT table_schema FROM information_schema.tables + WHERE table_name = 'main_system_sku_mappings' AND table_schema IN ('tenant_template', 'tenant_br002') + ORDER BY table_schema` + ); + expect(tables.rows.map((row) => row.table_schema)).toEqual(['tenant_br002', 'tenant_template']); + + const registered = await pool().query<{ n: number }>( + `SELECT count(*)::int AS n FROM unnest(public.tenant_business_tables()) AS t(name) + WHERE t.name = 'main_system_sku_mappings'` + ); + expect(registered.rows[0].n).toBe(1); + }); + + it('status CHECK 只接受 active/disabled/pending(未知状态被拦)', async () => { + await expect(upsert({ supplier_sku_code: 'SKU_TESTMAP_A', delivery_sku_code: null, status: 'bogus' })).rejects.toThrow(); + }); + + it('一个我方 SKU 只有一行:二次 upsert 走 ON CONFLICT(不新增行、值被更新)', async () => { + await upsert({ supplier_sku_code: 'SKU_TESTMAP_A', delivery_sku_code: 'D-A', status: 'active', name: '第一次' }); + await upsert({ supplier_sku_code: 'SKU_TESTMAP_A', delivery_sku_code: 'D-A2', status: 'active', name: '第二次' }); + const rows = await pool().query<{ supplier_sku_code: string; supplier_sku_name: string; delivery_sku_code: string }>( + `SELECT supplier_sku_code, supplier_sku_name, delivery_sku_code FROM ${SCHEMA}.main_system_sku_mappings + WHERE supplier_sku_code = 'SKU_TESTMAP_A'` + ); + expect(rows.rows).toHaveLength(1); + expect(rows.rows[0]).toMatchObject({ supplier_sku_name: '第二次', delivery_sku_code: 'D-A2' }); + }); + + it('active 的 delivery_sku_code 唯一:第二个我方 SKU 抢占同一配送 SKU 会被唯一索引拦下', async () => { + await upsert({ supplier_sku_code: 'SKU_TESTMAP_B', delivery_sku_code: 'D-B', status: 'active' }); + await expect( + upsert({ supplier_sku_code: 'SKU_TESTMAP_C', delivery_sku_code: 'D-B', status: 'active' }) + ).rejects.toThrow(/uq_main_system_sku_mappings_delivery|duplicate key/); + }); + + it('完整拉取的删除语义:DELETE ... WHERE supplier_sku_code <> ALL(远端集合)', async () => { + await upsert({ supplier_sku_code: 'SKU_TESTMAP_B', delivery_sku_code: 'D-B', status: 'active' }); + await upsert({ supplier_sku_code: 'SKU_TESTMAP_C', delivery_sku_code: null, status: 'pending' }); + const deleted = await pool().query<{ id: string }>( + `DELETE FROM ${SCHEMA}.main_system_sku_mappings + WHERE supplier_sku_code LIKE 'SKU_TESTMAP_%' AND supplier_sku_code <> ALL($1::text[]) + RETURNING id::text AS id`, + [[SUPPLIER_SKUS[0], SUPPLIER_SKUS[1]]] + ); + expect(deleted.rowCount).toBe(1); + const remain = await pool().query<{ supplier_sku_code: string }>( + `SELECT supplier_sku_code FROM ${SCHEMA}.main_system_sku_mappings WHERE supplier_sku_code LIKE 'SKU_TESTMAP_%' ORDER BY 1` + ); + expect(remain.rows.map((row) => row.supplier_sku_code)).toEqual([SUPPLIER_SKUS[0], SUPPLIER_SKUS[1]]); + }); + + it('方向 B 反查只认 active + delivery_sku_code 非空(pending/disabled ⇒ 按未映射)', async () => { + await upsert({ supplier_sku_code: 'SKU_TESTMAP_D', delivery_sku_code: 'D-MAP-ACTIVE', status: 'active' }); + await upsert({ supplier_sku_code: 'SKU_TESTMAP_E', delivery_sku_code: 'D-MAP-PENDING', status: 'pending' }); + await upsert({ supplier_sku_code: 'SKU_TESTMAP_F', delivery_sku_code: 'D-MAP-DISABLED', status: 'disabled' }); + + const tenant = await import('../src/services/tenantDbContext'); + const { getMappingByDeliverySku } = await import('../src/services/skuMappingService'); + await tenant.runWithTenantDbContext(SCHEMA.replace('tenant_', '').toUpperCase(), async () => { + expect(await getMappingByDeliverySku('BR002', 'D-MAP-ACTIVE')).toMatchObject({ + supplier_sku_code: 'SKU_TESTMAP_D', + }); + // 非 active 的映射不得被反查到(否则会把价写到错误的我方 SKU) + expect(await getMappingByDeliverySku('BR002', 'D-MAP-PENDING')).toBeNull(); + expect(await getMappingByDeliverySku('BR002', 'D-MAP-DISABLED')).toBeNull(); + expect(await getMappingByDeliverySku('BR002', 'D-MAP-NONE')).toBeNull(); + expect(await getMappingByDeliverySku('BR002', '')).toBeNull(); + }); + }); +}); diff --git a/src/i18n/locales/en/quotes.ts b/src/i18n/locales/en/quotes.ts index d477035..07ffcdf 100644 --- a/src/i18n/locales/en/quotes.ts +++ b/src/i18n/locales/en/quotes.ts @@ -4,6 +4,8 @@ export const quotes: MessageDict = { 'tab.active': 'Active', 'tab.history': 'History', 'tab.library': 'Product library', + 'tab.pendingCharges': 'Pending changes', + 'tab.deliveryPrice': 'Delivery cost confirmation', 'history.hint': 'Expired, rollover-archived, or replaced by a newer quote', 'filter.allCustomers': 'All customers', @@ -154,11 +156,74 @@ export const quotes: MessageDict = { 'toast.invalidSaleRatio': 'Sale ratio must be a number of at least 100', 'toast.autoSalePriceToggled': 'Auto pricing switch updated', 'toast.updated': 'Quote sheet updated; only affects future orders', + 'toast.submittedForApproval': 'Submitted for approval', + 'toast.submittedForDeliveryReview': 'Submitted to delivery for review', + 'toast.submitForDeliveryFail': 'Failed to submit for delivery review', 'toast.created': 'Quote sheet created and active', 'toast.updateFail': 'Update failed', 'toast.createFail': 'Create failed', 'toast.sheetNotFound': 'Quote sheet not found', + 'tab.skuMappings': 'SKU mappings', + 'action.syncSkuDictionary': 'Sync product dictionary', + 'toast.syncSkuDictionaryDone': 'Product dictionary synced: matched {matched}, pending {pending}', + 'toast.syncSkuDictionaryFail': 'Failed to sync product dictionary', + 'toast.mappingStats': '{total} items in this sheet, mapped {mapped} / unmapped {unmapped}', + 'priceProposal.unmapped': 'Unmapped', + 'skuMapping.title': 'SKU mappings (read-only)', + 'skuMapping.summary': '{total} items, mapped {mapped} / unmapped {unmapped}', + 'skuMapping.unmappedOnly': 'Unmapped only', + 'skuMapping.searchPh': 'Search SKU/name', + 'skuMapping.supplierSku': 'Our item', + 'skuMapping.deliverySku': 'Delivery item', + 'skuMapping.unit': 'Unit', + 'skuMapping.status': 'Status', + 'skuMapping.statusActive': 'Mapped', + 'skuMapping.statusPending': 'Unmapped', + 'skuMapping.statusDisabled': 'Disabled', + 'skuMapping.empty': 'No mappings yet. Sync the product dictionary first.', + 'skuMapping.loadFail': 'Failed to load SKU mappings', + 'priceProposal.title': 'Delivery cost confirmation', + 'priceProposal.empty': 'No delivery cost proposals to review', + 'priceProposal.directionFromDelivery': 'From delivery', + 'priceProposal.directionToDelivery': 'Submitted by us', + 'priceProposal.statusPending': 'Pending', + 'priceProposal.statusApproved': 'Approved', + 'priceProposal.statusRejected': 'Rejected', + 'priceProposal.statusSuperseded': 'Superseded', + 'priceProposal.statusCancelled': 'Cancelled', + 'priceProposal.waitedDays': 'Waiting {days} day(s)', + 'priceProposal.submittedBy': 'Submitted by', + 'priceProposal.submittedAt': 'Submitted at', + 'priceProposal.itemCount': '{count} item(s)', + 'priceProposal.approve': 'Approve', + 'priceProposal.reject': 'Reject', + 'priceProposal.rejectReason': 'Reject reason', + 'priceProposal.rejectReasonPh': 'Please enter a reject reason', + 'priceProposal.approvedWithUpdated': 'Approved; {updated} row(s) updated and cost synced', + 'priceProposal.approvedWithSkipped': 'Approved; {updated} row(s) updated, {skipped} skipped', + 'priceProposal.rejected': 'Rejected', + 'priceProposal.loadFail': 'Failed to load delivery cost proposals', + 'priceProposal.approveFail': 'Failed to approve delivery cost proposal', + 'priceProposal.rejectFail': 'Failed to reject delivery cost proposal', + 'action.submitForDeliveryReview': 'Submit to delivery', + + 'changeRequest.title': 'Pending price changes', + 'changeRequest.submittedBy': 'Submitted by', + 'changeRequest.submittedAt': 'Submitted at', + 'changeRequest.summary': 'Summary', + 'changeRequest.itemCount': '{count} item(s)', + 'changeRequest.approve': 'Approve', + 'changeRequest.reject': 'Reject', + 'changeRequest.approved': 'Approved', + 'changeRequest.rejected': 'Rejected', + 'changeRequest.rejectReason': 'Reject reason', + 'changeRequest.rejectReasonPh': 'Please enter a reject reason', + 'changeRequest.empty': 'No pending price changes', + 'changeRequest.loadFail': 'Failed to load pending price changes', + 'changeRequest.approveFail': 'Approve failed', + 'changeRequest.rejectFail': 'Reject failed', + 'export.col.quote_sheet_code': 'Sheet code', 'export.col.title': 'Title', 'export.col.version_no': 'Version', diff --git a/src/i18n/locales/id/quotes.ts b/src/i18n/locales/id/quotes.ts index 2b29783..8a91076 100644 --- a/src/i18n/locales/id/quotes.ts +++ b/src/i18n/locales/id/quotes.ts @@ -4,6 +4,8 @@ export const quotes: MessageDict = { 'tab.active': 'Aktif', 'tab.history': 'Riwayat', 'tab.library': 'Pustaka produk', + 'tab.pendingCharges': 'Perubahan menunggu', + 'tab.deliveryPrice': 'Konfirmasi biaya pengiriman', 'history.hint': 'Kedaluwarsa, diarsipkan rollover, atau diganti penawaran baru', @@ -157,6 +159,9 @@ export const quotes: MessageDict = { 'toast.needValidLine': 'Tambahkan setidaknya satu baris produk valid', 'toast.invalidSaleRatio': 'Rasio harga jual harus berupa angka minimal 100', 'toast.autoSalePriceToggled': 'Sakelar harga otomatis diperbarui', + 'toast.submittedForApproval': 'Terkirim untuk persetujuan', + 'toast.submittedForDeliveryReview': 'Terkirim ke pengiriman untuk ditinjau', + 'toast.submitForDeliveryFail': 'Gagal mengirim ke pengiriman', 'toast.updated': 'Lembar penawaran diperbarui; hanya memengaruhi pesanan berikutnya', 'toast.created': 'Lembar penawaran dibuat dan aktif', @@ -164,6 +169,66 @@ export const quotes: MessageDict = { 'toast.createFail': 'Gagal membuat', 'toast.sheetNotFound': 'Lembar penawaran tidak ditemukan', + 'tab.skuMappings': 'Pemetaan SKU', + 'action.syncSkuDictionary': 'Sinkronkan kamus produk', + 'toast.syncSkuDictionaryDone': 'Kamus produk tersinkron: cocok {matched}, menunggu {pending}', + 'toast.syncSkuDictionaryFail': 'Gagal menyinkronkan kamus produk', + 'toast.mappingStats': '{total} barang di penawaran ini, terpetakan {mapped} / belum {unmapped}', + 'priceProposal.unmapped': 'Belum dipetakan', + 'skuMapping.title': 'Pemetaan SKU (hanya baca)', + 'skuMapping.summary': '{total} barang, terpetakan {mapped} / belum {unmapped}', + 'skuMapping.unmappedOnly': 'Hanya yang belum dipetakan', + 'skuMapping.searchPh': 'Cari SKU/nama', + 'skuMapping.supplierSku': 'Barang kami', + 'skuMapping.deliverySku': 'Barang pengiriman', + 'skuMapping.unit': 'Satuan', + 'skuMapping.status': 'Status', + 'skuMapping.statusActive': 'Terpetakan', + 'skuMapping.statusPending': 'Belum dipetakan', + 'skuMapping.statusDisabled': 'Nonaktif', + 'skuMapping.empty': 'Belum ada pemetaan. Sinkronkan kamus produk dulu.', + 'skuMapping.loadFail': 'Gagal memuat pemetaan SKU', + 'priceProposal.title': 'Konfirmasi biaya pengiriman', + 'priceProposal.empty': 'Tidak ada usulan biaya pengiriman', + 'priceProposal.directionFromDelivery': 'Dari pengiriman', + 'priceProposal.directionToDelivery': 'Diajukan oleh kami', + 'priceProposal.statusPending': 'Menunggu', + 'priceProposal.statusApproved': 'Disetujui', + 'priceProposal.statusRejected': 'Ditolak', + 'priceProposal.statusSuperseded': 'Digantikan', + 'priceProposal.statusCancelled': 'Dibatalkan', + 'priceProposal.waitedDays': 'Menunggu {days} hari', + 'priceProposal.submittedBy': 'Diajukan oleh', + 'priceProposal.submittedAt': 'Waktu pengajuan', + 'priceProposal.itemCount': '{count} barang', + 'priceProposal.approve': 'Setujui', + 'priceProposal.reject': 'Tolak', + 'priceProposal.rejectReason': 'Alasan penolakan', + 'priceProposal.rejectReasonPh': 'Mohon isi alasan penolakan', + 'priceProposal.approvedWithUpdated': 'Disetujui; {updated} baris diperbarui dan biaya disinkronkan', + 'priceProposal.approvedWithSkipped': 'Disetujui; {updated} baris diperbarui, {skipped} dilewati', + 'priceProposal.rejected': 'Ditolak', + 'priceProposal.loadFail': 'Gagal memuat usulan biaya pengiriman', + 'priceProposal.approveFail': 'Gagal menyetujui usulan biaya pengiriman', + 'priceProposal.rejectFail': 'Gagal menolak usulan biaya pengiriman', + 'action.submitForDeliveryReview': 'Kirim ke pengiriman', + + 'changeRequest.title': 'Perubahan harga menunggu', + 'changeRequest.submittedBy': 'Diajukan oleh', + 'changeRequest.submittedAt': 'Waktu pengajuan', + 'changeRequest.summary': 'Ringkasan', + 'changeRequest.itemCount': '{count} barang', + 'changeRequest.approve': 'Setujui', + 'changeRequest.reject': 'Tolak', + 'changeRequest.approved': 'Disetujui', + 'changeRequest.rejected': 'Ditolak', + 'changeRequest.rejectReason': 'Alasan penolakan', + 'changeRequest.rejectReasonPh': 'Mohon isi alasan penolakan', + 'changeRequest.empty': 'Tidak ada perubahan harga menunggu', + 'changeRequest.loadFail': 'Gagal memuat perubahan harga menunggu', + 'changeRequest.approveFail': 'Gagal menyetujui', + 'changeRequest.rejectFail': 'Gagal menolak', + 'export.col.quote_sheet_code': 'Kode lembar', 'export.col.title': 'Judul', 'export.col.version_no': 'Versi', diff --git a/src/i18n/locales/zh-CN/quotes.ts b/src/i18n/locales/zh-CN/quotes.ts index c171429..e1674a8 100644 --- a/src/i18n/locales/zh-CN/quotes.ts +++ b/src/i18n/locales/zh-CN/quotes.ts @@ -4,6 +4,8 @@ export const quotes: MessageDict = { 'tab.active': '当前执行', 'tab.history': '历史报价', 'tab.library': '商品库', + 'tab.pendingCharges': '待审改价', + 'tab.deliveryPrice': '配送商成本价确认', 'history.hint': '已过期、顺延归档或已被新报价替换', 'filter.allCustomers': '全部客户', @@ -150,11 +152,74 @@ export const quotes: MessageDict = { 'toast.invalidSaleRatio': '销售比例须为不低于 100 的数字', 'toast.autoSalePriceToggled': '自动调价开关已更新', 'toast.updated': '报价单已更新,仅影响后续下单价格', + 'toast.submittedForApproval': '已提交审核', + 'toast.submittedForDeliveryReview': '已提交配送商审核', + 'toast.submitForDeliveryFail': '提交配送商审核失败', 'toast.created': '报价单已创建并生效', 'toast.updateFail': '修改失败', 'toast.createFail': '创建失败', 'toast.sheetNotFound': '未找到报价单', + 'tab.skuMappings': '商品映射', + 'action.syncSkuDictionary': '同步商品字典', + 'toast.syncSkuDictionaryDone': '商品字典已同步:已匹配 {matched} 个、待映射 {pending} 个', + 'toast.syncSkuDictionaryFail': '同步商品字典失败', + 'toast.mappingStats': '本单 {total} 个商品,已映射 {mapped} / 未映射 {unmapped}', + 'priceProposal.unmapped': '未映射', + 'skuMapping.title': '商品映射(只读)', + 'skuMapping.summary': '共 {total} 个商品,已映射 {mapped} / 未映射 {unmapped}', + 'skuMapping.unmappedOnly': '只看未映射', + 'skuMapping.searchPh': '搜索 SKU/名称', + 'skuMapping.supplierSku': '我方商品', + 'skuMapping.deliverySku': '配送商品', + 'skuMapping.unit': '单位', + 'skuMapping.status': '状态', + 'skuMapping.statusActive': '已映射', + 'skuMapping.statusPending': '未映射', + 'skuMapping.statusDisabled': '已停用', + 'skuMapping.empty': '暂无映射数据,请先同步商品字典', + 'skuMapping.loadFail': '加载商品映射失败', + 'priceProposal.title': '配送商成本价确认', + 'priceProposal.empty': '暂无待处理的配送商成本价提议', + 'priceProposal.directionFromDelivery': '配送商提交', + 'priceProposal.directionToDelivery': '我方提交', + 'priceProposal.statusPending': '待审', + 'priceProposal.statusApproved': '已通过', + 'priceProposal.statusRejected': '已驳回', + 'priceProposal.statusSuperseded': '已覆盖', + 'priceProposal.statusCancelled': '已取消', + 'priceProposal.waitedDays': '已等待 {days} 天', + 'priceProposal.submittedBy': '提交人', + 'priceProposal.submittedAt': '提交时间', + 'priceProposal.itemCount': '{count} 个商品', + 'priceProposal.approve': '通过', + 'priceProposal.reject': '驳回', + 'priceProposal.rejectReason': '驳回理由', + 'priceProposal.rejectReasonPh': '请填写驳回理由', + 'priceProposal.approvedWithUpdated': '审核通过,已更新 {updated} 行售价并同步成本价', + 'priceProposal.approvedWithSkipped': '审核通过,已更新 {updated} 行、跳过 {skipped} 行', + 'priceProposal.rejected': '已驳回', + 'priceProposal.loadFail': '加载配送商成本价提议失败', + 'priceProposal.approveFail': '审批配送商成本价失败', + 'priceProposal.rejectFail': '驳回配送商成本价失败', + 'action.submitForDeliveryReview': '提交配送商审核', + + 'changeRequest.title': '待审改价', + 'changeRequest.submittedBy': '提交人', + 'changeRequest.submittedAt': '提交时间', + 'changeRequest.summary': '变更摘要', + 'changeRequest.itemCount': '商品 {count} 条', + 'changeRequest.approve': '通过', + 'changeRequest.reject': '驳回', + 'changeRequest.approved': '审核通过', + 'changeRequest.rejected': '审核驳回', + 'changeRequest.rejectReason': '驳回理由', + 'changeRequest.rejectReasonPh': '请填写驳回理由', + 'changeRequest.empty': '暂无待审改价', + 'changeRequest.loadFail': '加载待审改价失败', + 'changeRequest.approveFail': '审核通过失败', + 'changeRequest.rejectFail': '审核驳回失败', + 'export.col.quote_sheet_code': '报价单号', 'export.col.title': '标题', 'export.col.version_no': '版本', diff --git a/src/pages/customers/QuoteChangeRequestsPanel.test.tsx b/src/pages/customers/QuoteChangeRequestsPanel.test.tsx new file mode 100644 index 0000000..57372a2 --- /dev/null +++ b/src/pages/customers/QuoteChangeRequestsPanel.test.tsx @@ -0,0 +1,186 @@ +// @vitest-environment jsdom +import React from 'react'; +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +/** + * 「待审改价」面板(2026-10-18 增量需求)版式与权限契约: + * · 列表展示:单号 / 提交人 / 提交时间 / 变更摘要(改前 → 改后); + * · `canApprove=false`(没有 `customer_manage`)⇒ **只读**,不渲染通过/驳回按钮; + * · 通过 ⇒ 调审核接口 + 成功提示 + 刷新 + `onApplied` 回调(页面据此刷新报价单); + * · 驳回 ⇒ 必须先填理由(空理由不调接口),调驳回接口后刷新; + * · 空列表 ⇒ 「暂无待审改价」。 + */ + +const listApi = vi.fn(); +const approveApi = vi.fn(); +const rejectApi = vi.fn(); + +vi.mock('../../utils/workflowApi', () => ({ + listQuoteChangeRequestsApi: (...args: unknown[]) => listApi(...args), + approveQuoteChangeRequestApi: (...args: unknown[]) => approveApi(...args), + rejectQuoteChangeRequestApi: (...args: unknown[]) => rejectApi(...args), +})); + +const notify = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() })); +vi.mock('../../utils/notify', () => ({ notify })); + +// 用真实 zh-CN 报价单文案做 t() +vi.mock('../../i18n', async () => { + const { quotes } = (await import('../../i18n/locales/zh-CN/quotes')) as unknown as { + quotes: Record; + }; + const { common } = (await import('../../i18n/locales/zh-CN/common')) as unknown as { + common: Record; + }; + const dict: Record = {}; + for (const [key, value] of Object.entries(quotes)) dict[`quotes.${key}`] = value; + for (const [key, value] of Object.entries(common)) dict[`common.${key}`] = value; + const t = (key: string, vars?: Record) => { + const raw = dict[key] ?? key; + if (!vars) return raw; + return Object.entries(vars).reduce( + (acc, [name, value]) => acc.replace(new RegExp(`\\{${name}\\}`, 'g'), String(value)), + raw + ); + }; + return { useT: () => t }; +}); + +import { QuoteChangeRequestsPanel } from './QuoteChangeRequestsPanel'; + +const ROW = { + id: '11111111-1111-4111-8111-111111111111', + branch_code: 'BR002', + quote_sheet_code: 'QS1792200796033LUTV', + payload: { items: [{ sku_code: 'SKU1' }] }, + base_version_no: 1, + base_items_fingerprint: 'fp', + status: 'pending', + requested_by: 'u1', + requested_by_name: '张三', + requested_at: '2026-10-18T02:00:00.000Z', + reviewed_by: null, + reviewed_by_name: null, + reviewed_at: null, + reject_reason: null, + applied_at: null, + updated_at: '2026-10-18T02:00:00.000Z', + summary: { + title: null, + quote_cycle: null, + effective_at: null, + auto_sale_price_by_cost: null, + customer_codes: null, + items_provided: true, + item_count: 2, + added: 0, + removed: 0, + updated: 2, + lines: [ + { + sku_code: 'SKU1', + sku_name: '草鱼', + unit: '斤', + before_sale_price: 10, + after_sale_price: 11, + before_cost_price: 5, + after_cost_price: 5, + change: 'updated' as const, + }, + { + sku_code: 'SKU2', + sku_name: '鲤鱼', + unit: '袋', + before_sale_price: null, + after_sale_price: 20, + before_cost_price: null, + after_cost_price: 9, + change: 'added' as const, + }, + ], + truncated: false, + }, +}; + +beforeEach(() => { + listApi.mockReset(); + approveApi.mockReset(); + rejectApi.mockReset(); + notify.success.mockReset(); + notify.error.mockReset(); + listApi.mockResolvedValue({ data: [ROW] }); + approveApi.mockResolvedValue({ data: { quote_sheet_code: ROW.quote_sheet_code }, change_request: { ...ROW, status: 'approved' } }); + rejectApi.mockResolvedValue({ change_request: { ...ROW, status: 'rejected' } }); +}); + +afterEach(() => { + cleanup(); +}); + +describe('待审改价面板', () => { + it('渲染单号 / 提交人 / 提交时间 / 变更摘要(改前 → 改后)与操作按钮', async () => { + render(); + expect(await screen.findByText('QS1792200796033LUTV')).toBeTruthy(); + expect(screen.getByText(/张三/)).toBeTruthy(); + expect(screen.getByText('待审改价')).toBeTruthy(); + expect(screen.getByText('变更摘要')).toBeTruthy(); + // 草鱼:10.00 → 11.00;鲤鱼:新增 + 20.00 + expect(screen.getByText('10.00 → 11.00')).toBeTruthy(); + expect(screen.getByText('+ 20.00')).toBeTruthy(); + expect(screen.getByText('草鱼')).toBeTruthy(); + expect(screen.getByText('鲤鱼')).toBeTruthy(); + expect(screen.getByText('通过')).toBeTruthy(); + expect(screen.getByText('驳回')).toBeTruthy(); + }); + + it('无审批权 ⇒ 只读(不渲染通过/驳回)', async () => { + render(); + expect(await screen.findByText('QS1792200796033LUTV')).toBeTruthy(); + expect(screen.queryByText('通过')).toBeNull(); + expect(screen.queryByText('驳回')).toBeNull(); + }); + + it('空列表 ⇒ 暂无待审改价', async () => { + listApi.mockResolvedValue({ data: [] }); + render(); + expect(await screen.findByText('暂无待审改价')).toBeTruthy(); + }); + + it('通过 ⇒ 调审核接口、成功提示、刷新列表并回调 onApplied', async () => { + const onApplied = vi.fn(); + render(); + await screen.findByText('QS1792200796033LUTV'); + fireEvent.click(screen.getByText('通过')); + await waitFor(() => expect(approveApi).toHaveBeenCalledWith(ROW.id)); + await waitFor(() => expect(notify.success).toHaveBeenCalledWith('审核通过')); + expect(onApplied).toHaveBeenCalledTimes(1); + expect(listApi.mock.calls.length).toBeGreaterThanOrEqual(2); + }); + + it('驳回:空理由不调接口;填理由后调驳回接口', async () => { + render(); + await screen.findByText('QS1792200796033LUTV'); + fireEvent.click(screen.getByText('驳回')); + const input = await screen.findByLabelText('驳回理由'); + // 行内「驳回」打开输入条后,页面上会出现第二个「驳回」(= 确认按钮),取最后一个 + const clickConfirmReject = () => { + const buttons = screen.getAllByText('驳回'); + fireEvent.click(buttons[buttons.length - 1]); + }; + clickConfirmReject(); + await waitFor(() => expect(notify.error).toHaveBeenCalledWith('请填写驳回理由')); + expect(rejectApi).not.toHaveBeenCalled(); + + fireEvent.change(input, { target: { value: '价格谈不拢' } }); + clickConfirmReject(); + await waitFor(() => expect(rejectApi).toHaveBeenCalledWith(ROW.id, '价格谈不拢')); + expect(notify.success).toHaveBeenCalledWith('审核驳回'); + }); + + it('加载失败 ⇒ 错误提示(不是静默空白)', async () => { + listApi.mockRejectedValue(new Error('加载失败')); + render(); + await waitFor(() => expect(notify.error).toHaveBeenCalledWith('加载失败')); + }); +}); diff --git a/src/pages/customers/QuoteChangeRequestsPanel.tsx b/src/pages/customers/QuoteChangeRequestsPanel.tsx new file mode 100644 index 0000000..0d4338c --- /dev/null +++ b/src/pages/customers/QuoteChangeRequestsPanel.tsx @@ -0,0 +1,250 @@ +import React, { useCallback, useEffect, useState } from 'react'; +import { Check, RefreshCw, X } from 'lucide-react'; +import { notify } from '../../utils/notify'; +import { useT } from '../../i18n'; +import { + approveQuoteChangeRequestApi, + listQuoteChangeRequestsApi, + rejectQuoteChangeRequestApi, + type QuoteChangeLineDto, + type QuoteChangeRequestDto, +} from '../../utils/workflowApi'; + +/** + * 「待审改价」面板(2026-10-18 增量需求): + * 编辑**生效中**报价单里价格相关的改动,保存时只落「待审变更」,**审核通过才真正改单并同步成本价**。 + * + * 放在报价单页内(`QuoteVersionManagement` 的 chrome tab),不新增独立菜单。 + * 权限一分为二(Lead 裁定):查看 = `customer_manage | order_manage`;**通过/驳回只认 `customer_manage`** + * ⇒ 没有 `customer_manage` 的人是**只读**(不渲染操作按钮,不额外加提示文案)。 + */ + +function formatPrice(value: number | null | undefined): string { + if (value === null || value === undefined) return '—'; + return Number(value).toFixed(2); +} + +function formatTime(value: string | null | undefined): string { + if (!value) return '—'; + const date = new Date(value); + return Number.isNaN(date.getTime()) ? String(value) : date.toLocaleString(); +} + +function lineText(line: QuoteChangeLineDto): string { + if (line.change === 'added') return `+ ${formatPrice(line.after_sale_price)}`; + if (line.change === 'removed') return `− ${formatPrice(line.before_sale_price)}`; + return `${formatPrice(line.before_sale_price)} → ${formatPrice(line.after_sale_price)}`; +} + +function lineCostText(line: QuoteChangeLineDto): string | null { + if (line.before_cost_price === null && line.after_cost_price === null) return null; + const changed = + Math.abs(Number(line.before_cost_price ?? 0) - Number(line.after_cost_price ?? 0)) > 1e-6; + if (!changed) return null; + return `${formatPrice(line.before_cost_price)} → ${formatPrice(line.after_cost_price)}`; +} + +export type QuoteChangeRequestsPanelProps = { + /** 是否有审批权(`customer_manage`);false = 只读 */ + canApprove: boolean; + /** 审核通过后回调(页面用来刷新报价单列表/详情) */ + onApplied?: () => void; +}; + +export const QuoteChangeRequestsPanel: React.FC = ({ + canApprove, + onApplied, +}) => { + const t = useT(); + const [rows, setRows] = useState([]); + const [loading, setLoading] = useState(false); + const [actingId, setActingId] = useState(null); + const [rejecting, setRejecting] = useState<{ id: string; reason: string } | null>(null); + + const load = useCallback(async () => { + setLoading(true); + try { + const { data } = await listQuoteChangeRequestsApi({ status: 'pending' }); + setRows(Array.isArray(data) ? data : []); + } catch (error: any) { + notify.error(error?.message || t('quotes.changeRequest.loadFail')); + } finally { + setLoading(false); + } + }, [t]); + + useEffect(() => { + void load(); + }, [load]); + + const handleApprove = async (row: QuoteChangeRequestDto) => { + setActingId(row.id); + try { + await approveQuoteChangeRequestApi(row.id); + notify.success(t('quotes.changeRequest.approved')); + setRejecting(null); + await load(); + onApplied?.(); + } catch (error: any) { + // 409 base_changed / already_decided / sku_unavailable 等后端会带中文说明,直接透出 + notify.error(error?.message || t('quotes.changeRequest.approveFail')); + } finally { + setActingId(null); + } + }; + + const handleReject = async () => { + if (!rejecting) return; + const reason = rejecting.reason.trim(); + if (!reason) { + notify.error(t('quotes.changeRequest.rejectReasonPh')); + return; + } + setActingId(rejecting.id); + try { + await rejectQuoteChangeRequestApi(rejecting.id, reason); + notify.success(t('quotes.changeRequest.rejected')); + setRejecting(null); + await load(); + } catch (error: any) { + notify.error(error?.message || t('quotes.changeRequest.rejectFail')); + } finally { + setActingId(null); + } + }; + + return ( +
+
+

+ {t('quotes.changeRequest.title')} + {rows.length ? ({rows.length}) : null} +

+ +
+ + {!loading && rows.length === 0 ? ( +
+ {t('quotes.changeRequest.empty')} +
+ ) : ( +
+ {rows.map((row) => { + const summary = row.summary; + const busy = actingId === row.id; + return ( +
+
+
+

+ {row.quote_sheet_code} + {summary ? ( + + {t('quotes.changeRequest.itemCount', { count: summary.item_count })} + + ) : null} +

+

+ {t('quotes.changeRequest.submittedBy')}:{row.requested_by_name || '—'} ·{' '} + {t('quotes.changeRequest.submittedAt')}:{formatTime(row.requested_at)} +

+
+ {canApprove ? ( +
+ + +
+ ) : null} +
+ + {summary ? ( +
+

{t('quotes.changeRequest.summary')}

+
    + {summary.lines.map((line) => ( +
  • + {line.sku_name || line.sku_code} + {line.unit ? {line.unit} : null} + {lineText(line)} + {lineCostText(line) ? ( + + {t('quotes.export.col.cost_price')} {lineCostText(line)} + + ) : null} +
  • + ))} + {summary.lines.length === 0 ? ( +
  • + {t('quotes.changeRequest.itemCount', { count: summary.item_count })} +
  • + ) : null} + {summary.truncated ?
  • …
  • : null} +
+
+ ) : null} + + {rejecting?.id === row.id ? ( +
+ + setRejecting((current) => + current ? { ...current, reason: event.target.value } : current + ) + } + placeholder={t('quotes.changeRequest.rejectReasonPh')} + aria-label={t('quotes.changeRequest.rejectReason')} + className="app-input app-focus-ring flex-1 min-w-[12rem] px-3 py-1.5 text-sm rounded-lg border border-slate-200 dark:border-slate-600" + /> + + +
+ ) : null} +
+ ); + })} +
+ )} +
+ ); +}; diff --git a/src/pages/customers/QuoteDeliveryPriceProposalsPanel.test.tsx b/src/pages/customers/QuoteDeliveryPriceProposalsPanel.test.tsx new file mode 100644 index 0000000..145260e --- /dev/null +++ b/src/pages/customers/QuoteDeliveryPriceProposalsPanel.test.tsx @@ -0,0 +1,188 @@ +// @vitest-environment jsdom +import React from 'react'; +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +/** + * 「配送商成本价确认」面板(2026-10-18 增量)版式与权限契约: + * · 展示方向(配送商提交 / 我方提交)、状态、提交人/时间、等待天数、改前 → 改后; + * · 仅「配送商提交 + pending + 有 customer_manage」才渲染通过/驳回;其余只读; + * · 通过 ⇒ 调审批接口 + 按 applied.updated/skipped 给出摘要提示 + 刷新 + onApplied; + * · 驳回 ⇒ 必须填理由;空理由不调接口; + * · 空列表 ⇒ 暂无待处理的配送商成本价提议。 + */ + +const listApi = vi.fn(); +const approveApi = vi.fn(); +const rejectApi = vi.fn(); + +vi.mock('../../utils/workflowApi', () => ({ + listQuotePriceProposalsApi: (...args: unknown[]) => listApi(...args), + approveQuotePriceProposalApi: (...args: unknown[]) => approveApi(...args), + rejectQuotePriceProposalApi: (...args: unknown[]) => rejectApi(...args), +})); + +const notify = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() })); +vi.mock('../../utils/notify', () => ({ notify })); + +vi.mock('../../i18n', async () => { + const { quotes } = (await import('../../i18n/locales/zh-CN/quotes')) as unknown as { + quotes: Record; + }; + const { common } = (await import('../../i18n/locales/zh-CN/common')) as unknown as { + common: Record; + }; + const dict: Record = {}; + for (const [key, value] of Object.entries(quotes)) dict[`quotes.${key}`] = value; + for (const [key, value] of Object.entries(common)) dict[`common.${key}`] = value; + const t = (key: string, vars?: Record) => { + const raw = dict[key] ?? key; + if (!vars) return raw; + return Object.entries(vars).reduce( + (acc, [name, value]) => acc.replace(new RegExp(`\\{${name}\\}`, 'g'), String(value)), + raw + ); + }; + return { useT: () => t }; +}); + +import { QuoteDeliveryPriceProposalsPanel } from './QuoteDeliveryPriceProposalsPanel'; + +const INCOMING = { + id: '11111111-1111-4111-8111-111111111111', + branch_code: 'BR002', + quote_sheet_code: 'QS1792200796033LUTV', + main_branch_code: 'BR002', + direction: 'from_delivery' as const, + items: [ + { sku_code: 'SKU1', unit: '斤', price: 11 }, + { sku_code: 'SKU2', unit: '袋', price: 21 }, + ], + status: 'pending' as const, + reject_reason: null, + remote_proposal_id: 'remote-1', + requested_by_name: '配送商甲', + requested_at: '2026-10-15T02:00:00.000Z', + reviewed_by_name: null, + reviewed_at: null, + applied_at: null, + waited_days: 3, + lines: [ + { sku_code: 'SKU1', sku_name: '草鱼', unit: '斤', before_sale_price: 10, after_sale_price: 11, change: 'updated' as const }, + { sku_code: 'SKU2', sku_name: '鲤鱼', unit: '袋', before_sale_price: null, after_sale_price: 21, change: 'added' as const }, + ], +}; + +const OUTGOING = { + ...INCOMING, + id: '22222222-2222-4222-8222-222222222222', + quote_sheet_code: 'QS2492200796033OTHER', + direction: 'to_delivery' as const, + status: 'approved' as const, + lines: undefined, +}; + +beforeEach(() => { + listApi.mockReset(); + approveApi.mockReset(); + rejectApi.mockReset(); + notify.success.mockReset(); + notify.error.mockReset(); + listApi.mockResolvedValue({ data: [INCOMING, OUTGOING], sync: null }); + approveApi.mockResolvedValue({ + data: { ...INCOMING, status: 'approved' }, + applied: { updated: 2, unchanged: 0, skipped: [] }, + receipt_sent: true, + }); + rejectApi.mockResolvedValue({ data: { ...INCOMING, status: 'rejected' }, receipt_sent: true }); +}); + +afterEach(() => { + cleanup(); +}); + +describe('配送商成本价确认面板', () => { + it('展示方向/状态/提交人/等待天数/改前→改后;只有配送商提交的待审行有操作按钮', async () => { + render(); + expect(await screen.findByText('QS1792200796033LUTV')).toBeTruthy(); + expect(screen.getByText(/配送商提交/)).toBeTruthy(); + expect(screen.getByText(/我方提交/)).toBeTruthy(); + expect(screen.getByText(/已通过/)).toBeTruthy(); + expect(screen.getByText(/已等待 3 天/)).toBeTruthy(); + expect(screen.getByText('10.00 → 11.00')).toBeTruthy(); + expect(screen.getByText('+ 21.00')).toBeTruthy(); + // 两条记录里只有「配送商提交 + pending」那条有按钮 + expect(screen.getAllByText('通过')).toHaveLength(1); + expect(screen.getAllByText('驳回')).toHaveLength(1); + // 列表带 refresh=1(页面手动刷新会先做 D2 对账) + expect((listApi.mock.calls[0][0] as any).refresh).toBe(true); + }); + + it('无审批权 ⇒ 只读(不渲染通过/驳回)', async () => { + render(); + expect(await screen.findByText('QS1792200796033LUTV')).toBeTruthy(); + expect(screen.queryByText('通过')).toBeNull(); + expect(screen.queryByText('驳回')).toBeNull(); + }); + + it('空列表 ⇒ 暂无待处理的配送商成本价提议', async () => { + listApi.mockResolvedValue({ data: [], sync: null }); + render(); + expect(await screen.findByText('暂无待处理的配送商成本价提议')).toBeTruthy(); + }); + + it('通过 ⇒ 调审批接口、按 applied 摘要提示、刷新并回调 onApplied', async () => { + const onApplied = vi.fn(); + render(); + await screen.findByText('QS1792200796033LUTV'); + fireEvent.click(screen.getByText('通过')); + await waitFor(() => expect(approveApi).toHaveBeenCalledWith(INCOMING.id)); + await waitFor(() => + expect(notify.success).toHaveBeenCalledWith('审核通过,已更新 2 行售价并同步成本价') + ); + expect(onApplied).toHaveBeenCalledTimes(1); + expect(listApi.mock.calls.length).toBeGreaterThanOrEqual(2); + }); + + it('驳回:空理由不调接口;填理由后调驳回接口', async () => { + render(); + await screen.findByText('QS1792200796033LUTV'); + fireEvent.click(screen.getByText('驳回')); + const input = await screen.findByLabelText('驳回理由'); + const confirm = () => { + const buttons = screen.getAllByText('驳回'); + fireEvent.click(buttons[buttons.length - 1]); + }; + confirm(); + await waitFor(() => expect(notify.error).toHaveBeenCalledWith('请填写驳回理由')); + expect(rejectApi).not.toHaveBeenCalled(); + + fireEvent.change(input, { target: { value: '成本谈不拢' } }); + confirm(); + await waitFor(() => expect(rejectApi).toHaveBeenCalledWith(INCOMING.id, '成本谈不拢')); + expect(notify.success).toHaveBeenCalledWith('已驳回'); + }); + + it('加载失败 ⇒ 错误提示(不是静默空白)', async () => { + listApi.mockRejectedValue(new Error('加载失败')); + render(); + await waitFor(() => expect(notify.error).toHaveBeenCalledWith('加载失败')); + }); +}); + +describe('开关关闭(803 → 503 feature_disabled)的空态', () => { + it('显示后端原文空态,不弹 toast、无刷新按钮(不诱导重复请求)', async () => { + listApi.mockRejectedValue( + Object.assign(new Error('报价单价格传递未开启(MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL)'), { + status: 503, + code: 'feature_disabled', + }) + ); + render(); + expect( + await screen.findByText('报价单价格传递未开启(MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL)') + ).toBeTruthy(); + expect(notify.error).not.toHaveBeenCalled(); + expect(screen.queryByRole('button')).toBeNull(); + }); +}); diff --git a/src/pages/customers/QuoteDeliveryPriceProposalsPanel.tsx b/src/pages/customers/QuoteDeliveryPriceProposalsPanel.tsx new file mode 100644 index 0000000..1fad6a0 --- /dev/null +++ b/src/pages/customers/QuoteDeliveryPriceProposalsPanel.tsx @@ -0,0 +1,277 @@ +import React, { useCallback, useEffect, useState } from 'react'; +import { Check, RefreshCw, X } from 'lucide-react'; +import { notify } from '../../utils/notify'; +import { useT } from '../../i18n'; +import { + approveQuotePriceProposalApi, + listQuotePriceProposalsApi, + rejectQuotePriceProposalApi, + type QuotePriceProposalDto, +} from '../../utils/workflowApi'; + +/** + * 「配送商成本价确认」面板(2026-10-18 增量,冻结契约 T2/T3/T8): + * · 列出双向价格提议:`from_delivery` = 配送商发起、**待我方审**(可写我方 sale_price); + * `to_delivery` = 我方提交、等配送商审(只读状态)。 + * · 通过(仅 `from_delivery` 且 `customer_manage`):后端**按行 UPDATE** 写 `sale_price`, + * `triggerQuoteCostSync`(rearm)推对方 `cost_price`,再 D3 回执;返回 `applied.updated/skipped` 摘要。 + * · 驳回:只记状态 + 理由,不写价;`pending` 不自动过期(展示已等待天数)。 + * · 无审批权 ⇒ 只读(不渲染操作按钮,不额外加提示文案)。 + */ + +function formatPrice(value: number | null | undefined): string { + if (value === null || value === undefined) return '—'; + return Number(value).toFixed(2); +} + +function formatTime(value: string | null | undefined): string { + if (!value) return '—'; + const date = new Date(value); + return Number.isNaN(date.getTime()) ? String(value) : date.toLocaleString(); +} + +export type QuoteDeliveryPriceProposalsPanelProps = { + /** 是否有审批权(`customer_manage`);false = 只读 */ + canApprove: boolean; + /** 审核通过后回调(页面用来刷新报价单列表/详情) */ + onApplied?: () => void; +}; + +export const QuoteDeliveryPriceProposalsPanel: React.FC = ({ + canApprove, + onApplied, +}) => { + const t = useT(); + const [rows, setRows] = useState([]); + const [loading, setLoading] = useState(false); + const [actingId, setActingId] = useState(null); + const [rejecting, setRejecting] = useState<{ id: string; reason: string } | null>(null); + /** + * 开关关闭(后端 503 `feature_disabled`)时的**空态原因**:显示后端原文,且**只显示不弹 toast**。 + * 否则每次进页签都会弹一次"请求失败",用户以为坏了。 + */ + const [disabledReason, setDisabledReason] = useState(null); + + const load = useCallback(async () => { + setLoading(true); + try { + const { data } = await listQuotePriceProposalsApi({ status: 'pending', refresh: true }); + setDisabledReason(null); + setRows(Array.isArray(data) ? data : []); + } catch (error: any) { + // 功能未开启:走空态文案(后端原文),不 toast、不重复弹 + if (Number(error?.status) === 503 || error?.code === 'feature_disabled') { + setRows([]); + setDisabledReason(error?.message || t('quotes.priceProposal.loadFail')); + return; + } + notify.error(error?.message || t('quotes.priceProposal.loadFail')); + } finally { + setLoading(false); + } + }, [t]); + + useEffect(() => { + void load(); + }, [load]); + + const handleApprove = async (row: QuotePriceProposalDto) => { + setActingId(row.id); + try { + const result = await approveQuotePriceProposalApi(row.id); + const updated = Number(result?.applied?.updated) || 0; + const skipped = Array.isArray(result?.applied?.skipped) ? result.applied.skipped.length : 0; + notify.success( + skipped + ? t('quotes.priceProposal.approvedWithSkipped', { updated, skipped }) + : t('quotes.priceProposal.approvedWithUpdated', { updated }) + ); + setRejecting(null); + await load(); + onApplied?.(); + } catch (error: any) { + notify.error(error?.message || t('quotes.priceProposal.approveFail')); + } finally { + setActingId(null); + } + }; + + const handleReject = async () => { + if (!rejecting) return; + const reason = rejecting.reason.trim(); + if (!reason) { + notify.error(t('quotes.priceProposal.rejectReasonPh')); + return; + } + setActingId(rejecting.id); + try { + await rejectQuotePriceProposalApi(rejecting.id, reason); + notify.success(t('quotes.priceProposal.rejected')); + setRejecting(null); + await load(); + } catch (error: any) { + notify.error(error?.message || t('quotes.priceProposal.rejectFail')); + } finally { + setActingId(null); + } + }; + + const statusLabel = (status: QuotePriceProposalDto['status']): string => { + switch (status) { + case 'pending': + return t('quotes.priceProposal.statusPending'); + case 'approved': + return t('quotes.priceProposal.statusApproved'); + case 'rejected': + return t('quotes.priceProposal.statusRejected'); + case 'superseded': + return t('quotes.priceProposal.statusSuperseded'); + default: + return t('quotes.priceProposal.statusCancelled'); + } + }; + + return ( +
+
+

+ {t('quotes.priceProposal.title')} + {rows.length ? ({rows.length}) : null} +

+ {disabledReason ? null : ( + + )} +
+ + {disabledReason ? ( +
+ {disabledReason} +
+ ) : !loading && rows.length === 0 ? ( +
+ {t('quotes.priceProposal.empty')} +
+ ) : ( +
+ {rows.map((row) => { + const busy = actingId === row.id; + const isIncoming = row.direction === 'from_delivery'; + return ( +
+
+
+

+ {row.quote_sheet_code} + + {isIncoming + ? t('quotes.priceProposal.directionFromDelivery') + : t('quotes.priceProposal.directionToDelivery')} + {' · '} + {statusLabel(row.status)} + {row.status === 'pending' && row.waited_days !== null && row.waited_days !== undefined + ? ` · ${t('quotes.priceProposal.waitedDays', { days: row.waited_days })}` + : ''} + +

+

+ {t('quotes.priceProposal.submittedBy')}:{row.requested_by_name || '—'} ·{' '} + {t('quotes.priceProposal.submittedAt')}:{formatTime(row.requested_at)} +

+
+ {canApprove && isIncoming && row.status === 'pending' ? ( +
+ + +
+ ) : null} +
+ +
    + {(row.lines || []).map((line) => ( +
  • + {line.sku_name || line.sku_code} + {line.unit ? {line.unit} : null} + + {line.change === 'added' + ? `+ ${formatPrice(line.after_sale_price)}` + : `${formatPrice(line.before_sale_price)} → ${formatPrice(line.after_sale_price)}`} + +
  • + ))} + {!(row.lines || []).length ? ( +
  • + {t('quotes.priceProposal.itemCount', { count: row.items.length })} +
  • + ) : null} + {row.reject_reason ? ( +
  • + {t('quotes.priceProposal.rejectReason')}:{row.reject_reason} +
  • + ) : null} +
+ + {rejecting?.id === row.id ? ( +
+ + setRejecting((current) => + current ? { ...current, reason: event.target.value } : current + ) + } + placeholder={t('quotes.priceProposal.rejectReasonPh')} + aria-label={t('quotes.priceProposal.rejectReason')} + className="app-input app-focus-ring flex-1 min-w-[12rem] px-3 py-1.5 text-sm rounded-lg border border-slate-200 dark:border-slate-600" + /> + + +
+ ) : null} +
+ ); + })} +
+ )} +
+ ); +}; diff --git a/src/pages/customers/QuoteSkuMappingsPanel.test.tsx b/src/pages/customers/QuoteSkuMappingsPanel.test.tsx new file mode 100644 index 0000000..f66dec2 --- /dev/null +++ b/src/pages/customers/QuoteSkuMappingsPanel.test.tsx @@ -0,0 +1,133 @@ +// @vitest-environment jsdom +import React from 'react'; +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +/** + * 「商品映射(只读)」面板(2026-10-18 增量,契约 §5/§6): + * · 只读展示 我方商品/SKU ↔ 配送商品/SKU、单位、状态;**没有编辑/绑定/解绑入口**; + * · 汇总「共 N 个商品,已映射 X / 未映射 Y」; + * · 「只看未映射」筛选会带 `status=pending` 重新请求; + * · 开关关闭(503 feature_disabled)⇒ 空态显示后端原文,不弹 toast。 + */ + +const listApi = vi.fn(); +vi.mock('../../utils/workflowApi', () => ({ + listSkuMappingsApi: (...args: unknown[]) => listApi(...args), +})); + +const notify = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() })); +vi.mock('../../utils/notify', () => ({ notify })); + +vi.mock('../../i18n', async () => { + const { quotes } = (await import('../../i18n/locales/zh-CN/quotes')) as unknown as { + quotes: Record; + }; + const { common } = (await import('../../i18n/locales/zh-CN/common')) as unknown as { + common: Record; + }; + const dict: Record = {}; + for (const [key, value] of Object.entries(quotes)) dict[`quotes.${key}`] = value; + for (const [key, value] of Object.entries(common)) dict[`common.${key}`] = value; + const t = (key: string, vars?: Record) => { + const raw = dict[key] ?? key; + if (!vars) return raw; + return Object.entries(vars).reduce( + (acc, [name, value]) => acc.replace(new RegExp(`\\{${name}\\}`, 'g'), String(value)), + raw + ); + }; + return { useT: () => t }; +}); + +import { QuoteSkuMappingsPanel } from './QuoteSkuMappingsPanel'; + +const ROWS = [ + { + supplier_sku_code: 'SKU1', + supplier_sku_name: '草鱼', + supplier_unit: '斤', + delivery_sku_code: 'D-001', + delivery_sku_name: '草鱼(配送)', + status: 'active', + synced_at: '2026-10-18T00:00:00.000Z', + }, + { + supplier_sku_code: 'SKU2', + supplier_sku_name: '鲤鱼', + supplier_unit: '袋', + delivery_sku_code: null, + delivery_sku_name: null, + status: 'pending', + synced_at: null, + }, +]; + +beforeEach(() => { + listApi.mockReset(); + notify.error.mockReset(); + notify.success.mockReset(); + listApi.mockResolvedValue({ + data: ROWS, + summary: { total: 2, mapped: 1, unmapped: 1 }, + pull: null, + }); +}); + +afterEach(() => { + cleanup(); +}); + +describe('商品映射(只读)面板', () => { + it('展示我方/配送 SKU、单位、状态与汇总;只读(无编辑入口)', async () => { + render(); + expect(await screen.findByText('草鱼')).toBeTruthy(); + expect(screen.getByText('D-001')).toBeTruthy(); + expect(screen.getByText('草鱼(配送)')).toBeTruthy(); + expect(screen.getByText('共 2 个商品,已映射 1 / 未映射 1')).toBeTruthy(); + expect(screen.getAllByText('已映射').length).toBeGreaterThanOrEqual(1); + expect(screen.getAllByText('未映射').length).toBeGreaterThanOrEqual(1); + // 只读:没有编辑/绑定/解绑/保存按钮 + for (const forbidden of ['编辑', '绑定', '解绑', '保存']) { + expect(screen.queryByText(forbidden)).toBeNull(); + } + // 进入时 refresh=1(先拉 D5 再展示) + expect((listApi.mock.calls[0][0] as any).refresh).toBe(true); + }); + + it('「只看未映射」⇒ 带 status=pending 重新请求', async () => { + render(); + await screen.findByText('草鱼'); + fireEvent.click(screen.getByLabelText('只看未映射')); + await waitFor(() => + expect(listApi.mock.calls.some(([arg]) => (arg as any).status === 'pending')).toBe(true) + ); + }); + + it('关键字搜索 ⇒ 带 q 重新请求', async () => { + render(); + await screen.findByText('草鱼'); + fireEvent.change(screen.getByLabelText('搜索 SKU/名称'), { target: { value: '草鱼' } }); + await waitFor(() => expect(listApi.mock.calls.some(([arg]) => (arg as any).q === '草鱼')).toBe(true)); + }); + + it('开关关闭(503)⇒ 空态显示后端原文,不弹 toast', async () => { + listApi.mockRejectedValue( + Object.assign(new Error('报价单价格传递未开启(MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL)'), { + status: 503, + code: 'feature_disabled', + }) + ); + render(); + expect( + await screen.findByText('报价单价格传递未开启(MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL)') + ).toBeTruthy(); + expect(notify.error).not.toHaveBeenCalled(); + }); + + it('普通失败 ⇒ 弹错误(不是静默空白)', async () => { + listApi.mockRejectedValue(new Error('网络错误')); + render(); + await waitFor(() => expect(notify.error).toHaveBeenCalledWith('网络错误')); + }); +}); diff --git a/src/pages/customers/QuoteSkuMappingsPanel.tsx b/src/pages/customers/QuoteSkuMappingsPanel.tsx new file mode 100644 index 0000000..29008bd --- /dev/null +++ b/src/pages/customers/QuoteSkuMappingsPanel.tsx @@ -0,0 +1,169 @@ +import React, { useCallback, useEffect, useState } from 'react'; +import { RefreshCw, Search } from 'lucide-react'; +import { notify } from '../../utils/notify'; +import { useT } from '../../i18n'; +import { listSkuMappingsApi, type SkuMappingDto } from '../../utils/workflowApi'; + +/** + * **商品映射(只读)**面板(2026-10-18 增量,冻结契约 `.team/sku-mapping-shared-sheet/contract.md` §5)。 + * + * 映射在**配送系统维护**,供应商侧只读同步、**不可编辑**(没有绑定/解绑/编辑入口): + * · 展示 我方商品/SKU ↔ 配送商品/SKU、单位、状态(已映射 / 未映射 / 已停用); + * · 「只看未映射」筛选;进入时 `refresh=1` 拉一次 D5;开关关闭走空态(不弹重复错误)。 + */ + +function statusLabel(t: (key: string) => string, status: string): string { + if (status === 'active') return t('quotes.skuMapping.statusActive'); + if (status === 'disabled') return t('quotes.skuMapping.statusDisabled'); + return t('quotes.skuMapping.statusPending'); +} + +function isMapped(row: SkuMappingDto): boolean { + return row.status === 'active' && Boolean(row.delivery_sku_code); +} + +export const QuoteSkuMappingsPanel: React.FC = () => { + const t = useT(); + const [rows, setRows] = useState([]); + const [summary, setSummary] = useState({ total: 0, mapped: 0, unmapped: 0 }); + const [loading, setLoading] = useState(false); + const [unmappedOnly, setUnmappedOnly] = useState(false); + const [keyword, setKeyword] = useState(''); + const [disabledReason, setDisabledReason] = useState(null); + + const load = useCallback( + async (options?: { refresh?: boolean }) => { + setLoading(true); + try { + const result = await listSkuMappingsApi({ + status: unmappedOnly ? 'pending' : undefined, + q: keyword.trim() || undefined, + refresh: options?.refresh === true, + }); + setDisabledReason(null); + setRows(Array.isArray(result.data) ? result.data : []); + setSummary(result.summary || { total: 0, mapped: 0, unmapped: 0 }); + } catch (error: any) { + if (Number(error?.status) === 503 || error?.code === 'feature_disabled') { + setRows([]); + setDisabledReason(error?.message || t('quotes.skuMapping.loadFail')); + return; + } + notify.error(error?.message || t('quotes.skuMapping.loadFail')); + } finally { + setLoading(false); + } + }, + [keyword, unmappedOnly, t] + ); + + useEffect(() => { + void load({ refresh: true }); + }, [load]); + + return ( +
+
+
+

{t('quotes.skuMapping.title')}

+ + {t('quotes.skuMapping.summary', { total: summary.total, mapped: summary.mapped, unmapped: summary.unmapped })} + +
+ {disabledReason ? null : ( +
+ +
+ + setKeyword(event.target.value)} + placeholder={t('quotes.skuMapping.searchPh')} + aria-label={t('quotes.skuMapping.searchPh')} + className="app-input app-focus-ring w-48 pl-8 pr-2 py-1.5 text-sm rounded-lg border border-slate-200 dark:border-slate-600" + /> +
+ +
+ )} +
+ + {disabledReason ? ( +
+ {disabledReason} +
+ ) : !loading && rows.length === 0 ? ( +
+ {t('quotes.skuMapping.empty')} +
+ ) : ( +
+ + + + + + + + + + + {rows.map((row) => ( + + + + + + + ))} + +
{t('quotes.skuMapping.supplierSku')}{t('quotes.skuMapping.unit')}{t('quotes.skuMapping.deliverySku')}{t('quotes.skuMapping.status')}
+
+ {row.supplier_sku_name || row.supplier_sku_code} +
+
{row.supplier_sku_code}
+
{row.supplier_unit || '—'} + {isMapped(row) ? ( + <> +
+ {row.delivery_sku_name || row.delivery_sku_code} +
+
{row.delivery_sku_code}
+ + ) : ( + {t('quotes.skuMapping.statusPending')} + )} +
+ + {statusLabel(t, row.status)} + +
+
+ )} +
+ ); +}; diff --git a/src/pages/customers/QuoteVersionManagement.changeRequest.contract.test.ts b/src/pages/customers/QuoteVersionManagement.changeRequest.contract.test.ts new file mode 100644 index 0000000..a5d4128 --- /dev/null +++ b/src/pages/customers/QuoteVersionManagement.changeRequest.contract.test.ts @@ -0,0 +1,53 @@ +import { readFileSync } from 'node:fs'; +import { describe, expect, it } from 'vitest'; + +/** + * 报价单页接入「改价需审核」的**接线契约**(2026-10-18 增量需求)。 + * + * 为什么用源码断言而不是整页渲染:这一页有 1700 行、十几个异步数据源(客户/商品/分类/权限/导出), + * 整页 render 的失败面与本次改动无关;而这里要钉的恰恰是**接线**: + * · 保存响应 `applied === false` ⇒ 必须提示「已提交审核」并切到「待审改价」页签(不能提示"已更新"); + * · 「待审改价」是页内 chrome tab(不新增独立菜单),只对有报价单编辑权的人可见; + * · 面板的审批按钮按 `customer_manage` 再收一次(无权限只读); + * · 审核通过后刷新报价单列表。 + */ +const page = readFileSync(new URL('./QuoteVersionManagement.tsx', import.meta.url), 'utf8'); + +describe('报价单页 · 改价审核接线', () => { + it('保存响应 applied === false ⇒ 提示「已提交审核」+ 切到待审页签 + 关弹窗(不得提示"已更新")', () => { + const start = page.indexOf('const handleSave = async () => {'); + expect(start).toBeGreaterThan(-1); + const end = page.indexOf('const toggleExpand', start); + expect(end).toBeGreaterThan(start); + const handler = page.slice(start, end); + + expect(handler).toMatch(/const response = await updateQuoteSheetApi\(editingCode, payload\);/); + expect(handler).toMatch(/if \(response\.applied === false\)/); + expect(handler).toContain("notify.success(t('quotes.toast.submittedForApproval'))"); + expect(handler).toMatch(/closeFormModal\(\);\s*\n\s*setPageTab\('pending'\);/); + // 「已提交审核」分支必须在「已更新」之前 return,不能两个提示都弹 + expect(handler.indexOf("t('quotes.toast.submittedForApproval')")).toBeLessThan( + handler.indexOf("t('quotes.toast.updated')") + ); + }); + + it('「待审改价」是页内页签(不新增菜单),且只对有报价单编辑权的人可见', () => { + expect(page).toContain("t('quotes.tab.pendingCharges')"); + expect(page).toMatch(/id: 'pending', label: t\('quotes\.tab\.pendingCharges'\), hidden: !canManageQuotes/); + // 页签值参与 chromeTab 映射('pending' 不能被吞成 active/history;2026-10-18 后又加了 deliveryPrice) + expect(page).toMatch(/pageTab === 'pending'[\s\S]{0,80}?'pending'/); + }); + + it('待审页签渲染面板;审批权按 customer_manage 收窄;通过后刷新报价单列表', () => { + expect(page).toContain(' \{[\s\S]{0,240}?void loadSheets\(\);/); + }); + + it('待审页签不显示客户筛选(避免误导"按客户筛待审")', () => { + // 2026-10-18 增加「配送商成本价确认」「商品映射」两个页签后,非报价单列表页签都不显示客户筛选 + expect(page).toMatch( + /\{pageTab !== 'pending' && pageTab !== 'deliveryPrice' && pageTab !== 'skuMappings' \? \(/ + ); + }); +}); diff --git a/src/pages/customers/QuoteVersionManagement.priceProposal.contract.test.ts b/src/pages/customers/QuoteVersionManagement.priceProposal.contract.test.ts new file mode 100644 index 0000000..292062c --- /dev/null +++ b/src/pages/customers/QuoteVersionManagement.priceProposal.contract.test.ts @@ -0,0 +1,71 @@ +import { readFileSync } from 'node:fs'; +import { describe, expect, it } from 'vitest'; + +/** + * 报价单页接入「双向价格传递」的**接线契约**(2026-10-18 增量): + * · 行为:`提交配送商审核` 按钮只对"生效中 + 有报价单编辑权"的行显示,点击调 A 发起接口, + * 成功提示「已提交配送商审核」并切到「配送商成本价确认」页签;失败把后端中文说明透出; + * · 只读:无 `customer_manage` 时通过/驳回按钮不渲染(面板内按权限收); + * · 页内页签(不新增菜单),手输 URL 无权限也退回当前执行; + * · **不碰订单取价公式**(T1:协商的是成本价,订单行价仍读 `sale_price`)。 + */ +const page = readFileSync(new URL('./QuoteVersionManagement.tsx', import.meta.url), 'utf8'); + +describe('报价单页 · 双向价格传递接线', () => { + it('「提交配送商审核」按钮:生效中 + 有编辑权才显示,点击调 A 发起并切到确认页签', () => { + expect(page).toContain("t('quotes.action.submitForDeliveryReview')"); + expect(page).toMatch(/\{isActiveSheet\(row\) && canManageQuotes && \(/); + expect(page).toContain('submitQuotePriceProposalApi(row.quote_sheet_code)'); + expect(page).toContain("notify.success(t('quotes.toast.submittedForDeliveryReview'))"); + expect(page).toMatch(/setPageTab\('deliveryPrice'\)/); + expect(page).toContain("notify.error(error?.message || t('quotes.toast.submitForDeliveryFail'))"); + // 防连点:同一时刻只允许一条在途 + expect(page).toContain('submittingProposalCode'); + expect(page).toMatch(/disabled=\{submittingProposalCode === row\.quote_sheet_code\}/); + }); + + it('「配送商成本价确认」是页内页签(不新增菜单),审批权按 customer_manage 收窄', () => { + expect(page).toContain("t('quotes.tab.deliveryPrice')"); + expect(page).toMatch(/id: 'deliveryPrice', label: t\('quotes\.tab\.deliveryPrice'\), hidden: !canManageQuotes/); + expect(page).toMatch(/pageTab === 'deliveryPrice'/); + expect(page).toContain(' { + expect(page).toMatch( + /if \(\(view !== 'pending' && view !== 'deliveryPrice' && view !== 'skuMappings'\) \|\| canManageQuotes\) return;/ + ); + }); + + it('提交配送商审核失败时透出后端中文说明(如内部审核在途 409)', () => { + expect(page).toMatch(/catch \(error: any\) \{\s*\n\s*notify\.error\(error\?\.message \|\| t\('quotes\.toast\.submitForDeliveryFail'\)\);/); + }); + + it('SKU 映射:报价单页有「同步商品字典」按钮(D4 推字典 + D5 拉映射)', () => { + expect(page).toContain("t('quotes.action.syncSkuDictionary')"); + expect(page).toContain('syncSkuDictionaryApi()'); + expect(page).toContain("t('quotes.toast.syncSkuDictionaryDone'"); + expect(page).toContain("notify.error(error?.message || t('quotes.toast.syncSkuDictionaryFail'))"); + expect(page).toContain('syncingDictionary'); + }); + + it('提交前展示映射统计「本单 N 个商品,已映射 X / 未映射 Y」', () => { + expect(page).toContain('getSheetMappingStatsApi(row.quote_sheet_code)'); + expect(page).toContain("t('quotes.toast.mappingStats'"); + const statsIdx = page.indexOf('getSheetMappingStatsApi(row.quote_sheet_code)'); + const submitIdx = page.indexOf('submitQuotePriceProposalApi(row.quote_sheet_code)'); + expect(statsIdx).toBeGreaterThan(-1); + expect(submitIdx).toBeGreaterThan(statsIdx); + }); + + it('商品映射是页内只读页签(不新增菜单;无编辑/绑定入口)', () => { + expect(page).toContain("id: 'skuMappings', label: t('quotes.tab.skuMappings')"); + expect(page).toContain(''); + }); + + it('T1:不在报价单页改订单取价(只改成本,订单价仍读 sale_price)', () => { + expect(page).not.toContain('orderPricingService'); + expect(page).not.toMatch(/order_items/); + }); +}); diff --git a/src/pages/customers/QuoteVersionManagement.tsx b/src/pages/customers/QuoteVersionManagement.tsx index bd7a938..3b05612 100644 --- a/src/pages/customers/QuoteVersionManagement.tsx +++ b/src/pages/customers/QuoteVersionManagement.tsx @@ -17,6 +17,9 @@ import { getQuoteSheetApi, updateQuoteSheetApi, setQuoteSheetAutoSalePriceApi, + submitQuotePriceProposalApi, + syncSkuDictionaryApi, + getSheetMappingStatsApi, deleteQuoteSheetApi, } from '../../utils/workflowApi'; import { DocumentExportButton } from '../../components/export/DocumentExportButton'; @@ -44,6 +47,9 @@ import { useClientTablePagination } from '../../hooks/useClientTablePagination'; import { TablePaginationBar } from '../../components/ui/TablePaginationBar'; import { SortableThLabel } from '../../components/ui/SortableThLabel'; import { CustomerSkuLibraryPanel } from '../../components/customers/CustomerSkuLibraryPanel'; +import { QuoteChangeRequestsPanel } from './QuoteChangeRequestsPanel'; +import { QuoteDeliveryPriceProposalsPanel } from './QuoteDeliveryPriceProposalsPanel'; +import { QuoteSkuMappingsPanel } from './QuoteSkuMappingsPanel'; import { AppPageTabs } from '../../components/ModuleTabLayout'; import { PageFilterToolbar } from '../../components/ui/PagePrimitives'; import { useT } from '../../i18n'; @@ -330,10 +336,19 @@ export const QuoteVersionManagement: React.FC = () => { const canManageQuotes = hasPermission(['customer_manage', 'order_manage']); const canManageCustomerLibrary = hasPermission('customer_manage'); const [searchParams, setSearchParams] = useSearchParams(); - const pageTab: 'sheets' | 'library' = searchParams.get('view') === 'library' ? 'library' : 'sheets'; - const setPageTab = (tab: 'sheets' | 'library') => { + const pageTab: 'sheets' | 'library' | 'pending' | 'deliveryPrice' | 'skuMappings' = + searchParams.get('view') === 'library' + ? 'library' + : searchParams.get('view') === 'pending' + ? 'pending' + : searchParams.get('view') === 'deliveryPrice' + ? 'deliveryPrice' + : searchParams.get('view') === 'skuMappings' + ? 'skuMappings' + : 'sheets'; + const setPageTab = (tab: 'sheets' | 'library' | 'pending' | 'deliveryPrice' | 'skuMappings') => { const next = new URLSearchParams(searchParams); - if (tab === 'library') next.set('view', 'library'); + if (tab === 'library' || tab === 'pending' || tab === 'deliveryPrice' || tab === 'skuMappings') next.set('view', tab); else next.delete('view'); setSearchParams(next, { replace: true }); }; @@ -344,12 +359,25 @@ export const QuoteVersionManagement: React.FC = () => { const prevBranchRef = useRef(effectiveBranchCode); const loading = initialLoading || refreshing; const [saving, setSaving] = useState(false); + /** 「提交配送商审核」在途的单号(同一时刻只允许一条,防连点重复提交) */ + const [submittingProposalCode, setSubmittingProposalCode] = useState(null); + /** 「同步商品字典」在途(D4 推字典 + D5 拉映射) */ + const [syncingDictionary, setSyncingDictionary] = useState(false); const [viewFilter, setViewFilter] = useState<'active' | 'history'>('active'); - type QuoteChromeTab = 'active' | 'history' | 'library'; - const chromeTab: QuoteChromeTab = pageTab === 'library' ? 'library' : viewFilter; + type QuoteChromeTab = 'active' | 'history' | 'library' | 'pending' | 'deliveryPrice' | 'skuMappings'; + const chromeTab: QuoteChromeTab = + pageTab === 'library' + ? 'library' + : pageTab === 'pending' + ? 'pending' + : pageTab === 'deliveryPrice' + ? 'deliveryPrice' + : pageTab === 'skuMappings' + ? 'skuMappings' + : viewFilter; const setChromeTab = (tab: QuoteChromeTab) => { - if (tab === 'library') { - setPageTab('library'); + if (tab === 'library' || tab === 'pending' || tab === 'deliveryPrice' || tab === 'skuMappings') { + setPageTab(tab); return; } setPageTab('sheets'); @@ -487,6 +515,15 @@ export const QuoteVersionManagement: React.FC = () => { setSearchParams(next, { replace: true }); }, [canManageCustomerLibrary, searchParams, setSearchParams]); + // 无报价单编辑权的人看不到「待审改价 / 配送商成本价确认」页签:手输 URL 进来也退回当前执行(后端另有 403 兜底) + useEffect(() => { + const view = searchParams.get('view'); + if ((view !== 'pending' && view !== 'deliveryPrice' && view !== 'skuMappings') || canManageQuotes) return; + const next = new URLSearchParams(searchParams); + next.delete('view'); + setSearchParams(next, { replace: true }); + }, [canManageQuotes, searchParams, setSearchParams]); + const customerFilterOptions = useMemo( () => customers.map((c) => ({ value: c.customer_code, label: c.company_name, searchText: c.customer_code })), [customers] @@ -791,6 +828,64 @@ export const QuoteVersionManagement: React.FC = () => { return result; }; + /** + * 方向 A:把整张单的销售价提交给配送商审核(2026-10-18 冻结契约)。 + * 后端会先检查**内部改价审核无在途 pending**(否则 409 internal_review_pending),再调 D1;**不写价**。 + */ + const submitForDeliveryReview = async (row: QuoteSheetRow) => { + if (!canManageQuotes) { + notify(t('quotes.toast.noEditPermission')); + return; + } + if (submittingProposalCode) return; + setSubmittingProposalCode(row.quote_sheet_code); + try { + // 提交前先算映射统计(契约 §5):未映射不阻止提交,但要让用户看到「本单 N 个商品,已映射 X / 未映射 Y」 + try { + const stats = await getSheetMappingStatsApi(row.quote_sheet_code); + const data = stats?.data; + if (data) { + notify.info( + t('quotes.toast.mappingStats', { + total: Number(data.total) || 0, + mapped: Number(data.mapped) || 0, + unmapped: Number(data.unmapped) || 0, + }) + ); + } + } catch { + // 统计失败不拦提交:真正的错误(如开关未开启)由下面的提交请求透出 + } + await submitQuotePriceProposalApi(row.quote_sheet_code); + notify.success(t('quotes.toast.submittedForDeliveryReview')); + setPageTab('deliveryPrice'); + } catch (error: any) { + notify.error(error?.message || t('quotes.toast.submitForDeliveryFail')); + } finally { + setSubmittingProposalCode(null); + } + }; + + /** 同步商品字典:把我方 skus 整批推配送侧(D4),随后拉回映射(D5)。映射仍由配送侧维护,本系统只读。 */ + const handleSyncSkuDictionary = async () => { + if (!canManageQuotes || syncingDictionary) return; + setSyncingDictionary(true); + try { + const result = await syncSkuDictionaryApi(); + const push = result?.data?.push; + notify.success( + t('quotes.toast.syncSkuDictionaryDone', { + matched: Number(push?.matched) || 0, + pending: Number(push?.pending) || 0, + }) + ); + } catch (error: any) { + notify.error(error?.message || t('quotes.toast.syncSkuDictionaryFail')); + } finally { + setSyncingDictionary(false); + } + }; + const handleSave = async () => { if (lines.some((line) => { if (!line.markup_ratio.trim()) return false; @@ -831,7 +926,18 @@ export const QuoteVersionManagement: React.FC = () => { items, }; if (editingCode) { - await updateQuoteSheetApi(editingCode, payload); + const response = await updateQuoteSheetApi(editingCode, payload); + if (response.applied === false) { + /** + * 价格相关改动需要审核(2026-10-18 增量):报价单**一点没动**,只落了一条待审变更。 + * 明确提示并切到「待审改价」页签展示待审摘要(那里能看到 改前 → 改后)。 + * 本次口径只审 `PUT /quote/sheets/:code`;只改标题/周期/生效日/客户仍直接保存(`applied:true`)。 + */ + notify.success(t('quotes.toast.submittedForApproval')); + closeFormModal(); + setPageTab('pending'); + return; + } notify.success(t('quotes.toast.updated')); } else { await createQuoteSheetApi(payload); @@ -956,20 +1062,27 @@ export const QuoteVersionManagement: React.FC = () => { { id: 'active', label: t('quotes.tab.active') }, { id: 'history', label: t('quotes.tab.history') }, { id: 'library', label: t('quotes.tab.library'), hidden: !canManageCustomerLibrary }, + // 待审改价:能编辑报价单的人都能看(只读);审批按钮在面板内按 customer_manage 再收一次 + { id: 'pending', label: t('quotes.tab.pendingCharges'), hidden: !canManageQuotes }, + // 配送商成本价确认:能看报价单的人都能看(只读);通过/驳回在面板内按 customer_manage 再收一次 + { id: 'deliveryPrice', label: t('quotes.tab.deliveryPrice'), hidden: !canManageQuotes }, + { id: 'skuMappings', label: t('quotes.tab.skuMappings'), hidden: !canManageQuotes }, ]} /> {pageTab === 'sheets' && viewFilter === 'history' ? ( {t('quotes.history.hint')} ) : null} - + {pageTab !== 'pending' && pageTab !== 'deliveryPrice' && pageTab !== 'skuMappings' ? ( + + ) : null} {pageTab === 'sheets' ? (
+ )} + {isActiveSheet(row) && canManageQuotes && ( + + )} {row.status !== 0 && (