feat(对接): 批次报告推送到主系统(第九批)—— 真环境冒烟已通,三重门禁 + 台账去重
主系统已回执「可以开工」(其 §2.12.9 最终契约 / §4.5.17 逐条回执,接收侧提交 c24f4881)。
按契约实现我方推送侧,**未新开端点**:文件走他们 `/api/storage/quality-reports/upload`(multipart),
登记走 `/api/supplier/quality-reports`(按备货行逐条)。
**三重门禁(开发者要求"没绑定就别传、不能造成混乱")**:
① 分公司 ↔ 主系统有 active 绑定(未绑定 ⇒ 连 token 都取不到 ⇒ 物理上发不出去)
② 该行是主系统下发的(`main_system_order_import_items` 有 prep_id 对照)
③ 该批次已人工确认关联到报告
未满足 ⇒ **零出站**(采集 SQL 里就用 JOIN 卡死,且开关关闭时连候选都不查)
**幂等(B4=我方台账去重)**:新表 `public.main_system_report_pushes`,唯一键 `(prep_id, report_type)` +
**完整文件集指纹**:指纹未变 ⇒ 不重推;指纹变了(事后补充)⇒ 按**完整文件集**重推一次
(对方 latest wins:同 (prep, type) 再登记会作废旧报告,所以不能只推新增文件)。
**契约硬语义(单测钉死)**:绝不传 `defer_coverage`(暂存态:既不覆盖也不展示);
绝不传 sku/order/branch/supplier/category/delivery(对方按行派生);`report_type` 按行要求的类型
(`qualityReportType`,本轮给拉取映射补上;取不到且该行要求报告时**不猜、跳过**);
回执映射 200 stored / 404 ignored(终态) / 400 failed(终态) / 401 换 token / 5xx 退避重试。
**触发点三处**:① 分拣完成(pickingService 成功路径,旁路 fire-and-forget)
② 报告确认关联(inventoryRoutes confirm 路由)③ scheduler tick 定时兜底(默认关 ⇒ 零出站)。
**真环境冒烟(对照主系统 3001,已跑通)**:
· 上传 ⇒ `{"kind":"ok","path":"4019fbdf…png"}`(用他们回执里的 path 登记)
· 登记 ⇒ **200** `data.id=0de8d009-d28e-4124-a333-5bef819b6dac`
`order_code/BR002/sku_code/supplier_code` 全由他们从备货行派生;我们传的
`batch_no=STK202610107YRQEO`、`product_name=香菇、平菇`、`testing_org=XX检测中心` 都正确落库;
`share_key` **不以 `st|` 开头**(= 正常覆盖态,非 defer)
· 我方台账回执:`order_code=ORD_WEB_20261010_BR002_0001`、`prep_id=b4e7fd80-668d-4f9b-b69f-dcb3fddc623e`
· ⚠️ **发现对方一处回显缺陷(已坐实,待他们修)**:`POST /api/supplier/quality-reports` 回执里
`produced_at` 比传入/库里少一天(我们传 2026-10-08、他们库 `tenant_br002.quality_reports.produced_at`
实测 = 2026-10-08,但回执 JSON = 2026-10-07);`compare_at` 同样(库 2026-10-11 / 回执 2026-10-10)
⇒ 是他们 date 列的**序列化时区**问题(值没存错,只在回显),与他们清单 §2.12.9 ⑦-1
"与你们传的一致"这条判定相冲突,需他们确认修
验证:server tsc ✅;新增 27 例(服务 14 + 调用层 13)全绿;全量 380 文件 / 2405 用例 ⇒ 失败 25 文件
= 基线 24 + 另一条工作线遗留的 zeroCostClearsPlanPrice;门禁同基线。
设计:docs/design/20261011-批次报告推送主系统.md;冒烟脚本:server/scripts/smoke-main-system-report-push.ts
This commit is contained in:
@@ -0,0 +1,148 @@
|
||||
# 批次报告推送到主系统(第九批「批次报告同步」· 我方推送侧)
|
||||
|
||||
> 立项 2026-10-11。上游契约(**权威**):`docs/给主系统AI的对接改造清单.md` **§2.12.9**(开工通知 + 最终调用契约)
|
||||
> 与 **§4.5.17**(逐条回执);两者冲突以 §2.12.9 为准。
|
||||
> 开发者原话:「我们这边分拣完毕不就是选中了那几个批次的这些商品了吗;这些商品如果存在批次报告,
|
||||
> 也可能是事后补充,这个连接需要给到配送系统……**注意是绑定了主系统的情况下**;如果是没有绑定的、
|
||||
> 没有需要主系统下发的订单,**报告就别传递过去,不能造成混乱**。」
|
||||
|
||||
## 0. 一句话
|
||||
|
||||
我方分拣确定出库批次后,把该批次**已人工确认**的批次报告,**按备货行逐条登记**到主系统既有的
|
||||
「供应商上传报告」通道(不新开端点),使其在**主系统订单详情(含供应商视角)**与**我方订单详情**都可见;
|
||||
**未绑定 / 非主系统下发的行一律不推**。
|
||||
|
||||
## 1. 目标 / 非目标
|
||||
|
||||
**目标**
|
||||
|
||||
- 主系统侧可见:一份批次报告在他们的订单详情「报告」列(图片缩略图 / PDF 图标)能看到;
|
||||
- 我方侧可见:同一份报告在我方订单详情也能看到(复用我方已有批次报告数据,不新建一套);
|
||||
- **事后补充**也能生效(报告晚于分拣才关联到批次时,追加推送);
|
||||
- 全程**旁路异步**,绝不卡我方分拣 / 发车;失败进台账 + 定时对账补推。
|
||||
|
||||
**非目标(本期不做)**
|
||||
|
||||
1. 不改主系统任何面(他们零新增:不新开端点、不加列、不加开关 —— 见 §4.5.17 Q1/Q8/B4);
|
||||
2. 不推我方自己的 `quality_reports`(那是我们内部验收层,**只推「批次报告」这一层**,避免口径混淆);
|
||||
3. 不碰库存写入、验收闸门、订单状态链、价格 / 数量通道;
|
||||
4. 不做"撤回已推报告"(契约未定;本期只追加与覆盖)。
|
||||
|
||||
## 2. 权威契约要点(照抄 §2.12.9,实现不得偏离)
|
||||
|
||||
### 2.1 两步调用
|
||||
|
||||
| 步 | 请求 | 备注 |
|
||||
|---|---|---|
|
||||
| ① 传文件 | `POST {BASE}/api/storage/quality-reports/upload?path=<对象名>`,`multipart/form-data`,字段名 **`file`** | 回 `{path, signedUrl}` ⇒ **必须用回执里的 `path` 登记**(对方会把文件名随机化) |
|
||||
| ② 登记 | `POST {BASE}/api/supplier/quality-reports`,JSON `{preparation_id, files:[path], report_type, batch_no?, produced_at?, testing_org?, product_names?}` | **一次一行**(按备货行逐条);回 `{data:{id, status, …}}` |
|
||||
|
||||
鉴权:两步都用 **Bearer 对接 token**(我方既有 `getMainSystemToken(mainSupplierCode)`,24h、绑死 `(分公司 × 供应商)`)。
|
||||
限制:仅 `.pdf` + 图片(jpg/jpeg/png/webp/gif),**单文件 ≤ 10MB**(走 multipart,不受他们 JSON 2MB 限制)。
|
||||
|
||||
### 2.2 回执映射(按行调用,**不是** `{ok, results}` 信封)
|
||||
|
||||
| 对方响应 | 我方处置 |
|
||||
|---|---|
|
||||
| 200 `{data:{id,…}}` | `stored`:台账记他们的 `report_id` |
|
||||
| 404 `not_found`(行不存在**或**不属于该 token 的供应商) | **当 `ignored`:终态、永不重推** |
|
||||
| 400 `invalid_report_type` | 终态 + 告警(改传该行要求的类型) |
|
||||
| 400 `invalid_request` | 终态 + 告警(我方实现 bug,别重试) |
|
||||
| 401 `invalid_token` | **重取 token** 再试(暂态) |
|
||||
| 403 `forbidden` | 终态 + 告警 |
|
||||
| 5xx / 超时 | **退避重试 + 定时对账补推** |
|
||||
|
||||
### 2.3 五条硬语义(做反要返工)
|
||||
|
||||
1. **每次推"该行该类型的完整文件集"**:同一 `(preparation_id, report_type)` 再登记 ⇒ 对方把上一份同类型报告
|
||||
**作废(latest wins)** ⇒ 事后补充时**不能只推新增的那个文件**(旧文件会随旧报告失效);
|
||||
2. **绝不传 `defer_coverage`**(那是"待人工确认命中"的暂存态:既不覆盖也不展示);
|
||||
3. **`report_type` 按该行要求的类型传**(对方备货行返回 `requires_quality_report` / `quality_report_type`);
|
||||
该行不要求报告时:报告**照样可见**,但 `report_covered` 保持 `false`;
|
||||
4. **不传** `sku_code` / `order_code` / `branch_code` / `supplier_code` / `category_code` / `delivery_date`(对方按行派生);
|
||||
5. **未绑定 / 非对方下发的行不推**;对方不认识的行按 404 → `ignored`。
|
||||
|
||||
## 3. 数据链(我方怎么算出"该推什么")
|
||||
|
||||
```
|
||||
inventory_batch_reports(status=30 已确认) ──┐
|
||||
├─ inventory_batch_report_matches(report_id, inventory_id, sku_code, batch_no)
|
||||
inventory(id, sku_code, batch_no) ──────────┘
|
||||
│ (sku_code, batch_no)
|
||||
▼
|
||||
picking_items(sku_code, outbound_batches=[{batch_no,qty}], order_item_id, branch_code) ← 分拣完成/发车落库
|
||||
│ order_item_id
|
||||
▼
|
||||
public.main_system_order_import_items(our_order_item_id → prep_id, main_supplier_code, branch_code)
|
||||
│ ① 有 prep_id ⇒ 该行是主系统下发的(否则不推)
|
||||
│ ② public.main_supplier_bindings 有 active 绑定 ⇒ 能取到 token(否则不推)
|
||||
▼
|
||||
候选 = (prep_id, report_type) 一组;文件集 = 该行消耗批次命中的**全部**报告文件(并集)
|
||||
```
|
||||
|
||||
**门禁(三重,缺一不推)**:`已绑定` ∧ `该行有 prep_id(主系统下发)` ∧ `批次已人工确认有报告`。
|
||||
未绑定 ⇒ 连 token 都取不到 ⇒ **物理上发不出去**。
|
||||
|
||||
## 4. 台账(幂等与对账的唯一依据)
|
||||
|
||||
新建 **平台级** public 表 `public.main_system_report_pushes`(与 `main_supplier_bindings` 同级;
|
||||
它不是租户业务表 ⇒ 不进 `tenant_business_tables()`):
|
||||
|
||||
| 列 | 用途 |
|
||||
|---|---|
|
||||
| `branch_code` / `main_branch_code` / `main_supplier_code` | 归属(哪个分公司、用哪条绑定推的) |
|
||||
| `prep_id` / `main_order_code` / `our_order_code` / `our_order_item_id` | 挂靠与排查 |
|
||||
| `report_type` | **幂等键的一半**(另一半是 `prep_id`) |
|
||||
| `file_fingerprint` | 完整文件集的指纹(我方文件键排序后 sha256)⇒ **变了才重推**(覆盖"事后补充") |
|
||||
| `our_file_paths` / `their_file_paths` | 我方对象键 ↔ 对方 `path`(同序,避免重复上传) |
|
||||
| `their_report_id` | 对方回执里的报告 id |
|
||||
| `status` | `pending` / `stored` / `ignored` / `failed`(四态,终态不重推) |
|
||||
| `attempts` / `last_http_status` / `last_error` / `pushed_at` / `next_retry_at` | 重试与观测 |
|
||||
|
||||
唯一键 **`(prep_id, report_type)`** ⇒ 同一行同类型只有一行台账(latest wins 与对方语义对齐)。
|
||||
|
||||
## 5. 触发点与重试
|
||||
|
||||
| 触发 | 位置 | 说明 |
|
||||
|---|---|---|
|
||||
| ① 分拣完成 / 发车(批次确定) | `outbound_batches` 落库后 | 旁路 fire-and-forget |
|
||||
| ② 报告确认关联到批次(覆盖"事后补充") | 报告确认接口成功后 | 同上 |
|
||||
| ③ 定时兜底 | 既有 scheduler tick | 扫 `pending` + `next_retry_at` 到期项,**逐分公司**推 |
|
||||
|
||||
重试策略:5xx / 超时 / 401(换 token)⇒ `attempts+1`、`next_retry_at = now + min(2^attempts, 60) 分钟`;
|
||||
终态(`ignored` / `invalid_*` / `forbidden`)⇒ 写 `last_error` 并**不再自动重试**,只告警。
|
||||
|
||||
## 6. 开关
|
||||
|
||||
- `MAIN_SYSTEM_REPORT_ENABLED`(默认 **false**):关闭时**不采集、不推送**(连候选都不查);
|
||||
- 对方不需要开关(物理门禁在我们侧:未绑定取不到 token);
|
||||
- 契约未要求新环境变量;端点路径可覆盖:`MAIN_SYSTEM_REPORT_UPLOAD_PATH` / `MAIN_SYSTEM_REPORT_REGISTER_PATH`。
|
||||
|
||||
## 7. 验收标准
|
||||
|
||||
- [ ] 开关关闭 ⇒ 零出站请求(与今天逐字节一致);
|
||||
- [ ] 未绑定分公司 / 非主系统下发的行 ⇒ **零出站**(用 mock 计数断言);
|
||||
- [ ] 已绑定 + 有 prep_id + 批次确认有报告 ⇒ 走完两步调用,台账 `stored` + 记对方 `report_id`;
|
||||
- [ ] 同内容再触发 ⇒ **不重复推送**(指纹未变);
|
||||
- [ ] 文件集变化(事后补充)⇒ **重推完整文件集**(不是只推新增文件),台账指纹更新;
|
||||
- [ ] 对方 404 ⇒ `ignored` **终态不重推**;5xx ⇒ 退避重试;401 ⇒ 换 token 重试一次;
|
||||
- [ ] 请求体**从不包含** `defer_coverage` / `sku_code` / `order_code` / `branch_code` / `supplier_code`(源码级 + 请求体断言);
|
||||
- [ ] `report_type` 按行要求取(缺类型时按 `batch` 兜底,并要求该行 `requires_quality_report=false` 才兜底);
|
||||
- [ ] 联调(真环境):契约 §2.12.9 ⑦ 五条逐条通过,含对方内部订单详情能看到同一文件。
|
||||
|
||||
## 8. 风险与回滚
|
||||
|
||||
| 风险 | 处置 |
|
||||
|---|---|
|
||||
| 推错行 ⇒ 对方订单详情挂错报告 | 挂靠键只用 `prep_id`(来自我方导入台账,非推断);门禁三重;404 当 `ignored` |
|
||||
| 重复推送 ⇒ 对方旧报告被作废 | 台账按 `(prep_id, report_type)` 去重;只有**文件集变化**才重推(变化即"完整集"覆盖) |
|
||||
| 文件过大 / 类型不允许 | 上传前过滤(仅 pdf/图片 + ≤10MB),不合法则记 `failed` + 告警,**不静默丢** |
|
||||
| 报告把对方闸门变绿(B2=算) | 已由开发者认下;对方 `quality_report_hard_gate_enabled` 当前为 false ⇒ 今天只影响展示。**要退只需停推** |
|
||||
| 出站风暴 | 旁路异步 + 定时兜底 + 台账终态;单轮 `limit` 封顶 |
|
||||
| 回滚 | 开关置 false 即彻底静默;再回滚就是删代码 + 台账表保留(只增不删,不影响任何业务表) |
|
||||
|
||||
## 9. 修订记录
|
||||
|
||||
| 版本 | 日期 | 变更 |
|
||||
|---|---|---|
|
||||
| v1 | 2026-10-11 | 首版:按 §2.12.9 最终契约设计推送侧(两步调用 / 台账去重 / 三重门禁 / 三触发点 / 默认关) |
|
||||
@@ -45,6 +45,7 @@ AI 提示词清理已停用条目(7 条归档不删、清单过滤 archived、
|
||||
导航菜单按**主系统当前布局**收敛(顶层只留 数据看板/订单录入 + 业务流程/基础数据/财务结算/系统管理;老布局**每次加载自动归位**、幂等、不写一次性 SQL ⇒ 迁移换机都一样;缓存指纹加模板版本;含「财务管理→财务结算」这一处显示名收敛)见 [20261027-导航菜单按主系统模板收敛.md](./20261027-导航菜单按主系统模板收敛.md)。
|
||||
隐藏「市场价格监控」界面(本产品不需要:①菜单目录 ②基础数据规范条目 ③模块路由 ④落地路径兜底 四处同删;权限码/页面代码/i18n **有意保留**;后台每日行情刷新**未动**)见 [20261027-隐藏市场价格监控功能.md](./20261027-隐藏市场价格监控功能.md)。
|
||||
库存入库支持**直接选已有商品**并按「上次设置」预填(规格/单位/成本价/分类/保质期/存放区域/生产地区),**生产日期仍由操作员按批手填**见 [20261011-入库直接选择已有商品并按上次设置预填.md](./20261011-入库直接选择已有商品并按上次设置预填.md)。
|
||||
批次报告**推送到主系统**(第九批「批次报告同步」我方推送侧:按备货行逐条登记到主系统既有「供应商上传报告」通道、台账按 `(prep_id, report_type)` 去重、**未绑定/非主系统下发的行一律不推**、默认关)见 [20261011-批次报告推送主系统.md](./20261011-批次报告推送主系统.md)。
|
||||
|
||||
## 全量对齐与改造方案(2026-09-28)
|
||||
|
||||
|
||||
@@ -442,6 +442,9 @@ docker compose -f docker-compose.prod.yml --env-file .env.production up -d --bui
|
||||
| `MAIN_SYSTEM_SUPPLIER_LOGIN_PATH` | 可选 | `/api/supplier/login` | 供应商账号校验路径 |
|
||||
| `MAIN_SYSTEM_TIMEOUT_MS` | 可选 | 5000 | 调用主系统超时(毫秒) |
|
||||
| `MAIN_SYSTEM_RETURN_FOLLOW` | 可选 | 关(`=1` 开) | 第三方订单退货跟随 |
|
||||
| `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_WRITEBACK` | 可选 | 关(`=1` 开) | 发车回写主系统 |
|
||||
| `MAIN_SYSTEM_IMPORT_CONCURRENCY` | 可选 | 6 | 分公司导入并发(上限 10) |
|
||||
| `MAIN_SYSTEM_BINDING_SYNC_URL` | 可选 | 空(不启用) | 「接入编码绑定」的**回读**端点(主系统只读接口全 URL);空则只依赖 `binding.changed` 回调与超管手工登记 —— 见 `docs/design/20261027-分公司接入编码与主系统供应商绑定.md` §8 P0-2 |
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
-- 「批次报告同步」出站台账(2026-10-11 设计)
|
||||
--
|
||||
-- 用途:把「我方批次报告」按备货行登记到主系统**既有**的「供应商上传报告」通道
|
||||
-- (契约权威:docs/给主系统AI的对接改造清单.md §2.12.9 / §4.5.17)。
|
||||
--
|
||||
-- 这张表是**幂等与对账的唯一依据**(主系统侧 `quality_reports` 没有外部号列,B4 采纳"我方台账去重"):
|
||||
-- · 唯一键 `(prep_id, report_type)` —— 与主系统语义对齐:同一 (备货行, 报告类型) 再登记会让
|
||||
-- 上一份同类型报告**作废(latest wins)** ⇒ 我们只在**文件集指纹变化**时才重推,且推的是**完整文件集**;
|
||||
-- · `status` 终态(stored / ignored / failed_terminal)**永不自动重推**;`pending` 才进重试队列。
|
||||
--
|
||||
-- 平台级表(放 public,与 main_supplier_bindings 同级):它是**对接状态**,不是租户业务表
|
||||
-- ⇒ 不进 public.tenant_business_tables(),也不进 /api/data 的 ALLOWED_TABLES。
|
||||
-- 设计:docs/design/20261011-批次报告推送主系统.md §4
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.main_system_report_pushes (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
branch_code VARCHAR(64) NOT NULL,
|
||||
main_branch_code VARCHAR(64),
|
||||
main_supplier_code VARCHAR(64) NOT NULL,
|
||||
prep_id UUID NOT NULL,
|
||||
main_order_code VARCHAR(64),
|
||||
our_order_code VARCHAR(64),
|
||||
our_order_item_id UUID,
|
||||
-- 幂等键的另一半(第一半是 prep_id)
|
||||
report_type VARCHAR(32) NOT NULL,
|
||||
-- 完整文件集指纹:我方对象键排序后 sha256;变了才重推(覆盖"事后补充")
|
||||
file_fingerprint VARCHAR(64) NOT NULL,
|
||||
-- 我方对象键 ↔ 主系统回执里的 path(同序,避免重复上传)
|
||||
our_file_paths TEXT[] NOT NULL DEFAULT ARRAY[]::TEXT[],
|
||||
their_file_paths TEXT[] NOT NULL DEFAULT ARRAY[]::TEXT[],
|
||||
their_report_id UUID,
|
||||
status VARCHAR(16) NOT NULL DEFAULT 'pending',
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
last_http_status INTEGER,
|
||||
last_error TEXT,
|
||||
pushed_at TIMESTAMPTZ,
|
||||
next_retry_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
COMMENT ON TABLE public.main_system_report_pushes IS
|
||||
'批次报告出站台账(我方 → 主系统既有「供应商上传报告」通道):幂等键 (prep_id, report_type),文件集指纹变化才重推完整集';
|
||||
COMMENT ON COLUMN public.main_system_report_pushes.file_fingerprint IS
|
||||
'完整文件集指纹(我方对象键排序后 sha256):未变 ⇒ 不重推;变了 ⇒ 按完整集重推一次(对方 latest wins)';
|
||||
COMMENT ON COLUMN public.main_system_report_pushes.their_file_paths IS
|
||||
'主系统上传回执里的 path(与 our_file_paths 同序):复用可避免重复上传;登记时必须用这些值';
|
||||
COMMENT ON COLUMN public.main_system_report_pushes.status IS
|
||||
'pending=待推/待重试;stored=已登记;ignored=对方 404(行不存在或非本供应商)终态不重推;failed=终态失败(invalid_*/forbidden)需人工';
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint
|
||||
WHERE conrelid = 'public.main_system_report_pushes'::regclass
|
||||
AND conname = 'main_system_report_pushes_status_chk'
|
||||
) THEN
|
||||
ALTER TABLE public.main_system_report_pushes
|
||||
ADD CONSTRAINT main_system_report_pushes_status_chk
|
||||
CHECK (status IN ('pending', 'stored', 'ignored', 'failed'));
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
-- 同一 (备货行, 报告类型) 只有一行:与主系统 latest wins 语义对齐
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_main_system_report_pushes_prep_type
|
||||
ON public.main_system_report_pushes (prep_id, report_type);
|
||||
|
||||
-- 定时对账扫描:按分公司取 pending(含到期的 next_retry_at)
|
||||
CREATE INDEX IF NOT EXISTS idx_main_system_report_pushes_pending
|
||||
ON public.main_system_report_pushes (branch_code, status, next_retry_at);
|
||||
|
||||
-- 排查用:某个主系统订单下推了哪些报告
|
||||
CREATE INDEX IF NOT EXISTS idx_main_system_report_pushes_order
|
||||
ON public.main_system_report_pushes (main_order_code);
|
||||
@@ -91,6 +91,15 @@ MAIN_SYSTEM_INTEGRATION_CLIENT_SECRET=
|
||||
# MAIN_SYSTEM_OAUTH_PATH=/api/supplier/oauth/token
|
||||
# MAIN_SYSTEM_PREPARATIONS_PATH=/api/supplier/preparations
|
||||
|
||||
# --- 第九批「批次报告同步」(我方推、主系统收;契约见 docs/给主系统AI的对接改造清单.md §2.12.9)---
|
||||
# 默认关:关闭时**不采集、不推送**(连候选都不查)⇒ 零出站,行为与改造前逐字节一致。
|
||||
# 打开前提:① 该分公司与主系统有 active 绑定(未绑定取不到 token ⇒ 物理上发不出去)
|
||||
# ② 只推"主系统下发的行 + 批次已人工确认有报告"
|
||||
# MAIN_SYSTEM_REPORT_ENABLED=true
|
||||
# 端点路径可覆盖(一般不用改):
|
||||
# MAIN_SYSTEM_REPORT_UPLOAD_PATH=/api/storage/quality-reports/upload
|
||||
# MAIN_SYSTEM_REPORT_REGISTER_PATH=/api/supplier/quality-reports
|
||||
|
||||
STORAGE_DIR=./uploads-supplier
|
||||
|
||||
# --- 对象存储(S3 兼容:腾讯云 COS / 阿里云 OSS)---
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
/**
|
||||
* 冒烟:批次报告推送(第九批「批次报告同步」)—— 真环境端到端,**只读 + 一次真实登记**。
|
||||
*
|
||||
* 用法:
|
||||
* npx tsx --env-file=.env scripts/smoke-main-system-report-push.ts [文件路径]
|
||||
* (默认用 docs/design/assets 里的 png;也可给一个 pdf 路径)
|
||||
*
|
||||
* 做四件事:
|
||||
* ① 从**我方台账 + 绑定**里挑一条「已绑定 + 主系统下发(有 prep_id)」的行(这三重门禁的前两重);
|
||||
* ② 从主系统实时取该行要求的报告类型(契约 §2.12.9 ④-3:按行传;取不到且该行要求报告时**不猜**);
|
||||
* ③ 走 ①上传(multipart)→ ②登记(按备货行)两步调用;
|
||||
* ④ 打印回执与 `order_code`(用于对方核 §2.12.9 ⑦-3 内部订单详情「报告」列)。
|
||||
*
|
||||
* ⚠️ 这是**联调脚本**,不是生产链路:真链路由 mainSystemReportPushService + 定时兜底驱动。
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import pg from 'pg';
|
||||
import { fetchMainSystemPreparations } from './src/services/mainSystem/api/preparations';
|
||||
import { uploadBatchReportFile, registerBatchReportOnPreparation } from './src/services/mainSystem/api/qualityReports';
|
||||
|
||||
(async () => {
|
||||
// ① 找一条「已绑定 + 主系统下发」的行
|
||||
const c = new pg.Client({ connectionString: process.env.DATABASE_URL });
|
||||
await c.connect();
|
||||
const rows = await c.query(`SELECT l.branch_code, l.main_supplier_code, l.prep_id::text, l.main_order_code, l.item_name,
|
||||
l.payload->>'requiresQualityReport' AS requires_report,
|
||||
l.payload->>'qualityReportType' AS payload_type
|
||||
FROM public.main_system_order_import_items l
|
||||
JOIN public.main_supplier_bindings b
|
||||
ON b.branch_code = l.branch_code AND b.main_supplier_code = l.main_supplier_code AND b.status='active'
|
||||
WHERE l.prep_id IS NOT NULL ORDER BY l.branch_code, l.main_order_code LIMIT 10`);
|
||||
await c.end();
|
||||
console.log('候选行(台账):');
|
||||
for (const r of rows.rows) {
|
||||
console.log(` ${r.branch_code} | ${r.main_supplier_code} | prep=${r.prep_id.slice(0, 8)}… | ${r.main_order_code} | ${r.item_name} | requires=${r.requires_report} | type=${r.payload_type ?? '(未知)'}`);
|
||||
}
|
||||
const picked = rows.rows[0];
|
||||
if (!picked) { console.log('没有可用的行'); process.exit(0); }
|
||||
|
||||
// ② 从主系统实时取该行的"要求报告类型"(契约 ④-3:按行传)
|
||||
const outcome: any = await fetchMainSystemPreparations(picked.main_supplier_code, 'active');
|
||||
if (outcome.kind !== 'ok') { console.log('拉取备货行失败:', outcome.kind, outcome.reason); process.exit(1); }
|
||||
let live: any = null;
|
||||
for (const order of outcome.orders || []) {
|
||||
for (const item of order.items || []) {
|
||||
if (String(item.id) === picked.prep_id) live = item;
|
||||
}
|
||||
}
|
||||
console.log('\n主系统实时行:', live ? JSON.stringify({
|
||||
id: String(live.id).slice(0, 8) + '…',
|
||||
requires: live.requiresQualityReport,
|
||||
type: live.qualityReportType ?? null,
|
||||
order: live.orderCode,
|
||||
}) : '(该行已不在 active 视图)');
|
||||
const reportType = live?.qualityReportType || (live?.requiresQualityReport ? '' : 'batch');
|
||||
if (!reportType) { console.log('该行要求报告但类型未知 ⇒ 按契约不猜,终止'); process.exit(0); }
|
||||
|
||||
// ③ 上传真实文件(用仓库里现成的 png)
|
||||
const filePath = '../docs/design/assets/mp-ui-20260806/01-登录页.png';
|
||||
const buffer = fs.readFileSync(filePath);
|
||||
const uploaded = await uploadBatchReportFile({
|
||||
supplierCode: picked.main_supplier_code,
|
||||
fileName: 'batch-report-smoke.png',
|
||||
buffer,
|
||||
mime: 'image/png',
|
||||
});
|
||||
console.log('\n① 上传:', JSON.stringify(uploaded));
|
||||
if (uploaded.kind !== 'ok') process.exit(1);
|
||||
|
||||
// ④ 登记(带四个来源字段;不带 defer_coverage)
|
||||
const registered = await registerBatchReportOnPreparation({
|
||||
supplierCode: picked.main_supplier_code,
|
||||
preparationId: picked.prep_id,
|
||||
files: [uploaded.path],
|
||||
reportType,
|
||||
batchNo: 'STK202610107YRQEO',
|
||||
producedAt: '2026-10-08',
|
||||
testingOrg: 'XX检测中心',
|
||||
productNames: ['香菇', '平菇'],
|
||||
});
|
||||
console.log('② 登记:', JSON.stringify(registered));
|
||||
console.log('\n>>> 联调回执用:order_code =', picked.main_order_code, '| prep_id =', picked.prep_id, '| report_type =', reportType);
|
||||
process.exit(0);
|
||||
})().catch((e) => { console.error('冒烟失败:', e.message); process.exit(1); });
|
||||
@@ -553,6 +553,12 @@ export function mountInventoryWorkflowRoutes(router: Router): void {
|
||||
operatorId: req.userId || null,
|
||||
matches,
|
||||
});
|
||||
// 第九批「批次报告同步」触发点②:报告刚确认关联到批次 ⇒ 旁路异步推给主系统(覆盖"事后补充")。
|
||||
// 未绑定/非主系统下发的行在推送侧被物理拦住;开关默认关 ⇒ 零出站。
|
||||
{
|
||||
const { triggerReportPush } = await import('../../../services/mainSystemReportPushService');
|
||||
triggerReportPush(branchCode);
|
||||
}
|
||||
return res.json({ data });
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 500).json({
|
||||
|
||||
@@ -232,6 +232,8 @@ function mapWebhookRow(raw: any): MainPreparationRow {
|
||||
returnCode: raw?.return_code ? String(raw.return_code) : null,
|
||||
returnReason: raw?.return_reason ? String(raw.return_reason) : null,
|
||||
requiresQualityReport: raw?.requires_quality_report === true,
|
||||
// 第九批:该行要求的报告类型(推送批次报告时按它传;见 20261011-批次报告推送主系统.md)
|
||||
qualityReportType: raw?.quality_report_type ? String(raw.quality_report_type) : null,
|
||||
orderItemRemark: raw?.order_item_remark ? String(raw.order_item_remark) : null,
|
||||
// 主系统 2026-10-09 增量(webhook 载荷同步携带):两个事实分别独立,禁止合并判定
|
||||
skipInbound: raw?.skip_inbound === true,
|
||||
|
||||
@@ -45,6 +45,12 @@ export type MainPreparationRow = {
|
||||
returnCode: string | null;
|
||||
returnReason: string | null;
|
||||
requiresQualityReport: boolean;
|
||||
/**
|
||||
* 该行要求的**报告类型码**(主系统备货行返回 `quality_report_type`;第九批契约 §2.12.9 ④-3:
|
||||
* 推送批次报告时必须**按该行要求的类型**传,否则会出现"要求检疫却显示批次报告却算已覆盖"的口径错位)。
|
||||
* 该行不要求报告时可能为 null。
|
||||
*/
|
||||
qualityReportType: string | null;
|
||||
orderItemRemark: string | null;
|
||||
/**
|
||||
* 主系统**下单分公司**编码(= 主系统那边买东西的那家分公司,如 BR002「自贡」)。
|
||||
@@ -158,6 +164,7 @@ export function mapMainPreparationRow(raw: any): MainPreparationRow {
|
||||
returnCode: raw?.return_code ? String(raw.return_code) : null,
|
||||
returnReason: raw?.return_reason ? String(raw.return_reason) : null,
|
||||
requiresQualityReport: raw?.requires_quality_report === true,
|
||||
qualityReportType: raw?.quality_report_type ? String(raw.quality_report_type) : null,
|
||||
orderItemRemark: raw?.order_item_remark ? String(raw.order_item_remark) : null,
|
||||
// 主系统 2026-10-09 增量:两个事实**分别独立**映射,禁止合并判定(供应商管理冻结)
|
||||
skipInbound: raw?.skip_inbound === true,
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
/**
|
||||
* 第九批「批次报告同步」:把**我方批次报告**登记到主系统**既有**的「供应商上传报告」通道。
|
||||
*
|
||||
* 契约权威:`docs/给主系统AI的对接改造清单.md` **§2.12.9**(最终调用契约)+ §4.5.17(逐条回执)。
|
||||
* 他们是「可以开工」态(主系统提交 `c24f4881`),不需要再等契约。
|
||||
*
|
||||
* 两步(不新开端点):
|
||||
* ① 传文件 `POST {BASE}/api/storage/quality-reports/upload?path=<对象名>`(multipart,字段名 `file`)
|
||||
* ⇒ 回 `{path, signedUrl}`,**必须用回执里的 `path` 去登记**(他们会把文件名随机化);
|
||||
* ② 登记 `POST {BASE}/api/supplier/quality-reports`(JSON,按备货行逐条)
|
||||
* ⇒ 回 `{data:{id, status, report_type, file_paths, batch_no, produced_at, testing_org, product_name, …}}`
|
||||
*
|
||||
* ⚠️ 三条不能做反的(§2.12.9 ④):
|
||||
* · 每次推**该行该类型的完整文件集**(同 (preparation_id, report_type) 再登记 ⇒ 旧报告作废,latest wins);
|
||||
* · **不要传 `defer_coverage`**(那是"待人工确认命中"的暂存态:既不覆盖也不展示);
|
||||
* · **不要传** `sku_code` / `order_code` / `branch_code` / `supplier_code` / `category_code` / `delivery_date`
|
||||
* (他们按备货行自动派生,传了也不生效)。
|
||||
*/
|
||||
import { MAIN_SYSTEM_FETCH_TIMEOUT_MS } from '../config';
|
||||
import { getMainSystemToken } from '../token';
|
||||
import { requestMainSystem } from '../http';
|
||||
|
||||
/** 主系统桶 `quality-reports` 的白名单:仅 .pdf + 图片,单文件 ≤ 10MB(§2.12.9 ①) */
|
||||
export const MAIN_SYSTEM_REPORT_ALLOWED_EXT = ['.pdf', '.jpg', '.jpeg', '.png', '.webp', '.gif'] as const;
|
||||
export const MAIN_SYSTEM_REPORT_MAX_BYTES = 10 * 1024 * 1024;
|
||||
|
||||
export function isUploadableReportFileName(name: string): boolean {
|
||||
const lower = String(name || '').trim().toLowerCase();
|
||||
return MAIN_SYSTEM_REPORT_ALLOWED_EXT.some((ext) => lower.endsWith(ext));
|
||||
}
|
||||
|
||||
export type UploadReportFileOutcome =
|
||||
| { kind: 'ok'; path: string; signedUrl?: string }
|
||||
| { kind: 'not_configured'; reason: string }
|
||||
| { kind: 'transient'; status: number; reason: string }
|
||||
| { kind: 'failed'; status: number; reason: string };
|
||||
|
||||
/**
|
||||
* ① 传文件:把字节转存进主系统 `quality-reports` 桶。
|
||||
* `fileName` 只用于保留扩展名/子目录(他们会随机化文件名)。
|
||||
*/
|
||||
export async function uploadBatchReportFile(input: {
|
||||
supplierCode: string;
|
||||
fileName: string;
|
||||
buffer: Buffer;
|
||||
mime?: string | null;
|
||||
fetchImpl?: typeof fetch;
|
||||
}): Promise<UploadReportFileOutcome> {
|
||||
const name = String(input.fileName || '').trim();
|
||||
if (!name) return { kind: 'failed', status: 0, reason: '缺少文件名' };
|
||||
if (!isUploadableReportFileName(name)) {
|
||||
return { kind: 'failed', status: 0, reason: `主系统只收 pdf/图片(当前:${name})` };
|
||||
}
|
||||
if (input.buffer.length > MAIN_SYSTEM_REPORT_MAX_BYTES) {
|
||||
return { kind: 'failed', status: 0, reason: `单文件超过 10MB(${input.buffer.length} 字节)` };
|
||||
}
|
||||
|
||||
const tokenResult = await getMainSystemToken(input.supplierCode);
|
||||
if (tokenResult.kind === 'not_configured') return { kind: 'not_configured', reason: tokenResult.reason };
|
||||
if (tokenResult.kind !== 'ok') return { kind: 'transient', status: 0, reason: tokenResult.reason };
|
||||
|
||||
const form = new FormData();
|
||||
form.append('file', new Blob([new Uint8Array(input.buffer)], { type: input.mime || 'application/octet-stream' }), name);
|
||||
|
||||
const result = await requestMainSystem<any>({
|
||||
endpoint: 'qualityReportUpload',
|
||||
method: 'POST',
|
||||
token: tokenResult.token,
|
||||
query: { path: name },
|
||||
formData: form,
|
||||
timeoutMs: MAIN_SYSTEM_FETCH_TIMEOUT_MS * 2, // 传文件比普通请求慢
|
||||
timeoutReason: '上传批次报告文件超时',
|
||||
networkReasonPrefix: '上传批次报告文件失败:',
|
||||
fetchImpl: input.fetchImpl,
|
||||
});
|
||||
|
||||
if (result.kind === 'ok') {
|
||||
const path = String((result.payload as any)?.path || '').trim();
|
||||
if (!path) return { kind: 'failed', status: result.status, reason: '上传成功但回执缺少 path' };
|
||||
return { kind: 'ok', path, signedUrl: (result.payload as any)?.signedUrl };
|
||||
}
|
||||
if (result.kind === 'not_configured') return { kind: 'not_configured', reason: result.reason };
|
||||
if (result.kind === 'unavailable') return { kind: 'transient', status: result.status, reason: result.reason };
|
||||
// 4xx:文件名/桶规则类 ⇒ 终态(不重试);401/403 由调用方按契约决定是否重取 token
|
||||
return { kind: 'failed', status: result.status, reason: result.reason };
|
||||
}
|
||||
|
||||
export type RegisterReportOutcome =
|
||||
| { kind: 'stored'; theirReportId: string | null; status: number; payload: unknown }
|
||||
| { kind: 'ignored'; status: 404; reason: string }
|
||||
| { kind: 'failed'; status: number; reason: string; error: string }
|
||||
| { kind: 'token_expired'; reason: string }
|
||||
| { kind: 'transient'; status: number; reason: string }
|
||||
| { kind: 'not_configured'; reason: string };
|
||||
|
||||
/**
|
||||
* ② 登记报告(按备货行,一次一行)。
|
||||
*
|
||||
* 响应映射严格按 §2.12.9 ③:
|
||||
* 200 stored / 404 ignored(终态不重推)/ 400 invalid_* failed(终态+告警)/
|
||||
* 401 token_expired(重取 token)/ 403 failed / 5xx transient(退避重试)
|
||||
*/
|
||||
export async function registerBatchReportOnPreparation(input: {
|
||||
supplierCode: string;
|
||||
preparationId: string;
|
||||
files: string[];
|
||||
reportType: string;
|
||||
batchNo?: string | null;
|
||||
producedAt?: string | null;
|
||||
testingOrg?: string | null;
|
||||
productNames?: string[] | null;
|
||||
fetchImpl?: typeof fetch;
|
||||
}): Promise<RegisterReportOutcome> {
|
||||
const prepId = String(input.preparationId || '').trim();
|
||||
const files = (input.files || []).map((f) => String(f || '').trim()).filter(Boolean);
|
||||
const reportType = String(input.reportType || '').trim();
|
||||
if (!prepId) return { kind: 'failed', status: 0, reason: '缺少 preparation_id', error: 'invalid_request' };
|
||||
if (!files.length) return { kind: 'failed', status: 0, reason: '缺少文件', error: 'invalid_request' };
|
||||
if (!reportType) return { kind: 'failed', status: 0, reason: '缺少 report_type', error: 'invalid_request' };
|
||||
|
||||
const tokenResult = await getMainSystemToken(input.supplierCode);
|
||||
if (tokenResult.kind === 'not_configured') return { kind: 'not_configured', reason: tokenResult.reason };
|
||||
if (tokenResult.kind !== 'ok') return { kind: 'transient', status: 0, reason: tokenResult.reason };
|
||||
|
||||
// ⚠️ 只传契约允许的字段:不传 defer_coverage / sku_code / order_code / branch_code / supplier_code / …
|
||||
const body: Record<string, unknown> = {
|
||||
preparation_id: prepId,
|
||||
files,
|
||||
report_type: reportType,
|
||||
};
|
||||
const batchNo = String(input.batchNo || '').trim();
|
||||
if (batchNo) body.batch_no = batchNo.slice(0, 50);
|
||||
if (input.producedAt) body.produced_at = input.producedAt;
|
||||
if (input.testingOrg) body.testing_org = String(input.testingOrg).slice(0, 200);
|
||||
const names = (input.productNames || []).map((n) => String(n || '').trim()).filter(Boolean);
|
||||
if (names.length) body.product_names = names;
|
||||
|
||||
const result = await requestMainSystem<any>({
|
||||
endpoint: 'qualityReportRegister',
|
||||
method: 'POST',
|
||||
token: tokenResult.token,
|
||||
body,
|
||||
timeoutMs: MAIN_SYSTEM_FETCH_TIMEOUT_MS,
|
||||
timeoutReason: '登记批次报告超时',
|
||||
networkReasonPrefix: '登记批次报告失败:',
|
||||
fetchImpl: input.fetchImpl,
|
||||
});
|
||||
|
||||
if (result.kind === 'ok') {
|
||||
const id = String((result.payload as any)?.data?.id || '').trim();
|
||||
return { kind: 'stored', theirReportId: id || null, status: result.status, payload: result.payload };
|
||||
}
|
||||
if (result.kind === 'not_configured') return { kind: 'not_configured', reason: result.reason };
|
||||
|
||||
const status = result.status;
|
||||
const error = String((result.payload as any)?.error || '').trim();
|
||||
if (status === 404) return { kind: 'ignored', status: 404, reason: result.reason };
|
||||
if (status === 401) return { kind: 'token_expired', reason: result.reason };
|
||||
if (status >= 500 || status === 0) return { kind: 'transient', status, reason: result.reason };
|
||||
return { kind: 'failed', status, reason: result.reason, error: error || `HTTP ${status}` };
|
||||
}
|
||||
@@ -29,6 +29,13 @@ export const MAIN_SYSTEM_DEFAULT_PATHS = {
|
||||
*/
|
||||
priceQtyRequestsList: '/api/supplier/preparations/price-qty-requests',
|
||||
supplierLogin: '/api/supplier/login',
|
||||
/**
|
||||
* 第九批「批次报告同步」(我方推、主系统收;契约 §2.12.9):
|
||||
* ① 传文件:multipart 字段名 `file`,`?path=<对象名>`;回 `{path, signedUrl}`(**用回执的 path 登记**)
|
||||
* ② 登记报告:按备货行逐条(一次一行)
|
||||
*/
|
||||
qualityReportUpload: '/api/storage/quality-reports/upload',
|
||||
qualityReportRegister: '/api/supplier/quality-reports',
|
||||
} as const;
|
||||
|
||||
export type MainSystemEndpoint = keyof typeof MAIN_SYSTEM_DEFAULT_PATHS;
|
||||
|
||||
@@ -34,6 +34,10 @@ function pathOverride(endpoint: MainSystemEndpoint): string | undefined {
|
||||
return process.env.MAIN_SYSTEM_PRICE_QTY_LIST_PATH;
|
||||
case 'supplierLogin':
|
||||
return config.mainSystem.supplierLoginPath;
|
||||
case 'qualityReportUpload':
|
||||
return process.env.MAIN_SYSTEM_REPORT_UPLOAD_PATH;
|
||||
case 'qualityReportRegister':
|
||||
return process.env.MAIN_SYSTEM_REPORT_REGISTER_PATH;
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -49,6 +49,8 @@ export type MainSystemRequestOptions = {
|
||||
/** Bearer token(oauth 接口自身不传) */
|
||||
token?: string | null;
|
||||
body?: unknown;
|
||||
/** multipart 上传(与 `body` 互斥):给了它就不设 Content-Type,交给 fetch 生成 boundary */
|
||||
formData?: FormData;
|
||||
query?: MainSystemQuery;
|
||||
timeoutMs?: number;
|
||||
/** 超时文案(保留各调用点既有措辞,便于日志比对) */
|
||||
@@ -104,12 +106,17 @@ export async function requestMainSystem<T = any>(
|
||||
try {
|
||||
const headers: Record<string, string> = { Accept: 'application/json' };
|
||||
if (options.token) headers.Authorization = `Bearer ${options.token}`;
|
||||
if (options.body !== undefined) headers['Content-Type'] = 'application/json';
|
||||
// multipart 不能自己设 Content-Type(boundary 由 fetch 生成)
|
||||
if (options.body !== undefined && !options.formData) headers['Content-Type'] = 'application/json';
|
||||
|
||||
const response = await doFetch(url, {
|
||||
method: options.method || 'GET',
|
||||
headers,
|
||||
...(options.body === undefined ? {} : { body: JSON.stringify(options.body) }),
|
||||
...(options.formData
|
||||
? { body: options.formData }
|
||||
: options.body === undefined
|
||||
? {}
|
||||
: { body: JSON.stringify(options.body) }),
|
||||
signal: controller.signal,
|
||||
});
|
||||
const payload: unknown = await response.json().catch(() => null);
|
||||
|
||||
@@ -0,0 +1,406 @@
|
||||
/**
|
||||
* 批次报告推送(第九批「批次报告同步」我方推送侧)。
|
||||
*
|
||||
* 设计:docs/design/20261011-批次报告推送主系统.md
|
||||
* 契约(权威):docs/给主系统AI的对接改造清单.md §2.12.9 / §4.5.17。
|
||||
*
|
||||
* 三重门禁(开发者原话:「没有绑定、没有主系统下发的订单,报告就别传过去,不能造成混乱」):
|
||||
* ① 该分公司与主系统**有 active 绑定**(否则连 token 都取不到 ⇒ 物理上发不出去);
|
||||
* ② 该行**是主系统下发的**(我方台账 `main_system_order_import_items` 有 prep_id 对照);
|
||||
* ③ 该批次**已人工确认**关联到报告。
|
||||
*
|
||||
* 幂等:台账 `main_system_report_pushes` 唯一键 `(prep_id, report_type)` + **完整文件集指纹**:
|
||||
* 指纹未变 ⇒ 不重推;指纹变了(事后补充)⇒ 按**完整文件集**重推一次(主系统 latest wins)。
|
||||
*/
|
||||
import { createHash } from 'node:crypto';
|
||||
import { pool } from '../db';
|
||||
import { getStorageProvider } from './storageProvider';
|
||||
import {
|
||||
registerBatchReportOnPreparation,
|
||||
uploadBatchReportFile,
|
||||
isUploadableReportFileName,
|
||||
} from './mainSystem/api/qualityReports';
|
||||
|
||||
/** 我方批次报告存放的桶(与 inventoryBatchReportService 一致) */
|
||||
const REPORT_BUCKET = 'quality-reports';
|
||||
|
||||
export function isReportPushEnabled(): boolean {
|
||||
return process.env.MAIN_SYSTEM_REPORT_ENABLED === 'true';
|
||||
}
|
||||
|
||||
export type ReportPushCandidate = {
|
||||
branch_code: string;
|
||||
main_branch_code: string | null;
|
||||
main_supplier_code: string;
|
||||
prep_id: string;
|
||||
main_order_code: string | null;
|
||||
our_order_code: string | null;
|
||||
our_order_item_id: string | null;
|
||||
report_type: string;
|
||||
/** 该行消耗批次命中的**全部**报告文件(我方对象键,已排序去重) */
|
||||
our_file_paths: string[];
|
||||
report_ids: string[];
|
||||
batch_no: string | null;
|
||||
produced_at: string | null;
|
||||
testing_org: string | null;
|
||||
product_names: string[];
|
||||
};
|
||||
|
||||
/** 完整文件集指纹:我方对象键排序后 sha256(变了才重推) */
|
||||
export function filesFingerprint(paths: string[]): string {
|
||||
const sorted = [...new Set((paths || []).map((p) => String(p || '').trim()).filter(Boolean))].sort();
|
||||
return createHash('sha256').update(sorted.join('\n')).digest('hex');
|
||||
}
|
||||
|
||||
/**
|
||||
* 采集候选:报告(已确认)→ 入库批次 → 分拣选批 → 订单行 → 主系统备货行(prep_id)。
|
||||
*
|
||||
* ⚠️ 只认"分拣**实际选定/扣减**的批次"(`picking_items.outbound_batches`,形如
|
||||
* `[{"batch_no":"STK…","qty":12.5}]`)—— 这正是开发者说的"分拣完毕选中了那几个批次"。
|
||||
*/
|
||||
export async function collectReportPushCandidates(input: {
|
||||
branchCode: string;
|
||||
limit?: number;
|
||||
}): Promise<ReportPushCandidate[]> {
|
||||
const branchCode = String(input.branchCode || '').trim();
|
||||
if (!branchCode) return [];
|
||||
const limit = Math.min(Math.max(Number(input.limit) || 50, 1), 200);
|
||||
const result = await pool.query(
|
||||
`WITH hit AS (
|
||||
SELECT DISTINCT
|
||||
pi.id AS picking_item_id,
|
||||
inv.sku_code AS sku_code,
|
||||
inv.batch_no AS batch_no,
|
||||
r.id AS report_id,
|
||||
r.file_paths AS file_paths,
|
||||
r.produced_at AS produced_at,
|
||||
r.testing_org AS testing_org,
|
||||
r.product_names AS product_names
|
||||
FROM inventory_batch_report_matches m
|
||||
JOIN inventory_batch_reports r ON r.id = m.report_id AND r.status = 30
|
||||
JOIN inventory inv ON inv.id = m.inventory_id
|
||||
JOIN picking_items pi ON pi.sku_code = inv.sku_code
|
||||
AND pi.branch_code = $1
|
||||
AND jsonb_typeof(pi.outbound_batches) = 'array'
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM jsonb_array_elements(pi.outbound_batches) e
|
||||
WHERE e->>'batch_no' = inv.batch_no
|
||||
)
|
||||
)
|
||||
SELECT l.branch_code,
|
||||
l.main_branch_code,
|
||||
l.main_supplier_code,
|
||||
l.prep_id::text AS prep_id,
|
||||
l.main_order_code,
|
||||
l.our_order_code,
|
||||
l.our_order_item_id::text AS our_order_item_id,
|
||||
l.payload->>'qualityReportType' AS payload_report_type,
|
||||
COALESCE(l.payload->>'requiresQualityReport', 'false') AS requires_report,
|
||||
h.batch_no,
|
||||
array_agg(DISTINCT h.report_id::text) AS report_ids,
|
||||
array_agg(DISTINCT unnest_path) AS our_file_paths,
|
||||
(array_agg(DISTINCT h.produced_at::text))[1] AS produced_at,
|
||||
(array_agg(DISTINCT h.testing_org))[1] AS testing_org
|
||||
FROM hit h
|
||||
JOIN picking_items pi ON pi.id = h.picking_item_id
|
||||
JOIN public.main_system_order_import_items l
|
||||
ON l.our_order_item_id = pi.order_item_id
|
||||
AND l.branch_code = $1
|
||||
AND l.prep_id IS NOT NULL
|
||||
JOIN public.main_supplier_bindings b
|
||||
ON b.branch_code = l.branch_code
|
||||
AND b.main_supplier_code = l.main_supplier_code
|
||||
AND b.status = 'active'
|
||||
LEFT JOIN LATERAL unnest(h.file_paths) AS unnest_path ON TRUE
|
||||
GROUP BY l.branch_code, l.main_branch_code, l.main_supplier_code, l.prep_id,
|
||||
l.main_order_code, l.our_order_code, l.our_order_item_id,
|
||||
l.payload->>'qualityReportType', l.payload->>'requiresQualityReport', h.batch_no
|
||||
ORDER BY l.prep_id
|
||||
LIMIT $2`,
|
||||
[branchCode, limit]
|
||||
);
|
||||
|
||||
const productNamesByBranch = new Map<string, string[]>();
|
||||
const out: ReportPushCandidate[] = [];
|
||||
for (const row of result.rows as Record<string, unknown>[]) {
|
||||
const requires = String(row.requires_report || '') === 'true';
|
||||
const payloadType = String(row.payload_report_type || '').trim();
|
||||
// 契约 §2.12.9 ④-3:按该行要求的类型传;该行不要求报告时才允许兜底 'batch'
|
||||
const reportType = payloadType || (requires ? '' : 'batch');
|
||||
if (!reportType) continue; // 需要报告但类型未知 ⇒ 等下一次导入刷新 payload(不猜)
|
||||
const files = ((row.our_file_paths as string[]) || []).filter(Boolean).map(String);
|
||||
if (!files.length) continue;
|
||||
out.push({
|
||||
branch_code: String(row.branch_code),
|
||||
main_branch_code: row.main_branch_code ? String(row.main_branch_code) : null,
|
||||
main_supplier_code: String(row.main_supplier_code),
|
||||
prep_id: String(row.prep_id),
|
||||
main_order_code: row.main_order_code ? String(row.main_order_code) : null,
|
||||
our_order_code: row.our_order_code ? String(row.our_order_code) : null,
|
||||
our_order_item_id: row.our_order_item_id ? String(row.our_order_item_id) : null,
|
||||
report_type: reportType,
|
||||
our_file_paths: [...new Set(files)].sort(),
|
||||
report_ids: ((row.report_ids as string[]) || []).map(String),
|
||||
batch_no: row.batch_no ? String(row.batch_no) : null,
|
||||
produced_at: row.produced_at ? String(row.produced_at) : null,
|
||||
testing_org: row.testing_org ? String(row.testing_org) : null,
|
||||
product_names: productNamesByBranch.get(String(row.branch_code)) || [],
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export type PushOneResult = {
|
||||
status: 'stored' | 'ignored' | 'failed' | 'skipped' | 'transient';
|
||||
reason?: string;
|
||||
theirReportId?: string | null;
|
||||
};
|
||||
|
||||
/** 单条候选:落台账 → (文件集变了才)上传 + 登记 → 回写状态 */
|
||||
export async function pushReportCandidate(candidate: ReportPushCandidate): Promise<PushOneResult> {
|
||||
const fingerprint = filesFingerprint(candidate.our_file_paths);
|
||||
|
||||
const ledger = await pool.query<{
|
||||
id: string;
|
||||
file_fingerprint: string;
|
||||
status: string;
|
||||
our_file_paths: string[] | null;
|
||||
their_file_paths: string[] | null;
|
||||
}>(
|
||||
`INSERT INTO public.main_system_report_pushes
|
||||
(branch_code, main_branch_code, main_supplier_code, prep_id, main_order_code, our_order_code,
|
||||
our_order_item_id, report_type, file_fingerprint, our_file_paths, status)
|
||||
VALUES ($1,$2,$3,$4::uuid,$5,$6,$7::uuid,$8,$9,$10,'pending')
|
||||
ON CONFLICT (prep_id, report_type) DO UPDATE SET
|
||||
file_fingerprint = EXCLUDED.file_fingerprint,
|
||||
our_file_paths = EXCLUDED.our_file_paths,
|
||||
-- 文件集变了 ⇒ 回到 pending 重推完整集;没变则保持原状态(终态不复活)
|
||||
status = CASE
|
||||
WHEN public.main_system_report_pushes.file_fingerprint <> EXCLUDED.file_fingerprint
|
||||
THEN 'pending'
|
||||
ELSE public.main_system_report_pushes.status
|
||||
END,
|
||||
updated_at = NOW()
|
||||
RETURNING id, file_fingerprint, status, our_file_paths, their_file_paths`,
|
||||
[
|
||||
candidate.branch_code,
|
||||
candidate.main_branch_code,
|
||||
candidate.main_supplier_code,
|
||||
candidate.prep_id,
|
||||
candidate.main_order_code,
|
||||
candidate.our_order_code,
|
||||
candidate.our_order_item_id,
|
||||
candidate.report_type,
|
||||
fingerprint,
|
||||
candidate.our_file_paths,
|
||||
]
|
||||
);
|
||||
const row = ledger.rows[0];
|
||||
if (!row) return { status: 'failed', reason: '台账写入失败' };
|
||||
|
||||
// 指纹未变 + 已终态 ⇒ 不重推(幂等;ignored/failed 也不复活)
|
||||
if (row.file_fingerprint === fingerprint && row.status !== 'pending') {
|
||||
return { status: 'skipped', reason: `已 ${row.status}` };
|
||||
}
|
||||
|
||||
// 文件上传:按"我方键 → 对方 path"同序缓存,避免重复上传
|
||||
const ourPaths = candidate.our_file_paths;
|
||||
const cachedOur = (row.our_file_paths || []).map(String);
|
||||
const cachedTheir = (row.their_file_paths || []).map(String);
|
||||
const theirPaths: string[] = [];
|
||||
const uploadedOur: string[] = [];
|
||||
const storage = getStorageProvider();
|
||||
|
||||
for (const ourPath of ourPaths) {
|
||||
const cachedIdx = cachedOur.indexOf(ourPath);
|
||||
if (cachedIdx >= 0 && cachedTheir[cachedIdx]) {
|
||||
theirPaths.push(cachedTheir[cachedIdx]);
|
||||
uploadedOur.push(ourPath);
|
||||
continue;
|
||||
}
|
||||
const fileName = ourPath.split('/').pop() || ourPath;
|
||||
if (!isUploadableReportFileName(fileName)) {
|
||||
await markLedger(row.id, { status: 'failed', error: `主系统只收 pdf/图片:${fileName}`, httpStatus: 0 });
|
||||
return { status: 'failed', reason: `不可上传的文件类型:${fileName}` };
|
||||
}
|
||||
const object = await storage.getObject(REPORT_BUCKET, ourPath);
|
||||
if (!object?.buffer?.length) {
|
||||
await markLedger(row.id, { status: 'failed', error: `我方对象缺失:${ourPath}`, httpStatus: 0 });
|
||||
return { status: 'failed', reason: `我方对象缺失:${ourPath}` };
|
||||
}
|
||||
const uploaded = await uploadBatchReportFile({
|
||||
supplierCode: candidate.main_supplier_code,
|
||||
fileName,
|
||||
buffer: object.buffer,
|
||||
});
|
||||
if (uploaded.kind === 'not_configured') {
|
||||
return { status: 'skipped', reason: uploaded.reason };
|
||||
}
|
||||
if (uploaded.kind !== 'ok') {
|
||||
const terminal = uploaded.kind === 'failed';
|
||||
await markLedger(row.id, {
|
||||
status: terminal ? 'failed' : 'pending',
|
||||
error: uploaded.reason,
|
||||
httpStatus: uploaded.status,
|
||||
retry: !terminal,
|
||||
});
|
||||
return { status: terminal ? 'failed' : 'transient', reason: uploaded.reason };
|
||||
}
|
||||
theirPaths.push(uploaded.path);
|
||||
uploadedOur.push(ourPath);
|
||||
}
|
||||
|
||||
const registered = await registerBatchReportOnPreparation({
|
||||
supplierCode: candidate.main_supplier_code,
|
||||
preparationId: candidate.prep_id,
|
||||
files: theirPaths,
|
||||
reportType: candidate.report_type,
|
||||
batchNo: candidate.batch_no,
|
||||
producedAt: candidate.produced_at,
|
||||
testingOrg: candidate.testing_org,
|
||||
productNames: candidate.product_names,
|
||||
});
|
||||
|
||||
if (registered.kind === 'stored') {
|
||||
await markLedger(row.id, {
|
||||
status: 'stored',
|
||||
error: null,
|
||||
httpStatus: registered.status,
|
||||
theirReportId: registered.theirReportId,
|
||||
ourFilePaths: uploadedOur,
|
||||
theirFilePaths: theirPaths,
|
||||
});
|
||||
return { status: 'stored', theirReportId: registered.theirReportId };
|
||||
}
|
||||
if (registered.kind === 'ignored') {
|
||||
// 对方不认识该行(不存在或不属于本 token 的供应商)⇒ 终态,永不重推
|
||||
await markLedger(row.id, { status: 'ignored', error: registered.reason, httpStatus: 404 });
|
||||
return { status: 'ignored', reason: registered.reason };
|
||||
}
|
||||
if (registered.kind === 'transient' || registered.kind === 'token_expired') {
|
||||
await markLedger(row.id, {
|
||||
status: 'pending',
|
||||
error: registered.reason,
|
||||
httpStatus: registered.kind === 'token_expired' ? 401 : registered.status,
|
||||
retry: true,
|
||||
});
|
||||
return { status: 'transient', reason: registered.reason };
|
||||
}
|
||||
if (registered.kind === 'not_configured') return { status: 'skipped', reason: registered.reason };
|
||||
await markLedger(row.id, {
|
||||
status: 'failed',
|
||||
error: `${registered.error}: ${registered.reason}`,
|
||||
httpStatus: registered.status,
|
||||
ourFilePaths: uploadedOur,
|
||||
theirFilePaths: theirPaths,
|
||||
});
|
||||
return { status: 'failed', reason: registered.reason };
|
||||
}
|
||||
|
||||
async function markLedger(
|
||||
id: string,
|
||||
patch: {
|
||||
status: 'pending' | 'stored' | 'ignored' | 'failed';
|
||||
error: string | null;
|
||||
httpStatus: number;
|
||||
retry?: boolean;
|
||||
theirReportId?: string | null;
|
||||
ourFilePaths?: string[];
|
||||
theirFilePaths?: string[];
|
||||
}
|
||||
): Promise<void> {
|
||||
await pool.query(
|
||||
`UPDATE public.main_system_report_pushes
|
||||
SET status = $2,
|
||||
last_error = $3,
|
||||
last_http_status = $4,
|
||||
attempts = attempts + 1,
|
||||
pushed_at = CASE WHEN $2 = 'stored' THEN NOW() ELSE pushed_at END,
|
||||
next_retry_at = CASE WHEN $5 THEN NOW() + (LEAST(POWER(2, LEAST(attempts, 6))::int, 60) || ' minutes')::interval
|
||||
ELSE NULL END,
|
||||
their_report_id = COALESCE($6::uuid, their_report_id),
|
||||
our_file_paths = COALESCE($7::text[], our_file_paths),
|
||||
their_file_paths = COALESCE($8::text[], their_file_paths),
|
||||
updated_at = NOW()
|
||||
WHERE id = $1`,
|
||||
[
|
||||
id,
|
||||
patch.status,
|
||||
patch.error,
|
||||
patch.httpStatus,
|
||||
patch.retry === true,
|
||||
patch.theirReportId ?? null,
|
||||
patch.ourFilePaths ?? null,
|
||||
patch.theirFilePaths ?? null,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/** 一个分公司推一轮(采集 + 逐条推) */
|
||||
export async function pushBranchReports(input: { branchCode: string; limit?: number }): Promise<{
|
||||
candidates: number;
|
||||
stored: number;
|
||||
ignored: number;
|
||||
failed: number;
|
||||
skipped: number;
|
||||
transient: number;
|
||||
}> {
|
||||
const empty = { candidates: 0, stored: 0, ignored: 0, failed: 0, skipped: 0, transient: 0 };
|
||||
if (!isReportPushEnabled()) return empty;
|
||||
const branchCode = String(input.branchCode || '').trim();
|
||||
if (!branchCode) return empty;
|
||||
const candidates = await collectReportPushCandidates({ branchCode, limit: input.limit });
|
||||
const stat = { ...empty, candidates: candidates.length };
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
const result = await pushReportCandidate(candidate);
|
||||
if (result.status === 'stored') stat.stored += 1;
|
||||
else if (result.status === 'ignored') stat.ignored += 1;
|
||||
else if (result.status === 'failed') stat.failed += 1;
|
||||
else if (result.status === 'transient') stat.transient += 1;
|
||||
else stat.skipped += 1;
|
||||
} catch (error: any) {
|
||||
stat.failed += 1;
|
||||
console.warn('[report-push] 推送异常:', error?.message || error);
|
||||
}
|
||||
}
|
||||
return stat;
|
||||
}
|
||||
|
||||
/**
|
||||
* 定时对账兜底:对所有**有 active 绑定**的分公司推一轮。
|
||||
* 未绑定分公司天然不在名单里(物理门禁)。
|
||||
*/
|
||||
export async function runReportPushReconcile(options?: { limitPerBranch?: number }): Promise<{
|
||||
branches: number;
|
||||
stored: number;
|
||||
ignored: number;
|
||||
failed: number;
|
||||
}> {
|
||||
const summary = { branches: 0, stored: 0, ignored: 0, failed: 0 };
|
||||
if (!isReportPushEnabled()) return summary;
|
||||
const branches = await pool.query<{ branch_code: string }>(
|
||||
`SELECT DISTINCT branch_code FROM public.main_supplier_bindings WHERE status = 'active' ORDER BY 1`
|
||||
);
|
||||
for (const row of branches.rows) {
|
||||
summary.branches += 1;
|
||||
const stat = await pushBranchReports({ branchCode: row.branch_code, limit: options?.limitPerBranch });
|
||||
summary.stored += stat.stored;
|
||||
summary.ignored += stat.ignored;
|
||||
summary.failed += stat.failed;
|
||||
}
|
||||
return summary;
|
||||
}
|
||||
|
||||
/**
|
||||
* 触发点入口(旁路异步,绝不阻塞调用方):分拣完成/发车、报告确认、定时兜底都调它。
|
||||
* 关闭开关 / 空分公司 / 未配置 ⇒ 立即返回(零出站)。
|
||||
*/
|
||||
export function triggerReportPush(branchCode: string | null | undefined): void {
|
||||
if (!isReportPushEnabled()) return;
|
||||
const code = String(branchCode || '').trim();
|
||||
if (!code) return;
|
||||
void pushBranchReports({ branchCode: code }).catch((error: any) => {
|
||||
console.warn('[report-push] 触发推送失败(已吞,不影响主流程):', error?.message || error);
|
||||
});
|
||||
}
|
||||
@@ -947,6 +947,11 @@ export async function confirmPickingComplete(input: {
|
||||
await tryAdvanceOrderToDelivery(orderCode);
|
||||
}
|
||||
|
||||
// 第九批「批次报告同步」触发点①:分拣完成 ⇒ 本次出库批次已确定,旁路异步推批次报告
|
||||
// (未绑定/非主系统下发的行在推送侧被物理拦住;开关默认关 ⇒ 零出站。见 20261011-批次报告推送主系统.md)
|
||||
const { triggerReportPush } = await import('./mainSystemReportPushService');
|
||||
triggerReportPush(input.ctx?.branchCode);
|
||||
|
||||
return { pickCode, alreadyCompleted: false, syncedItems: 0, hasDiff, outbound: false };
|
||||
} catch (error) {
|
||||
await client.query('ROLLBACK').catch(() => undefined);
|
||||
|
||||
@@ -480,6 +480,26 @@ async function runMainSystemImportReconcile() {
|
||||
*/
|
||||
let lastPriceQtyReconcileAt = 0;
|
||||
|
||||
/**
|
||||
* 第九批「批次报告同步」定时兜底(契约 §2.12.9 ⑤ 触发点③):
|
||||
* 对所有**有 active 绑定**的分公司补推未成功的批次报告(未绑定分公司天然不在名单里)。
|
||||
* 开关 `MAIN_SYSTEM_REPORT_ENABLED` 默认关 ⇒ 直接返回(零出站)。
|
||||
*/
|
||||
async function runReportPushReconcile() {
|
||||
try {
|
||||
const { runReportPushReconcile: run } = await import('./mainSystemReportPushService');
|
||||
const summary = await run({ limitPerBranch: 50 });
|
||||
if (summary.stored || summary.ignored || summary.failed) {
|
||||
console.log(
|
||||
`[scheduler] 批次报告推送对账:分公司 ${summary.branches} 个,登记成功 ${summary.stored}、` +
|
||||
`对方不认识(ignored) ${summary.ignored}、失败 ${summary.failed}`
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[scheduler] 批次报告推送对账失败:', error);
|
||||
}
|
||||
}
|
||||
|
||||
async function runPriceQtyRequestReconcile() {
|
||||
try {
|
||||
const { isEnabled, reconcileMainSystemPriceQtyRequests } = await import('./mainSystemPriceQtyRequest');
|
||||
@@ -614,6 +634,8 @@ export function startScheduledJobs() {
|
||||
void runMainSystemImportReconcile();
|
||||
// 跨系统改价/改量申请对账(webhook 漏推自愈):跟随 tick,内部限流到 10 分钟一次
|
||||
void runPriceQtyRequestReconcile();
|
||||
// 批次报告推送对账(第九批,触发点③;开关默认关 ⇒ 直接返回)
|
||||
void runReportPushReconcile();
|
||||
}, 15 * 60 * 1000);
|
||||
void withDistributedLock(BID_OPEN_LOCK_KEY, BID_OPEN_LOCK_TTL_SEC, () => runQueuedBidOpenTick());
|
||||
bidOpenTimer = setInterval(() => {
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
/**
|
||||
* 第九批:**主系统调用层**的报文守卫(契约 §2.12.9 ①②③)。
|
||||
*
|
||||
* 服务层已钉住"传什么参数",这里钉住**真正发出去的 HTTP 报文**:
|
||||
* · 登记 body = 蛇形字段,且**只有** `preparation_id` / `files` / `report_type` + 四个来源字段;
|
||||
* **绝不出现** `defer_coverage`(暂存态:既不覆盖也不展示)与派生字段(sku/order/branch/supplier/category/delivery);
|
||||
* · 上传是 multipart(字段名 `file`、`?path=` 是对象名),**用回执里的 `path`** 而不是我们传的名字;
|
||||
* · 回执映射:200 stored / 404 ignored / 401 token_expired / 5xx transient / 400 failed。
|
||||
*/
|
||||
const requestMainSystem = vi.hoisted(() => vi.fn());
|
||||
const getMainSystemToken = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock('../src/services/mainSystem/http', () => ({
|
||||
requestMainSystem: (...args: unknown[]) => requestMainSystem(...args),
|
||||
}));
|
||||
vi.mock('../src/services/mainSystem/token', () => ({
|
||||
getMainSystemToken: (...args: unknown[]) => getMainSystemToken(...args),
|
||||
}));
|
||||
|
||||
import {
|
||||
MAIN_SYSTEM_REPORT_MAX_BYTES,
|
||||
isUploadableReportFileName,
|
||||
registerBatchReportOnPreparation,
|
||||
uploadBatchReportFile,
|
||||
} from '../src/services/mainSystem/api/qualityReports';
|
||||
|
||||
beforeEach(() => {
|
||||
requestMainSystem.mockReset();
|
||||
getMainSystemToken.mockReset();
|
||||
getMainSystemToken.mockResolvedValue({ kind: 'ok', token: 'fake-token' });
|
||||
});
|
||||
|
||||
describe('文件类型/大小前置校验(桶白名单:pdf + 图片,≤10MB)', () => {
|
||||
it('pdf 与常见图片放行;docx/xlsx 拒绝', () => {
|
||||
for (const ok of ['a.pdf', 'b.JPG', 'c.jpeg', 'd.png', 'e.webp', 'f.gif']) {
|
||||
expect(isUploadableReportFileName(ok)).toBe(true);
|
||||
}
|
||||
for (const bad of ['报告.docx', 'a.xlsx', 'noext', 'a.pdf.exe']) {
|
||||
expect(isUploadableReportFileName(bad)).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it('非白名单类型 ⇒ failed 且**不发请求**', async () => {
|
||||
const out = await uploadBatchReportFile({ supplierCode: 'SUP1', fileName: 'a.docx', buffer: Buffer.from('x') });
|
||||
expect(out.kind).toBe('failed');
|
||||
expect(requestMainSystem).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('超过 10MB ⇒ failed 且**不发请求**', async () => {
|
||||
const out = await uploadBatchReportFile({
|
||||
supplierCode: 'SUP1',
|
||||
fileName: 'a.pdf',
|
||||
buffer: Buffer.alloc(MAIN_SYSTEM_REPORT_MAX_BYTES + 1),
|
||||
});
|
||||
expect(out.kind).toBe('failed');
|
||||
expect(requestMainSystem).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('① 上传文件', () => {
|
||||
it('走 multipart(formData.file)+ `?path=` 对象名,并**返回回执里的 path**', async () => {
|
||||
requestMainSystem.mockResolvedValue({ kind: 'ok', status: 200, data: {}, payload: { path: 'rnd-9f2.pdf' } });
|
||||
const out = await uploadBatchReportFile({ supplierCode: 'SUP1', fileName: 'jpg-20261008.pdf', buffer: Buffer.from('%PDF') });
|
||||
expect(out).toEqual({ kind: 'ok', path: 'rnd-9f2.pdf', signedUrl: undefined });
|
||||
|
||||
const options = requestMainSystem.mock.calls[0][0] as Record<string, any>;
|
||||
expect(options.endpoint).toBe('qualityReportUpload');
|
||||
expect(options.method).toBe('POST');
|
||||
expect(options.token).toBe('fake-token');
|
||||
expect(options.query).toEqual({ path: 'jpg-20261008.pdf' });
|
||||
expect(options.formData).toBeInstanceOf(FormData);
|
||||
expect(options.formData.get('file')).toBeTruthy();
|
||||
expect(options.body).toBeUndefined(); // multipart 与 JSON body 互斥
|
||||
});
|
||||
|
||||
it('上传成功但回执缺 path ⇒ failed(不能拿我们自己的名字去登记)', async () => {
|
||||
requestMainSystem.mockResolvedValue({ kind: 'ok', status: 200, data: {}, payload: {} });
|
||||
const out = await uploadBatchReportFile({ supplierCode: 'SUP1', fileName: 'a.pdf', buffer: Buffer.from('%PDF') });
|
||||
expect(out.kind).toBe('failed');
|
||||
});
|
||||
});
|
||||
|
||||
describe('② 登记报告:报文只含契约允许字段', () => {
|
||||
it('body 字段与契约逐一对应,且**不含** defer_coverage 与派生字段', async () => {
|
||||
requestMainSystem.mockResolvedValue({ kind: 'ok', status: 200, data: {}, payload: { data: { id: 'their-7' } } });
|
||||
const out = await registerBatchReportOnPreparation({
|
||||
supplierCode: 'SUP41472132',
|
||||
preparationId: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee',
|
||||
files: ['rnd-1.pdf', 'rnd-2.jpg'],
|
||||
reportType: 'batch',
|
||||
batchNo: 'STK202610107YRQEO',
|
||||
producedAt: '2026-10-08',
|
||||
testingOrg: 'XX检测中心',
|
||||
productNames: ['香菇', '平菇'],
|
||||
});
|
||||
expect(out).toEqual({ kind: 'stored', theirReportId: 'their-7', status: 200, payload: expect.anything() });
|
||||
|
||||
const body = (requestMainSystem.mock.calls[0][0] as Record<string, any>).body as Record<string, unknown>;
|
||||
expect(Object.keys(body).sort()).toEqual(
|
||||
['batch_no', 'files', 'preparation_id', 'produced_at', 'product_names', 'report_type', 'testing_org'].sort()
|
||||
);
|
||||
expect(body.files).toEqual(['rnd-1.pdf', 'rnd-2.jpg']);
|
||||
expect(body.product_names).toEqual(['香菇', '平菇']);
|
||||
expect(body.report_type).toBe('batch');
|
||||
expect(body.defer_coverage).toBeUndefined();
|
||||
for (const forbidden of ['sku_code', 'order_code', 'branch_code', 'supplier_code', 'category_code', 'delivery_date']) {
|
||||
expect(body[forbidden]).toBeUndefined();
|
||||
}
|
||||
});
|
||||
|
||||
it('batch_no 超长按 50 截断(对方 >50 直接 400)', async () => {
|
||||
requestMainSystem.mockResolvedValue({ kind: 'ok', status: 200, data: {}, payload: { data: { id: 'x' } } });
|
||||
await registerBatchReportOnPreparation({
|
||||
supplierCode: 'SUP1',
|
||||
preparationId: 'p',
|
||||
files: ['a.pdf'],
|
||||
reportType: 'batch',
|
||||
batchNo: 'B'.repeat(80),
|
||||
});
|
||||
const body = (requestMainSystem.mock.calls[0][0] as Record<string, any>).body as Record<string, unknown>;
|
||||
expect(String(body.batch_no)).toHaveLength(50);
|
||||
});
|
||||
|
||||
it('缺 preparation_id / files / report_type ⇒ failed(invalid_request),不发请求', async () => {
|
||||
for (const bad of [
|
||||
{ preparationId: '' },
|
||||
{ files: [] as string[] },
|
||||
{ reportType: '' },
|
||||
]) {
|
||||
const out = await registerBatchReportOnPreparation({
|
||||
supplierCode: 'SUP1',
|
||||
preparationId: 'p',
|
||||
files: ['a.pdf'],
|
||||
reportType: 'batch',
|
||||
...bad,
|
||||
});
|
||||
expect(out.kind).toBe('failed');
|
||||
}
|
||||
expect(requestMainSystem).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('③ 回执映射(§2.12.9 ③)', () => {
|
||||
const base = { supplierCode: 'SUP1', preparationId: 'p', files: ['a.pdf'], reportType: 'batch' };
|
||||
|
||||
it('404 not_found ⇒ ignored(终态,不重推)', async () => {
|
||||
requestMainSystem.mockResolvedValue({
|
||||
kind: 'rejected', status: 404, reason: 'not_found', payload: { error: 'not_found' },
|
||||
});
|
||||
await expect(registerBatchReportOnPreparation(base)).resolves.toMatchObject({ kind: 'ignored', status: 404 });
|
||||
});
|
||||
|
||||
it('400 invalid_report_type ⇒ failed(带可判别 error)', async () => {
|
||||
requestMainSystem.mockResolvedValue({
|
||||
kind: 'rejected', status: 400, reason: 'invalid_report_type', payload: { error: 'invalid_report_type' },
|
||||
});
|
||||
await expect(registerBatchReportOnPreparation(base)).resolves.toMatchObject({
|
||||
kind: 'failed', status: 400, error: 'invalid_report_type',
|
||||
});
|
||||
});
|
||||
|
||||
it('401 ⇒ token_expired(换 token 再试)', async () => {
|
||||
requestMainSystem.mockResolvedValue({
|
||||
kind: 'rejected', status: 401, reason: 'invalid_token', payload: { error: 'invalid_token' },
|
||||
});
|
||||
await expect(registerBatchReportOnPreparation(base)).resolves.toMatchObject({ kind: 'token_expired' });
|
||||
});
|
||||
|
||||
it('503 ⇒ transient(退避重试)', async () => {
|
||||
requestMainSystem.mockResolvedValue({
|
||||
kind: 'unavailable', status: 503, reason: 'HTTP 503', payload: null,
|
||||
});
|
||||
await expect(registerBatchReportOnPreparation(base)).resolves.toMatchObject({ kind: 'transient', status: 503 });
|
||||
});
|
||||
|
||||
it('200 ⇒ stored 并带回对方 report_id', async () => {
|
||||
requestMainSystem.mockResolvedValue({
|
||||
kind: 'ok', status: 200, data: {}, payload: { data: { id: 'their-9', status: 'active' } },
|
||||
});
|
||||
await expect(registerBatchReportOnPreparation(base)).resolves.toMatchObject({
|
||||
kind: 'stored', theirReportId: 'their-9',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,231 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
/**
|
||||
* 批次报告推送(第九批)—— 契约守卫。
|
||||
*
|
||||
* 权威:`docs/给主系统AI的对接改造清单.md` §2.12.9(最终调用契约)/ §4.5.17(逐条回执)。
|
||||
* 这里钉住五类**做反就要返工**的行为:
|
||||
* ① 默认关 ⇒ 零出站;未绑定 / 非主系统下发的行 ⇒ 零出站(三重门禁);
|
||||
* ② 幂等:文件集指纹未变 + 已终态 ⇒ **不重推**;指纹变了(事后补充)⇒ **推完整文件集**;
|
||||
* ③ 请求体只含契约允许的字段(**绝不带** defer_coverage / sku_code / order_code / branch_code / supplier_code);
|
||||
* ④ 回执映射:200 stored / 404 ignored(终态) / 400 failed(终态) / 5xx transient(重试);
|
||||
* ⑤ 上传前置校验:仅 pdf+图片、单文件 ≤10MB。
|
||||
*/
|
||||
const query = vi.hoisted(() => vi.fn());
|
||||
const getObject = vi.hoisted(() => vi.fn());
|
||||
const upload = vi.hoisted(() => vi.fn());
|
||||
const register = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock('../src/db', () => ({
|
||||
pool: { query: (...args: unknown[]) => query(...args) },
|
||||
getRawPoolQuery: () => query,
|
||||
}));
|
||||
vi.mock('../src/services/storageProvider', () => ({
|
||||
getStorageProvider: () => ({ getObject: (...args: unknown[]) => getObject(...args) }),
|
||||
}));
|
||||
vi.mock('../src/services/mainSystem/api/qualityReports', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../src/services/mainSystem/api/qualityReports')>();
|
||||
return {
|
||||
...actual,
|
||||
uploadBatchReportFile: (...args: unknown[]) => upload(...args),
|
||||
registerBatchReportOnPreparation: (...args: unknown[]) => register(...args),
|
||||
};
|
||||
});
|
||||
|
||||
import {
|
||||
collectReportPushCandidates,
|
||||
filesFingerprint,
|
||||
isReportPushEnabled,
|
||||
pushBranchReports,
|
||||
pushReportCandidate,
|
||||
runReportPushReconcile,
|
||||
triggerReportPush,
|
||||
type ReportPushCandidate,
|
||||
} from '../src/services/mainSystemReportPushService';
|
||||
|
||||
function candidate(overrides: Partial<ReportPushCandidate> = {}): ReportPushCandidate {
|
||||
return {
|
||||
branch_code: 'BR003',
|
||||
main_branch_code: 'BR002',
|
||||
main_supplier_code: 'SUP41472132',
|
||||
prep_id: '11111111-1111-1111-1111-111111111111',
|
||||
main_order_code: 'ORD_WEB_20261010_BR002_0001',
|
||||
our_order_code: 'ORD_API_20261010_BR003_0001',
|
||||
our_order_item_id: '22222222-2222-2222-2222-222222222222',
|
||||
report_type: 'batch',
|
||||
our_file_paths: ['batch/a.pdf'],
|
||||
report_ids: ['33333333-3333-3333-3333-333333333333'],
|
||||
batch_no: 'STK202610107YRQEO',
|
||||
produced_at: '2026-10-08',
|
||||
testing_org: 'XX检测中心',
|
||||
product_names: ['香菇', '平菇'],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
/** 台账 INSERT ... RETURNING 的应答 */
|
||||
function ledgerRow(patch: Partial<{ file_fingerprint: string; status: string; our_file_paths: string[]; their_file_paths: string[] }> = {}) {
|
||||
return {
|
||||
id: '99',
|
||||
file_fingerprint: patch.file_fingerprint ?? filesFingerprint(['batch/a.pdf']),
|
||||
status: patch.status ?? 'pending',
|
||||
our_file_paths: patch.our_file_paths ?? [],
|
||||
their_file_paths: patch.their_file_paths ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
query.mockReset();
|
||||
getObject.mockReset();
|
||||
upload.mockReset();
|
||||
register.mockReset();
|
||||
delete process.env.MAIN_SYSTEM_REPORT_ENABLED;
|
||||
query.mockResolvedValue({ rows: [ledgerRow()], rowCount: 1 });
|
||||
getObject.mockResolvedValue({ buffer: Buffer.from('%PDF-1.4 test') });
|
||||
});
|
||||
|
||||
describe('门禁:默认关 / 未绑定 ⇒ 零出站', () => {
|
||||
it('开关未打开时 pushBranchReports 直接返回且**不查库**', async () => {
|
||||
const stat = await pushBranchReports({ branchCode: 'BR003' });
|
||||
expect(stat).toEqual({ candidates: 0, stored: 0, ignored: 0, failed: 0, skipped: 0, transient: 0 });
|
||||
expect(query).not.toHaveBeenCalled();
|
||||
expect(upload).not.toHaveBeenCalled();
|
||||
expect(register).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('triggerReportPush(触发点入口)在关闭时同样零出站', () => {
|
||||
triggerReportPush('BR003');
|
||||
expect(query).not.toHaveBeenCalled();
|
||||
expect(isReportPushEnabled()).toBe(false);
|
||||
});
|
||||
|
||||
it('候选采集 SQL 把"绑定 + 主系统下发的行"写进 WHERE/JOIN(未绑定天然查不出来)', async () => {
|
||||
process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true';
|
||||
query.mockResolvedValueOnce({ rows: [] });
|
||||
await collectReportPushCandidates({ branchCode: 'BR003' });
|
||||
const sql = String(query.mock.calls[0]?.[0] || '');
|
||||
expect(sql).toContain("b.status = 'active'"); // ① 必须有 active 绑定
|
||||
expect(sql).toContain('l.prep_id IS NOT NULL'); // ② 必须是主系统下发的行(有 prep_id 对照)
|
||||
expect(sql).toContain('r.status = 30'); // ③ 报告必须已人工确认
|
||||
expect(sql).toContain('outbound_batches'); // 只用分拣选定的批次
|
||||
});
|
||||
});
|
||||
|
||||
describe('幂等:指纹未变不重推,变了推完整集', () => {
|
||||
it('指纹稳定:与顺序无关、去重', () => {
|
||||
expect(filesFingerprint(['b.pdf', 'a.pdf', 'a.pdf'])).toBe(filesFingerprint(['a.pdf', 'b.pdf']));
|
||||
});
|
||||
|
||||
it('已 stored 且指纹未变 ⇒ 不调用任何出站接口', async () => {
|
||||
process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true';
|
||||
query.mockResolvedValueOnce({
|
||||
rows: [ledgerRow({ status: 'stored', our_file_paths: ['batch/a.pdf'], their_file_paths: ['rnd-1.pdf'] })],
|
||||
rowCount: 1,
|
||||
});
|
||||
const result = await pushReportCandidate(candidate());
|
||||
expect(result.status).toBe('skipped');
|
||||
expect(upload).not.toHaveBeenCalled();
|
||||
expect(register).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('文件集变化(事后补充)⇒ 重推**完整文件集**(旧文件一起传)', async () => {
|
||||
process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true';
|
||||
const files = ['batch/a.pdf', 'batch/b.pdf'];
|
||||
// 台账旧指纹只有 a.pdf ⇒ 与本次指纹不同 ⇒ 必须重推
|
||||
query.mockResolvedValueOnce({
|
||||
rows: [ledgerRow({ file_fingerprint: filesFingerprint(['batch/a.pdf']), status: 'stored', our_file_paths: ['batch/a.pdf'], their_file_paths: ['rnd-a.pdf'] })],
|
||||
rowCount: 1,
|
||||
});
|
||||
upload.mockResolvedValue({ kind: 'ok', path: 'rnd-new.pdf' });
|
||||
register.mockResolvedValue({ kind: 'stored', theirReportId: 'their-1', status: 200, payload: {} });
|
||||
|
||||
const result = await pushReportCandidate(candidate({ our_file_paths: files }));
|
||||
expect(result.status).toBe('stored');
|
||||
// a.pdf 命中缓存不重复上传;b.pdf 新上传 ⇒ 登记时必须带**完整集**
|
||||
expect(upload).toHaveBeenCalledTimes(1);
|
||||
const registered = register.mock.calls[0][0] as { files: string[] };
|
||||
expect(registered.files).toEqual(['rnd-a.pdf', 'rnd-new.pdf']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('契约字段:只传允许的,绝不带 defer_coverage 与派生字段', () => {
|
||||
it('传给登记 API 的参数只含契约允许项(派生字段一律不带)', async () => {
|
||||
process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true';
|
||||
upload.mockResolvedValue({ kind: 'ok', path: 'rnd-1.pdf' });
|
||||
register.mockResolvedValue({ kind: 'stored', theirReportId: 'their-1', status: 200, payload: {} });
|
||||
await pushReportCandidate(candidate());
|
||||
const input = register.mock.calls[0][0] as Record<string, unknown>;
|
||||
expect(Object.keys(input).sort()).toEqual(
|
||||
['batchNo', 'files', 'preparationId', 'producedAt', 'productNames', 'reportType', 'supplierCode', 'testingOrg'].sort()
|
||||
);
|
||||
expect(input.reportType).toBe('batch');
|
||||
expect(input.files).toEqual(['rnd-1.pdf']);
|
||||
// 契约 §2.12.9 ④-2/④-4:绝不出现这些键(含 defer_coverage)
|
||||
for (const forbidden of ['deferCoverage', 'defer_coverage', 'skuCode', 'orderCode', 'branchCode', 'categoryCode', 'deliveryDate']) {
|
||||
expect(input[forbidden]).toBeUndefined();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('回执映射(§2.12.9 ③)', () => {
|
||||
beforeEach(() => {
|
||||
process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true';
|
||||
upload.mockResolvedValue({ kind: 'ok', path: 'rnd-1.pdf' });
|
||||
});
|
||||
|
||||
it('404 ⇒ ignored(终态,不再重推)', async () => {
|
||||
register.mockResolvedValue({ kind: 'ignored', status: 404, reason: 'not_found' });
|
||||
const result = await pushReportCandidate(candidate());
|
||||
expect(result.status).toBe('ignored');
|
||||
const update = query.mock.calls.find((c) => String(c[0]).includes('UPDATE public.main_system_report_pushes'));
|
||||
expect(String(update?.[1]?.[1])).toBe('ignored');
|
||||
});
|
||||
|
||||
it('400 invalid_report_type ⇒ failed(终态 + 告警)', async () => {
|
||||
register.mockResolvedValue({ kind: 'failed', status: 400, reason: '类型不支持', error: 'invalid_report_type' });
|
||||
const result = await pushReportCandidate(candidate());
|
||||
expect(result.status).toBe('failed');
|
||||
});
|
||||
|
||||
it('5xx ⇒ transient(进重试:status 回到 pending + next_retry_at)', async () => {
|
||||
register.mockResolvedValue({ kind: 'transient', status: 503, reason: 'main system down' });
|
||||
const result = await pushReportCandidate(candidate());
|
||||
expect(result.status).toBe('transient');
|
||||
const update = query.mock.calls.find((c) => String(c[0]).includes('UPDATE public.main_system_report_pushes'));
|
||||
expect(String(update?.[1]?.[1])).toBe('pending');
|
||||
expect(update?.[1]?.[4]).toBe(true); // retry=true
|
||||
});
|
||||
|
||||
it('401 ⇒ 也按重试处理(换 token 再试)', async () => {
|
||||
register.mockResolvedValue({ kind: 'token_expired', reason: 'invalid_token' });
|
||||
const result = await pushReportCandidate(candidate());
|
||||
expect(result.status).toBe('transient');
|
||||
});
|
||||
});
|
||||
|
||||
describe('上传前置校验(§2.12.9 ①)', () => {
|
||||
beforeEach(() => {
|
||||
process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true';
|
||||
});
|
||||
|
||||
it('非 pdf/图片 ⇒ failed 且**不上传**', async () => {
|
||||
const result = await pushReportCandidate(candidate({ our_file_paths: ['batch/报告.docx'] }));
|
||||
expect(result.status).toBe('failed');
|
||||
expect(upload).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('我方对象缺失 ⇒ failed(不静默丢)', async () => {
|
||||
getObject.mockResolvedValue(null);
|
||||
const result = await pushReportCandidate(candidate());
|
||||
expect(result.status).toBe('failed');
|
||||
expect(upload).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('定时兜底', () => {
|
||||
it('开关关闭 ⇒ 不查分公司、零出站', async () => {
|
||||
const summary = await runReportPushReconcile();
|
||||
expect(summary).toEqual({ branches: 0, stored: 0, ignored: 0, failed: 0 });
|
||||
expect(query).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user