feat(报价单): 双向价格传递/改价审核/SKU 映射/成本同步推送(供应商侧)
- 报价单生效自动推销售价 → 配送成本价(台账+重试+rearm,映射优先) - 编辑生效单改价走内部审核(quote_sheet_change_requests) - 双向价格传递:A 提交配送商审核 / B 拉回并反查映射后写价、D3 回执 - SKU 映射:D4 字典推送、D5 完整拉取(截断不删)、只读本地副本 - 迁移登记 tenant_business_tables(三张租户表数组互相补齐,避免顺序敏感)
This commit is contained in:
@@ -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)。
|
||||
|
||||
@@ -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_*)
|
||||
|
||||
@@ -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_<X> 解析);整单级跳过(无 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> 的 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 $$;
|
||||
@@ -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();
|
||||
@@ -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();
|
||||
@@ -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();
|
||||
@@ -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)---
|
||||
|
||||
@@ -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 || '驳回配送商成本价失败',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -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<MainSystemResult<unknown>, { 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<T>(
|
||||
supplierCode: string,
|
||||
call: (token: string) => Promise<MainSystemResult<T>>
|
||||
): Promise<MainSystemResult<T>> {
|
||||
const first = await getMainSystemToken(supplierCode);
|
||||
if (first.kind !== 'ok') {
|
||||
return {
|
||||
kind: first.kind === 'not_configured' ? 'not_configured' : 'unavailable',
|
||||
status: 0,
|
||||
reason: first.reason,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
const result = await call(first.token);
|
||||
if (result.kind === 'ok' || Number(result.status) !== 401) return result;
|
||||
const refreshed = await getMainSystemToken(supplierCode, { forceRefresh: true });
|
||||
if (refreshed.kind !== 'ok') {
|
||||
return {
|
||||
kind: refreshed.kind === 'not_configured' ? 'not_configured' : 'unavailable',
|
||||
status: 0,
|
||||
reason: refreshed.reason,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
return call(refreshed.token);
|
||||
}
|
||||
|
||||
/**
|
||||
* 403 在本项目 HTTP 层的默认归类是"暂态"(下轮重试),但本端点 403 是**语义拒绝**
|
||||
* (`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<string, unknown>;
|
||||
// 兼容对方包一层 `data` 的写法(契约是 `{ success, data }`)
|
||||
const data = (body.data && typeof body.data === 'object' ? body.data : body) as Record<string, unknown>;
|
||||
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<string, unknown>;
|
||||
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<QuoteCostSyncOutcome> {
|
||||
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<any>(supplierCode, (token) =>
|
||||
requestMainSystem<any>({
|
||||
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) };
|
||||
}
|
||||
@@ -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<MainSystemResult<unknown>, { kind: 'ok' }>
|
||||
): { kind: 'rejected' | 'unavailable' | 'not_configured'; status: number; code: string; reason: string; payload: unknown } {
|
||||
const status = Number(result.status) || 0;
|
||||
const payload = (result as { payload?: unknown }).payload ?? null;
|
||||
return {
|
||||
kind: result.kind,
|
||||
status,
|
||||
code: result.kind === 'not_configured' ? 'not_configured' : readSkuMappingErrorCode(payload, status),
|
||||
reason: result.reason || '调用主系统失败',
|
||||
payload,
|
||||
};
|
||||
}
|
||||
|
||||
async function callWithToken<T>(
|
||||
supplierCode: string,
|
||||
call: (token: string) => Promise<MainSystemResult<T>>
|
||||
): Promise<MainSystemResult<T>> {
|
||||
const first = await getMainSystemToken(supplierCode);
|
||||
if (first.kind !== 'ok') {
|
||||
return {
|
||||
kind: first.kind === 'not_configured' ? 'not_configured' : 'unavailable',
|
||||
status: 0,
|
||||
reason: first.reason,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
const result = await call(first.token);
|
||||
if (result.kind === 'ok' || Number(result.status) !== 401) return result;
|
||||
const refreshed = await getMainSystemToken(supplierCode, { forceRefresh: true });
|
||||
if (refreshed.kind !== 'ok') {
|
||||
return {
|
||||
kind: refreshed.kind === 'not_configured' ? 'not_configured' : 'unavailable',
|
||||
status: 0,
|
||||
reason: refreshed.reason,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
return call(refreshed.token);
|
||||
}
|
||||
|
||||
/** 403 在本端点也是语义拒绝(未绑定该分公司/无权同步),按 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<string, unknown>;
|
||||
const data = (body.data && typeof body.data === 'object' ? body.data : body) as Record<string, unknown>;
|
||||
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<string, unknown>;
|
||||
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<PushSkuDictionaryOutcome> {
|
||||
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<any>(supplierCode, (token) =>
|
||||
requestMainSystem<any>({
|
||||
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<PullSkuMappingsOutcome> {
|
||||
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<any>(supplierCode, (token) =>
|
||||
requestMainSystem<any>({
|
||||
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<string, unknown>;
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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_<X>` 解析出的主系统分公司码(去重、升序) */
|
||||
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<string | null> {
|
||||
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<QuoteCostSyncPlan> {
|
||||
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<string>();
|
||||
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<void> {
|
||||
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<string, unknown>
|
||||
): Record<string, unknown> {
|
||||
const counts: Record<string, number> = {};
|
||||
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<LedgerSnapshot | null> {
|
||||
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<string, unknown>).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<string | null> {
|
||||
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<string, unknown>), 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<boolean> {
|
||||
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<QuoteCostSyncPushSummary> {
|
||||
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<string, unknown>), 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<QuoteCostSyncRetrySummary> {
|
||||
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<QuoteCostSyncRetryRow>(
|
||||
`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;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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_<action>`,四要素:变更单 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<void> {
|
||||
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<string>();
|
||||
const duplicates = new Set<string>();
|
||||
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<QuoteChangeSummary, 'item_count' | 'added' | 'removed' | 'updated' | 'lines' | 'truncated'> {
|
||||
const index = (rows: ItemLike[]) => {
|
||||
const map = new Map<string, ItemLike>();
|
||||
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<ItemLike[]> {
|
||||
const result = await pool.query<ItemLike>(
|
||||
`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<QuoteChangeSummary> {
|
||||
return buildChangeSummaryFromItems(payload, await loadSheetItems(quoteSheetCode));
|
||||
}
|
||||
|
||||
function toDto(row: Record<string, any>): 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<string, any>), 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<SaveQuoteSheetEditResult> {
|
||||
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<QuoteChangeRequestDto[]> {
|
||||
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<string, any>));
|
||||
const pendingCodes = [...new Set(rows.filter((row) => row.status === 'pending').map((row) => row.quote_sheet_code))];
|
||||
if (pendingCodes.length) {
|
||||
const items = await pool.query<ItemLike & { quote_sheet_code: string }>(
|
||||
`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<string, ItemLike[]>();
|
||||
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<string, unknown>;
|
||||
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<void> {
|
||||
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<string, any>;
|
||||
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<string, any>;
|
||||
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<string, any>;
|
||||
// 系统自动驳回也留审计(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<string, any>;
|
||||
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<string, any>);
|
||||
// 审计(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 };
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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(),
|
||||
]);
|
||||
|
||||
@@ -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<SkuDictionaryPushSummary> {
|
||||
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<SkuMappingPullSummary> {
|
||||
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<string, RemoteSkuMappingRow>();
|
||||
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<SheetMappingStats> {
|
||||
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<LocalSkuMappingList> {
|
||||
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<any>(
|
||||
`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 };
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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<typeof import('../src/services/mainSystem/config')>();
|
||||
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');
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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<Record<string, unknown>>,
|
||||
}));
|
||||
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<string, unknown>) => {
|
||||
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<string> {
|
||||
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]]
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -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_<main_branch_code>` 解析唯一生效单,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<typeof import('../src/services/mainSystemQuoteCostSync')>();
|
||||
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<T = Record<string, unknown>>(sql: string, params: unknown[] = []): Promise<T[]> {
|
||||
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<ItemRow[]> {
|
||||
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<string> {
|
||||
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<string> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<Awaited<ReturnType<typeof approvePriceProposal>>> =>
|
||||
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');
|
||||
});
|
||||
});
|
||||
@@ -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<string, unknown> | 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<typeof import('../src/modules/workflow/context')>();
|
||||
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<string, unknown> = {}) {
|
||||
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<string, unknown> = {}) => ({
|
||||
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<string, unknown>;
|
||||
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<string, unknown>;
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -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<typeof import('../src/services/quoteSheetService')>();
|
||||
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<typeof import('../src/services/mainSystemQuoteCostSync')>();
|
||||
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<string, any>;
|
||||
|
||||
type DbState = {
|
||||
sheet: Record<string, any>;
|
||||
items: Array<Record<string, any>>;
|
||||
sheetCustomers: string[];
|
||||
changeRequests: Map<string, MockChangeRequest>;
|
||||
aliveSkus: Set<string>;
|
||||
branchCustomers: Set<string>;
|
||||
events: string[];
|
||||
};
|
||||
|
||||
const SHEET = 'QS1';
|
||||
const BRANCH = 'BR002';
|
||||
|
||||
function seedSheet(overrides: Partial<Record<string, any>> = {}) {
|
||||
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> = {}): 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);
|
||||
});
|
||||
});
|
||||
@@ -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<string, unknown>;
|
||||
}) {
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -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<unknown>) => 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<typeof import('../src/services/mainSystem/config')>();
|
||||
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<void> {
|
||||
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');
|
||||
});
|
||||
});
|
||||
@@ -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<string, any>;
|
||||
items: Array<Record<string, any>>;
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -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<typeof import('../src/services/mainSystemQuoteCostSync')>();
|
||||
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<typeof import('../src/services/mainSystem/api/skuMappings')>();
|
||||
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> = {}): 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<unknown>) => 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();
|
||||
});
|
||||
});
|
||||
@@ -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<void> {
|
||||
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();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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',
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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': '版本',
|
||||
|
||||
@@ -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<string, string>;
|
||||
};
|
||||
const { common } = (await import('../../i18n/locales/zh-CN/common')) as unknown as {
|
||||
common: Record<string, string>;
|
||||
};
|
||||
const dict: Record<string, string> = {};
|
||||
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<string, unknown>) => {
|
||||
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(<QuoteChangeRequestsPanel canApprove />);
|
||||
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(<QuoteChangeRequestsPanel canApprove={false} />);
|
||||
expect(await screen.findByText('QS1792200796033LUTV')).toBeTruthy();
|
||||
expect(screen.queryByText('通过')).toBeNull();
|
||||
expect(screen.queryByText('驳回')).toBeNull();
|
||||
});
|
||||
|
||||
it('空列表 ⇒ 暂无待审改价', async () => {
|
||||
listApi.mockResolvedValue({ data: [] });
|
||||
render(<QuoteChangeRequestsPanel canApprove />);
|
||||
expect(await screen.findByText('暂无待审改价')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('通过 ⇒ 调审核接口、成功提示、刷新列表并回调 onApplied', async () => {
|
||||
const onApplied = vi.fn();
|
||||
render(<QuoteChangeRequestsPanel canApprove onApplied={onApplied} />);
|
||||
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(<QuoteChangeRequestsPanel canApprove />);
|
||||
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(<QuoteChangeRequestsPanel canApprove />);
|
||||
await waitFor(() => expect(notify.error).toHaveBeenCalledWith('加载失败'));
|
||||
});
|
||||
});
|
||||
@@ -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<QuoteChangeRequestsPanelProps> = ({
|
||||
canApprove,
|
||||
onApplied,
|
||||
}) => {
|
||||
const t = useT();
|
||||
const [rows, setRows] = useState<QuoteChangeRequestDto[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [actingId, setActingId] = useState<string | null>(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 (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-sm font-semibold text-gray-800 dark:text-gray-100">
|
||||
{t('quotes.changeRequest.title')}
|
||||
{rows.length ? <span className="ml-2 text-gray-500">({rows.length})</span> : null}
|
||||
</h2>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void load()}
|
||||
className="p-2 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700"
|
||||
title={t('common.refresh')}
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{!loading && rows.length === 0 ? (
|
||||
<div className="app-surface rounded-2xl border border-gray-200 dark:border-gray-700 p-8 text-center text-sm text-gray-500">
|
||||
{t('quotes.changeRequest.empty')}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{rows.map((row) => {
|
||||
const summary = row.summary;
|
||||
const busy = actingId === row.id;
|
||||
return (
|
||||
<div
|
||||
key={row.id}
|
||||
className="app-surface rounded-2xl border border-gray-200 dark:border-gray-700 p-4 space-y-3"
|
||||
>
|
||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div className="space-y-1">
|
||||
<p className="font-medium text-gray-900 dark:text-gray-100">
|
||||
{row.quote_sheet_code}
|
||||
{summary ? (
|
||||
<span className="ml-2 text-xs text-gray-500">
|
||||
{t('quotes.changeRequest.itemCount', { count: summary.item_count })}
|
||||
</span>
|
||||
) : null}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
{t('quotes.changeRequest.submittedBy')}:{row.requested_by_name || '—'} ·{' '}
|
||||
{t('quotes.changeRequest.submittedAt')}:{formatTime(row.requested_at)}
|
||||
</p>
|
||||
</div>
|
||||
{canApprove ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void handleApprove(row)}
|
||||
className="app-button-primary inline-flex items-center gap-1 px-3 py-1.5 rounded-lg text-sm disabled:opacity-50"
|
||||
>
|
||||
<Check className="w-4 h-4" />
|
||||
{t('quotes.changeRequest.approve')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => setRejecting({ id: row.id, reason: '' })}
|
||||
className="inline-flex items-center gap-1 px-3 py-1.5 rounded-lg text-sm border border-red-300 text-red-600 hover:bg-red-50 disabled:opacity-50"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
{t('quotes.changeRequest.reject')}
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{summary ? (
|
||||
<div className="space-y-1">
|
||||
<p className="text-xs font-medium text-gray-500">{t('quotes.changeRequest.summary')}</p>
|
||||
<ul className="space-y-1 text-sm text-gray-700 dark:text-gray-200">
|
||||
{summary.lines.map((line) => (
|
||||
<li key={`${line.change}-${line.sku_code}`} className="flex flex-wrap items-center gap-2">
|
||||
<span className="app-product-name">{line.sku_name || line.sku_code}</span>
|
||||
{line.unit ? <span className="text-xs text-gray-500">{line.unit}</span> : null}
|
||||
<span className="tabular-nums">{lineText(line)}</span>
|
||||
{lineCostText(line) ? (
|
||||
<span className="text-xs text-gray-500 tabular-nums">
|
||||
{t('quotes.export.col.cost_price')} {lineCostText(line)}
|
||||
</span>
|
||||
) : null}
|
||||
</li>
|
||||
))}
|
||||
{summary.lines.length === 0 ? (
|
||||
<li className="text-xs text-gray-500">
|
||||
{t('quotes.changeRequest.itemCount', { count: summary.item_count })}
|
||||
</li>
|
||||
) : null}
|
||||
{summary.truncated ? <li className="text-xs text-gray-500">…</li> : null}
|
||||
</ul>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{rejecting?.id === row.id ? (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<input
|
||||
value={rejecting.reason}
|
||||
onChange={(event) =>
|
||||
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"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void handleReject()}
|
||||
className="inline-flex items-center gap-1 px-3 py-1.5 rounded-lg text-sm bg-red-600 text-white hover:bg-red-700 disabled:opacity-50"
|
||||
>
|
||||
{t('quotes.changeRequest.reject')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => setRejecting(null)}
|
||||
className="px-3 py-1.5 rounded-lg text-sm text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
|
||||
>
|
||||
{t('common.cancel')}
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -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<string, string>;
|
||||
};
|
||||
const { common } = (await import('../../i18n/locales/zh-CN/common')) as unknown as {
|
||||
common: Record<string, string>;
|
||||
};
|
||||
const dict: Record<string, string> = {};
|
||||
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<string, unknown>) => {
|
||||
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(<QuoteDeliveryPriceProposalsPanel canApprove />);
|
||||
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(<QuoteDeliveryPriceProposalsPanel canApprove={false} />);
|
||||
expect(await screen.findByText('QS1792200796033LUTV')).toBeTruthy();
|
||||
expect(screen.queryByText('通过')).toBeNull();
|
||||
expect(screen.queryByText('驳回')).toBeNull();
|
||||
});
|
||||
|
||||
it('空列表 ⇒ 暂无待处理的配送商成本价提议', async () => {
|
||||
listApi.mockResolvedValue({ data: [], sync: null });
|
||||
render(<QuoteDeliveryPriceProposalsPanel canApprove />);
|
||||
expect(await screen.findByText('暂无待处理的配送商成本价提议')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('通过 ⇒ 调审批接口、按 applied 摘要提示、刷新并回调 onApplied', async () => {
|
||||
const onApplied = vi.fn();
|
||||
render(<QuoteDeliveryPriceProposalsPanel canApprove onApplied={onApplied} />);
|
||||
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(<QuoteDeliveryPriceProposalsPanel canApprove />);
|
||||
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(<QuoteDeliveryPriceProposalsPanel canApprove />);
|
||||
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(<QuoteDeliveryPriceProposalsPanel canApprove />);
|
||||
expect(
|
||||
await screen.findByText('报价单价格传递未开启(MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL)')
|
||||
).toBeTruthy();
|
||||
expect(notify.error).not.toHaveBeenCalled();
|
||||
expect(screen.queryByRole('button')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -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<QuoteDeliveryPriceProposalsPanelProps> = ({
|
||||
canApprove,
|
||||
onApplied,
|
||||
}) => {
|
||||
const t = useT();
|
||||
const [rows, setRows] = useState<QuotePriceProposalDto[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [actingId, setActingId] = useState<string | null>(null);
|
||||
const [rejecting, setRejecting] = useState<{ id: string; reason: string } | null>(null);
|
||||
/**
|
||||
* 开关关闭(后端 503 `feature_disabled`)时的**空态原因**:显示后端原文,且**只显示不弹 toast**。
|
||||
* 否则每次进页签都会弹一次"请求失败",用户以为坏了。
|
||||
*/
|
||||
const [disabledReason, setDisabledReason] = useState<string | null>(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 (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-sm font-semibold text-gray-800 dark:text-gray-100">
|
||||
{t('quotes.priceProposal.title')}
|
||||
{rows.length ? <span className="ml-2 text-gray-500">({rows.length})</span> : null}
|
||||
</h2>
|
||||
{disabledReason ? null : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void load()}
|
||||
className="p-2 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700"
|
||||
title={t('common.refresh')}
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{disabledReason ? (
|
||||
<div className="app-surface rounded-2xl border border-amber-200 dark:border-amber-800 bg-amber-50/60 dark:bg-amber-950/20 p-6 text-center text-sm text-amber-800 dark:text-amber-200">
|
||||
{disabledReason}
|
||||
</div>
|
||||
) : !loading && rows.length === 0 ? (
|
||||
<div className="app-surface rounded-2xl border border-gray-200 dark:border-gray-700 p-8 text-center text-sm text-gray-500">
|
||||
{t('quotes.priceProposal.empty')}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{rows.map((row) => {
|
||||
const busy = actingId === row.id;
|
||||
const isIncoming = row.direction === 'from_delivery';
|
||||
return (
|
||||
<div
|
||||
key={row.id}
|
||||
className="app-surface rounded-2xl border border-gray-200 dark:border-gray-700 p-4 space-y-3"
|
||||
>
|
||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div className="space-y-1">
|
||||
<p className="font-medium text-gray-900 dark:text-gray-100">
|
||||
{row.quote_sheet_code}
|
||||
<span className="ml-2 text-xs text-gray-500">
|
||||
{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 })}`
|
||||
: ''}
|
||||
</span>
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
{t('quotes.priceProposal.submittedBy')}:{row.requested_by_name || '—'} ·{' '}
|
||||
{t('quotes.priceProposal.submittedAt')}:{formatTime(row.requested_at)}
|
||||
</p>
|
||||
</div>
|
||||
{canApprove && isIncoming && row.status === 'pending' ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void handleApprove(row)}
|
||||
className="app-button-primary inline-flex items-center gap-1 px-3 py-1.5 rounded-lg text-sm disabled:opacity-50"
|
||||
>
|
||||
<Check className="w-4 h-4" />
|
||||
{t('quotes.priceProposal.approve')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => setRejecting({ id: row.id, reason: '' })}
|
||||
className="inline-flex items-center gap-1 px-3 py-1.5 rounded-lg text-sm border border-red-300 text-red-600 hover:bg-red-50 disabled:opacity-50"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
{t('quotes.priceProposal.reject')}
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<ul className="space-y-1 text-sm text-gray-700 dark:text-gray-200">
|
||||
{(row.lines || []).map((line) => (
|
||||
<li key={`${line.change}-${line.sku_code}`} className="flex flex-wrap items-center gap-2">
|
||||
<span className="app-product-name">{line.sku_name || line.sku_code}</span>
|
||||
{line.unit ? <span className="text-xs text-gray-500">{line.unit}</span> : null}
|
||||
<span className="tabular-nums">
|
||||
{line.change === 'added'
|
||||
? `+ ${formatPrice(line.after_sale_price)}`
|
||||
: `${formatPrice(line.before_sale_price)} → ${formatPrice(line.after_sale_price)}`}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
{!(row.lines || []).length ? (
|
||||
<li className="text-xs text-gray-500">
|
||||
{t('quotes.priceProposal.itemCount', { count: row.items.length })}
|
||||
</li>
|
||||
) : null}
|
||||
{row.reject_reason ? (
|
||||
<li className="text-xs text-red-600">
|
||||
{t('quotes.priceProposal.rejectReason')}:{row.reject_reason}
|
||||
</li>
|
||||
) : null}
|
||||
</ul>
|
||||
|
||||
{rejecting?.id === row.id ? (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<input
|
||||
value={rejecting.reason}
|
||||
onChange={(event) =>
|
||||
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"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void handleReject()}
|
||||
className="inline-flex items-center gap-1 px-3 py-1.5 rounded-lg text-sm bg-red-600 text-white hover:bg-red-700 disabled:opacity-50"
|
||||
>
|
||||
{t('quotes.priceProposal.reject')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => setRejecting(null)}
|
||||
className="px-3 py-1.5 rounded-lg text-sm text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
|
||||
>
|
||||
{t('common.cancel')}
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -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<string, string>;
|
||||
};
|
||||
const { common } = (await import('../../i18n/locales/zh-CN/common')) as unknown as {
|
||||
common: Record<string, string>;
|
||||
};
|
||||
const dict: Record<string, string> = {};
|
||||
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<string, unknown>) => {
|
||||
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(<QuoteSkuMappingsPanel />);
|
||||
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(<QuoteSkuMappingsPanel />);
|
||||
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(<QuoteSkuMappingsPanel />);
|
||||
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(<QuoteSkuMappingsPanel />);
|
||||
expect(
|
||||
await screen.findByText('报价单价格传递未开启(MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL)')
|
||||
).toBeTruthy();
|
||||
expect(notify.error).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('普通失败 ⇒ 弹错误(不是静默空白)', async () => {
|
||||
listApi.mockRejectedValue(new Error('网络错误'));
|
||||
render(<QuoteSkuMappingsPanel />);
|
||||
await waitFor(() => expect(notify.error).toHaveBeenCalledWith('网络错误'));
|
||||
});
|
||||
});
|
||||
@@ -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<SkuMappingDto[]>([]);
|
||||
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<string | null>(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 (
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<div className="flex items-center gap-3">
|
||||
<h2 className="text-sm font-semibold text-gray-800 dark:text-gray-100">{t('quotes.skuMapping.title')}</h2>
|
||||
<span className="text-xs text-gray-500">
|
||||
{t('quotes.skuMapping.summary', { total: summary.total, mapped: summary.mapped, unmapped: summary.unmapped })}
|
||||
</span>
|
||||
</div>
|
||||
{disabledReason ? null : (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<label className="inline-flex items-center gap-1.5 text-xs text-gray-600 dark:text-gray-300">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={unmappedOnly}
|
||||
onChange={(event) => setUnmappedOnly(event.target.checked)}
|
||||
aria-label={t('quotes.skuMapping.unmappedOnly')}
|
||||
/>
|
||||
{t('quotes.skuMapping.unmappedOnly')}
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-slate-400 pointer-events-none" />
|
||||
<input
|
||||
type="text"
|
||||
value={keyword}
|
||||
onChange={(event) => 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"
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void load({ refresh: true })}
|
||||
className="p-2 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700"
|
||||
title={t('common.refresh')}
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{disabledReason ? (
|
||||
<div className="app-surface rounded-2xl border border-amber-200 dark:border-amber-800 bg-amber-50/60 dark:bg-amber-950/20 p-6 text-center text-sm text-amber-800 dark:text-amber-200">
|
||||
{disabledReason}
|
||||
</div>
|
||||
) : !loading && rows.length === 0 ? (
|
||||
<div className="app-surface rounded-2xl border border-gray-200 dark:border-gray-700 p-8 text-center text-sm text-gray-500">
|
||||
{t('quotes.skuMapping.empty')}
|
||||
</div>
|
||||
) : (
|
||||
<div className="app-surface rounded-2xl border border-gray-200 dark:border-gray-700 overflow-x-auto">
|
||||
<table className="min-w-full divide-y divide-slate-200 dark:divide-slate-700 text-sm">
|
||||
<thead className="app-table-head">
|
||||
<tr>
|
||||
<th className="px-4 py-2 text-left font-medium">{t('quotes.skuMapping.supplierSku')}</th>
|
||||
<th className="px-4 py-2 text-left font-medium">{t('quotes.skuMapping.unit')}</th>
|
||||
<th className="px-4 py-2 text-left font-medium">{t('quotes.skuMapping.deliverySku')}</th>
|
||||
<th className="px-4 py-2 text-left font-medium">{t('quotes.skuMapping.status')}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-slate-100 dark:divide-slate-800">
|
||||
{rows.map((row) => (
|
||||
<tr key={row.supplier_sku_code}>
|
||||
<td className="px-4 py-2">
|
||||
<div className="text-gray-900 dark:text-gray-100">
|
||||
{row.supplier_sku_name || row.supplier_sku_code}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500">{row.supplier_sku_code}</div>
|
||||
</td>
|
||||
<td className="px-4 py-2 text-gray-600 dark:text-gray-300">{row.supplier_unit || '—'}</td>
|
||||
<td className="px-4 py-2">
|
||||
{isMapped(row) ? (
|
||||
<>
|
||||
<div className="text-gray-900 dark:text-gray-100">
|
||||
{row.delivery_sku_name || row.delivery_sku_code}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500">{row.delivery_sku_code}</div>
|
||||
</>
|
||||
) : (
|
||||
<span className="text-amber-600 dark:text-amber-400">{t('quotes.skuMapping.statusPending')}</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-2">
|
||||
<span
|
||||
className={
|
||||
isMapped(row)
|
||||
? 'text-emerald-600 dark:text-emerald-400'
|
||||
: row.status === 'disabled'
|
||||
? 'text-gray-400'
|
||||
: 'text-amber-600 dark:text-amber-400'
|
||||
}
|
||||
>
|
||||
{statusLabel(t, row.status)}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -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('<QuoteChangeRequestsPanel');
|
||||
expect(page).toMatch(/canApprove=\{canManageCustomerLibrary\}/);
|
||||
expect(page).toMatch(/onApplied=\{\(\) => \{[\s\S]{0,240}?void loadSheets\(\);/);
|
||||
});
|
||||
|
||||
it('待审页签不显示客户筛选(避免误导"按客户筛待审")', () => {
|
||||
// 2026-10-18 增加「配送商成本价确认」「商品映射」两个页签后,非报价单列表页签都不显示客户筛选
|
||||
expect(page).toMatch(
|
||||
/\{pageTab !== 'pending' && pageTab !== 'deliveryPrice' && pageTab !== 'skuMappings' \? \(/
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -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('<QuoteDeliveryPriceProposalsPanel');
|
||||
expect(page).toMatch(/canApprove=\{canManageCustomerLibrary\}/);
|
||||
});
|
||||
|
||||
it('无权限手输 URL 会退回当前执行(后端另有 403/503 兜底)', () => {
|
||||
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('<QuoteSkuMappingsPanel />');
|
||||
});
|
||||
|
||||
it('T1:不在报价单页改订单取价(只改成本,订单价仍读 sale_price)', () => {
|
||||
expect(page).not.toContain('orderPricingService');
|
||||
expect(page).not.toMatch(/order_items/);
|
||||
});
|
||||
});
|
||||
@@ -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<string | null>(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 },
|
||||
]}
|
||||
/>
|
||||
<PageFilterToolbar>
|
||||
{pageTab === 'sheets' && viewFilter === 'history' ? (
|
||||
<span className="text-xs text-gray-500">{t('quotes.history.hint')}</span>
|
||||
) : null}
|
||||
<SearchableSelect
|
||||
value={customerFilter}
|
||||
onChange={setCustomerFilter}
|
||||
allowEmpty
|
||||
emptyLabel={pageTab === 'library' ? t('quotes.filter.selectCustomer') : t('quotes.filter.allCustomers')}
|
||||
className="min-w-[12rem] flex-1 max-w-xs"
|
||||
options={customerFilterOptions}
|
||||
/>
|
||||
{pageTab !== 'pending' && pageTab !== 'deliveryPrice' && pageTab !== 'skuMappings' ? (
|
||||
<SearchableSelect
|
||||
value={customerFilter}
|
||||
onChange={setCustomerFilter}
|
||||
allowEmpty
|
||||
emptyLabel={pageTab === 'library' ? t('quotes.filter.selectCustomer') : t('quotes.filter.allCustomers')}
|
||||
className="min-w-[12rem] flex-1 max-w-xs"
|
||||
options={customerFilterOptions}
|
||||
/>
|
||||
) : null}
|
||||
{pageTab === 'sheets' ? (
|
||||
<div className="ml-auto flex shrink-0 flex-wrap items-center justify-end gap-2">
|
||||
<button
|
||||
@@ -981,6 +1094,15 @@ export const QuoteVersionManagement: React.FC = () => {
|
||||
<Plus className="w-4 h-4" />
|
||||
{t('quotes.btn.create')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void handleSyncSkuDictionary()}
|
||||
disabled={syncingDictionary}
|
||||
className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg text-sm border border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-50"
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 ${syncingDictionary ? 'animate-spin' : ''}`} />
|
||||
{t('quotes.action.syncSkuDictionary')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void loadSheets()}
|
||||
@@ -1005,7 +1127,24 @@ export const QuoteVersionManagement: React.FC = () => {
|
||||
) : null}
|
||||
</PageFilterToolbar>
|
||||
|
||||
{pageTab === 'library' && canManageCustomerLibrary ? (
|
||||
{pageTab === 'skuMappings' ? (
|
||||
<QuoteSkuMappingsPanel />
|
||||
) : pageTab === 'deliveryPrice' ? (
|
||||
<QuoteDeliveryPriceProposalsPanel
|
||||
canApprove={canManageCustomerLibrary}
|
||||
onApplied={() => {
|
||||
void loadSheets();
|
||||
}}
|
||||
/>
|
||||
) : pageTab === 'pending' ? (
|
||||
<QuoteChangeRequestsPanel
|
||||
canApprove={canManageCustomerLibrary}
|
||||
onApplied={() => {
|
||||
// 审核通过并已触发成本价同步 ⇒ 刷新报价单列表(详情用「展开」时再读)
|
||||
void loadSheets();
|
||||
}}
|
||||
/>
|
||||
) : pageTab === 'library' && canManageCustomerLibrary ? (
|
||||
customerFilter ? (
|
||||
<CustomerSkuLibraryPanel customerCode={customerFilter} customerName={libraryCustomerName} />
|
||||
) : (
|
||||
@@ -1137,6 +1276,16 @@ export const QuoteVersionManagement: React.FC = () => {
|
||||
{t('quotes.action.edit')}
|
||||
</button>
|
||||
)}
|
||||
{isActiveSheet(row) && canManageQuotes && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void submitForDeliveryReview(row)}
|
||||
disabled={submittingProposalCode === row.quote_sheet_code}
|
||||
className="text-xs font-medium text-emerald-600 hover:underline whitespace-nowrap disabled:opacity-50"
|
||||
>
|
||||
{t('quotes.action.submitForDeliveryReview')}
|
||||
</button>
|
||||
)}
|
||||
{row.status !== 0 && (
|
||||
<button
|
||||
type="button"
|
||||
|
||||
+273
-4
@@ -2645,11 +2645,256 @@ export async function getQuoteSheetApi(code: string) {
|
||||
return workflowFetch<{ data: unknown }>(`/quote/sheets/${encodeURIComponent(code)}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 编辑生效报价单:**价格相关改动需审核**(2026-10-18)。
|
||||
* 后端按「是否价格相关」分流:价格相关 ⇒ `applied:false` + `change_request`(已提交审核,报价单未动);
|
||||
* 非价格 ⇒ `applied:true`(已直接保存)。
|
||||
*/
|
||||
export async function updateQuoteSheetApi(code: string, body: Record<string, unknown>) {
|
||||
return workflowFetch<{ data: unknown }>(`/quote/sheets/${encodeURIComponent(code)}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
return workflowFetch<{ data: unknown; applied?: boolean; change_request?: QuoteChangeRequestDto }>(
|
||||
`/quote/sheets/${encodeURIComponent(code)}`,
|
||||
{
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(body),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/** 待审改价:一条明细的「改前 → 改后」(审核摘要用) */
|
||||
export type QuoteChangeLineDto = {
|
||||
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 QuoteChangeSummaryDto = {
|
||||
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: QuoteChangeLineDto[];
|
||||
truncated: boolean;
|
||||
};
|
||||
|
||||
export type QuoteChangeRequestDto = {
|
||||
id: string;
|
||||
branch_code: string;
|
||||
quote_sheet_code: string;
|
||||
payload: Record<string, unknown>;
|
||||
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 | null;
|
||||
reviewed_by: string | null;
|
||||
reviewed_by_name: string | null;
|
||||
reviewed_at: string | null;
|
||||
reject_reason: string | null;
|
||||
applied_at: string | null;
|
||||
updated_at: string | null;
|
||||
summary?: QuoteChangeSummaryDto;
|
||||
};
|
||||
|
||||
/** 待审改价列表(默认只看 pending) */
|
||||
export async function listQuoteChangeRequestsApi(options?: { status?: string; limit?: number }) {
|
||||
const params = new URLSearchParams();
|
||||
if (options?.status) params.set('status', options.status);
|
||||
if (options?.limit) params.set('limit', String(options.limit));
|
||||
const qs = params.toString();
|
||||
return workflowFetch<{ data: QuoteChangeRequestDto[] }>(`/quote/change-requests${qs ? `?${qs}` : ''}`);
|
||||
}
|
||||
|
||||
/** 报价单双向价格传递:一条提议(方向 A 我方提交 / B 配送商发起) */
|
||||
export type QuotePriceProposalItemDto = { sku_code: string; unit?: string | null; price: number };
|
||||
|
||||
export type QuotePriceProposalDto = {
|
||||
id: string;
|
||||
branch_code: string;
|
||||
quote_sheet_code: string;
|
||||
main_branch_code: string;
|
||||
direction: 'to_delivery' | 'from_delivery';
|
||||
items: QuotePriceProposalItemDto[];
|
||||
status: 'pending' | 'approved' | 'rejected' | 'cancelled' | 'superseded';
|
||||
reject_reason: string | null;
|
||||
remote_proposal_id: string | null;
|
||||
requested_by_name: string | null;
|
||||
requested_at: string | null;
|
||||
reviewed_by_name: string | null;
|
||||
reviewed_at: string | null;
|
||||
applied_at: string | null;
|
||||
waited_days?: number | null;
|
||||
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';
|
||||
supplier_sku_code?: string | null;
|
||||
}>;
|
||||
};
|
||||
|
||||
/**
|
||||
* 报价单**双向价格传递**的 4 个内部端点。
|
||||
*
|
||||
* ⚠️ 全部带 `preserveErrorBody: true`:开关关闭时后端返回 **503 `feature_disabled`**,
|
||||
* 不带就会统一显示成「保存超时,服务器可能仍在处理,请勿重复点击」⇒ 用户看不到真实原因;
|
||||
* 400/409(`not_usage_company` / `ambiguous_main_branch` / `internal_review_pending` /
|
||||
* `main_supplier_code_missing` / `proposal_not_pending` / `remote_status_unverified`)同样要透出后端原文。
|
||||
*/
|
||||
|
||||
export async function submitQuotePriceProposalApi(code: string, body?: { note?: string }) {
|
||||
return workflowFetch<{
|
||||
data: QuotePriceProposalDto;
|
||||
applied: false;
|
||||
replayed: boolean;
|
||||
/** 提交时本单映射统计(未映射不阻止提交,但要让用户看到) */
|
||||
mapping: SheetMappingStatsDto;
|
||||
}>(
|
||||
`/quote/sheets/${encodeURIComponent(code)}/price-proposals`,
|
||||
{ method: 'POST', body: JSON.stringify(body ?? {}) },
|
||||
{ preserveErrorBody: true }
|
||||
);
|
||||
}
|
||||
|
||||
/* ── SKU 映射(映射在配送侧维护,本系统只读同步;契约 .team/sku-mapping-shared-sheet/contract.md §5) ── */
|
||||
|
||||
export type SkuMappingDto = {
|
||||
supplier_sku_code: string;
|
||||
supplier_sku_name: string | null;
|
||||
supplier_unit: string | null;
|
||||
delivery_sku_code: string | null;
|
||||
delivery_sku_name: string | null;
|
||||
status: 'active' | 'disabled' | 'pending' | string;
|
||||
synced_at: string | null;
|
||||
};
|
||||
|
||||
export type SheetMappingStatsDto = {
|
||||
quote_sheet_code: string;
|
||||
total: number;
|
||||
mapped: number;
|
||||
unmapped: number;
|
||||
unmapped_skus: Array<{ sku_code: string; sku_name: string | null }>;
|
||||
};
|
||||
|
||||
export type SkuDictionarySyncResult = {
|
||||
push: {
|
||||
skus: number;
|
||||
batches: number;
|
||||
matched: number;
|
||||
pending: number;
|
||||
kept: number;
|
||||
total: number;
|
||||
};
|
||||
pull: { total: number; upserted: number; deleted: number; conflicts: number; truncated: boolean; pages: number };
|
||||
};
|
||||
|
||||
/**
|
||||
* 把我方**商品字典**整批推给配送侧(D4),随后拉回映射(D5)。映射仍在配送侧维护,本系统不可编辑。
|
||||
* ⚠️ `preserveErrorBody`:开关关闭时 503 `feature_disabled` 要显示后端原文,而不是"保存超时"。
|
||||
*/
|
||||
export async function syncSkuDictionaryApi() {
|
||||
return workflowFetch<{ data: SkuDictionarySyncResult }>(
|
||||
'/quote/sku-mappings/sync-dictionary',
|
||||
{ method: 'POST', body: JSON.stringify({}) },
|
||||
{ preserveErrorBody: true }
|
||||
);
|
||||
}
|
||||
|
||||
/** 只读映射列表(`refresh=1` 先拉 D5) */
|
||||
export async function listSkuMappingsApi(options?: { status?: string; q?: string; limit?: number; refresh?: boolean }) {
|
||||
const params = new URLSearchParams();
|
||||
if (options?.status) params.set('status', options.status);
|
||||
if (options?.q) params.set('q', options.q);
|
||||
if (options?.limit) params.set('limit', String(options.limit));
|
||||
if (options?.refresh) params.set('refresh', '1');
|
||||
const qs = params.toString();
|
||||
return workflowFetch<{
|
||||
data: SkuMappingDto[];
|
||||
summary: { total: number; mapped: number; unmapped: number };
|
||||
pull: unknown;
|
||||
}>(`/quote/sku-mappings${qs ? `?${qs}` : ''}`, {}, { preserveErrorBody: true });
|
||||
}
|
||||
|
||||
/** 提交前映射统计:「本单 N 个商品,已映射 X / 未映射 Y」(不按名称猜,只认配送侧下发映射) */
|
||||
export async function getSheetMappingStatsApi(code: string) {
|
||||
return workflowFetch<{ data: SheetMappingStatsDto }>(
|
||||
`/quote/sheets/${encodeURIComponent(code)}/mapping-stats`,
|
||||
{},
|
||||
{ preserveErrorBody: true }
|
||||
);
|
||||
}
|
||||
|
||||
/** 提议列表(`refresh=1` 时后端先调 D2 对账再返回;T10 游标由后端负责) */
|
||||
export async function listQuotePriceProposalsApi(options?: {
|
||||
direction?: 'to_delivery' | 'from_delivery';
|
||||
status?: string;
|
||||
limit?: number;
|
||||
refresh?: boolean;
|
||||
}) {
|
||||
const params = new URLSearchParams();
|
||||
if (options?.direction) params.set('direction', options.direction);
|
||||
if (options?.status) params.set('status', options.status);
|
||||
if (options?.limit) params.set('limit', String(options.limit));
|
||||
if (options?.refresh) params.set('refresh', '1');
|
||||
const qs = params.toString();
|
||||
return workflowFetch<{ data: QuotePriceProposalDto[]; sync: unknown }>(
|
||||
`/quote/price-proposals${qs ? `?${qs}` : ''}`,
|
||||
{},
|
||||
{ preserveErrorBody: true }
|
||||
);
|
||||
}
|
||||
|
||||
/** 方向 B 通过:按行写我方 sale_price + rearm 推配送 cost_price + D3 回执 */
|
||||
export async function approveQuotePriceProposalApi(id: string) {
|
||||
return workflowFetch<{
|
||||
data: QuotePriceProposalDto;
|
||||
applied: { updated: number; unchanged: number; skipped: Array<{ sku_code: string; reason: string; detail?: string }> };
|
||||
receipt_sent: boolean;
|
||||
}>(
|
||||
`/quote/price-proposals/${encodeURIComponent(id)}/approve`,
|
||||
{ method: 'POST', body: JSON.stringify({}) },
|
||||
{ preserveErrorBody: true }
|
||||
);
|
||||
}
|
||||
|
||||
/** 方向 B 驳回:只记状态 + 理由(不写价、不同步) */
|
||||
export async function rejectQuotePriceProposalApi(id: string, reason: string) {
|
||||
return workflowFetch<{ data: QuotePriceProposalDto; receipt_sent: boolean }>(
|
||||
`/quote/price-proposals/${encodeURIComponent(id)}/reject`,
|
||||
{ method: 'POST', body: JSON.stringify({ reason }) },
|
||||
{ preserveErrorBody: true }
|
||||
);
|
||||
}
|
||||
|
||||
/** 审核通过:应用变更并触发成本价同步(后端单事务) */
|
||||
export async function approveQuoteChangeRequestApi(id: string) {
|
||||
return workflowFetch<{ data: unknown; change_request: QuoteChangeRequestDto }>(
|
||||
`/quote/change-requests/${encodeURIComponent(id)}/approve`,
|
||||
{ method: 'POST', body: JSON.stringify({}) }
|
||||
);
|
||||
}
|
||||
|
||||
/** 审核驳回:只改变更单状态(报价单不变、不同步) */
|
||||
export async function rejectQuoteChangeRequestApi(id: string, reason: string) {
|
||||
return workflowFetch<{ change_request: QuoteChangeRequestDto }>(
|
||||
`/quote/change-requests/${encodeURIComponent(id)}/reject`,
|
||||
{ method: 'POST', body: JSON.stringify({ reason }) }
|
||||
);
|
||||
}
|
||||
|
||||
export async function setQuoteSheetAutoSalePriceApi(code: string, enabled: boolean) {
|
||||
@@ -6771,6 +7016,8 @@ export interface BidInvitationDto {
|
||||
localStatus: BidLocalStatus;
|
||||
quotedAt: string | null;
|
||||
lastSyncedAt: string | null;
|
||||
/** 软删除时间(非空 = 仅「显示已删除」时可见) */
|
||||
deletedAt?: string | null;
|
||||
}
|
||||
|
||||
/** 单轮明细行(含我方报价与中标结果,全部只读字段由对方返回覆盖) */
|
||||
@@ -6814,10 +7061,12 @@ export interface BidInvitationQuoteInput {
|
||||
export async function listMainSystemBidInvitationsApi(params?: {
|
||||
status?: 'all' | 'pending' | 'history';
|
||||
limit?: number;
|
||||
includeDeleted?: boolean;
|
||||
}) {
|
||||
const query = new URLSearchParams();
|
||||
if (params?.status) query.set('status', params.status);
|
||||
if (params?.limit) query.set('limit', String(params.limit));
|
||||
if (params?.includeDeleted) query.set('include_deleted', '1');
|
||||
const suffix = query.toString() ? `?${query.toString()}` : '';
|
||||
return workflowFetch<{
|
||||
data: BidInvitationDto[];
|
||||
@@ -6845,6 +7094,26 @@ export async function getMainSystemBidInvitationApi(roundId: string, supplierCod
|
||||
).then((res) => res.data);
|
||||
}
|
||||
|
||||
/** 软删除一条竞价邀约(本系统台账里隐藏;仅管理员;只有 pending/expired 可删) */
|
||||
export async function deleteMainSystemBidInvitationApi(roundId: string, supplierCode?: string | null) {
|
||||
const qs = supplierCode ? `?supplier=${encodeURIComponent(supplierCode)}` : '';
|
||||
return workflowFetch<{ data: { round_code: string | null; deleted: boolean }; error?: null }>(
|
||||
`/main-system/bid-invitations/${encodeURIComponent(roundId)}/delete${qs}`,
|
||||
{ method: 'POST' },
|
||||
{ preserveErrorBody: true }
|
||||
).then((res) => res.data);
|
||||
}
|
||||
|
||||
/** 恢复一条被软删的竞价邀约(仅管理员) */
|
||||
export async function restoreMainSystemBidInvitationApi(roundId: string, supplierCode?: string | null) {
|
||||
const qs = supplierCode ? `?supplier=${encodeURIComponent(supplierCode)}` : '';
|
||||
return workflowFetch<{ data: { round_code: string | null; deleted: boolean }; error?: null }>(
|
||||
`/main-system/bid-invitations/${encodeURIComponent(roundId)}/restore${qs}`,
|
||||
{ method: 'POST' },
|
||||
{ preserveErrorBody: true }
|
||||
).then((res) => res.data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交报价(批量 upsert,只回我自己视角)。
|
||||
*
|
||||
|
||||
Reference in New Issue
Block a user