From e1e3bb638fdf44a973625eec7b2c146609ca1b7b Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 4 Nov 2026 20:53:35 +0800 Subject: [PATCH] =?UTF-8?q?feat(order):=20=E6=8B=89=E5=8D=95=E4=BB=BB?= =?UTF-8?q?=E5=8A=A1=E3=80=81=E5=A4=96=E9=83=A8=E5=8F=91=E8=B4=A7=E5=90=8C?= =?UTF-8?q?=E6=AD=A5=E4=B8=8E=E5=8F=96=E5=8F=B7=E8=AE=B0=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 拉单任务:新增 order_sync_tasks 异步任务池,按店铺逐店拉取外部打单平台订单,前端轮询进度 - 外部发货同步:配送后把发货结果同步回店管家,提供数量统计与批量重试(externalSendSync) - 取号:新增 waybill_fetch_records 记录取号过程,外部快递接口补充菜鸟授权信息 - 补齐相关迁移、订单页同步入口/状态展示,并新增对接说明文档 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- WMS-OMS-取号对接.md | 896 +++++++++++++++++ backend/app/contract/index.js | 85 ++ .../app/controller/externalPrintAccount.js | 5 +- backend/app/controller/externalSendSync.js | 61 ++ backend/app/controller/openapi.js | 22 +- backend/app/controller/orderStatus.js | 7 +- backend/app/controller/orderSyncTask.js | 101 ++ backend/app/lib/openapiIdempotency.js | 28 +- backend/app/lib/openapiMethods.js | 4 +- backend/app/lib/orderCallback.js | 4 + backend/app/lib/orderFields.js | 26 + backend/app/lib/printPlatform/dgj.js | 947 +++++++++++++++++- backend/app/lib/waybillGet.js | 334 +++++- backend/app/lib/wms/qimenClient.js | 19 +- .../model/externalPrintExpressInterface.js | 1 + backend/app/model/orderSyncTask.js | 49 + backend/app/model/waybillFetchRecord.js | 41 + backend/app/router.js | 11 + .../app/schedule/externalSendSyncWorker.js | 35 + .../app/schedule/fetchExternalShopOrders.js | 6 +- backend/app/schedule/orderSyncWorker.js | 34 + .../service/externalPrintExpressInterface.js | 1 + backend/app/service/externalPrintOrder.js | 261 ++++- backend/app/service/externalSendSync.js | 349 +++++++ backend/app/service/orderItemResolve.js | 13 +- backend/app/service/orderStatus.js | 54 + backend/app/service/orderSyncTask.js | 463 +++++++++ backend/app/service/orderWms.js | 57 +- .../20261104030000-create-order-sync-tasks.js | 80 ++ ...1104040000-create-waybill-fetch-records.js | 129 +++ ...dd-external-send-fields-to-order-status.js | 69 ++ ...104050100-backfill-external-send-status.js | 20 + ...niao-auth-info-id-to-express-interfaces.js | 36 + backend/scripts/dgj-waybill-probe.js | 320 ++++++ backend/scripts/rebuild-order-items.js | 54 +- frontend/src/api/externalSendSync.ts | 49 + frontend/src/api/orderStatus.ts | 7 + frontend/src/api/orderSyncTask.ts | 98 ++ frontend/src/views/Order/OrderSyncDialog.vue | 352 +++++++ frontend/src/views/Order/StatusPanel.vue | 145 ++- 店管家取号-旧系统提取.md | 419 ++++++++ 41 files changed, 5580 insertions(+), 112 deletions(-) create mode 100644 WMS-OMS-取号对接.md create mode 100644 backend/app/controller/externalSendSync.js create mode 100644 backend/app/controller/orderSyncTask.js create mode 100644 backend/app/model/orderSyncTask.js create mode 100644 backend/app/model/waybillFetchRecord.js create mode 100644 backend/app/schedule/externalSendSyncWorker.js create mode 100644 backend/app/schedule/orderSyncWorker.js create mode 100644 backend/app/service/externalSendSync.js create mode 100644 backend/app/service/orderSyncTask.js create mode 100644 backend/database/migrations/20261104030000-create-order-sync-tasks.js create mode 100644 backend/database/migrations/20261104040000-create-waybill-fetch-records.js create mode 100644 backend/database/migrations/20261104050000-add-external-send-fields-to-order-status.js create mode 100644 backend/database/migrations/20261104050100-backfill-external-send-status.js create mode 100644 backend/database/migrations/20261104060000-add-cai-niao-auth-info-id-to-express-interfaces.js create mode 100644 backend/scripts/dgj-waybill-probe.js create mode 100644 frontend/src/api/externalSendSync.ts create mode 100644 frontend/src/api/orderSyncTask.ts create mode 100644 frontend/src/views/Order/OrderSyncDialog.vue create mode 100644 店管家取号-旧系统提取.md diff --git a/WMS-OMS-取号对接.md b/WMS-OMS-取号对接.md new file mode 100644 index 0000000..ed08844 --- /dev/null +++ b/WMS-OMS-取号对接.md @@ -0,0 +1,896 @@ +# OMS ↔ WMS 取号联调说明(现状 / 契约 / 待办) + +> 文档用途:作为 OMS 侧与 WMS 侧 agent 对接取号链路的沟通基线。 +> 核对时间:2026-11-04,OMS 仓库 `D:\oms`(后端 Egg.js + Sequelize + MySQL,前端 Vue3),WMS 仓库 `D:\wms`(Egg.js)。 +> 文中数据快照来自**本地开发库**,生产以实际查询为准(文末附核对 SQL)。 + +# 规则说明:每轮工作内容以/oms或wms开头oms或wms/结尾,完成当前内容后汇报写入文档结尾,以记录或保持沟通 + +/oms +--- + +## 1. 结论速览(TL;DR) + +| 能力 | OMS 侧 | WMS 侧 | 说明 | +|---|---|---|---| +| 订单推送 `deliveryorder.create` + `need_oms_waybill` | ✅ 已完成 | ✅ 已识别 | OMS 按平台配置自动下发,WMS 已能把这类订单分流到 `waiting_oms` | +| 取号入站方法 `deliveryorder.getwaybill` | ✅ 已完成 | ❌ 未接通 | OMS 可批量回取号并逐单返回结果 | +| WMS 侧「oms 取号平台」实现 | — | ❌ 缺失 | `express_platform.js` 只有 `polyapi / cainiao / pdd` | +| WMS 侧消费 `waiting_oms` | — | ❌ 缺失 | 目前 `waiting_oms` 是终态,不会被再次处理 | +| 店管家(dgj)真实取号调用 | ✅ 已实现(默认开启) | — | `dgj.fetchWaybillNo()` 已按旧系统流程实现,平台无运单号时会真实取号(消耗面单);可用 `DGJ_WAYBILL_ENABLE=0` 临时关闭 | + +> **当前为真实校验模式**:`deliveryorder.getwaybill` 会真实回读订单(单号/主体/仓库/状态/平台/店铺/打单账号/平台配置/编码绑定), +> 按「账号 + 平台 + 编码」定位快递接口;**取不到接口时直接返回绑定入口与操作步骤**(详见 §4.6)。 +> 店管家真实取号已按旧系统流程实现(见 `店管家取号-旧系统提取.md`):回读平台订单行 → 已发货拦截 → +> 模板校验 → `ExpressPrint` 取号并返回面单打印数据。**每次调用都会真实向平台取号(不判断平台已有运单号)**, +> 是否算重复调用只由幂等表按 `request_id` 决定;需要只读联调时设 `DGJ_WAYBILL_ENABLE=0` 关闭。 +**当前风险**:平台配置 `external_print_platforms.fetch_waybill_no` 对 dgj 已置为 `1`,所以新推送的外部打单订单会带 `need_oms_waybill=1`。但 WMS 端还没人调用 OMS 取号、OMS 端 dgj 取号也没实现,**这些订单推送后会在 WMS 停在 `waiting_oms` 且拿不到运单号**。 + +--- + +## 2. 链路总览 + +``` + ① 推送(已有) +OMS ─────────────────────────────► WMS POST {warehouse_apis.base_url} + deliveryorder.create ?method=deliveryorder.create&app_key=...×tamp=...&sign=... + 根节点 need_oms_waybill=0|1 + + ② 回取号(本次要打通,WMS 发起) +WMS ─────────────────────────────► OMS POST {api_app.callback_url} → OMS /openapi + deliveryorder.getwaybill ?method=deliveryorder.getwaybill&app_key=...×tamp=...&sign=...&request_id=... + body: { orders: [{ deliveryOrderCode, expressCode }] } + + ③ 发货确认(已有) +WMS ─────────────────────────────► OMS deliveryorder.confirm +``` + +- ②③ 都由 WMS 主动调 OMS 的同一个入口 `/openapi`,用**同一套 app_key/app_secret 与签名算法**。 +- OMS 侧按 `app_key` 定位「主体 + 仓库」(`warehouse_apis`),因此 WMS 用哪个 app_key 调,就只会操作该主体该仓库的单据。 + +--- + +## 3. 鉴权与签名(两侧完全一致,务必对齐) + +### 3.1 请求形态 + +``` +POST {OMS_BASE}/openapi?method=deliveryorder.getwaybill&v=1.0×tamp=1750000000&app_key=xxx&sign=abc&request_id=uuid +Content-Type: application/json + +{ "orders": [ { "deliveryOrderCode": "XK202611040001", "expressCode": "ZTO" } ] } +``` + +- 系统参数一律走 **query**,业务参数走 **JSON body**。 +- `timestamp` 为 **秒级** 时间戳,OMS 校验窗口 **±600 秒**(毫秒时间戳会自动换算)。 +- 未传 `request_id` 就不启用幂等(不建议)。 + +### 3.2 签名算法 + +``` +bodySign = md5( stableStringify(body) ) # 小写 hex +canonicalQuery = query 的 key 升序拼接 "k=v&k2=v2",忽略 sign/signature 与 undefined 值 +sign = md5( canonicalQuery + app_secret + bodySign ) # 小写 hex +``` + +`stableStringify`:对象 key 递归升序;数组保序;`undefined` 视为空串。 + +WMS 侧已有实现可直接复用:`D:\wms\app\lib\api_sign.js`(`signRequest`)、`app/service/openapi/callback.js#signCallback`。 +OMS 侧实现:`D:\oms\backend\app\lib\wms\sign.js`。 + +> ⚠️ body 参与签名的是**解析后的对象**,不是原始 JSON 字符串;两边都必须用稳定序列化,否则 query 顺序/空格差异会导致验签失败。 + +### 3.3 app_key 两侧对应关系 + +| 方向 | 调用方取什么 | 被调方校验什么 | +|---|---|---| +| OMS → WMS | OMS `warehouse_apis.app_key / app_secret` | WMS `api_app.self_app_key / self_app_secret` | +| WMS → OMS | WMS `api_app.self_app_key / self_app_secret` + `api_app.callback_url` | OMS `warehouse_apis.app_key / app_secret`(且 `status=1`) | + +**结论:同一条 `api_app` 记录同时承担两个方向**,只需保证: + +1. WMS `api_app` 的 `self_app_key / self_app_secret` = OMS 某条 `warehouse_apis` 的 `app_key / app_secret`; +2. WMS `api_app.callback_url` 指向 **OMS 的 `/openapi`**(例:`https://api.example.com/openapi`,不要带 query); +3. OMS 该条 `warehouse_apis.status = 1`,`principal_id / warehouse_id` 指向要操作的仓库。 + +> OMS 的仓库接口配置入口:前端「仓库 → 接口配置」(`frontend/src/views/ExternalApi/Index.vue`,表 `warehouse_apis`)。 + +### 3.4 响应结构(奇门风格) + +```json +// 成功 +{ "flag": "success", "code": 1, "message": "ok", "data": { }, "timestamp": 1750000000 } +// 失败 +{ "flag": "failure", "code": 400, "message": "参数缺失或错误: sign", "data": null, "timestamp": 1750000000 } +``` + +| HTTP / code | 场景 | +|---|---| +| 200 / 1 | 业务处理成功(**批量逐单失败也返回 200/1**,逐单结果在 `data.results`) | +| 400 | 参数缺失、时间戳过期、签名错误、`request_id` 报文不一致 | +| 401 | `app_key` 不存在/被禁用/未配置密钥 | +| 409 | 同一 `request_id` 正在处理中(调用方稍后重试) | +| 500 | 服务端异常 | + +--- + +## 4. 接口契约:`deliveryorder.getwaybill` + +### 4.1 请求 + +支持以下任一种写法(会兼容 `{request:{...}}` / `{data:{...}}` 包装): + +```json +// 推荐 +{ "orders": [ { "deliveryOrderCode": "XK202611040001", "expressCode": "ZTO" } ] } +// 也支持 +{ "deliveryOrders": { "deliveryOrder": [ ] } } +{ "list": [ ] } +{ "request": { "orders": [ ] } } +``` + +字段: + +| 字段 | 必填 | 说明 | +|---|---|---| +| `deliveryOrderCode` | ✅ | **OMS 订单号**(= 当初 `deliveryorder.create` 里的 `deliveryOrderCode`)。也兼容 `outBizCode` / `orderCode`,以及放在 `deliveryOrder` 对象内 | +| `expressCode` | ✅ | 本次要取的**快递编码**。也兼容 `express_code` / `logisticsCode` / `logistics_code` / `express.code` | +| `packageIndex` | ❌ | **包裹/子单序号(0 基)**,仅用于日志留痕。也兼容 `package_index` / `packageNo` / `package_no` / `waybillIndex`,以及 WMS 原生的 `businessKey` / `business_key`(1 基,自动转 0 基)。**每次取号都会分配一个新号**(店管家「新单号打印」口径),所以 WMS 按包裹各调一次即可,序号不需要下发给平台 | + +约束: + +- **单次最多 100 单**,超限整批失败:`单次最多取号 100 单`。 +- 快递编码**只以报文为准**,OMS 不读取订单上已设置的 `logistics_code`。 +- OMS 内部并发 4 逐单调用平台,返回结果顺序与请求一致。 +- **每单都会真实向打单平台取号,不判断平台订单上是否已有运单号**(店管家 `LastWaybillCode` 只用于事后对比是否换号)。 + 也就是说:**重复调用与否只由幂等表(`request_id`)决定**——清掉幂等记录或换 `request_id` 就会再取一次新号,并消耗一张面单。 + +### 4.2 响应 + +```json +{ + "flag": "success", + "code": 1, + "message": "ok", + "data": { + "total": 2, + "success": 1, + "failed": 1, + "results": [ + { + "delivery_order_code": "XK202611040001", + "success": true, + "message": "ok", + "waybill_source": "express_print", + "express_code": "ZTO", + "platform_code": "TB", + "waybill_code": "78812345678901", + "waybill_codes": ["78812345678901"], + "package_index": 0, + "cai_niao_auth_info_id": 364375, + "printinfo": "eyJQYXBlclNpemUiOi...", + "signature": "MEQCIB..." + }, + { + "delivery_order_code": "XK202611040002", + "success": false, + "message": "平台TB(淘宝)快递YTO(圆通速递)在账号15197817068下未绑定到快递接口,请到 OMS 店铺管理→外部打单平台→快递接口 查看绑定对应的快递接口" + } + ] + }, + "timestamp": 1750000000 +} +``` + +逐单结果字段: + +| 字段 | 出现条件 | 说明 | +|---|---|---| +| `delivery_order_code` | 始终 | 回显单号(取不到单号时为空串) | +| `success` | 始终 | 是否取号成功 | +| `message` | 始终 | `ok` 或失败原因(见 4.4);若平台返回的号码与订单行上原有的 `LastWaybillCode` 相同,会提示「本次调用平台取号,但平台仍返回原运单号 X」 | +| `waybill_source` | 成功 | 现阶段固定为 `express_print`(本次向打单平台取号,不再复用平台已有运单号) | +| `express_code` | 成功 | 回显本次快递编码 | +| `platform_code` | 成功 | 订单来源平台(OMS 预设编码,如 `TB`/`PDD`/`DYXD`) | +| `waybill_code` | 成功 | 主运单号 | +| `waybill_codes` | 成功 | 全部运单号(当前每次取号只对应 1 个包裹,恒为单元素) | +| `package_index` | 成功 | 本次取号对应的包裹序号(0 基),回显便于核对「这个号是哪个包裹的」 | +| `cai_niao_auth_info_id` | 成功 | **菜鸟授权网点ID**(模板绑定的 `CaiNiaoAuthInfoId`,如视频号 `6890457`、淘宝 `364375/393235`);同平台不同授权网点取值不同,WMS 需要按网点归集/对账时用它,取不到为 `null` | +| `printinfo` | 成功 | **面单打印数据**,打单平台原样返回:店管家取 `Data.PrintDataList.task.documents[].printInfo`(base64 的 URL-encoded JSON)。WMS 落 `order_express.printinfo`,打印时**原样**塞进 `task.printInfo`,不要解码 | +| `signature` | 成功 | 面单签名,取 `documents[].contents[0].signature`;视频号自定义模板平台不返回 `contents`,此时为空串 | +| `encryptprintinfo` | 成功 | 加密打印数据,取 `contents[0].encryptedData`(需要加密打印的平台才有值,店管家当前为空串) | +| `ver` | 成功 | 打印数据版本,取 `contents[0].ver`(无则为空串) | + +> **取号结果不回写 OMS 订单表**(现阶段取号与订单表不做关联),运单号与打印数据只在响应里返回,由 WMS 自行落单。 +> **WMS 仍需落自己的 `order_express`**(`waybill_code` + `printinfo` + `signature` + `encryptprintinfo` + `ver`)**/ 队列状态**,不要依赖 OMS 的库。 +> 每次取号的平台原始返回都会写进 OMS 的 `waybill_fetch_records`(见 §4.7),出问题可直接查表对账,不必再让 WMS 重放报文。 +> +> **同一包裹重复取号会拿到新号**:店管家「新单号打印」口径是每次分配一个新号(`WaybillCodePid` 第二段自增), +> 所以重试必须复用同一个 `request_id`,否则会多耗一张面单。包裹序号由 OMS 从 `deliveryOrderCode` 尾部 `_N` 推导 +> 或由报文 `packageIndex` / `businessKey` 指定,仅用于留痕。 + +### 4.3 幂等(请求级去重,只回放成功结果) + +`request_id` 来源优先级:`query.request_id` → `query.requestId` → Header `X-Request-Id` → `body.request_id` → `body.requestId` → `body.request.request_id`(最长 100 字符)。 + +唯一键:`(app_key, method, request_id)`。 + +| 场景 | OMS 行为 | +|---|---| +| 首次请求 | 正常处理;**成功则保存完整响应** | +| 已完成且成功 + 相同报文 | **直接回放**当时的完整响应(含逐单结果),不再调平台 | +| 已完成但失败 / 批量中**任一单失败** | **不保存、释放该 request_id**;下次同 `request_id` 会**重新执行** | +| 相同 `request_id` + 报文不同 | `400`:`request_id 已被使用且报文不一致,请更换 request_id 后重试` | +| 相同 `request_id` + 仍在处理 | `409`:`相同 request_id 的请求正在处理中,请稍后重试` | +| 处理中超过 30 分钟(进程异常退出) | 允许接管重跑 | +| 记录保留 | 7 天(每日 02:00 清理,`OPENAPI_IDEMPOTENCY_KEEP_DAYS` 可调) | + +**语义要点:请求幂等 ≠ 取号幂等** + +- 请求幂等(本表):只保证「同一批成功的结果不重复执行」;失败结果**允许用同一 `request_id` 重试**,不会被锁死。 +- **取号不与订单表关联**:不读也不写订单上的 `express_code`,重复调用会再次向平台取号(需重测时无需清理订单数据)。 +- 因此 WMS 可以放心用**稳定的 `request_id`** 做自动重试:先成功的单不会重复取号,之前失败的单会被重新处理。 +- **重测取号时要清这张表**(成功结果会回放):`DELETE FROM openapi_request_idempotency WHERE method='deliveryorder.getwaybill'`,或换个 `request_id`。**订单表已不参与幂等,无需清理 `express_code`。** +- 清表后就会真正向平台再取一次号(会消耗面单);取号记录表 `waybill_fetch_records` 里能看到每次的 `waybill_source=express_print` 与平台返回。 +- ⚠️ 反过来要注意:批量里只要有**一单失败**,整批的 `request_id` 就不会被锁。用同一 `request_id` 重试会**整批重跑**,已成功的单会再取一次号(多消耗面单)。生产上建议按「单」或小批提交,减少重复取号。 + +### 4.4 逐单失败原因全表(OMS 侧) + +| message | 触发条件 | WMS 建议处理 | +|---|---|---| +| `缺少发货单号(deliveryOrderCode / outBizCode)` | 报文没有单号 | 修报文,不重试 | +| `缺少快递编码(expressCode)` | 报文没有编码 | 修报文,不重试 | +| `未找到发货单:{code}` | OMS 查不到该单(或不属于该主体) | 不重试,人工核查 | +| `单据 {code} 不属于当前 app_key 对应的仓库` | 仓库不匹配 | 不重试,检查 app_key | +| `订单已取消,取号失败` | 订单状态 `canceled` | 不重试,队列置失败 | +| `订单已作废,取号失败` | `void` | 不重试 | +| `订单已归档,取号失败` | `history` | 不重试 | +| `订单已配送,取号失败` | 订单状态已是 `delivery` | 不重试 | +| `订单已完成,取号失败` | 老模型 `status=4` | 不重试 | +| `订单缺少来源平台,无法匹配快递接口` | 订单没有 `source_platform_code` | 不重试 | +| `订单未关联店铺,无法确定打单账号` | 订单无 `shop_id` | 不重试 | +| `订单未关联外部打单账号,无法取号:…` | 店铺不是 `type=2`(外部打单商家)或无 `external_print_account_id` | 检查店铺类型/账号同步 | +| `外部打单账号或平台配置不存在:…` | 账号/平台被删或跨主体 | 检查账号与平台配置 | +| `平台X(中文名)快递Y(中文名)在账号Z下未绑定到快递接口…` | 该账号该平台该编码没有唯一绑定模板(含重复绑定) | 不重试;按提示到 OMS 店铺管理→外部打单平台→快递接口 绑定 | +| `快递编码X不存在(…均无此编码)…` | 系统快递公司字典与自定义快递编码字典都没有该编码 | 不重试;到 OMS 系统管理→自定义快递编码 新增后再试 | +| `快递编码X已停用…` | 编码在字典里但 `status=0` | 到 OMS 系统管理→自定义快递编码 启用后再试 | +| `打单平台「X」未开启回平台取号:…` | 平台 `fetch_waybill_no != 1` | 先改平台配置 | +| `店管家真实取号已关闭(DGJ_WAYBILL_ENABLE=0):…` | 显式关闭了真实取号,且平台侧还没有运单号 | 去掉该环境变量后重试 | +| `店管家未找到订单:系统编号 X(域名 Y)` | 订单不在该平台的订单域名/分区,或系统编号不对 | 检查平台域名(视频号/淘宝走 `fxali`、抖店 `fxdd`)、分区 dbname | +| `店管家面单余额不足,请充值后再取号` | 模板余额 < 本次张数 | 充值后重试 | +| `订单在店管家已发货或已终结(ErpState=sended,平台运单号 X…),取号失败:请作废或取消该单` | 平台侧已发货/已终结(常见于平台先发货、OMS 后审核) | 不重试;OMS 作废/取消该单,WMS 同步取消 | + +**取号失败提示都带操作指引**,示例(真实返回): + +``` +平台SPH(视频号)快递STO(申通快递)在账号15197817068下未绑定到快递接口,请到 OMS 店铺管理→外部打单平台→快递接口 查看绑定对应的快递接口 +请在 OMS「外部打单平台 → 快递接口」中为该模板绑定编码 STO,同一账号同平台下一个编码只能绑定一个模板 +``` + +提示的三种形态:①该平台没有模板 → 提示先去「从平台同步数据」;②有同快递公司的模板但未绑定 → 直接点名模板;③模板快递公司不匹配 → 列出该平台现有模板及其快递公司编码,提示改用正确编码。 +| `平台未返回运单号` | 平台调用成功但没解析到单号 | 可重试(谨慎) | +| `接口错误: ...` / 平台异常 | 平台接口异常 | 可有限重试 | + +**注意:不复用任何已有运单号。** 既不读 OMS 订单上的 `express_code`,也不判断店管家订单行上的 `LastWaybillCode`; +每次请求都真实调用平台取号(消耗面单),去重只靠幂等表的 `request_id`。 + +### 4.5 快递接口定位规则(OMS 内部,用于理解失败原因) +``` +订单.source_platform_code ──┐ +订单.shop_id → shops(type=2) ─┼─► external_print_accounts(打单账号) + │ └─► external_print_platforms(平台配置 fetch_waybill_no) +WMS 传入的 expressCode ───────┴─► external_print_express_interfaces + where account_id + platform_code + custom_code + status=1 + (必须唯一命中,重复绑定视为未命中) +``` + +- **不按店铺区分**:店管家里的「店铺」是商家,同一账号下的快递接口共用。 +- **同一账号 + 同一平台**下,一个快递编码只能绑定一个模板;不同平台可以重复(互不影响)。 +- 平台字典 `external_print_platforms.fetch_waybill_no` 目前由**迁移/开发者维护**,前端只读。 + +### 4.6 校验顺序与「取不到接口」的提示(真实模式) + +`getwaybill` 的逐单校验顺序(任一不通过即返回该单失败,不影响其它单): + +1. 报文单号 / 快递编码齐全; +2. 按 `deliveryOrderCode` 回读订单(`order_index.order_no`,回退老发货单 `order_deliveries.delivery_order_code`),并按 `app_key` 校验主体与仓库; +3. 订单状态:`canceled` / `void` / `history` / `delivery` 直接失败(不读也不写订单上的运单号); +4. 订单来源平台 `source_platform_code`; +5. 店铺 → `shops.type=2` → `external_print_account_id`(打单账号); +6. 打单账号 + 平台配置(`fetch_waybill_no`); +7. **按「账号 + 平台 + WMS 传入编码」定位快递接口** → 找不到时返回带入口与步骤的提示; +8. 调用平台取号(当前店管家未实现 → 返回「店管家取号接口尚未接入」)。 + +取不到快递接口时,返回一句话的简短提示(平台/快递优先带中文名,查不到名称时只显示编码),真实示例: + +``` +平台SPH(视频号)快递STO(申通快递)在账号15197817068下未绑定到快递接口,请到 OMS 店铺管理→外部打单平台→快递接口 查看绑定对应的快递接口 +``` + +附加说明只在必要时出现(很短的括号补充): + +| 场景 | 返回 | +|---|---| +| 快递编码在系统 + 自定义字典里**都不存在** | `快递编码XYZ999不存在(系统快递编码与自定义快递编码均无此编码),请到 OMS 系统管理→自定义快递编码 新增后再重试` | +| 快递编码**已停用** | `快递编码XYZ999已停用,请到 OMS 系统管理→自定义快递编码 启用后再重试` | +| 该平台没有任何模板 | 主提示 + `(该平台暂无面单模板,请先点「从平台同步数据」)` | +| 该平台没有该快递公司的模板 | 主提示 + `(该平台暂无对应快递公司的模板,请先点「从平台同步数据」)` | +| 同一编码被多个模板绑定 | 整句换成「…下绑定了 N 个快递接口,请到 OMS 店铺管理→外部打单平台→快递接口 只保留一个后重试」 | + +> 判定顺序:先按「账号 + 平台 + 编码」找绑定,命中就直接取号;**找不到才校验编码是否存在**(避免历史绑定了字典外编码的单据无法取号)。 + +> 已实测(本地真实 HTTP + 真实签名,订单 `dgj-10000266092590` / 平台 `SPH`): +> 编码 `STO` → 未绑定提示;编码 `XYZ999` → 「编码不存在」;停用编码 → 「已停用」。 +> 这些失败结果**都不占用 `request_id`**,WMS 可直接重试。 + +### 4.7 取号记录(`waybill_fetch_records`)——平台返回全部留存 + +取号**不只是拿单号**:店管家 `ExpressPrint` 会同时返回面单打印数据(`PrintInfo`)与签名,WMS 打印时必须用它们。 +因此 OMS 会把每次取号的平台原始返回整条落库,**不写订单表**,只做留痕。 + +写入时机:逐单处理中一旦定位到打单账号(即真正接触平台)就写一条,成功 / 失败都写。 + +| 字段 | 说明 | +|---|---| +| `principal_id` / `warehouse_id` | 来自 `app_key` 的主体与仓库 | +| `request_id` | 调用方 `request_id`,同一次批量取号共用,便于按批串起来 | +| `delivery_order_code` | OMS 发货单号 | +| `express_code` / `platform_code` | 本次快递编码 / 订单来源平台 | +| `account_id` / `template_id` | 打单账号 / 面单模板 | +| `status` | `1` 成功、`0` 失败 | +| `waybill_source` | 现阶段固定 `express_print`(每次请求都真实向平台取号) | +| `waybill_code` / `waybill_codes` | 主运单号 / 全部运单号(JSON 数组) | +| `printinfo` / `signature` | **面单打印数据与签名**(平台原样,透传给 WMS 的同一份) | +| `raw_response` | 平台原始返回 JSON(含 `Data.WaybillCode[]`、失败时的 `Message/ErrorCode`) | +| `error_message` | 失败原因(与响应里的 `message` 一致) | + +排查用的常用 SQL: + +```sql +-- 某单最近 5 次取号(每次的号码与平台原始返回) +SELECT id, created_at, status, waybill_source, waybill_code, error_message +FROM waybill_fetch_records WHERE delivery_order_code = 'dgj-10000267890142_1' +ORDER BY id DESC LIMIT 5; + +-- 看某次真取号的面单打印数据(WMS 该怎么落库、打印时该传什么) +SELECT waybill_code, length(printinfo) AS printinfo_len, signature, raw_response +FROM waybill_fetch_records WHERE delivery_order_code = 'dgj-10000267890142_1' AND status = 1 +ORDER BY id DESC LIMIT 1; + +-- 按批排查(与 openapi_request_idempotency 的 request_id 对齐) +SELECT * FROM waybill_fetch_records WHERE request_id = 'oms-getwaybill-xxx' ORDER BY id; +``` + +> WMS 侧对应落库字段建议:`order_express.waybill_code` ← `waybill_code`,`order_express.printinfo` ← `printinfo`, +> `order_express.signature` ← `signature`,`status=1`;打印时把 `printinfo` 原样交给打印服务即可,**不要自己拼格式**。 + +> ⚠️ `printinfo` 是整张面单的打印数据(单张常见几十到几百 KB),批量取号时响应会明显变大: +> 建议一次批量不超过 20 单,或让 WMS 逐单/小批取号,避免响应体过大拖慢回调。 + +--- + +## 5. 推送侧:`need_oms_waybill` + +### 5.1 OMS 下发的值 + +- 报文位置:`deliveryorder.create` 的**请求根节点**,与 `deliveryOrder`、`orderLines` 同级: + +```json +{ "deliveryOrder": { }, "orderLines": { "orderLine": [] }, "need_oms_waybill": 1 } +``` + +- 取值规则(推送时实时判定,并回写单据): + - 订单店铺 `type = 2`(外部打单平台商家)且该账号所属平台 `fetch_waybill_no = 1` → `1` + - 其他(手工单、平台店铺、数据库模式店铺)→ `0` +- 平台配置改动**不需要重新建单**,下一次推送即生效(读缓存,TTL 300 秒;绑定/账号变更会主动失效)。 + +### 5.2 WMS 现有行为 + +- `need_oms_waybill=1` 的订单在取号流水线里被跳过本地分配,`waybill_allocate_queue` 行被置为 `waiting_oms`(终态,`message='等待外部OMS取号'`)。 +- 相关代码:`D:\wms\app\service\systems\express.js`(`skipped_need_oms_waybill_order_ids`)、`D:\wms\app\schedule\consume_waybill_allocate_queue.js`(约 225~238 行)。 + +--- + +## 6. WMS 侧改造清单(给 WMS agent) + +### 6.1 新增 `oms` 取号平台实现 + +文件:`D:\wms\app\service\systems\express_platform.js` + +- 分发规则:`express.js#dispatchWaybillAsyncPlatform(platformCode, bizcontent)` 直接调用 + `this.service.systems.expressPlatform[request_platform_code](bizcontent)`;方法不存在会抛 `xxx接口未实现`。 +- 因此新增方法名必须叫 **`oms`**,与 `wms_print_platform.request_platform_code = 'oms'` 一致。 +- 返回值约定:成功返回 `{ flag: 'success' }`(或 undefined);失败返回 `{ flag: 'failure', message }` 或直接 `throw`。 +- `oms` **不要**加入 `shouldDispatchWaybillAsyncPerOrder()` 的逐单列表(保持整批调用,减少 HTTP 次数)。 + +参考骨架(伪代码,字段名以 WMS 现有 `bizcontent.orders` 为准): + +```js +async oms(bizcontent = {}) { + const orders = Array.isArray(bizcontent.orders) ? bizcontent.orders : []; + if (!orders.length) return { flag: 'success' }; + + // 1) 组报文:deliveryOrderCode 取 OMS 单号,expressCode 取 WMS 自己的快递编码 + const payload = { + orders: orders.map(o => ({ + deliveryOrderCode: o.order_info.delivery_order_code || o.delivery_order_code, + expressCode: o.logistics_code || o.express_code, + })), + }; + + // 2) 调用 OMS:appKey 取当前打印平台绑定的 api_app.self_app_key + // callback_url 必须是 OMS /openapi(sendByAppKey 内部会包成 { request: payload }) + const appKey = /* api_app.self_app_key */ ''; + const result = await this.service.openapi.callback.sendByAppKey({ + appKey, + event: 'deliveryorder.getwaybill', + request: payload, + }); + if (!result.success) throw new Error(result.error || 'OMS 取号调用失败'); + + // 3) 解析逐单结果 + const body = result.response || {}; + const results = (body.data && body.data.results) || []; + const failed = results.filter(r => !r.success); + const success = results.filter(r => r.success); + + // 4) 回写成功运单号(复用现成方法) + const successUpdates = success.map(r => { + const ctxOrder = orders.find(o => (o.order_info.delivery_order_code || o.delivery_order_code) === r.delivery_order_code); + return { + warehouse_id: Number(bizcontent.warehouse_id || 0), + order_id: Number(ctxOrder.order_id), + business_key: Number(ctxOrder.business_key) || 1, + waybill_code: r.waybill_code, + orderExpressValues: { + waybill_code: r.waybill_code, + logistics_code: r.express_code, + platform_code: r.platform_code, + create_at: new Date(), + delivery_order_code: r.delivery_order_code, + status: 1, + retry_count: 0, + }, + orderDeliveryValues: { post_status: 'fin', order_flag: '' }, + }; + }); + await this.persistWaybillSuccessUpdates(successUpdates, orders); + + // 5) 失败处理:按 message 区分「不可重试」与「可重试」 + if (failed.length) { + throw new Error(failed.map(f => `${f.delivery_order_code}: ${f.message}`).join('; ')); + } + return { flag: 'success' }; +} +``` + +> `persistWaybillSuccessUpdates(successUpdates, orders)` 的必需字段:`warehouse_id / order_id / business_key`、`orderExpressValues`(至少 `waybill_code`、`status:1`)。 +> 参考已有实现:`express_platform.js` 的 `KS` / `DY` / `pdd` 分支。 + +### 6.2 平台配置 + +- `wms_print_platform`:把对应打印平台的 `request_platform_code` 设为 `oms`(该字段决定分发到哪个方法)。 +- 该平台关联的 `api_app`(`self_app_key / self_app_secret / callback_url`)必须是 OMS 侧 `warehouse_apis` 的同一套凭据,`callback_url` = OMS `/openapi`。 +- 如果 WMS 回调调试页要展示该方法,可同步补 `methods/openapi_callback.json` / `callbackRegistry.js`(仅文档用,非必需)。 + +### 6.3 消费 `waiting_oms` + +文件:`D:\wms\app\schedule\consume_waybill_allocate_queue.js` + +现状:`waitingRows` 直接 `updateQueueRowsStatus(..., 'waiting_oms', '等待外部OMS取号')`,之后就没人处理。 + +建议改成: + +1. 组内先按 `warehouse_id + store_id` 分组(已有); +2. 把 `waitingRows` 对应的 `order_id → delivery_order_code` 查出来(`order_delivery.delivery_order_code`),按 **≤100/批** 切分(OMS 硬上限); +3. 调 OMS(走 `dispatchWaybillAsyncPlatform('oms', ...)` 或直接调 `sendByAppKey`); +4. 结果落地: + - 成功 → `order_express` 写入(见 6.1),队列行置 `done`; + - 失败: + - 不可重试类(取消/作废/归档/未绑定编码/仓库不符/单据不存在)→ 置 `failed`,把 `message` 写进队列行,便于运营看见; + - 可重试类(网络/OMS 5xx/`平台未返回运单号`)→ 按现有 `markGroupRetryOrFailed` 的重试策略处理; +5. 重试必须复用同一 `request_id`(建议 `request_id = oms-getwaybill-${queueBatchId}`,或用队列行 id 拼接的稳定值),否则 OMS 会重新走平台取号(可能重复下单/浪费面单)。 + +> 关键取舍:`waiting_oms` 不应是终态。要么消费后改为 `done/failed`,要么保持可重试状态——**不能让订单静默停在这里**。 + +### 6.4 可观测性 + +- 建议每批记录:`appKey / 批大小 / success / failed / 耗时 / 首个失败原因`; +- 失败信息写 `waybill_allocate_queue.message` 与订单操作日志(`operationLog`,`operationCode: 'WAYBILL'`)。 + +--- + +## 7. OMS 侧待办(我方) + +1. **店管家真实取号**:已按旧系统 `Dianguanjia.php` 提取并实现(见 `店管家取号-旧系统提取.md`)。 + 默认开启真实取号(会消耗面单,`DGJ_WAYBILL_ENABLE=0` 可关闭);首次使用前建议按该文档 §7 核对响应字段。 +2. **打印数据回传**:已实现——逐单结果回传 `printinfo / signature`,并落 `waybill_fetch_records`(见 §4.7)。 +3. **多包裹 / 拆单取号(已跑通)**:店管家用 `PrintMethod=NewPrint` + `IsIgnoreWaybillRepeat=false` 分配新号, + 每次调用 pid 第二段自增(`63274907ebce8f6b_1_1` → `_2_1` → `_3_1`),实测连续 3 次均拿到不同运单号。 + WMS 按包裹各调一次即可;多一次调用 = 多一张面单,重试必须复用 `request_id`。 + 详见 `店管家取号-旧系统提取.md` §4.2.1。 +4. **平台字典维护**:`external_print_platforms.fetch_waybill_no` 由迁移维护(当前 `dgj = 1`)。如需前端可配,另开需求。 +5. **生产 app_key/callback_url**:需要与 WMS 对齐生产环境的 `warehouse_apis` 与 `api_app` 记录。 + +--- + +## 8. 当前数据现状(本地开发库,2026-11-04) + +| 对象 | 现状 | +|---|---| +| 仓库 | 4 个(`WH2609111438491570` 科创仓 等,均启用) | +| `warehouse_apis` | 1 条:主体 5 / 仓库 1(科创仓)/ `type=qimen` / `base_url=http://127.0.0.1:6060/openapi` / app_key 前缀 `WMSD08…` / app_secret 已配置(64) / 启用 | +| 外部打单平台 | 1 条:`dgj`(店管家,`dgjapp.com`),**`fetch_waybill_no = 1`**,启用 | +| 外部打单账号 | 1 条(id=1,主体 5,已登录) | +| `type=2` 店铺 | 5 个(均挂账号 1) | +| 快递接口模板 | 29 条全部有效;**仅 2 条绑定了快递编码**;覆盖平台 TB 10 / XHS 5 / DYXD 4 / JD 3 / PDD 3 / KS 2 / SPH 2 | +| 自定义快递编码 | 0 条 | +| 订单量 | 待审核 22 / 委外中 5 / 配送 3;老发货单 5 | +| 幂等表 | 已建(`openapi_request_idempotency`) | +| 取号记录表 | 已建(`waybill_fetch_records`,存平台原始返回 + `printinfo` / `signature`) | + +> 结论:**29 个模板里只有 2 个绑了编码**,所以除这 2 个编码外,其余取号都会返回「…下未绑定到快递接口…」。联调前先在 OMS「外部打单平台 → 快递接口」把要测的编码(如 TB + `ZTO`)绑定好。 + +### 8.1 WMS 实测记录(2026-11-04 06:13~06:18) + +WMS 已成功调通 OMS `deliveryorder.getwaybill`,共 6 次请求(1 次真实执行 + 5 次幂等回放,`request_id` 相同): + +```json +{"request":{"orders":[{"deliveryOrderCode":"dgj-10000266092590","expressCode":"STO"}], + "request_id":"oms-getwaybill-db385b87054379228b1d9c52fc1d7c6a"}} +``` + +| 检查项 | 结果 | +|---|---| +| app_key / 签名 / 时间戳 | ✅ 通过,HTTP 200 `flag=success` | +| 报文结构 | ✅ `request.orders[].deliveryOrderCode / expressCode` 均被正确解析并回显 | +| 幂等 | ✅ 首笔 46ms,后续 2~12ms 回放;响应 `timestamp` 恒等于首笔 | +| 订单 | ✅ `dgj-10000266092590`(订单 id 271,状态 `outsourcing`,`need_oms_waybill=1`) | +| 来源平台 | `SPH`(视频号),店铺 18「东莞业思勤贸易」→ 打单账号 1(店管家) | +| 编码绑定 | ❌ `SPH` 平台没有任何编码绑定(已绑定仅 `TB + POSTB`、`TB + ZTKY`) | + +真实路径验证结果: + +``` +STO → 平台SPH(视频号)快递STO(申通快递)在账号15197817068下未绑定到快递接口,请到 OMS 店铺管理→外部打单平台→快递接口 查看绑定对应的快递接口… +ZTKY → 平台SPH(视频号)快递ZTKY在账号15197817068下未绑定到快递接口,…(已绑定的 TB 编码同样匹配不到 SPH,平台筛选生效) +``` + +> 视频号现有模板:`17 / 12411097 / 【视频号】韵达一联3 / YUNDA`、`29 / 10824270 / 【视频号】申通一联1 / STO`。 +> 绑定 `SPH + STO` 即可进入取号流程(随后会停在 dgj 取号未实现)。 + +生产核对 SQL(只读): + +```sql +-- 平台开关 +SELECT id, code, name, fetch_waybill_no, status FROM external_print_platforms; +-- 打单账号与店铺 +SELECT id, principal_id, platform_id, account, login_status FROM external_print_accounts; +SELECT id, code, name, type, external_print_account_id FROM shops WHERE type = 2; +-- 绑定情况(bound 为已绑定编码的模板数) +SELECT platform_code, COUNT(*) total, SUM(custom_code IS NOT NULL AND custom_code <> '') bound +FROM external_print_express_interfaces WHERE status = 1 GROUP BY platform_code; +-- 接口配置(务必与 WMS api_app 的 self_app_key/self_app_secret 一致) +SELECT id, principal_id, warehouse_id, name, base_url, app_key, CHAR_LENGTH(app_secret) secret_len, status +FROM warehouse_apis; +``` + +--- + +## 9. 联调步骤(建议顺序) + +1. **连通性**:WMS 用 `sendByAppKey({ appKey, event: 'index.ping', request: {} })` 调 OMS,确认返回 `flag=success`(先验证签名/时间戳/app_key)。返回体可用于确认凭据与仓库的对应关系: + ```json + { "flag": "success", "code": 1, "message": "ok", + "data": { "pong": true, "method": "index.ping", "app_key": "WMSD08…", + "warehouse": { "id": 1, "code": "WH2609111438491570", "name": "科创仓" }, + "principal_id": 5, "api_version": "1.0", "echo": {}, "server_time": 1750000000 }, + "timestamp": 1750000000 } + ``` +2. **准备绑定**:OMS 侧给至少 1 个淘宝模板绑定编码(例如 `ZTO`);确认该订单来源平台是 `TB`。 +3. **推送一单**:挑 1 张待审核的外部打单订单 → 审核 → 待推送 → 手动推送;到 WMS 查 `order_delivery.need_oms_waybill` 应为 `1`,队列行应为 `waiting_oms`。 +4. **单笔取号**:WMS 直接调 `deliveryorder.getwaybill`(单条),报文: + ```json + { "orders": [ { "deliveryOrderCode": "", "expressCode": "ZTO" } ] } + ``` + **当前预期**:`flag=success`,逐单返回真实校验结果。以订单 `dgj-10000266092590`(平台 `SPH`)+ 编码 `STO` 为例,会返回 + 「平台SPH(视频号)快递STO(申通快递)在账号15197817068下未绑定到快递接口,…」, + 按提示绑定后重试即可。 +5. **验证响应**:成功时响应里返回 `waybill_code / waybill_codes`;OMS 订单表不会写入运单号(现阶段不关联)。 +6. **验证幂等**:同一 `request_id` 重复调用,第二次应回放同样报文(日志有「幂等重放」)。 +7. **失败分支**:传一个不存在的编码 → 应返回「…下未绑定到快递接口…」;对已取消订单调用 → 应返回「订单已取消,取号失败」。 +8. **批量**:一次 20 单(混合成功/失败),确认 WMS 能分别落到 `done` / `failed`。 + +--- + +## 10. 附录:手工构造签名(联调/自测用) + +```js +// node sign.js → 打印可直接用于 curl 的完整 URL +const crypto = require('crypto'); + +const stable = v => { + if (v === undefined) return ''; + if (v === null || typeof v !== 'object') return JSON.stringify(v); + if (Array.isArray(v)) return `[${v.map(stable).join(',')}]`; + return `{${Object.keys(v).sort().map(k => `${JSON.stringify(k)}:${stable(v[k])}`).join(',')}}`; +}; + +const base = 'https://api.example.com/openapi'; +const secret = ''; +const query = { + method: 'deliveryorder.getwaybill', + v: '1.0', + timestamp: String(Math.floor(Date.now() / 1000)), + app_key: '', + request_id: 'test-' + Date.now(), // 可选:带上就启用幂等 +}; +const body = { orders: [{ deliveryOrderCode: 'XK202611040001', expressCode: 'ZTO' }] }; + +const canonical = Object.keys(query).sort().map(k => `${k}=${query[k]}`).join('&'); +const bodySign = crypto.createHash('md5').update(stable(body), 'utf8').digest('hex'); +const sign = crypto.createHash('md5').update(canonical + secret + bodySign, 'utf8').digest('hex'); + +console.log(`${base}?${canonical}&sign=${sign}`); +console.log(JSON.stringify(body)); +``` + +```bash +curl -X POST '<上面打印的 URL>' -H 'Content-Type: application/json' -d '<上面打印的 JSON>' +``` + +> 值里含特殊字符(空格、`&`、中文)时,URL 上要 `encodeURIComponent`,且**签名用的 query 值必须与 URL 上实际传的值一致**。 + +--- + +## 11. 风险与注意事项 + +| 风险 | 说明 | 建议 | +|---|---|---| +| 取号未实现就开着开关 | dgj `fetch_waybill_no=1` 会让订单进 `waiting_oms`,长期无运单号 | 要么先补 dgj 取号,要么临时把开关改回 0(改完 5 分钟内生效,或清缓存) | +| 平台侧重复取号 | WMS 重试换了 `request_id`,OMS 会再次调平台并消耗面单 | 重试务必复用 `request_id`;OMS 现在**每次都会真实取号**(不再复用平台已有运单号),所以幂等表是唯一的去重手段 | +| 批大小 | OMS 单次上限 100 | WMS 侧按 100 切分,注意超时(OMS 内部并发 4) | +| 绑定缺失 | 只有唯一命中才取号,重复绑定视为未命中 | 运营侧保持「一账号一平台一编码一模板」 | +| 配置缓存 | 平台配置/绑定缓存 TTL 300s | 改完配置要立刻生效时清 Redis:`oms:cache:external-print-account:*`、`oms:cache:express-template:*` | +| 幂等表增长 | 保留 7 天 | 已由每日定时任务清理 | + +--- + +## 12. 文件索引 + +### OMS(`D:\oms`) + +| 文件 | 作用 | +|---|---| +| `backend/app/controller/openapi.js` | `/openapi` 入口:参数校验、app_key→主体+仓库、验签、幂等回放、分发 | +| `backend/app/lib/openapiMethods.js` | 方法注册表:`index.ping` / `entryorder.confirm` / `entryorder.match` / `deliveryorder.confirm` / `deliveryorder.getwaybill` / `stockout.confirm` / `order.cancel` | +| `backend/app/lib/waybillGet.js` | `deliveryorder.getwaybill` 实现(解析、状态校验、模板定位、逐单结果、透传 `printinfo`/`signature`、写取号记录;不写订单表) | +| `backend/app/lib/openapiIdempotency.js` | 请求级幂等(begin/finish/回放/409/报文摘要) | +| `backend/app/lib/wms/sign.js` | 签名算法(stableStringify / qimenSign) | +| `backend/app/lib/apiResponse.js` | 响应封装 `{flag, code, message, data, timestamp}` | +| `backend/app/lib/wms/qimenClient.js` | OMS→WMS 推送(`deliveryorder.create`,根节点 `need_oms_waybill`) | +| `backend/app/service/orderWms.js` | 订单推送主流程;`resolveNeedOmsWaybill` 实时判定开关 | +| `backend/app/service/externalPrintOrder.js` | 店管家拉单入库(建单时写 `need_oms_waybill` 快照) | +| `backend/app/service/externalPrintExpressInterface.js` | 快递接口同步/列表/绑定/`resolveByCode` | +| `backend/app/lib/printPlatform/dgj.js` | 店管家实现(模板同步、明细、`fetchWaybillNo` 取号 + 打印数据解析) | +| `backend/app/lib/printPlatform/base.js` | 平台基类(`needFetchWaybillNo`、cookie/token 保存回调) | +| `backend/app/service/cache.js` | 店铺/打单账号/编码绑定缓存(`oms:cache:*`) | +| `backend/database/migrations/20261104000000-*.js` | `external_print_express_interfaces` 表 | +| `backend/database/migrations/20261104010000-*.js` | `custom_express_codes` 表 | +| `backend/database/migrations/20261104020000-*.js` | `openapi_request_idempotency` 表 | +| `backend/database/migrations/20261104040000-*.js` | `waybill_fetch_records` 表(取号平台原始返回留痕) | +| `backend/app/model/waybillFetchRecord.js` | 取号记录模型(`printinfo` / `signature` / `raw_response`) | + +### WMS(`D:\wms`) + +| 文件 | 作用 | +|---|---| +| `app/service/systems/express.js` | 取号流水线;`dispatchWaybillAsyncPlatform` 按 `request_platform_code` 分发;`skipped_need_oms_waybill_order_ids` 分流 | +| `app/service/systems/express_platform.js` | 平台实现:`polyapi` / `cainiao` / `pdd`(**需新增 `oms`**);`persistWaybillSuccessUpdates`、`cleanupFailedWaybillOrders` | +| `app/schedule/consume_waybill_allocate_queue.js` | 队列消费;`waiting_oms` 目前置终态(**需改为调用 OMS**) | +| `app/model/waybill_allocate_queue.js` | 队列状态定义(`pending/processing/done/failed/waiting_oms`) | +| `app/model/order_delivery.js` | 订单:`delivery_order_code`、`logistics_code`、`need_oms_waybill` | +| `app/model/order_express.js` | 运单:`waybill_code / status / printinfo / signature` | +| `app/service/openapi/callback.js` | `sendByAppKey({appKey,event,request})`:查 `api_app` 取 `callback_url` 与密钥,签名+重试(2s/5s/15s) | +| `app/model/api_app.js` | `self_app_key / self_app_secret / callback_url` | +| `app/lib/api_sign.js` | 与 OMS 一致的签名实现 | + +oms/ + +/wms + +## WMS 侧实施汇报(2026-11-04) + +### 已完成 + +**1. 新增 `express_platform.oms`**(`app/service/systems/express_platform.js`) + +- 方法名 `oms`,与 6.1 约定一致;不进入 `shouldDispatchWaybillAsyncPerOrder()` 逐单列表,保持整批调用。 +- 入参兼容 `orders[].order_delivery` 结构,内部归一化为 `{ order_id, business_key, delivery_order_code, express_code, store_id, warehouse_id }`。 +- 按 **100 单/批**自动切分(OMS 硬上限),批间顺序处理。 +- `request_id` 由「仓库 + 货主 + 订单集合」推导为 `oms-getwaybill-`(46 字符),**重试复用同一值**,命中 OMS 幂等回放。 +- `request_id` 走 **`body.request.request_id`**(文档 4.3 的 body 兜底通道),因此没有改动 `callback.js` 的签名逻辑 —— body 已参与 `bodySign`,无需新增 query 参数。 +- appKey 解析:`store_id + warehouse_id` → `store_warehouse(auth_status=2)` → `api_app(is_enabled=1 且 callback_url 非空)`,复用 `orderAsync.resolveOpenApiAppByStore`;解析不到直接失败且标记不可重试。 +- 成功项复用现有 `persistWaybillSuccessUpdates`(含结算扣减、`WAYBILL` 操作日志、`auto_sync_back`)。 +- 取号前先补 `order_express` 占位行(`status=0`,`ignoreDuplicates`):这类订单被本地流水线整体跳过、不建占位行,不补会导致取号后 update 命中 0 行而丢运单号。 + +**2. `waiting_oms` 不再是终态**(`app/schedule/consume_waybill_allocate_queue.js`) + +- 流水线返回 `skipped_need_oms_waybill_order_ids` 后,**同一轮**转调 `dispatchWaybillAsyncPlatform('oms', ...)`。 +- 结果落地:成功 → `done`;不可重试 → `failed`(原因写 `error_message`);可重试 → 退回 `pending`(沿用 3 次上限、60s×n 退避)。 +- 部分成功时不依赖 OMS 返回条数,统一按 `order_express.status=1` 的实际落库结果判定 done / 未完成。 +- 新增兜底:`waiting_oms` 超过 10 分钟未更新自动退回 `pending`,避免进程中断后订单静默停住。 + +**3. 失败可重试性**(对齐 4.4) + +- 不可重试:订单已取消/作废/归档、未找到发货单、仓库不符、未关联店铺/外部打单账号、未绑定到快递接口、平台未开启取号、缺少单号或快递编码。 +- 可重试:平台未返回运单号、接口错误、OMS `409`/`5xx`、网络错误、返回条数不一致。 + +### 需要 OMS 侧确认(3 点) + +1. **`expressCode` 口径**:WMS 传订单上的 `logistics_code`(如 `ZTO`/`STO`),与 `wms_express_interface.sys_express_code` 同源。请确认它与 `external_print_express_interfaces.custom_code` 是同一套编码;若不是,请告知 WMS 应改传哪个字段。 +2. **`request_id` 通道**:WMS 放在 `body.request.request_id`。请确认 OMS 取值链确实覆盖该位置(4.3 有列出),否则幂等不生效、重试会重复打平台。 +3. **`data.results` 顺序**:WMS 按请求顺序逐单匹配(不按 `delivery_order_code` 反查,因为取号失败时该字段可能为空串)。请确认「失败项也保持顺序」。 + +### 与原文档 6.2 的差异:不需要平台配置 + +WMS 在 `createWaybillCodePipeline` 分流 `need_oms_waybill` **之后**才调 OMS,而流水线在进入平台分组前就会对这类订单 early return。 +因此 `wms_print_platform.request_platform_code` **不需要设为 `oms`**;只有走流水线内部平台分发的场景才需要。 +仍必须保证:`api_app.callback_url` 指向 OMS `/openapi`,`self_app_key / self_app_secret` 与 OMS `warehouse_apis` 对齐。 + +### 测试 + +| 文件 | 用例 | +|---|---| +| `test/app/service/systems/express_platform.oms.test.js` | 7 例:报文结构、request_id 稳定性、100 单切分、不可重试失败、可重试判定、409、缺 api_app | +| `test/app/schedule/consume_waybill_allocate_queue.oms.test.js` | 5 例:成功置 done、不可重试置 failed、可重试退回 pending、部分成功、平台方法缺失 | + +12 例全部通过,eslint 通过。 + +### 联调前置(WMS 侧 blocker) + +1. OMS `dgj.fetchWaybillNo()` 未实现前,`deliveryorder.getWaybill` 只能返回「接口错误/平台异常」这类可重试失败,WMS 队列会重试 3 次后置 `failed`。 +2. 建议联调期先把 `external_print_platforms.fetch_waybill_no` 临时置 `0`,避免新单持续进入 `waiting_oms`。 +3. 联调第一步仍建议先跑 `index.ping` 验证签名与 `api_app ↔ warehouse_apis` 凭据对应关系。 +4. WMS 侧 `express_platform.oms` 未补 `methods/openapi_callback.json`(仅回调调试页展示用),如需可视化再补。 + +wms/ + +/wms + +## WMS 侧对齐新版文档(2026-11-04 08:40) + +已按更新后的文档(`已取号复用` 规则删除、`printinfo/signature` 透传、批大小建议)调整实现: + +### 1. 落面单打印数据(4.2 / 4.7) + +取号成功时除 `waybill_code` 外,同时落库: + +```js +order_express.printinfo ← row.printinfo // 字段类型 LONGTEXT,单张几十~几百 KB 无压力 +order_express.signature ← row.signature // TEXT +``` + +打印时原样下发,不自行拼格式。 + +### 2. 批大小 100 → 20 + +`OMS_WAYBILL_MAX_BATCH_SIZE = 20`,与文档 4.7「建议一次批量不超过 20 单」一致。 + +### 3. `request_id` 改为包裹标识摘要 + +摘要输入改为 `warehouse_id(16进制)_order_id(16进制)_business_key` 的排序拼接,再取 md5: + +``` +object_id = 186a0_394c77c9_1 +request_id = oms-getwaybill-f3ea07d27abbbb8262592ed9606130e7 +``` + +同一订单的主单/子单因此得到不同 `request_id`。 + +### 4. 子单号分配接入 OMS + +既然「不再复用任何已有运单号、每次真实取号、不回写订单表」,同一 OMS 单的不同包裹可以各自取到独立面单。 +`allocateSubOrderNumber` 已接上 OMS:流水线返回的 `skipped_need_oms_waybill_order_ids` 会带各自 `business_key` 转调 `oms`, +`buildSubOrderDetails` 回查后能反映真实结果,不再固定返回「未找到分配的运单记录」。 + +### 5. 失败关键词按 4.4 新版重写 + +不可重试:订单已配送/已完成/已取消/已作废/已归档、未绑定到快递接口、快递编码不存在/已停用、 +未开启回平台取号、真实取号已关闭、未找到订单、面单余额不足、已发货或已终结、未关联店铺/外部打单账号等。 + +可重试:平台未返回运单号、接口错误、`店管家取号接口尚未接入`、OMS `409`/`5xx`、网络错误。 + +### 6. 关于「批量中任一单失败不锁 request_id」的风险说明 + +WMS 侧不会整批重取:成功的订单行会置 `done` 并已落库,只有失败行退回 `pending`。 +下一轮组批时批次里只剩失败单 → `request_id` 随之变化 → OMS 只会对失败单重新取号。 +因此 20 单/批不会因单笔失败而重复消耗 20 张面单。 + +### 7. 一个需要留意的副作用 + +`request_id` 构造方式变更后,之前用旧格式(`md5(warehouse|store|order集合)`)写进 +`openapi_request_idempotency` 的记录不再命中,同一批重试会新建记录并真实取号(消耗面单)。 +本地已存在的 id=50 记录(订单 `961312713`)属于旧格式,重测时请先按文档 4.3 清理该表。 + +wms/ + +/wms + +## WMS 侧跟进子单号契约(2026-11-04 09:10) + +按文档 4.1/4.2 新增的 `packageIndex` 契约调整: + +### 1. 请求显式传包裹序号 + +```js +orders: batch.map(item => ({ + deliveryOrderCode: item.delivery_order_code, + expressCode: item.express_code, + packageIndex: Math.max((Number(item.business_key) || 1) - 1, 0), // business_key 1 基 → 0 基 +})) +``` + +不传时 OMS 按 `deliveryOrderCode` 尾部 `_N` 推导;WMS 的 OMS 单号都是 `_1` 结尾(驳回复推后缀,非包裹号), +导致主单与子单都推导成 0 号包裹 —— 这正是之前「子单拿到主单运单号」的原因。现在显式传入即可区分。 + +### 2. 落库补齐新字段 + +```js +order_express.printinfo ← row.printinfo // base64 URL-encoded JSON,原样存储不解码 +order_express.signature ← row.signature +order_express.encryptprintinfo ← row.encryptprintinfo +order_express.ver ← row.ver +order_express.platform_code ← 订单 sys_platform_code(回退 row.platform_code) +``` + +> `platform_code` 必须落**来源平台**(如 `SPH`),不能落 `oms`:打印时用它在 `wms_print_platform` +> 匹配模板,而该表只有 `DY/CAINIAO/PDD/JD/DW/KS/SPH/XHS/QT`。 + +### 3. 回显校验 + +响应里 `package_index` 与请求的 `packageIndex` 不一致时判该单失败(可重试),避免把运单号落到错误的包裹行。 + +### 4. 已知现象说明 + +文档 4.2 提到「同一包裹重复取号会拿到同一个号」(店管家按 `_<包裹序号>` 分配), +WMS 侧不做特殊处理,按成功落库;`message` 里的提示会原样进 `aggregatedResults`。 + +wms/ + +/wms + +## WMS 侧修正 API 渠道出库单回传取号(2026-11-04 11:20) + +### 问题 + +OMS(API) 渠道订单同步时报「发货单缺少奇门货主编码」: + +- `processApiOrderInternal` 组装 `deliveryorder.confirm` 报文后,要求 `requestData.ownerCode` 非空; +- `ownerCode` 只能来自请求上下文 `customerId`、订单明细 `owner_code` 或奇门合同; +- OMS 推送的 `orderLines` 不带 `ownerCode`,明细 `owner_code` 为空 → 直接判失败,订单 `sync_status='error'`。 + +### 修正(与回 OMS 取号同口径) + +1. **appKey 按 `from_key` 回原通道**:`context.appKey` → `orderRow.from_key` → 按货主反查 `api_app`。 + 与 `express_platform.oms` 取号完全一致的解析优先级,「从哪里回哪里去」。 +2. **不再要求奇门货主编码**:OMS `deliveryorder.confirm` 不校验 `ownerCode` + (OMS 侧 `warehouseApiFields.js` 注释亦确认「OMS 接收回传不看 ownerCode」), + 组装失败判定改为只看 `requestData.request` 是否存在。 +3. 奇门(QM)渠道逻辑不变,仍要求 `ownerCode`。 + +### 验证 + +`test/app/service/systems/order_async.api-confirm.test.js`: + +- 明细无 `owner_code` 时仍能发起 `deliveryorder.confirm`,`appKey` 取自 `from_key`; +- `from_key` 缺失时回退按 `store_warehouse → api_app` 反查。 + +2 例通过,eslint 通过。 + +### 待确认 + +本地 `wms_api_app`(id=48 测试接口)的 `qimen_customer_id` / `qimen_warehouse_code` 为空。 +若后续需要回传 `ownerCode`,建议由 OMS 侧在 `warehouse_apis` 提供货主编码并同步到 `api_app.qimen_customer_id`。 + +wms/ \ No newline at end of file diff --git a/backend/app/contract/index.js b/backend/app/contract/index.js index 471dfcb..77b8977 100644 --- a/backend/app/contract/index.js +++ b/backend/app/contract/index.js @@ -2146,6 +2146,35 @@ module.exports = { message: { type: 'string', description: '提示信息' }, data: { type: 'orderStatusFilters', description: '筛选条件下拉数据源' }, }, + /** 外部打单平台同步发货:数量统计 */ + externalSendCountsResponse: { + code: { type: 'integer', description: '业务状态码,0 成功' }, + message: { type: 'string', description: '提示信息' }, + data: { type: 'externalSendCounts', description: '各同步状态数量' }, + }, + externalSendCounts: { + pending: { type: 'integer', description: '待同步数量' }, + retry: { type: 'integer', description: '同步失败待重试数量' }, + exception: { type: 'integer', description: '异常数量(重试超限,需人工处理)' }, + synced: { type: 'integer', description: '已同步数量' }, + total: { type: 'integer', description: '配送订单总数' }, + }, + /** 外部打单平台同步发货:批量重试结果 */ + externalSendRetryResponse: { + code: { type: 'integer', description: '业务状态码,0 成功' }, + message: { type: 'string', description: '提示信息' }, + data: { type: 'externalSendRetryResult', description: '本次重试结果' }, + }, + externalSendRetryResult: { + reset: { type: 'integer', description: '被重置为待同步的订单数' }, + success: { type: 'integer', description: '同步成功数量' }, + failed: { type: 'integer', description: '同步失败数量' }, + }, + /** 批量重试同步外部发货:请求体 */ + externalSendRetryRequest: { + ids: { type: 'array', itemType: 'integer', description: '要重试的订单ID数组;为空时按 statuses 筛选' }, + statuses: { type: 'array', itemType: 'integer', description: '状态筛选(默认 [2,3]:待重试 + 异常)' }, + }, /** 订单(列表行:4 张状态表与历史表同构,历史表另含归档/转入时间) */ orderStatusItem: { id: { type: 'integer', description: '订单ID(= order_index.id,全局唯一)' }, @@ -2161,6 +2190,12 @@ module.exports = { address: { type: 'string', description: '收货地址(省市区镇 + 详细地址的汇总快照)' }, // —— 以下为「为容纳老表(原订单表 orders + 发货单 order_deliveries)而扩展」的字段 —— order_type: { type: 'string', description: '订单类型:WMS 编码 JYCK/HHCK/BFCK(老 order_type 数值以字符串保留)' }, + external_send_status: { type: 'integer', description: '同步外部打单平台发货状态:0待同步 1已同步 2同步失败待重试 3异常(重试超限);系统托管' }, + external_send_status_label: { type: 'string', description: '同步外部发货状态中文(列表返回)' }, + external_send_times: { type: 'integer', description: '同步外部发货已尝试次数(达到 3 次转异常)' }, + external_send_error: { type: 'string', description: '最近一次同步失败原因' }, + external_send_at: { type: 'string', description: '最近一次同步尝试时间' }, + external_sent_at: { type: 'string', description: '同步成功时间' }, wms_status: { type: 'string', description: '外部WMS状态(回调回写)' }, wms_order_no: { type: 'string', description: '外部WMS单号' }, wms_synced_at: { type: 'string', description: '最近一次 WMS 同步时间' }, @@ -2647,4 +2682,54 @@ module.exports = { }, exportTaskPage: buildPage('exportTaskLine', '导出任务列表'), exportTaskListResponse: buildListResponse('exportTaskPage'), + + // ---------- 拉单任务 order_sync_tasks ---------- + createOrderSyncTaskRequest: { + scope: { type: 'string', description: '拉单范围:external_print=外部打单平台店铺(默认)' }, + lookback_days: { type: 'integer', description: '回看天数(按平台下单时间过滤);0 表示全部待处理,默认 3' }, + shop_ids: { type: 'array', itemType: 'integer', description: '指定店铺ID;不传表示该范围内的全部店铺' }, + }, + orderSyncTaskShopItem: { + shop_id: { type: 'integer', description: '店铺ID' }, + shop_code: { type: 'string', description: '店铺编码' }, + shop_name: { type: 'string', description: '店铺名称' }, + account_id: { type: 'integer', description: '关联的外部打单账号ID' }, + success: { type: 'boolean', description: '该店铺是否拉取成功' }, + message: { type: 'string', description: '结果说明 / 失败原因' }, + orders: { type: 'integer', description: '平台返回订单数' }, + created: { type: 'integer', description: '新增订单数' }, + updated: { type: 'integer', description: '更新订单数' }, + skipped: { type: 'integer', description: '跳过(平台已发货)订单数' }, + voided: { type: 'integer', description: '自动作废订单数' }, + items: { type: 'integer', description: '写入明细条数' }, + }, + orderSyncTaskLine: { + id: { type: 'integer', description: '任务ID' }, + principal_id: { type: 'integer', description: '所属主体ID' }, + scope: { type: 'string', description: '拉单范围:external_print' }, + scope_label: { type: 'string', description: '范围中文' }, + status: { type: 'integer', description: '状态:0待处理 1处理中 2已完成 3部分失败 4失败' }, + status_label: { type: 'string', description: '状态中文' }, + start_time: { type: 'string', description: '拉单起始时间' }, + end_time: { type: 'string', description: '拉单结束时间' }, + lookback_days: { type: 'integer', description: '回看天数(0=全部待处理)' }, + total_shops: { type: 'integer', description: '待拉取店铺数' }, + processed_shops: { type: 'integer', description: '已处理店铺数' }, + failed_shops: { type: 'integer', description: '失败店铺数' }, + created_orders: { type: 'integer', description: '新增订单数' }, + updated_orders: { type: 'integer', description: '更新订单数' }, + skipped_orders: { type: 'integer', description: '跳过订单数' }, + voided_orders: { type: 'integer', description: '自动作废订单数' }, + progress: { type: 'integer', description: '进度百分比 0-100' }, + items: { type: 'array', itemType: 'orderSyncTaskShopItem', description: '逐店结果(进度接口返回)' }, + failed_items: { type: 'array', itemType: 'orderSyncTaskShopItem', description: '失败店铺(进度接口返回)' }, + error_message: { type: 'string', description: '整体失败原因' }, + created_by: { type: 'integer', description: '提交人ID' }, + started_at: { type: 'string', description: '开始执行时间' }, + finished_at: { type: 'string', description: '执行结束时间' }, + created_at: { type: 'string', description: '创建时间' }, + updated_at: { type: 'string', description: '更新时间' }, + }, + orderSyncTaskPage: buildPage('orderSyncTaskLine', '拉单任务列表'), + orderSyncTaskListResponse: buildListResponse('orderSyncTaskPage'), }; diff --git a/backend/app/controller/externalPrintAccount.js b/backend/app/controller/externalPrintAccount.js index da4e3e7..6fbb130 100644 --- a/backend/app/controller/externalPrintAccount.js +++ b/backend/app/controller/externalPrintAccount.js @@ -713,7 +713,8 @@ class ExternalPrintAccountController extends Controller { await ctx.service.externalPrintOrder.markShopSynced( shop, new Date(), - `手动拉取成功:${saved.orders} 单,跳过平台已发货 ${saved.skipped || 0} 单,自动作废 ${saved.voided || 0} 单` + `手动拉取成功:${saved.orders} 单,跳过平台已发货 ${saved.skipped || 0} 单,自动作废 ${saved.voided || 0} 单` + + (saved.voidedMissing ? `(其中平台已查不到 ${saved.voidedMissing} 单)` : '') ); ctx.body = { code: 0, @@ -724,6 +725,8 @@ class ExternalPrintAccountController extends Controller { orders: saved.orders, skipped: saved.skipped || 0, voided: saved.voided || 0, + voided_shipped: saved.voidedShipped || 0, + voided_missing: saved.voidedMissing || 0, created: saved.created, updated: saved.updated, items: saved.items, diff --git a/backend/app/controller/externalSendSync.js b/backend/app/controller/externalSendSync.js new file mode 100644 index 0000000..31b6b7c --- /dev/null +++ b/backend/app/controller/externalSendSync.js @@ -0,0 +1,61 @@ +'use strict'; + +const Controller = require('egg').Controller; + +/** + * 外部打单平台「同步发货」相关接口 + * + * 用于配送视图:查看同步数量(异常数量快速展示)、批量重试同步异常/失败的订单。 + * 真正的同步由定时任务 `externalSendSyncWorker` 执行,批量重试会立刻跑一批并返回结果。 + * @controller ExternalSendSyncController + */ +class ExternalSendSyncController extends Controller { + /** + * @summary 同步状态数量 + * @description 返回当前主体下配送订单的外部发货同步数量:待同步 / 待重试 / 异常 / 已同步 / 合计。 + * @router get /api/external-send/counts + * @apikey + * @response 200 externalSendCountsResponse success + */ + async counts() { + const { ctx } = this; + try { + const data = await ctx.service.externalSendSync.counts(ctx.state.principalId); + ctx.body = { code: 0, message: 'success', data }; + } catch (err) { + const status = Number(err && err.status) || 500; + ctx.status = status; + ctx.body = { code: status, message: (err && err.message) || '查询同步数量失败' }; + } + } + + /** + * @summary 批量重试同步外部发货 + * @description 把指定订单(或按状态筛选的订单)重置为「待同步」并立刻同步一批。 + * 不传 ids 时默认重试「异常 + 待重试」的订单;次数会清零重新计数。 + * @router post /api/external-send/retry + * @apikey + * @request body externalSendRetryRequest retryRequest 重试参数 + * @response 200 externalSendRetryResponse success + */ + async retry() { + const { ctx } = this; + const body = ctx.request.body || {}; + const ids = Array.isArray(body.ids) ? body.ids : []; + const statuses = Array.isArray(body.statuses) ? body.statuses.map(Number) : undefined; + try { + const data = await ctx.service.externalSendSync.retry({ + ids, + statuses, + principalId: ctx.state.principalId, + }); + ctx.body = { code: 0, message: 'success', data }; + } catch (err) { + const status = Number(err && err.status) || 500; + ctx.status = status; + ctx.body = { code: status, message: (err && err.message) || '重试同步失败' }; + } + } +} + +module.exports = ExternalSendSyncController; diff --git a/backend/app/controller/openapi.js b/backend/app/controller/openapi.js index 803d198..a4d64b8 100644 --- a/backend/app/controller/openapi.js +++ b/backend/app/controller/openapi.js @@ -78,9 +78,14 @@ class OpenapiController extends Controller { ctx.body = body; ctx.type = 'application/json'; - // 幂等结果落库:同 request_id 重试时直接回放该响应 + // 幂等结果落库:只有成功结果才回放;失败 / 不可回放(占位、部分失败)释放 request_id 供重试 if (result.idempotency) { - await openapiIdempotency.finish(ctx, result.idempotency, { httpStatus, body, ok }); + await openapiIdempotency.finish(ctx, result.idempotency, { + httpStatus, + body, + ok, + replayable: result.replayable !== false, + }); } // 回调日志:请求(query/报文)+ 返回(业务码/报文),未通过 app_key 校验的请求同样记录 @@ -212,7 +217,16 @@ class OpenapiController extends Controller { let handled; try { - handled = await handler(ctx, { api, warehouse, body, query, appKey, method, timestamp }); + handled = await handler(ctx, { + api, + warehouse, + body, + query, + appKey, + method, + timestamp, + requestId: idempotency.requestId, + }); } catch (err) { ctx.logger.error('[openapi] 业务处理异常', err); return { @@ -243,6 +257,8 @@ class OpenapiController extends Controller { ok: true, message: (handled && handled.message) || 'ok', data: handled ? handled.data : null, + // 方法可声明本次结果是否可回放(如取号部分失败/占位响应时不锁定 request_id) + replayable: handled ? handled.replayable : undefined, api, warehouse, ...idemContext, diff --git a/backend/app/controller/orderStatus.js b/backend/app/controller/orderStatus.js index d850595..1130d42 100644 --- a/backend/app/controller/orderStatus.js +++ b/backend/app/controller/orderStatus.js @@ -70,6 +70,7 @@ class OrderStatusController extends Controller { * @request query string archived_from 归档时间起(仅 status=history) * @request query string archived_to 归档时间止(仅 status=history) * @request query integer exclude_unbound 传 1 时排除含未绑定商品明细的订单(前端「查看未绑定商品订单」开关关闭时使用) + * @request query string external_send_status 同步外部发货状态筛选(0待同步 1已同步 2待重试 3异常;多选用逗号分隔,仅配送视图有意义) * @response 200 orderStatusListResponse success */ async index() { @@ -297,9 +298,11 @@ class OrderStatusController extends Controller { } /** - * @summary 取消(待审核 / 异常 / 待推送 / 委外中 → 已取消) - * @description 已推送成功(委外中)的在途订单会先调用 WMS order.cancel 取消外部单据,成功后释放锁定库存再流转; + * @summary 取消(待审核 / 异常 / 待推送 → 已取消;委外中 → 撤单后退回待审核或直接作废) + * @description 已推送成功(委外中)的在途订单会先调用 WMS order.cancel 取消外部单据: + * 平台侧(店管家)已发货/已终结 → 作废;否则换号退回「待审核」。 * 已配送 / 已作废 / 已取消不可取消。 + * 待审核 / 异常 / 待推送:直接 → 已取消(释放锁定库存)。 * @router post /api/order-status/cancel * @apikey * @request body cancelOrderStatusRequest diff --git a/backend/app/controller/orderSyncTask.js b/backend/app/controller/orderSyncTask.js new file mode 100644 index 0000000..edc2634 --- /dev/null +++ b/backend/app/controller/orderSyncTask.js @@ -0,0 +1,101 @@ +'use strict'; + +const { Controller } = require('egg'); +const { parsePagination, buildPageResult } = require('../lib/pagination'); + +/** + * @controller OrderSyncTaskController 拉单任务(异步任务池) + * + * 一键拉取订单:提交(指定范围/回看天数/店铺)→ 立即返回任务ID → 定时任务逐店拉单 → + * 前端轮询进度查看每店结果。所有任务按主体隔离(principal_id 由 principalCheck 写入)。 + */ +class OrderSyncTaskController extends Controller { + /** + * @summary 提交拉单任务 + * @description 落一条「待处理」任务并立即返回任务ID;实际拉取由定时任务异步逐店执行 + * @router post /api/order-sync-tasks + * @apikey + * @request body createOrderSyncTaskRequest *body + * @response 200 baseResponse success + */ + async submit() { + const { ctx } = this; + try { + const task = await ctx.service.orderSyncTask.submit( + ctx.request.body || {}, + ctx.state.principalId, + ctx.userId + ); + ctx.body = { + code: 0, + message: 'success', + data: { + id: Number(task.id), + scope: task.scope, + status: task.status, + total_shops: task.total_shops, + start_time: task.start_time, + end_time: task.end_time, + }, + }; + } catch (err) { + ctx.status = err.status || 500; + ctx.body = { code: err.status || 500, message: err.message }; + } + } + + /** + * @summary 拉单任务列表 + * @router get /api/order-sync-tasks + * @apikey + * @request query integer page 页码 + * @request query integer pageSize 每页条数 + * @request query integer status 按状态筛选(0待处理 1处理中 2已完成 3部分失败 4失败) + * @request query string scope 按范围筛选 + * @response 200 orderSyncTaskListResponse success + */ + async index() { + const { ctx } = this; + const { page, pageSize } = parsePagination(ctx.query); + const { list, total } = await ctx.service.orderSyncTask.list(ctx.state.principalId, { + page, + pageSize, + status: ctx.query.status, + scope: ctx.query.scope, + }); + ctx.body = { code: 0, message: 'success', data: buildPageResult(list, total, { page, pageSize }) }; + } + + /** + * @summary 当前未完成的拉单任务 + * @description 进入页面时恢复进度条用;没有未完成任务时 data 为 null + * @router get /api/order-sync-tasks/running + * @apikey + * @response 200 baseResponse success + */ + async running() { + const { ctx } = this; + const task = await ctx.service.orderSyncTask.runningTask(ctx.state.principalId); + ctx.body = { code: 0, message: 'success', data: task }; + } + + /** + * @summary 拉单任务进度 + * @description 返回进度百分比与逐店结果(items) + * @router get /api/order-sync-tasks/:id + * @apikey + * @response 200 baseResponse success + */ + async progress() { + const { ctx } = this; + const task = await ctx.service.orderSyncTask.progress(Number(ctx.params.id), ctx.state.principalId); + if (!task) { + ctx.status = 404; + ctx.body = { code: 404, message: '任务不存在' }; + return; + } + ctx.body = { code: 0, message: 'success', data: task }; + } +} + +module.exports = OrderSyncTaskController; diff --git a/backend/app/lib/openapiIdempotency.js b/backend/app/lib/openapiIdempotency.js index 132d0aa..6e66702 100644 --- a/backend/app/lib/openapiIdempotency.js +++ b/backend/app/lib/openapiIdempotency.js @@ -89,6 +89,9 @@ function buildReplay(row) { /** * 处理已存在的幂等记录 + * + * 只有「已成功」的记录才回放:失败结果不缓存,允许调用方用同一 request_id 重新处理 + * (取号类接口的重复保护靠业务侧幂等,如订单已有运单号直接复用,而不是锁死请求)。 * @param {Object} ctx egg context * @param {Object} row 幂等记录 * @param {Object} params 参数 @@ -103,16 +106,17 @@ async function handleExisting(ctx, row, { requestId, hash, api, warehouse }) { return { requestId, entry: null, replay: { invalid: true }, hash }; } - if (Number(row.status) === STATUS.SUCCESS || Number(row.status) === STATUS.FAILURE) { + if (Number(row.status) === STATUS.SUCCESS) { return { requestId, entry: row, replay: buildReplay(row), hash }; } const updatedAt = new Date(row.updated_at || row.created_at || Date.now()).getTime(); - if (Date.now() - updatedAt < STALE_MS) { + const finished = Number(row.status) === STATUS.FAILURE; + if (!finished && Date.now() - updatedAt < STALE_MS) { return { requestId, entry: null, replay: { processing: true }, hash }; } - // 异常中断(进程退出等):接管后重新处理 + // 上次失败 / 异常中断(进程退出等):接管后重新处理 await row.update({ status: STATUS.PROCESSING, request_hash: hash, @@ -167,19 +171,33 @@ async function begin(ctx, { appKey, method, body, api, warehouse }) { /** * 记录处理结果(供重试回放) + * + * 仅「成功且可回放」的结果落库;失败或明确不可回放(如占位响应、部分订单失败)时删除占用, + * 让同一 request_id 的下次调用重新执行(取号重复保护由订单级幂等保证)。 * @param {Object} ctx egg context * @param {Object|null} state begin 返回的上下文 * @param {Object} result 结果 * @param {number} result.httpStatus HTTP 状态码 * @param {Object} result.body 完整响应报文 * @param {boolean} result.ok 业务是否成功 + * @param {boolean} [result.replayable] 是否允许回放,默认 true * @return {Promise} 无 */ -async function finish(ctx, state, { httpStatus, body, ok }) { +async function finish(ctx, state, { httpStatus, body, ok, replayable = true }) { if (!state || !state.entry) return; + + if (!ok || !replayable) { + try { + await state.entry.destroy(); + } catch (err) { + ctx.logger.error('[openapi-idempotency] 清除不可回放记录失败:%s', err.message); + } + return; + } + try { await state.entry.update({ - status: ok ? STATUS.SUCCESS : STATUS.FAILURE, + status: STATUS.SUCCESS, http_status: httpStatus, response_body: JSON.stringify(body), }); diff --git a/backend/app/lib/openapiMethods.js b/backend/app/lib/openapiMethods.js index 27315fa..8f18730 100644 --- a/backend/app/lib/openapiMethods.js +++ b/backend/app/lib/openapiMethods.js @@ -134,12 +134,14 @@ const METHODS = { * @param {Object} payload.api 按 app_key 定位到的接口配置 * @param {Object} payload.warehouse 接口配置关联的仓库 * @param {Object} payload.body 批量取号报文 + * @param {string} [payload.requestId] 调用方 request_id(写入取号记录) * @return {Promise} { ok, message, data } */ - 'deliveryorder.getwaybill': (ctx, { api, warehouse, body }) => waybillGet.getWaybills(ctx, { + 'deliveryorder.getwaybill': (ctx, { api, warehouse, body, requestId }) => waybillGet.getWaybills(ctx, { principalId: api.principal_id, warehouseId: warehouse.id, data: body, + requestId, }), /** diff --git a/backend/app/lib/orderCallback.js b/backend/app/lib/orderCallback.js index 2ce5768..25790a5 100644 --- a/backend/app/lib/orderCallback.js +++ b/backend/app/lib/orderCallback.js @@ -1026,6 +1026,10 @@ async function confirmOrderStatusDelivery(ctx, { resolved, payload, packages, li principalId: Number(order.principal_id), }); + // 配送后需要把发货结果同步回外部打单平台(店管家发货接口),这里只标记待同步, + // 真正的调用交给定时任务 externalSendSyncWorker(失败重试 / 转异常都在那边收敛) + await ctx.service.externalSendSync.markPending([ Number(order.id) ], Number(order.principal_id)); + const result = { ...base, status: ORDER_STATUS.DELIVERY, diff --git a/backend/app/lib/orderFields.js b/backend/app/lib/orderFields.js index 5e29eb4..c2f6b74 100644 --- a/backend/app/lib/orderFields.js +++ b/backend/app/lib/orderFields.js @@ -139,6 +139,30 @@ function deliveryLegacyColumns(Sequelize) { }; } +/** + * 外部打单平台「同步发货」状态字段(进入配送后需要把发货结果同步回店管家等平台) + * + * 与 `shop_sync_*`(回传平台店铺)分开:这里是**发货结果**同步, + * 失败按次数重试,超过上限转「异常」等人工批量重试。 + * @param {Object} Sequelize sequelize 构造函数 + * @return {Object} 字段定义 + */ +function externalSendColumns(Sequelize) { + const { STRING, TINYINT, INTEGER, DATE } = Sequelize; + return { + external_send_status: { + type: TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '同步外部发货状态:0待同步 1已同步 2同步失败待重试 3异常(重试超限,等人工处理)', + }, + external_send_times: { type: INTEGER.UNSIGNED, allowNull: false, defaultValue: 0, comment: '同步外部发货已尝试次数' }, + external_send_error: { type: STRING(500), comment: '最近一次同步失败原因' }, + external_send_at: { type: DATE, comment: '最近一次同步尝试时间' }, + external_sent_at: { type: DATE, comment: '同步成功时间' }, + }; +} + /** * 状态表 / 历史表的业务字段(CORE + 两套老表字段 = 老表超集) * @param {Object} Sequelize sequelize 构造函数(模型文件里的 app.Sequelize) @@ -152,6 +176,7 @@ function businessFields(Sequelize, status) { ...coreColumns(Sequelize, status), ...orderLegacyColumns(Sequelize), ...deliveryLegacyColumns(Sequelize), + ...externalSendColumns(Sequelize), created_at: { type: DATE, comment: '创建时间(用于超 3 个月自动归档判断)' }, updated_at: { type: DATE, comment: '更新时间' }, }; @@ -262,6 +287,7 @@ module.exports = { coreColumns, orderLegacyColumns, deliveryLegacyColumns, + externalSendColumns, businessFields, historyFields, itemFields, diff --git a/backend/app/lib/printPlatform/dgj.js b/backend/app/lib/printPlatform/dgj.js index 655528e..e532614 100644 --- a/backend/app/lib/printPlatform/dgj.js +++ b/backend/app/lib/printPlatform/dgj.js @@ -35,6 +35,44 @@ const TEMPLATE_LIST_PATH = '/TemplateSet/LoadTemplateListInOrderList'; /** 面单账号明细接口:查看单个模板对应的电子面单账号 / 网点明细 */ const TEMPLATE_DETAIL_PATH = '/TemplateSet/LoadWaybillAccountDetailInfo'; +/** 取号前校验模板可用性 / 面单余额(只读,不消耗面单) */ +const TEMPLATE_AVAILABLE_PATH = '/TemplateSet/CheckTemplateAvaliable'; + +/** + * 取号接口:一次调用即返回运单号与打印数据,**会真实消耗面单**。 + * 默认开启;需要临时停用时把环境变量 DGJ_WAYBILL_ENABLE 置为 0/false/off。 + */ +const EXPRESS_PRINT_PATH = '/NewOrder/ExpressPrint'; + +/** + * 通知平台发货接口:把 OMS 的发货结果同步回店管家(**不消耗面单**)。 + */ +const ONLINE_SEND_PATH = '/NewOrder/OnlineSendBatch'; + +/** + * 是否允许调用真实取号(默认开启) + * + * 平台配置 `fetch_waybill_no=1` 即表示要回打单平台取号,这里默认放行; + * 仅在需要「只读联调、绝不下单」时用 DGJ_WAYBILL_ENABLE=0 显式关闭。 + * @return {boolean} 是否允许调用 ExpressPrint + */ +function isWaybillEnabled() { + const value = String(process.env.DGJ_WAYBILL_ENABLE == null ? '' : process.env.DGJ_WAYBILL_ENABLE).trim().toLowerCase(); + return !(value === '0' || value === 'false' || value === 'off' || value === 'no'); +} + +/** + * 构造带平台原始返回的错误(供上层写入取号记录留痕) + * @param {string} message 错误提示 + * @param {{status: number, json: Object|null, text: string}} res 平台响应 + * @return {Error} 附带 rawResponse 的错误 + */ +function buildPlatformError(message, res) { + const error = new Error(message); + error.rawResponse = res && res.json ? res.json : { httpStatus: res && res.status, text: res && res.text }; + return error; +} + /** 订单列表单页条数(平台允许 500) */ const ORDER_PAGE_SIZE = 500; @@ -86,6 +124,22 @@ const TEMPLATE_HOST_TYPES = { 'fxtk.dgjapp.com': [ 'KuaiShou' ], }; +/** + * 订单/取号接口域名:与模板域名不同!旧系统 `$this->pingtais` 的口径是 + * 淘宝/1688/视频号/小红书/快手都走 fxali,抖店走 fxdd,拼多多走 fxpdd,京东走 fxjd。 + * 取错域名会查不到订单(实测:视频号订单只在 fxali 能查到)。 + */ +const ORDER_HOSTS = { + pinduoduo: 'fxpdd.dgjapp.com', + toutiao: 'fxdd.dgjapp.com', + douyin: 'fxdd.dgjapp.com', + doudian: 'fxdd.dgjapp.com', + jingdong: 'fxjd.dgjapp.com', + jd: 'fxjd.dgjapp.com', +}; +/** 未命中映射时的订单域名兜底(淘宝/视频号/小红书/快手/1688 等) */ +const ORDER_HOST_FALLBACK = 'fxali.dgjapp.com'; + /** 商品列表单页条数(平台允许 200) */ const PRODUCT_PAGE_SIZE = 200; @@ -136,6 +190,16 @@ function resolveTemplateHost(platformType) { return ''; } +/** + * 按 PlatformType 取订单 / 取号接口域名(与模板域名不同,见 ORDER_HOSTS 说明) + * @param {*} platformType 店管家 PlatformType(如 WxVideo) + * @return {string} 订单接口域名 + */ +function resolveOrderHost(platformType) { + const key = String(platformType == null ? '' : platformType).trim().toLowerCase(); + return ORDER_HOSTS[key] || ORDER_HOST_FALLBACK; +} + /** * 平台侧「已发货 / 已终结」的订单状态(ErpState): * sended=已发货、success=交易成功、close=交易关闭,其余为各平台交易状态的等价写法。 @@ -166,13 +230,30 @@ const FINISHED_ORDER_STATES = [ * @return {boolean} 是否已发货/已终结 */ function isOrderFinished(row) { + return describeFinishedOrder(row).finished; +} + +/** + * 判定平台侧是否已发货/已终结,并给出**可读原因**(用于自动作废备注,便于区分具体依据) + * @param {Object} row 店管家订单原始结构 + * @return {{finished: boolean, reason: string}} finished=是否已处理,reason=命中的具体依据 + */ +function describeFinishedOrder(row) { const data = row || {}; - const state = String(data.ErpState || data.Status || '').trim().toLowerCase(); - if (state && FINISHED_ORDER_STATES.includes(state)) return true; - if (String(data.OnlineSendTime || '').trim()) return true; + const state = String(data.ErpState || data.Status || '').trim(); + const signals = []; + if (state && FINISHED_ORDER_STATES.includes(state.toLowerCase())) { + signals.push(`平台订单状态 ErpState=${state}`); + } + const sendTime = String(data.OnlineSendTime || '').trim(); + if (sendTime) signals.push(`平台已有发货时间 ${sendTime}`); const waybills = Array.isArray(data.WaybillCodes) ? data.WaybillCodes : []; - if (waybills.some(code => code && code.IsSended === true)) return true; - return Number(data.LogisticStatus) > 0; + const sentCount = waybills.filter(code => code && code.IsSended === true).length; + if (sentCount > 0) signals.push(`${sentCount} 个面单包裹已发货`); + const logistic = Number(data.LogisticStatus); + if (logistic > 0) signals.push(`物流状态已推进(LogisticStatus=${logistic})`); + if (!signals.length) return { finished: false, reason: '' }; + return { finished: true, reason: signals.join('、') }; } /** @@ -357,6 +438,236 @@ function resolveOrderSkuId(data) { return ''; } +/** + * 递归收集打印数据里的运单号(旧系统口径:PrintDataList.task.documents[].documentID) + * @param {*} value 已解析的打印数据对象/数组 + * @param {string[]} out 收集结果 + * @return {void} + */ +function collectDocumentIds(value, out) { + if (!value || typeof value !== 'object') return; + if (Array.isArray(value)) { + for (const item of value) collectDocumentIds(item, out); + return; + } + for (const [ key, item ] of Object.entries(value)) { + if ((key === 'documentID' || key === 'DocumentID') && (typeof item === 'string' || typeof item === 'number')) { + const text = String(item).trim(); + if (text) out.push(text); + continue; + } + collectDocumentIds(item, out); + } +} + +/** + * 解析打印数据(字符串或对象),提取运单号 + * @param {*} printInfo 打印数据 + * @return {string[]} 运单号列表 + */ +function extractWaybillsFromPrintInfo(printInfo) { + if (!printInfo) return []; + let parsed = printInfo; + if (typeof printInfo === 'string') { + try { + parsed = JSON.parse(printInfo); + } catch { + return []; + } + } + const out = []; + collectDocumentIds(parsed, out); + return out; +} + +/** + * 从 ExpressPrint 响应的 Data.WaybillCode[] 里提取运单号 + * 兼容:WaybillCode / LogisticCode / MailNo 字段、OrderInfo 嵌套、PrintInfo 里的 documentID + * @param {Array} items Data.WaybillCode 数组 + * @return {string[]} 去重后的运单号 + */ +function extractWaybillCodes(items) { + const out = []; + for (const item of Array.isArray(items) ? items : []) { + if (!item || typeof item !== 'object') continue; + for (const key of [ 'WaybillCode', 'LogisticCode', 'MailNo', 'WaybillNo' ]) { + const value = item[key]; + if (typeof value === 'string' && value.trim()) out.push(value.trim()); + } + const nested = item.OrderInfo && item.OrderInfo.OrderInfo; + if (nested && typeof nested === 'object') { + for (const key of [ 'WaybillCode', 'LastWaybillCode' ]) { + const value = nested[key]; + if (typeof value === 'string' && value.trim()) out.push(value.trim()); + } + } + for (const key of [ 'PrintInfo', 'PrintData' ]) { + out.push(...extractWaybillsFromPrintInfo(item[key])); + } + } + return [ ...new Set(out) ]; +} + +/** + * 取平台返回的打印单据(`Data.PrintDataList.task.documents[]`) + * + * 店管家的 `ExpressPrint` 返回里,运单号在 `Data.WaybillCode[]`,而**面单打印数据在 + * `Data.PrintDataList.task.documents[]`**(`documentID` = 运单号,`printInfo` = 打印数据, + * `contents[]` = 需要加密打印的场景下的 encryptedData / signature / ver)。 + * 一次请求可能返回多个 document(多包裹),这里按运单号匹配,匹配不到取第一个。 + * @param {Object} printed ExpressPrint 响应 + * @param {string} waybillCode 本次运单号 + * @return {Object|null} document 对象,未找到为 null + */ +function firstPrintDocument(printed, waybillCode) { + const documents = printed && printed.Data && printed.Data.PrintDataList && + printed.Data.PrintDataList.task && printed.Data.PrintDataList.task.documents; + const list = Array.isArray(documents) ? documents.filter(doc => doc && typeof doc === 'object') : []; + if (!list.length) return null; + const matched = waybillCode ? list.find(doc => String(doc.documentID || '').trim() === String(waybillCode).trim()) : null; + return matched || list[0]; +} + +/** + * 取第一条打印数据(字符串化,便于原样回传给打印端) + * + * 顺序:`Data.PrintDataList.task.documents[].printInfo`(店管家实际下发的打印数据, + * base64 编码的 URL-encoded JSON,WMS 打印端按原样塞进 `task.printInfo`)→ + * `Data.WaybillCode[].PrintInfo / PrintData / PrintDataJson`(其它平台/旧版返回)。 + * @param {Array} items Data.WaybillCode 数组 + * @param {Object} printed ExpressPrint 响应 + * @param {string} waybillCode 本次运单号 + * @return {string} 打印数据,未找到为空串 + */ +function firstPrintInfo(items, printed, waybillCode) { + const document = firstPrintDocument(printed, waybillCode); + if (document && document.printInfo) { + return typeof document.printInfo === 'string' ? document.printInfo : JSON.stringify(document.printInfo); + } + for (const item of Array.isArray(items) ? items : []) { + const value = item && (item.PrintInfo || item.PrintData || item.PrintDataJson); + if (!value) continue; + return typeof value === 'string' ? value : JSON.stringify(value); + } + return ''; +} + +/** + * 从 document 的 contents[0] 取打印附加信息(旧系统同口径) + * + * 旧系统 `Dianguanjia.php` 取的是 + * `PrintDataList.task.documents[0].contents[0]` 的 `signature` / `encryptedData` / `ver`; + * 视频号等自定义模板场景平台不返回 `contents`,此时三个值都为空串。 + * @param {Object} document 打印单据 + * @return {{signature: string, encryptprintinfo: string, ver: string}} 签名、加密打印数据、版本 + */ +function extractDocumentContents(document) { + const empty = { signature: '', encryptprintinfo: '', ver: '' }; + const contents = document && document.contents; + const first = Array.isArray(contents) ? contents[0] : null; + if (!first || typeof first !== 'object') return empty; + return { + signature: typeof first.signature === 'string' ? first.signature : '', + encryptprintinfo: typeof first.encryptedData === 'string' ? first.encryptedData : '', + ver: first.ver == null ? '' : String(first.ver), + }; +} + +/** + * 构造 `Orders[0][WaybillCodes][]`(平台「新单号打印」请求里带的当前号清单) + * + * 平台前端在重新取号时会把这个订单已有的运单号(含 `WaybillCodeId` / `Pid`)一起回传, + * 平台据此分配**下一个**号(`WaybillCodePid` 的第二段自增)。不传时平台容易直接复用旧号。 + * @param {Object} row 平台订单行(含 WaybillCodes / SubOrders) + * @param {string} templateId 面单模板ID + * @param {string} expressCode 快递编码 + * @return {Array|string} 运单号清单;没有历史号时返回空串(表单里表现为空值) + */ +function buildWaybillCodesBlock(row, templateId, expressCode) { + const list = Array.isArray(row.WaybillCodes) ? row.WaybillCodes.filter(item => item && item.WaybillCode) : []; + if (!list.length) return ''; + const subs = Array.isArray(row.SubOrders) ? row.SubOrders : []; + return list.map(entry => ({ + TemplateId: String(entry.TemplateId || templateId || ''), + TemplateType: entry.TemplateType == null ? '' : entry.TemplateType, + ExpressCpCode: entry.ExpressCpCode || expressCode || '', + ExpressName: entry.ExpressName || '', + WaybillCode: entry.WaybillCode, + ChildWaybillCode: '', + ChildWaybillCodes: '', + CompanyCode: entry.CompanyCode || entry.ExpressCpCode || expressCode || '', + WaybillCodeId: entry.WaybillCodeId == null ? '' : entry.WaybillCodeId, + CreateDate: entry.CreateDate || '', + IsSended: entry.IsSended === true, + TotalWeight: 0, + SendType: 0, + Status: entry.Status == null ? 1 : entry.Status, + Pid: entry.Pid || '', + WaybillCodeOrderProducts: subs.map(sub => ({ + MasterId: `${row.Id}_${entry.WaybillCode}_iD`, + OrderItemId: sub.OrderItemId, + OrderItemIdStr: sub.OrderItemId, + Quantity: 1, + OrderItemCode: sub.OrderItemCode, + WaybillCodeId: entry.WaybillCodeId == null ? '' : entry.WaybillCodeId, + })), + })); +} + +/** + * 按 PHP `http_build_query` 口径把对象展开成表单 + * + * 店管家(ASP.NET MVC)按 PHP 风格的嵌套键解析表单:数组元素是 + * `orders[0][SourceShopId]=...`,**不是** `orders[0]={"SourceShopId":...}`。 + * 用 JSON 字符串提交会被平台判为参数缺失(表现为「打印校验失败,系统异常」)。 + * + * 取值口径与 PHP 一致:`null/undefined` → 空串;`true` → `1`;`false` → 空串; + * 空数组/空对象 → 空串;数字/字符串 → 原样。 + * @param {Object} data 表单数据(可含嵌套对象/数组) + * @return {URLSearchParams} 可直接作为 x-www-form-urlencoded body + */ +function buildPhpForm(data) { + const form = new URLSearchParams(); + + /** + * 递归写入一个值 + * @param {*} value 值 + * @param {string} key 字段名(含嵌套括号) + * @return {void} + */ + const walk = (value, key) => { + if (value === null || value === undefined) { + form.append(key, ''); + return; + } + if (typeof value === 'boolean') { + form.append(key, value ? '1' : ''); + return; + } + if (Array.isArray(value)) { + if (!value.length) { + form.append(key, ''); + return; + } + value.forEach((item, index) => walk(item, `${key}[${index}]`)); + return; + } + if (typeof value === 'object') { + const keys = Object.keys(value); + if (!keys.length) { + form.append(key, ''); + return; + } + for (const childKey of keys) walk(value[childKey], `${key}[${childKey}]`); + return; + } + form.append(key, String(value)); + }; + + for (const [ key, value ] of Object.entries(data || {})) walk(value, key); + return form; +} + /** * 店管家(dgj)外部打单平台服务。 * @@ -688,6 +999,8 @@ class DgjService extends PrintPlatformService { shop_id: toNumber(data.ShopId), shop_name: truncate(data.ShopName, 128), dbname: truncate(target.dbname, 128), + // 菜鸟授权网点ID:同平台下不同授权网点取值不同,取号时随结果回给 WMS 便于分店/多网点归集 + cai_niao_auth_info_id: toNumber(data.CaiNiaoAuthInfoId), platform_updated_at: parseOrderTime(data.UpdateDate), raw: data, }; @@ -773,7 +1086,7 @@ class DgjService extends PrintPlatformService { TemplateId: String(item.template_id || ''), ShopId: String(item.shop_id == null ? '' : item.shop_id), ExpressCompanyId: String(item.express_company_id == null ? '' : item.express_company_id), - CaiNiaoAuthInfoId: String(raw.CaiNiaoAuthInfoId || ''), + CaiNiaoAuthInfoId: String(raw.CaiNiaoAuthInfoId || (item.cai_niao_auth_info_id || '')), platformType, FxPageType: '2', }); @@ -1255,10 +1568,15 @@ class DgjService extends PrintPlatformService { const order = this.normalizeOrder(row); if (!order.external_order_id) continue; // 平台已发货/已终结:不进待审核,只登记给上层用于作废本地未处理的副本 - if (isOrderFinished(row)) { + // (带上命中的具体依据,作废备注里直接写明「平台订单状态 ErpState=sended」之类) + const finishedDetail = describeFinishedOrder(row); + if (finishedDetail.finished) { finished.set(order.external_order_id, { external_order_id: order.external_order_id, + platform_order_no: order.platform_order_no, platform_status: order.platform_status, + place_order_time: order.external_created_at, + reason: finishedDetail.reason, }); continue; } @@ -1618,13 +1936,523 @@ class DgjService extends PrintPlatformService { } /** - * 店管家取号尚未接入:平台配置 fetch_waybill_no = 0,等待平台取号接口确认后实现 - * @param {Object} order 订单数据 - * @param {Object} [options] 取号上下文(template / expressCode / platformCode) - * @return {Promise} 固定抛错 + * 店管家取号(Old 系统 Dianguanjia.php#ExpressPrint 同口径) + * + * 流程:回读平台订单行 → 已发货/已终结拦截 → + * CheckTemplateAvaliable(模板/余额)→ ExpressPrint(取号 + 打印数据)。 + * + * **不做「平台已有运单号就复用」的判断**:是否算重复调用只由幂等表 + * (`openapi_request_idempotency`,按 request_id)决定;平台订单行上的 `LastWaybillCode` + * 只用于诊断(判断是否真换了号),不参与取号决策。 + * ⚠️ ExpressPrint 会真实消耗面单:默认开启,需要「只读联调」时用 DGJ_WAYBILL_ENABLE=0 关闭。 + * @param {Object} order OMS 订单(order_no / parent_order_no / oaid_order_source_code / place_order_time) + * @param {Object} options 取号上下文 + * @param {Object} options.template 已绑定的快递接口记录(template_id / platform_type / dbname / raw) + * @param {number} [options.packageIndex] 包裹序号(0 基):>0 目前不支持,会直接报错(见下) + * @param {number} [options.packageCount] 包裹张数(默认 1):>1 时同一次请求取多张面单 + * @return {Promise<{waybill_code: string, waybill_codes: string[], printinfo: string, signature: string, previous_code: string, raw: Object}>} 取号结果 */ - async fetchWaybillNo(order, options = {}) { // eslint-disable-line no-unused-vars - throw new Error('店管家取号未接入(fetch_waybill_no=0),请先确认平台取号接口'); + async fetchWaybillNo(order, options = {}) { + if (!this.token || !this.cookie) throw new Error('店管家账号未登录:缺少 token 或 cookie,请先登录'); + + const template = options.template || {}; + const templateId = String(template.template_id || (template.raw && template.raw.Id) || '').trim(); + if (!templateId) throw new Error('取号缺少面单模板ID:请先在「外部打单平台 → 快递接口」为编码绑定模板'); + + // 订单/取号走「订单域名」,与模板域名不同(视频号订单只在 fxali 能查到) + const host = resolveOrderHost(template.platform_type); + + let traceId = ''; + try { + const info = await this.getUserInfo(); + traceId = (info.data && info.data.TraceId) || ''; + } catch { + // 忽略:traceId 缺失不阻断取号(与模板查询同口径) + } + + const dbname = String(template.dbname || '').trim(); + const logicalOrderId = String(order.parent_order_no || String(order.order_no || '').replace(/^[^-]+-/, '')).trim(); + const platformOrderId = String((order.extend_props && order.extend_props.platform_order_no) || order.oaid_order_source_code || '').trim(); + if (!logicalOrderId) throw new Error('订单缺少店管家系统编号(parent_order_no),无法取号'); + + const row = await this.findPlatformOrderRow(host, { + traceId, + dbname, + logicalOrderId, + platformOrderId, + placeOrderTime: order.place_order_time || order.pay_time || order.created_at, + }); + if (!row) throw new Error(`店管家未找到订单:系统编号 ${logicalOrderId}(域名 ${host})`); + + // 平台侧已发货/已终结:不能再取号,也不能把旧运单号当成取号成功(该单应作废/取消) + if (isOrderFinished(row)) { + const codeText = row.LastWaybillCode ? `,平台运单号 ${row.LastWaybillCode}` : ''; + throw new Error(`订单在店管家已发货或已终结(ErpState=${row.ErpState || '-'}${codeText}),取号失败:请作废或取消该单,不要再发货`); + } + + // 平台已取号但未发货:不再复用。重复调用是否要拦,由幂等表(request_id)负责; + // 这里只在结果里带上原来的号码,便于判断这次到底有没有换号。 + const previousCode = String(row.LastWaybillCode || '').trim(); + + // 多包裹 / 子单:每次调用都走「新单号打印」,平台会分配一个新号, + // 所以 WMS 按包裹各调一次即可(packageIndex 无需下发给平台)。 + if (!isWaybillEnabled()) { + throw new Error('店管家真实取号已关闭(DGJ_WAYBILL_ENABLE=0):当前只做只读校验,不会调用平台取号;需要真实取号请去掉该环境变量或置为 1'); + } + + const runPrint = async () => { + const check = await this.checkTemplateAvailable(host, { traceId, dbname, templateId, rows: [ row ] }); + const balance = Number(check && check.Data && check.Data.Balance); + const needCount = Number(check && check.Data && check.Data.PrintCount); + if (Number.isFinite(balance) && Number.isFinite(needCount) && balance < needCount) { + throw new Error('店管家面单余额不足,请充值后再取号'); + } + return await this.expressPrint(host, { + traceId, + dbname, + templateId, + rows: [ row ], + checkData: check && check.Data, + packageCount: Number(options.packageCount || 1), + expressCode: String(options.expressCode || '').trim(), + }); + }; + + let printed; + try { + printed = await runPrint(); + } catch (err) { + // 账号在别处重新登录会把这里的 token 顶掉(平台返回 401):重新登录后重试一次 + if (!/登录已失效|登录信息过期/.test(String(err && err.message))) throw err; + await this.loginByPassword(); + printed = await runPrint(); + } + const items = Array.isArray(printed && printed.Data && printed.Data.WaybillCode) ? printed.Data.WaybillCode : []; + + const errorItem = items.find(item => item && (item.IsError === true || Number(item.IsError) === 1)); + if (errorItem) { + const reason = errorItem.ErrorMsg || errorItem.Message || (errorItem.OrderInfo && errorItem.OrderInfo.ErrorMsg) || '平台返回取号失败'; + throw buildPlatformError(`店管家取号失败:${reason}`, { status: 200, json: printed, text: '' }); + } + + const waybillCodes = extractWaybillCodes(items); + if (!waybillCodes.length) { + throw buildPlatformError('店管家未返回运单号:请检查模板与订单状态,或查看原始响应', { status: 200, json: printed, text: '' }); + } + + const document = firstPrintDocument(printed, waybillCodes[0]); + const contents = extractDocumentContents(document); + return { + waybill_code: waybillCodes[0], + waybill_codes: waybillCodes, + // 面单打印数据:原样透传(WMS 打印端直接塞进 task.printInfo) + printinfo: firstPrintInfo(items, printed, waybillCodes[0]), + signature: contents.signature, + encryptprintinfo: contents.encryptprintinfo, + ver: contents.ver, + // 取号前后对比用的旧号码(不参与判断,只用于提示「平台仍返回原运单号」) + previous_code: previousCode, + raw: printed, + }; + } + + /** + * 按系统编号 / 平台单号回读店管家订单行(取号请求需要完整的订单结构) + * + * 优先按字段精确过滤(实测 `LogicOrderId` 可直接命中),失败时按订单创建时间窗扫描 + * (`NewOrder/List` 的 Filters 依赖平台内部查询实现,时间窗是更稳的兜底)。 + * @param {string} host 订单接口域名 + * @param {Object} options 查询参数 + * @param {string} options.traceId 登录上下文 traceId + * @param {string} options.dbname 分区库名 + * @param {string} options.logicalOrderId 店管家系统编号 + * @param {string} [options.platformOrderId] 店管家订单编号 + * @param {Date|string} [options.placeOrderTime] 订单下单时间(兜底扫描的时间窗基准) + * @return {Promise} 订单行,未找到为 null + */ + async findPlatformOrderRow(host, { traceId, dbname, logicalOrderId, platformOrderId, placeOrderTime }) { + const candidates = []; + if (logicalOrderId) candidates.push([ 'LogicOrderId', logicalOrderId, false ]); + if (platformOrderId && platformOrderId !== logicalOrderId) candidates.push([ 'PlatformOrderId', platformOrderId, true ]); + + for (const [ field, value, customQuery ] of candidates) { + const rows = await this.fetchOrderRows(host, { traceId, dbname, field, value, customQuery }); + if (!rows.length) continue; + const hit = rows.find(row => String(row.LogicOrderId || '') === String(logicalOrderId)) || rows[0]; + return hit; + } + + // 兜底:按下单时间窗口扫描(±2 天),再按系统编号匹配 + const base = placeOrderTime ? new Date(placeOrderTime) : new Date(); + if (Number.isNaN(base.getTime())) return null; + const startTime = new Date(base.getTime() - 2 * 24 * 3600 * 1000); + const endTime = new Date(base.getTime() + 2 * 24 * 3600 * 1000); + const rows = await this.fetchOrderPages(host, { traceId, dbname, startTime, endTime }); + return rows.find(row => String(row.LogicOrderId || '') === String(logicalOrderId)) || null; + } + + /** + * 按单个字段精确过滤订单列表 + * @param {string} host 平台域名 + * @param {Object} options 查询参数 + * @param {string} options.traceId 登录上下文 traceId + * @param {string} options.dbname 分区库名 + * @param {string} options.field 过滤字段(LogicOrderId / PlatformOrderId) + * @param {string} options.value 过滤值 + * @param {boolean} [options.customQuery] 是否附加平台自定义查询(PlatformOrderId 需要) + * @return {Promise} 订单行 + */ + async fetchOrderRows(host, { traceId, dbname, field, value, customQuery = false }) { + const query = new URLSearchParams({ + token: this.token, + traceId: traceId || '', + dbname: dbname || '', + dataFlag: '', + }); + + const form = new URLSearchParams(); + form.append('Filters[0][TableAlias]', 'o'); + form.append('Filters[0][FieldType]', 'string'); + form.append('Filters[0][TableName]', 'LogicOrder'); + form.append('Filters[0][Name]', field); + form.append('Filters[0][Value]', String(value)); + form.append('Filters[0][Contract]', 'in'); + if (customQuery) form.append('Filters[0][CustomQuery]', 'PlatformOrderIdSearch'); + form.set('IsOrderDesc', 'true'); + form.set('OrderByField', 'o.CreateTime'); + form.set('IsPdd', 'false'); + form.set('PageSize', '20'); + form.set('PageIndex', '1'); + form.set('isFilterDangerChar', 'false'); + form.set('TarType', ''); + form.set('requestUrl', `https://${host}/NewOrder/WaitOrder`); + form.set('IsCustomerOrder', 'false'); + form.set('FxPageType', '2'); + + const headers = { + accept: 'application/json, text/javascript, */*; q=0.01', + 'accept-language': 'zh-CN,zh;q=0.9', + 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8', + referer: `https://${host}/NewOrder/WaitOrder`, + 'user-agent': BROWSER_HEADERS['user-agent'], + 'x-requested-with': 'XMLHttpRequest', + }; + if (this.cookie) headers.cookie = this.cookie; + + const res = await this.request(`https://${host}${ORDER_LIST_PATH}?${query.toString()}`, { + method: 'POST', + headers, + body: form.toString(), + }); + if (res.status === 401) { + throw new Error(`店管家登录已失效:${(res.json && res.json.Message) || 'token is invalid'}`); + } + if (!res.json || res.json.Success !== true) { + const reason = (res.json && (res.json.Message || res.json.ErrorCode)) || `HTTP ${res.status}`; + throw new Error(`查询店管家订单失败:${reason}`); + } + const data = res.json.Data || {}; + return Array.isArray(data.Rows) ? data.Rows : []; + } + + /** + * 取号前校验模板可用性与面单余额(只读,与旧系统 TemplateSet/CheckTemplateAvaliable 同口径) + * @param {string} host 平台域名 + * @param {Object} options 参数 + * @param {string} options.traceId 登录上下文 traceId + * @param {string} options.dbname 分区库名 + * @param {string} options.templateId 面单模板ID + * @param {Array} options.rows 平台订单行 + * @return {Promise} 平台响应(Data.DateNow / DayPrintBatchNumber / Branches / Balance / PrintCount) + */ + async checkTemplateAvailable(host, { traceId, dbname, templateId, rows }) { + const items = (rows || []).map(row => ({ + SourceShopId: row.ShopId, + UpFxUserId: row.FxUserId, + SourceFxUserId: row.FxUserId, + LogicOrderId: row.LogicOrderId, + PlatformOrderId: row.LogicOrderId, + IsAllowNegativeStock: 'false', + SendType: row.SendState, + DataFlag: row.IsCold, + Items: (Array.isArray(row.SubOrders) ? row.SubOrders : []).map(sub => ({ + OrderItemCode: sub.OrderItemCode, + LogicOrderItemId: sub.OrderItemId, + Quantity: '1', + })), + })); + + const form = buildPhpForm({ + templateId: String(templateId), + printCount: String(items.length), + needCheck: 'true', + orders: items, + isResend: '', + pirntMethod: 'Normal', + IsContinueForStock: 'false', + IsCustomerOrder: 'false', + FxPageType: '2', + }); + + const res = await this.postPlatformForm(host, TEMPLATE_AVAILABLE_PATH, form, traceId, dbname); + if (!res.json || res.json.Success !== true) { + const reason = (res.json && (res.json.Message || res.json.ErrorCode)) || `HTTP ${res.status}`; + // 附带平台原始返回,便于取号记录留痕与排错 + throw buildPlatformError(`店管家模板校验失败:${reason}`, res); + } + return res.json; + } + + /** + * 取号(同时返回打印数据):**真实消耗面单**,仅供 fetchWaybillNo 在开关打开后调用 + * @param {string} host 平台域名 + * @param {Object} options 参数 + * @param {string} options.traceId 登录上下文 traceId + * @param {string} options.dbname 分区库名 + * @param {string} options.templateId 面单模板ID + * @param {Array} options.rows 平台订单行 + * @param {Object} [options.checkData] CheckTemplateAvaliable 返回的 Data(DateNow / DayPrintBatchNumber / Branches) + * @param {number} [options.packageCount] 包裹张数(默认 1):>1 时把同一订单行重复 N 份 + * @param {string} [options.expressCode] 快递编码(仅用于回传 WaybillCodes 时补 ExpressCpCode) + * @return {Promise} 平台响应(Data.WaybillCode[] 含运单号与打印数据) + */ + async expressPrint(host, { traceId, dbname, templateId, rows, checkData, packageCount = 1, expressCode = '' }) { + const data = checkData || {}; + const repeat = Number.isFinite(Number(packageCount)) && Number(packageCount) > 1 ? Math.floor(Number(packageCount)) : 1; + const currentWaybillCode = (() => { + const row = (rows || [])[0] || {}; + const list = Array.isArray(row.WaybillCodes) ? row.WaybillCodes.filter(item => item && item.WaybillCode) : []; + return String(row.LastWaybillCode || (list[list.length - 1] || {}).WaybillCode || '').trim(); + })(); + const branches = Array.isArray(data.Branches) ? data.Branches.map(branch => { + const copy = { ...branch }; + for (const key of Object.keys(copy)) { + if (copy[key] === null) copy[key] = ''; + else if (copy[key] === false) copy[key] = 'false'; + else if (copy[key] === true) copy[key] = 'true'; + } + return copy; + }) : ''; + + // 多包裹:同一订单行重复 N 份,Index 依次 1..N(平台按包裹各分配一个运单号) + const sourceRows = []; + for (let i = 0; i < repeat; i += 1) sourceRows.push(...(rows || [])); + + const orders = sourceRows.map((row, index) => { + const items = []; + const orderItems = []; + for (const sub of Array.isArray(row.SubOrders) ? row.SubOrders : []) { + items.push({ + OrderItemId: sub.OrderItemId, + OrderItemCode: sub.OrderItemCode, + Quantity: '1', + ShortTitle: sub.ShortTitle, + SkuCode: sub.SkuCode, + ProductCode: sub.ProductCode, + }); + orderItems.push(sub.OrderItemId); + } + return { + WaybillCodeId: '', + Index: index + 1, + Id: row.Id, + IdStr: row.Id, + PlatformOrderId: row.LogicOrderId, + LogicOrderId: row.LogicOrderId, + PathFlowCode: row.PathFlowCode, + CustomerOrderId: row.PlatformOrderId, + ShopId: row.ShopId, + // 与平台前端一致:PrintInfo 传 `[1];\n`(第 1 份) + PrintInfo: '[1];\n', + OrderItems: orderItems, + Items: items, + OrderItemStrList: orderItems, + // 新单号打印:把当前号(含 Pid/WaybillCodeId)带给平台,平台据此分配下一个号 + WaybillCode: currentWaybillCode, + WaybillCodes: buildWaybillCodesBlock(row, templateId, expressCode), + NewSellerRemark: '', + PrintRemark: '', + NewPrintRemark: '', + SellerRemark: row.SellerRemark, + BuyerRemark: row.BuyerRemark, + FxUserId: row.FxUserId, + IsSelectAllNotPrintedItem: '1', + SendType: '0', + DataFlag: row.IsCold, + Receiver: { + toFullName: row.ToName, + toMobile: row.ToPhone, + toArea: row.ToFullAddress, + toProvince: row.ToProvince, + toCity: row.ToCity, + toCounty: row.ToCounty, + toMaskAddress: `${row.ToTown || ''}${row.ToAddress || ''}`, + }, + Sender: { CompanyName: '' }, + Buyer: { BuyerWangWang: row.ToName }, + }; + }); + + const form = buildPhpForm({ + TemplateId: String(templateId), + PackageCount: String(repeat), + PackageDesc: '', + GoodsDesc: '', + PrintMethod: 'NewPrint', + // 关键:false + NewPrint = 「新单号打印」(每次分配新号);true/Normal 会被平台复用旧号 + IsIgnoreWaybillRepeat: 'false', + PrinterName: '默认打印机', + IsPreview: 'false', + IsContinueForStock: 'false', + PackageLength: '', + PackageWidth: '', + PackageHeight: '', + PackageType: '1', + ExpressSustenance: { name: '', desc: '' }, + Branches: Array.isArray(branches) ? branches : '', + Orders: orders, + RequestBatchNumber: `1/1/${data.DateNow || ''}${data.DayPrintBatchNumber || ''}`, + IsCustomerOrder: 'false', + FxPageType: '2', + }); + + const res = await this.postPlatformForm(host, EXPRESS_PRINT_PATH, form, traceId, dbname); + if (!res.json || res.json.Success !== true) { + const reason = (res.json && (res.json.Message || res.json.ErrorCode)) || `HTTP ${res.status}`; + // 附带平台原始返回(含 PrintInfo / WaybillCode 等),便于取号记录留痕与排错 + throw buildPlatformError(`店管家取号请求失败:${reason}`, res); + } + return res.json; + } + + /** + * 通知平台发货(旧系统 `Dianguanjia.php#OnlineSendBatch` 同口径) + * + * WMS 回传 `deliveryorder.confirm`、OMS 流转到「配送」后,需要把发货结果同步回店管家, + * 平台才会把订单状态推进为「已发货」。走**订单域名**(`fxali` / `fxdd` / `fxpdd` / `fxjd`)。 + * @param {string} host 订单接口域名 + * @param {Object} options 参数 + * @param {string} options.traceId 登录上下文 traceId + * @param {string} options.dbname 分区库名 + * @param {Array} options.rows 平台订单行(含 SubOrders / LastWaybillCode / WaybillCodes) + * @return {Promise} 平台响应 + */ + async sendOrders(host, { traceId, dbname, rows }) { + const orders = (rows || []).map((row, index) => { + const items = []; + const orderItems = []; + for (const sub of Array.isArray(row.SubOrders) ? row.SubOrders : []) { + items.push({ + OrderItemId: sub.OrderItemId, + OrderItemCode: sub.OrderItemCode, + Quantity: '1', + ShortTitle: sub.ShortTitle, + }); + orderItems.push(sub.OrderItemId); + } + const firstWaybill = (Array.isArray(row.WaybillCodes) ? row.WaybillCodes : []).find(code => code && code.WaybillCode) || {}; + return { + Id: row.Id, + Index: index + 1, + WaybillCodeId: '', + LogicOrderId: row.LogicOrderId, + OrderCode: row.OrderCode, + PlatformOrderId: row.LogicOrderId, + PathFlowCode: row.PathFlowCode, + CustomerOrderId: row.PlatformOrderId, + PlatformType: row.PlatformType, + PlatformStatus: 'waitsellersend', + RefunStatus: '', + FxUserId: row.FxUserId, + BuyerRemark: row.BuyerRemark, + SellerRemark: row.SellerRemark, + UpFxUserId: row.FxUserId, + IsPddCrossBorderOrder: row.IsPddCrossBorderOrder === true, + IsPddCourierDoorToDoorCollect: row.IsPddCourierDoorToDoorCollect === true, + ReceiverIsChange: row.ReceiverIsChange === true, + PrintState: row.PrintState, + SubOrders: row.SubOrders, + IsOfflineOrder: row.IsOfflineOrder === true, + PublishTime: row.PublishTime, + IsSelectAllNotPrintedItem: 1, + WaybillCode: row.LastWaybillCode || firstWaybill.WaybillCode || '', + ExpressCompanyCode: firstWaybill.ExpressCpCode || '', + weight: 0, + WaybillCodeUniqueKey: firstWaybill.UniqueKey || '', + OrderItems: orderItems, + NoPrintFlag: 'false', + Items: items, + SendType: '0', + DataFlag: row.DataFlag, + Receiver: { + toFullName: row.ToName, + toMobile: row.ToPhone, + toArea: row.ToFullAddress, + toProvince: row.ToProvince, + toCity: row.ToCity, + toCounty: row.ToCounty, + toMaskAddress: row.ToAddress, + }, + Sender: { CompanyName: '' }, + Buyer: { BuyerWangWang: '' }, + }; + }); + + const form = buildPhpForm({ + Orders: orders, + IsCustomerOrder: 'false', + FxPageType: '2', + IsSendPreCheck: 'true', + IsContinueForStock: 'false', + NoLogisticsInfoModel: '', + }); + + const res = await this.postPlatformForm(host, ONLINE_SEND_PATH, form, traceId, dbname); + if (res.status === 401) { + throw buildPlatformError(`店管家登录已失效:${(res.json && res.json.Message) || 'token is invalid'}`, res); + } + if (!res.json || res.json.Success !== true) { + const reason = (res.json && (res.json.Message || res.json.ErrorCode)) || `HTTP ${res.status}`; + throw buildPlatformError(`店管家发货同步失败:${reason}`, res); + } + return res.json; + } + + /** + * 统一提交平台表单(token/traceId/dbname 走 query,表单走 body) + * @param {string} host 平台域名 + * @param {string} path 接口路径 + * @param {URLSearchParams} form 表单 + * @param {string} traceId 登录上下文 traceId + * @param {string} dbname 分区库名 + * @return {Promise<{status: number, json: Object|null, text: string}>} 响应 + */ + async postPlatformForm(host, path, form, traceId, dbname) { + const query = new URLSearchParams({ + token: this.token, + traceId: traceId || '', + dbname: dbname || '', + dataFlag: '', + }); + const headers = { + accept: 'application/json, text/javascript, */*; q=0.01', + 'accept-language': 'zh-CN,zh;q=0.9', + 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8', + referer: `https://${host}/NewOrder/WaitOrder`, + 'user-agent': BROWSER_HEADERS['user-agent'], + 'x-requested-with': 'XMLHttpRequest', + }; + if (this.cookie) headers.cookie = this.cookie; + + const res = await this.request(`https://${host}${path}?${query.toString()}`, { + method: 'POST', + headers, + body: form.toString(), + }); + if (res.status === 401) { + throw new Error(`店管家登录已失效:${(res.json && res.json.Message) || 'token is invalid'}`); + } + return res; } /** @@ -1644,6 +2472,99 @@ class DgjService extends PrintPlatformService { static resolveOrderPlatform(platformType) { return resolveOrderPlatform(platformType); } + + /** + * 判定平台订单是否已发货/已终结,并给出可读依据(供上层拼接自动作废备注) + * @param {Object} row 店管家订单原始结构 + * @return {{finished: boolean, reason: string}} 判定结果与依据 + */ + static describeFinishedOrder(row) { + return describeFinishedOrder(row); + } + + /** + * 只读查询平台订单状态(审核前校验「平台是否已发货/已终结」、取号前回读订单行) + * @param {Object} params 参数 + * @param {string} params.platformType 店管家 PlatformType(如 WxVideo) + * @param {string} [params.dbname] 分区库名,缺省按分区接口解析 + * @param {string} params.logicalOrderId 店管家系统编号 + * @param {string} [params.platformOrderId] 店管家订单编号 + * @param {Date|string} [params.placeOrderTime] 下单时间(兜底扫描窗口) + * @return {Promise} 平台订单行 + */ + async fetchPlatformOrder({ platformType, dbname, logicalOrderId, platformOrderId, placeOrderTime }) { + if (!logicalOrderId) return null; + const host = resolveOrderHost(platformType); + let traceId = ''; + try { + const info = await this.getUserInfo(); + traceId = (info.data && info.data.TraceId) || ''; + } catch { + // 忽略:traceId 缺失不阻断查询 + } + + let area = String(dbname || '').trim(); + if (!area) { + const areas = await this.listProductAreas(host); + area = (areas.find(item => item && item.dbname) || {}).dbname || ''; + } + return await this.findPlatformOrderRow(host, { traceId, dbname: area, logicalOrderId, platformOrderId, placeOrderTime }); + } + + /** + * 按系统预设平台编码(SPH/TB/...)推断店管家 PlatformType + * @param {string} platformCode 系统预设平台编码 + * @return {string} 店管家 PlatformType,未知返回空串 + */ + static resolvePlatformType(platformCode) { + const map = { + SPH: 'WxVideo', + TB: 'Taobao', + TM: 'Tmall', + DYXD: 'TouTiao', + PDD: 'Pinduoduo', + JD: 'JingDong', + KS: 'KuaiShou', + XHS: 'XiaoHongShu', + 1688: 'Alibaba', + }; + return map[ String(platformCode || '').trim().toUpperCase() ] || ''; + } + + /** + * 店管家 PlatformType 对应的接口域名(供脚本/调试工具复用) + * @param {string} platformType 店管家 PlatformType(如 WxVideo / TouTiao) + * @return {string} 域名,未知返回空串 + */ + static resolveTemplateHost(platformType) { + return resolveTemplateHost(platformType); + } + + /** + * 店管家 PlatformType 对应的订单/取号域名(与模板域名不同) + * @param {string} platformType 店管家 PlatformType(如 WxVideo) + * @return {string} 域名 + */ + static resolveOrderHost(platformType) { + return resolveOrderHost(platformType); + } + + /** + * 是否允许真实取号(默认开启,DGJ_WAYBILL_ENABLE=0 关闭) + * @return {boolean} 是否允许 + */ + static isWaybillEnabled() { + return isWaybillEnabled(); + } + + /** + * 构造店管家表单(PHP http_build_query 口径,嵌套用括号) + * @param {Object} data 表单数据 + * @return {URLSearchParams} 表单 + */ + static buildForm(data) { + return buildPhpForm(data); + } } module.exports = DgjService; diff --git a/backend/app/lib/waybillGet.js b/backend/app/lib/waybillGet.js index e12511d..eecd95e 100644 --- a/backend/app/lib/waybillGet.js +++ b/backend/app/lib/waybillGet.js @@ -3,6 +3,7 @@ const orderCallback = require('./orderCallback'); const { ORDER_STATUS } = require('./orderStatus'); const { getShopBasic } = require('./externalPrintConfig'); +const { platformNameOf } = require('./platformCode'); /** 单号候选字段(与 deliveryorder.confirm 同口径,支持嵌套) */ const CODE_PATHS = [ @@ -37,6 +38,22 @@ const WAYBILL_KEYS = [ 'express_code', ]; +/** 包裹序号候选字段(WMS 拆单/多包裹时显式指定,0 基,优先生效) */ +const PACKAGE_INDEX_PATHS = [ + 'packageIndex', + 'package_index', + 'packageNo', + 'package_no', + 'waybillIndex', + 'waybill_index', +]; + +/** 包裹序号候选字段(WMS 侧的 business_key,1 基,会转成 0 基) */ +const BUSINESS_KEY_PATHS = [ + 'businessKey', + 'business_key', +]; + /** 单次批量上限(避免一次回调过大、平台侧限流) */ const MAX_BATCH = 100; @@ -98,6 +115,47 @@ function pickExpressCode(item) { return orderCallback.pickFirst(item || {}, EXPRESS_CODE_PATHS); } +/** + * 从发货单号尾部取包裹/子单序号(0 基) + * + * 店管家订单的 OMS 单号形如 `dgj-<系统编号>_1`、`_2`…,尾部数字即该单在拆单后的序号(1 基)。 + * 打单平台按 `_<序号0基>` 分配运单号,所以这里统一转成 0 基再下发; + * 非店管家单号(其它平台/手工单)或没有序号时一律按第 1 个包裹(0)处理。 + * @param {string} code 发货单号 + * @return {number} 包裹序号(0 基) + */ +function resolvePackageIndex(code) { + const text = String(code || '').trim(); + if (!/^dgj-/i.test(text)) return 0; + const matched = text.match(/_(\d+)$/); + if (!matched) return 0; + const seq = Number(matched[1]); + return Number.isFinite(seq) && seq > 0 ? seq - 1 : 0; +} + +/** + * 取 WMS 报文里显式指定的包裹序号(0 基,拆单/多包裹时用) + * + * 优先读 `packageIndex`(0 基);没有时读 WMS 原生的 `businessKey`(1 基,转 0 基)。 + * WMS 侧同一个 OMS 单号拆成多个包裹时,`deliveryOrderCode` 不变、只有 `business_key` 变, + * 所以必须由报文带过来,否则各包裹都会落到序号 0、拿回同一个运单号。 + * @param {Object} item 订单项 + * @return {number|null} 包裹序号;未指定返回 null + */ +function pickPackageIndex(item) { + const raw = orderCallback.pickFirst(item || {}, PACKAGE_INDEX_PATHS); + if (raw !== undefined && raw !== null && raw !== '') { + const value = Number(raw); + return Number.isFinite(value) && value >= 0 ? Math.floor(value) : null; + } + const businessKey = orderCallback.pickFirst(item || {}, BUSINESS_KEY_PATHS); + if (businessKey !== undefined && businessKey !== null && businessKey !== '') { + const value = Number(businessKey); + return Number.isFinite(value) && value > 0 ? Math.floor(value) - 1 : null; + } + return null; +} + /** * 递归提取平台返回的运单号(兼容字符串 / 数组 / 常见字段名) * @param {*} value 平台返回值 @@ -173,21 +231,110 @@ function fail(code, message) { } /** - * 订单已有运单号时的结果(重试 / 不同 request_id 重复取号都直接复用,避免重复请求平台) - * @param {string} code 单号 - * @param {string} expressCode WMS 传入的快递编码 - * @param {Object} order 订单 - * @return {Object} 成功结果 + * 组装「未绑定到快递接口」的简短提示 + * + * 两个分支: + * 1. 快递编码在「系统快递公司」和「自定义快递编码」里都不存在 → 提示去新增编码; + * 2. 编码存在但该账号该平台没绑定 → `平台SPH(视频号)快递STO(申通)在账号xxx下未绑定到快递接口,请到 OMS 店铺管理→外部打单平台→快递接口 绑定` + * 平台/快递优先显示中文名,查不到名称时只显示编码。 + * @param {Object} ctx egg context + * @param {Object} params 参数 + * @param {Object} params.account 打单账号(含 platform) + * @param {string} params.platformCode 订单来源平台编码 + * @param {string} params.expressCode WMS 传入的快递编码 + * @param {number} params.principalId 主体ID + * @return {Promise} 提示信息 */ -function existingWaybillResult(code, expressCode, order) { - return { - delivery_order_code: code, - success: true, - message: '已取号,返回已有运单号', - express_code: expressCode, - waybill_code: order.express_code, - waybill_codes: Array.isArray(order.express_codes) ? order.express_codes : [ order.express_code ], - }; +async function buildTemplateMissingMessage(ctx, { account, platformCode, expressCode, principalId }) { + const platformLabel = labelWithName(platformCode, platformNameOf(platformCode)); + const { name: expressName, exists: expressExists, disabled: expressDisabled } = await findExpressCode(ctx, expressCode, principalId); + const expressLabel = labelWithName(expressCode, expressName); + const accountText = account.account ? `账号${account.account}` : `账号#${account.id}`; + const head = `平台${platformLabel}快递${expressLabel}在${accountText}下未绑定到快递接口,请到 OMS 店铺管理→外部打单平台→快递接口 查看绑定对应的快递接口`; + + // 快递编码在系统字典与自定义字典里都没有:先让运营把编码建出来(否则绑定页也选不到它) + if (!expressExists) { + if (expressDisabled) { + return `快递编码${expressCode}已停用,请到 OMS 系统管理→自定义快递编码 启用后再重试`; + } + return `快递编码${expressCode}不存在(系统快递编码与自定义快递编码均无此编码),请到 OMS 系统管理→自定义快递编码 新增后再重试`; + } + + let rows = []; + try { + rows = await ctx.model.ExternalPrintExpressInterface.findAll({ + where: { principal_id: principalId, account_id: account.id, platform_code: platformCode, status: 1 }, + attributes: [ 'id', 'express_company_code', 'custom_code' ], + limit: 50, + }); + } catch (err) { + return head; + } + + if (!rows.length) return `${head}(该平台暂无面单模板,请先点「从平台同步数据」)`; + + // 同一编码被多个模板绑定 → resolveByCode 视为未命中 + const duplicated = rows.filter(row => String(row.custom_code || '').trim() === expressCode); + if (duplicated.length > 1) { + return `平台${platformLabel}快递${expressLabel}在${accountText}下绑定了 ${duplicated.length} 个快递接口,请到 OMS 店铺管理→外部打单平台→快递接口 只保留一个后重试`; + } + + const codeKey = String(expressCode).trim().toUpperCase(); + const hasSameCompany = rows.some(row => String(row.express_company_code || '').trim().toUpperCase() === codeKey); + if (!hasSameCompany) return `${head}(该平台暂无对应快递公司的模板,请先点「从平台同步数据」)`; + return head; +} + +/** + * 编码 + 中文名(有名称时 `STO(申通)`,没有名称只返回编码) + * @param {string} code 编码 + * @param {string} [name] 中文名 + * @return {string} 展示文本 + */ +function labelWithName(code, name) { + const text = String(name || '').trim(); + return text && text !== code ? `${code}(${text})` : String(code); +} + +/** + * 查快递编码:先查自定义快递编码字典(全局),再查系统快递公司字典 + * @param {Object} ctx egg context + * @param {string} expressCode 快递编码 + * @param {number} principalId 主体ID(自定义编码为全局字典,仅保留签名兼容) + * @return {Promise<{name: string, exists: boolean, disabled: boolean}>} 中文名(查不到为空串)、是否存在、是否已停用 + */ +async function findExpressCode(ctx, expressCode, principalId) { // eslint-disable-line no-unused-vars + const code = String(expressCode || '').trim(); + if (!code) return { name: '', exists: false, disabled: false }; + try { + // 自定义字典:不过滤状态,便于区分「不存在」与「已停用」 + const custom = await ctx.model.CustomExpressCode.findOne({ + where: { code }, + attributes: [ 'name', 'status' ], + }); + if (custom) { + return { + name: custom.name || '', + exists: Number(custom.status) === 1, + disabled: Number(custom.status) !== 1, + }; + } + } catch (err) { + // 字典缺失时继续走系统字典 + } + try { + const system = await ctx.model.ExpressCompany.findOne({ where: { code }, attributes: [ 'name', 'status' ] }); + if (system) { + return { + name: system.name || '', + exists: Number(system.status) === 1, + disabled: Number(system.status) !== 1, + }; + } + } catch (err) { + return { name: '', exists: false, disabled: false }; + } + return { name: '', exists: false, disabled: false }; } /** @@ -220,6 +367,47 @@ async function loadAccountModel(ctx, memo, accountId, principalId) { return await promise; } +/** + * 取号留痕:把本次取号拿到的平台原始返回(含 printinfo / signature)写入 waybill_fetch_records + * + * 只在「已定位到打单账号」之后调用(真正接触平台的单才留痕,避免报文类失败刷表); + * 写入失败只告警,绝不影响取号结果。 + * @param {Object} ctx egg context + * @param {Object} meta 本次取号的上下文(主体/仓库/单号/编码/账号/模板) + * @param {Object} result 逐单结果 + * @param {Object} [extra] 平台返回的补充数据 + * @param {string} [extra.raw] 平台原始返回 + * @param {string} [extra.printinfo] 面单打印数据 + * @param {string} [extra.signature] 面单签名 + * @return {Promise} 无返回值 + */ +async function saveRecord(ctx, meta, result, extra = {}) { + if (!meta || !meta.accountId) return; + const raw = extra.raw; + try { + await ctx.model.WaybillFetchRecord.create({ + principal_id: meta.principalId, + warehouse_id: meta.warehouseId || null, + request_id: meta.requestId || '', + delivery_order_code: meta.code, + express_code: meta.expressCode || '', + platform_code: meta.platformCode || '', + account_id: meta.accountId || null, + template_id: meta.templateId || '', + status: result && result.success ? 1 : 0, + waybill_source: (result && result.waybill_source) || '', + waybill_code: (result && result.waybill_code) || '', + waybill_codes: result && result.waybill_codes ? JSON.stringify(result.waybill_codes) : '', + printinfo: extra.printinfo || '', + signature: extra.signature || '', + raw_response: raw ? JSON.stringify(raw) : '', + error_message: result && result.success ? '' : (result && result.message) || '', + }); + } catch (err) { + ctx.logger.warn('[waybill.get] 写取号记录失败 %s:%s', meta.code, err.message); + } +} + /** * 处理单个订单取号 * @param {Object} ctx egg context @@ -228,9 +416,10 @@ async function loadAccountModel(ctx, memo, accountId, principalId) { * @param {number} params.warehouseId app_key 定位到的仓库ID * @param {Object} params.item 订单项(含单号与快递编码) * @param {Map} params.memo 批内缓存(账号实例等) + * @param {string} [params.requestId] 调用方 request_id(留痕用) * @return {Promise} 结果项 */ -async function processItem(ctx, { principalId, warehouseId, item, memo }) { +async function processItem(ctx, { principalId, warehouseId, item, memo, requestId }) { const code = orderCallback.pickFirst(item || {}, CODE_PATHS); if (!code) return fail('', '缺少发货单号(deliveryOrderCode / outBizCode)'); @@ -238,6 +427,29 @@ async function processItem(ctx, { principalId, warehouseId, item, memo }) { const expressCode = pickExpressCode(item); if (!expressCode) return fail(code, '缺少快递编码(expressCode)'); + // 留痕上下文:处理过程中逐步补齐(平台编码 / 打单账号 / 模板) + const meta = { principalId, warehouseId, requestId, code, expressCode, platformCode: '', accountId: null, templateId: null }; + const detail = { raw: null, printinfo: '', signature: '', encryptprintinfo: '', ver: '' }; + const result = await callPlatform(ctx, { principalId, warehouseId, code, expressCode, item, memo, meta, detail }); + await saveRecord(ctx, meta, result, detail); + return result; +} + +/** + * 单订单取号主流程(结果由 processItem 统一留痕) + * @param {Object} ctx egg context + * @param {Object} params 参数 + * @param {number} params.principalId 主体ID + * @param {number} params.warehouseId 仓库ID + * @param {string} params.code 发货单号 + * @param {string} params.expressCode 快递编码 + * @param {Object} params.item 订单项(可带 packageIndex 指定包裹序号) + * @param {Map} params.memo 批内缓存 + * @param {Object} params.meta 留痕上下文(会被补齐) + * @param {Object} params.detail 平台返回数据(raw / printinfo / signature) + * @return {Promise} 结果项 + */ +async function callPlatform(ctx, { principalId, warehouseId, code, expressCode, item, memo, meta, detail }) { try { const resolved = await orderCallback.resolveDeliveryBill(ctx, { code, principalId }); const order = resolved.order; @@ -251,31 +463,32 @@ async function processItem(ctx, { principalId, warehouseId, item, memo }) { if (resolved.isNewModel) { const status = resolved.index.current_status; if (BLOCKED_STATUS_LABELS[status]) return fail(code, BLOCKED_STATUS_LABELS[status]); - // 已有运单号:直接复用(幂等),不再请求平台 - if (order.express_code) return existingWaybillResult(code, expressCode, order); - if (status === ORDER_STATUS.DELIVERY) return fail(code, '订单已配送但没有运单号'); + if (status === ORDER_STATUS.DELIVERY) return fail(code, '订单已配送,取号失败'); } else { const status = Number(order.status); if (status === 9) return fail(code, BLOCKED_STATUS_LABELS[ORDER_STATUS.CANCELED]); if (status === 5) return fail(code, BLOCKED_STATUS_LABELS[ORDER_STATUS.VOID]); - if (order.express_code) return existingWaybillResult(code, expressCode, order); - if (status === 4) return fail(code, '订单已完成但没有运单号'); + if (status === 4) return fail(code, '订单已完成,取号失败'); } // 平台信息必须回读订单(订单来自哪个平台) const platformCode = String(order.source_platform_code || '').trim(); if (!platformCode) return fail(code, '订单缺少来源平台,无法匹配快递接口'); + meta.platformCode = platformCode; // 打单账号:订单店铺 → 外部打单账号(跨打单平台无法取号) // 店铺与账号平台配置走缓存,避免一批 100 单反复查同一份配置 if (!order.shop_id) return fail(code, '订单未关联店铺,无法确定打单账号'); const shop = await getShopBasic(ctx, order.shop_id, principalId); if (!shop || Number(shop.type) !== 2 || !shop.external_print_account_id) { - return fail(code, '订单未关联外部打单账号,无法取号'); + return fail(code, '订单未关联外部打单账号,无法取号:请确认订单店铺为「外部打单平台商家」且已同步打单账号'); } const account = await loadAccountModel(ctx, memo, shop.external_print_account_id, principalId); - if (!account || !account.platform) return fail(code, '外部打单账号或平台配置不存在'); + if (!account || !account.platform) { + return fail(code, '外部打单账号或平台配置不存在:请到「外部打单平台」检查该账号是否被删除、是否已关联平台'); + } + meta.accountId = account.id; // 按「账号 + 订单平台 + WMS 传入的快递编码」定位唯一模板 const template = await ctx.service.externalPrintExpressInterface.resolveByCode( @@ -284,41 +497,80 @@ async function processItem(ctx, { principalId, warehouseId, item, memo }) { principalId ); if (!template) { - return fail(code, `未找到匹配的快递接口(平台 ${platformCode},编码 ${expressCode})`); + return fail(code, await buildTemplateMissingMessage(ctx, { + account, + platformCode, + expressCode, + principalId, + })); } const platformService = ctx.service.externalPrintOrder.createPlatformService(account); if (!platformService.needFetchWaybillNo) { - return fail(code, `打单平台「${account.platform.name}」未开启取号`); + return fail(code, `打单平台「${account.platform.name}」未开启回平台取号:请在平台配置中开启 fetch_waybill_no 后重试`); } + meta.templateId = String(template.template_id || (template.raw && template.raw.Id) || ''); + // 菜鸟授权网点ID:随取号结果回给 WMS(同平台不同网点取号用的授权不同) + const caiNiaoAuthInfoId = template.cai_niao_auth_info_id == null ? null : Number(template.cai_niao_auth_info_id); const orderPlain = order.get ? order.get({ plain: true }) : { ...order }; + // 包裹序号:报文显式指定优先(拆单场景),否则按单号尾部 `_N` 推导 + const explicitIndex = pickPackageIndex(item); + const packageIndex = explicitIndex === null ? resolvePackageIndex(code) : explicitIndex; const fetched = await platformService.fetchWaybillNo(orderPlain, { template: template.get ? template.get({ plain: true }) : template, expressCode, platformCode, + packageIndex, }); const waybill = normalizeWaybill(fetched); if (!waybill.waybill_code) return fail(code, '平台未返回运单号'); - // 回写运单号(不覆盖订单上的物流编码/名称) - await order.update({ - express_code: waybill.waybill_code, - express_codes: waybill.waybill_codes, - }); + // 面单打印数据原样保留:既要透传给 WMS,也要落取号记录备查 + detail.raw = fetched && fetched.raw ? fetched.raw : null; + detail.printinfo = String((fetched && fetched.printinfo) || ''); + detail.signature = String((fetched && fetched.signature) || ''); + detail.encryptprintinfo = String((fetched && fetched.encryptprintinfo) || ''); + detail.ver = String((fetched && fetched.ver) || ''); - ctx.logger.info('[waybill.get] 取号成功', { code, expressCode, platformCode, waybillCode: waybill.waybill_code }); + // 取号结果只回给调用方(WMS 自行落单),不写回 OMS 订单表: + // 现阶段取号与订单表不做关联,需要重测时无需清理订单上的运单号 + const previousCode = String((fetched && fetched.previous_code) || '').trim(); + const message = previousCode && previousCode === waybill.waybill_code + ? `已取号:本次调用平台取号,但平台仍返回原运单号 ${previousCode}(平台按「${orderPlain.parent_order_no || orderPlain.order_no}_${packageIndex}」复用该包裹的运单号)` + : 'ok'; + ctx.logger.info('[waybill.get] 取号成功', { + code, + expressCode, + platformCode, + waybillCode: waybill.waybill_code, + printinfoLength: detail.printinfo.length, + }); return { delivery_order_code: code, success: true, - message: 'ok', + message, + // 运单号来源:现阶段一律为 express_print(本次向打单平台取号,不再复用平台已有运单号) + waybill_source: 'express_print', express_code: expressCode, platform_code: platformCode, waybill_code: waybill.waybill_code, waybill_codes: waybill.waybill_codes, + // 本次取号对应的包裹序号(0 基):平台按 _<序号> 分配/复用运单号 + package_index: packageIndex, + // 菜鸟授权网点ID(模板绑定的授权网点,平台 CaiNiaoAuthInfoId) + cai_niao_auth_info_id: caiNiaoAuthInfoId, + // 面单打印数据:平台原样返回,WMS 落 order_express 后打印时直接使用 + printinfo: detail.printinfo, + signature: detail.signature, + // 需要加密打印的平台(如菜鸟系)才有值,店管家视频号自定义模板一般为空 + encryptprintinfo: detail.encryptprintinfo, + ver: detail.ver, }; } catch (err) { ctx.logger.warn('[waybill.get] 取号失败 %s:%s', code, err.message); + // 平台异常时保留原始返回,便于在取号记录里看到平台到底回了什么 + if (err && err.rawResponse) detail.raw = err.rawResponse; return fail(code, err.message || '取号失败'); } } @@ -328,15 +580,18 @@ async function processItem(ctx, { principalId, warehouseId, item, memo }) { * * WMS 发起取号时携带快递编码,OMS 回读订单信息(平台 / 店铺 / 打单账号)后按 * 「账号 + 平台 + 编码」定位快递接口并调用平台取号;逐单返回成功/失败,不影响其它订单。 - * 订单已取消 / 已作废 / 已归档时返回该单取号失败。 + * 订单已取消 / 已作废 / 已归档 / 已配送时返回该单取号失败。 + * **取号结果不回写订单表**(现阶段取号与订单表不做关联,由 WMS 自行落单); + * 每次取号的平台原始返回(含 printinfo / signature)写入 waybill_fetch_records 留痕。 * @param {Object} ctx egg context * @param {Object} payload 调用上下文 * @param {number} payload.principalId 主体ID * @param {number} payload.warehouseId app_key 定位到的仓库ID * @param {Object} payload.data 回调报文 + * @param {string} [payload.requestId] 调用方 request_id(写入取号记录,便于按批排查) * @return {Promise<{ok: boolean, message: string, data?: Object}>} 批量结果 */ -async function getWaybills(ctx, { principalId, warehouseId, data }) { +async function getWaybills(ctx, { principalId, warehouseId, data, requestId }) { const body = unwrapBody(data); const items = extractItems(body); if (!items.length) { @@ -349,11 +604,20 @@ async function getWaybills(ctx, { principalId, warehouseId, data }) { // 同一批内按账号缓存完整账号实例(含 cookie/token,供平台客户端直接使用), // 一次批量回调通常只涉及 1 个打单账号,避免逐单重复查库 const memo = new Map(); - const results = await mapLimit(items, CONCURRENCY, item => processItem(ctx, { principalId, warehouseId, item, memo })); + const results = await mapLimit(items, CONCURRENCY, item => processItem(ctx, { + principalId, + warehouseId, + item, + memo, + requestId, + })); const success = results.filter(row => row.success).length; return { ok: true, message: 'ok', + // 有订单没取到号时不锁定 request_id:调用方用同一 request_id 重试会整批重跑, + // 已取到号的单会复用打单平台订单上的运单号(不重复消耗面单),只补真正失败的单 + replayable: success === results.length, data: { total: results.length, success, @@ -367,5 +631,7 @@ module.exports = { getWaybills, extractItems, pickExpressCode, + pickPackageIndex, + resolvePackageIndex, normalizeWaybill, }; diff --git a/backend/app/lib/wms/qimenClient.js b/backend/app/lib/wms/qimenClient.js index 24ed7c4..021fdf5 100644 --- a/backend/app/lib/wms/qimenClient.js +++ b/backend/app/lib/wms/qimenClient.js @@ -556,6 +556,9 @@ class QimenWmsClient { const warehouse = opts.warehouse && opts.warehouse.get ? opts.warehouse.get({ plain: true }) : (opts.warehouse || {}); const wmsItemIdByProduct = opts.wmsItemIdByProduct || {}; const wmsItemIdByItemCode = opts.wmsItemIdByItemCode || {}; + // OMS 商品信息(product_id → { item_code, item_name }):明细上的 item_code/name 可能是 + // 拉单时的平台原值(绑定系统商品后未回写),推送必须以系统商品为准 + const productById = opts.productById || {}; const deliveryOrder = { deliveryOrderCode: o.delivery_order_code || '', @@ -629,10 +632,18 @@ class QimenWmsClient { deliveryOrder.extendProps = o.extend_props; } + // 上游平台单号(店管家「订单编号」PlatformOrderId):WMS 用它做上游订单关联/展示; + // 明细行上的 sourceOrderCode 必须是平台单号,不能是 OMS / 店管家的内部系统编号 + const upstreamOrderCode = o.oaid_order_source_code + || (o.extend_props && typeof o.extend_props === 'object' ? o.extend_props.platform_order_no : '') + || ''; + const orderLineList = (items || []).map((it, idx) => { const i = it.get ? it.get({ plain: true }) : it; const product = i.product && i.product.get ? i.product.get({ plain: true }) : (i.product || {}); const productId = i.product_id != null ? Number(i.product_id) : (product.id != null ? Number(product.id) : null); + // 绑定系统商品的明细:编码/名称一律用系统商品,避免把平台编码(如 10000202451115)推给仓库 + const bound = productId != null ? productById[productId] : null; // itemId 优先取明细自带的 WMS 商品ID,其次按商品编码/OMS 商品ID 回查 warehouse_products.wms_item_id const mappedItemId = (i.item_code && wmsItemIdByItemCode[i.item_code]) || (productId != null ? wmsItemIdByProduct[productId] : undefined); @@ -640,8 +651,8 @@ class QimenWmsClient { const line = { orderLineNo: String(i.order_line_no == null || i.order_line_no === '' ? idx + 1 : i.order_line_no), - itemCode: i.item_code || product.item_code || '', - itemName: i.item_name || product.item_name || '', + itemCode: (bound && bound.item_code) || product.item_code || i.item_code || '', + itemName: (bound && bound.item_name) || product.item_name || i.item_name || '', planQty: Number(i.plan_qty) || 0, actualPrice: i.actual_price != null && i.actual_price !== '' ? Number(i.actual_price) : 0, retailPrice: i.retail_price != null && i.retail_price !== '' ? Number(i.retail_price) : 0, @@ -650,7 +661,9 @@ class QimenWmsClient { // itemId 与 itemCode 二选一:有 WMS 内部商品ID 时一并下发,命中率更高 if (itemId != null && !isNaN(itemId)) line.itemId = itemId; if (i.ext_code) line.extCode = i.ext_code; - if (i.source_order_code) line.sourceOrderCode = i.source_order_code; + // 平台单号优先(明细上的 source_order_code 存的是店管家系统编号,不能当作平台单号下发) + const lineSourceOrderCode = upstreamOrderCode || i.source_order_code || ''; + if (lineSourceOrderCode) line.sourceOrderCode = lineSourceOrderCode; if (i.sub_source_order_code) line.subSourceOrderCode = i.sub_source_order_code; if (i.stock_id) line.stockId = Number(i.stock_id); if (i.extend_props && typeof i.extend_props === 'object' && !Array.isArray(i.extend_props)) { diff --git a/backend/app/model/externalPrintExpressInterface.js b/backend/app/model/externalPrintExpressInterface.js index 942f935..97e1457 100644 --- a/backend/app/model/externalPrintExpressInterface.js +++ b/backend/app/model/externalPrintExpressInterface.js @@ -28,6 +28,7 @@ module.exports = app => { shop_id: { type: BIGINT.UNSIGNED, comment: '平台店铺ID' }, shop_name: { type: STRING(128), comment: '平台店铺名称' }, dbname: { type: STRING(128), comment: '拉取时使用的分区库名' }, + cai_niao_auth_info_id: { type: BIGINT.UNSIGNED, comment: '菜鸟授权网点ID(平台模板 CaiNiaoAuthInfoId)' }, custom_code: { type: STRING(50), comment: '绑定的快递编码(系统或自定义),回读时按账号+平台+编码定位' }, status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1有效 0失效' }, platform_updated_at: { type: DATE, comment: '平台侧更新时间' }, diff --git a/backend/app/model/orderSyncTask.js b/backend/app/model/orderSyncTask.js new file mode 100644 index 0000000..bb837c7 --- /dev/null +++ b/backend/app/model/orderSyncTask.js @@ -0,0 +1,49 @@ +'use strict'; + +/** + * 拉单任务模型,对应 order_sync_tasks。 + * + * 全局异步任务池:前端提交「拉取订单」→ 落一条待处理任务并立即返回任务ID → + * 定时任务(orderSyncWorker)认领后逐店拉单并实时写回进度 → 前端轮询展示。 + * + * 与 export_tasks 的区别:本表按「店铺」维度推进(total_shops / processed_shops), + * 逐店结果存 items(JSON 数组),便于直接展示每个店铺的拉单结果与失败原因。 + * @param {Egg.Application} app egg application + * @return {object} orderSyncTask model + */ +module.exports = app => { + const { BIGINT, STRING, TINYINT, INTEGER, JSON: JsonType, DATE } = app.Sequelize; + + const OrderSyncTask = app.model.define('order_sync_task', { + id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' }, + principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' }, + scope: { type: STRING(30), allowNull: false, defaultValue: 'external_print', comment: '拉单范围:external_print=外部打单平台店铺' }, + status: { type: TINYINT, allowNull: false, defaultValue: 0, comment: '状态:0待处理 1处理中 2已完成 3部分失败 4失败' }, + start_time: { type: DATE, comment: '拉单起始时间' }, + end_time: { type: DATE, comment: '拉单结束时间' }, + lookback_days: { type: INTEGER, comment: '回看天数(0=全部待处理)' }, + shop_ids: { type: JsonType, comment: '指定店铺ID数组;空表示按范围匹配全部' }, + total_shops: { type: INTEGER, allowNull: false, defaultValue: 0, comment: '待拉取店铺数' }, + processed_shops: { type: INTEGER, allowNull: false, defaultValue: 0, comment: '已处理店铺数' }, + failed_shops: { type: INTEGER, allowNull: false, defaultValue: 0, comment: '失败店铺数' }, + created_orders: { type: INTEGER, allowNull: false, defaultValue: 0, comment: '新增订单数' }, + updated_orders: { type: INTEGER, allowNull: false, defaultValue: 0, comment: '更新订单数' }, + skipped_orders: { type: INTEGER, allowNull: false, defaultValue: 0, comment: '跳过(平台已发货)订单数' }, + voided_orders: { type: INTEGER, allowNull: false, defaultValue: 0, comment: '自动作废订单数(合计)' }, + voided_shipped_orders: { type: INTEGER, allowNull: false, defaultValue: 0, comment: '自动作废中「平台已发货/已终结」的订单数' }, + voided_missing_orders: { type: INTEGER, allowNull: false, defaultValue: 0, comment: '自动作废中「平台已查不到」的订单数' }, + progress: { type: TINYINT, allowNull: false, defaultValue: 0, comment: '进度百分比 0-100' }, + items: { type: JsonType, comment: '逐店结果 JSON 数组' }, + error_message: { type: STRING(500), comment: '整体失败原因' }, + created_by: { type: BIGINT.UNSIGNED, comment: '提交人ID' }, + started_at: { type: DATE, comment: '开始执行时间' }, + finished_at: { type: DATE, comment: '执行结束时间' }, + created_at: { type: DATE, comment: '创建时间' }, + updated_at: { type: DATE, comment: '更新时间' }, + }, { + tableName: 'order_sync_tasks', + comment: '拉单异步任务', + }); + + return OrderSyncTask; +}; diff --git a/backend/app/model/waybillFetchRecord.js b/backend/app/model/waybillFetchRecord.js new file mode 100644 index 0000000..8cb062b --- /dev/null +++ b/backend/app/model/waybillFetchRecord.js @@ -0,0 +1,41 @@ +'use strict'; + +/** + * 取号明细记录模型,对应 waybill_fetch_records。 + * + * 每次 `deliveryorder.getwaybill` 逐单取号(成功/复用/失败)都写一条,保存打单平台的原始返回, + * 以及需要透传给 WMS 的 `printinfo / signature`。 + * 仅做留痕,不参与业务状态流转(取号与订单表暂不关联)。 + * @param {Egg.Application} app egg application + * @return {object} waybillFetchRecord model + */ +module.exports = app => { + const { BIGINT, STRING, TINYINT, TEXT, DATE } = app.Sequelize; + + const WaybillFetchRecord = app.model.define('waybill_fetch_record', { + id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' }, + principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '主体ID(来自 app_key)' }, + warehouse_id: { type: BIGINT.UNSIGNED, comment: '仓库ID(来自 app_key)' }, + request_id: { type: STRING(100), comment: '调用方 request_id' }, + delivery_order_code: { type: STRING(100), allowNull: false, comment: 'OMS 发货单号' }, + express_code: { type: STRING(50), comment: '本次取号的快递编码' }, + platform_code: { type: STRING(50), comment: '订单来源平台编码' }, + account_id: { type: BIGINT.UNSIGNED, comment: '外部打单账号ID' }, + template_id: { type: STRING(100), comment: '面单模板ID' }, + status: { type: TINYINT, allowNull: false, defaultValue: 0, comment: '状态:1成功 0失败' }, + waybill_source: { type: STRING(20), comment: '运单号来源:express_print / platform_last' }, + waybill_code: { type: STRING(100), comment: '主运单号' }, + waybill_codes: { type: TEXT, comment: '全部运单号(JSON 数组)' }, + printinfo: { type: TEXT('medium'), comment: '面单打印数据(平台原样返回)' }, + signature: { type: TEXT('medium'), comment: '面单签名(平台原样返回)' }, + raw_response: { type: TEXT('medium'), comment: '平台原始返回(JSON)' }, + error_message: { type: TEXT, comment: '失败原因' }, + created_at: { type: DATE, comment: '创建时间' }, + updated_at: { type: DATE, comment: '更新时间' }, + }, { + tableName: 'waybill_fetch_records', + comment: '取号明细记录(平台原始返回留痕)', + }); + + return WaybillFetchRecord; +}; diff --git a/backend/app/router.js b/backend/app/router.js index a254178..ad7656d 100644 --- a/backend/app/router.js +++ b/backend/app/router.js @@ -101,6 +101,10 @@ module.exports = app => { router.delete('/api/order-status/:id', jwtAuth, principalCheck(), controller.orderStatus.destroy); router.post('/api/order-status/:id/push-wms', jwtAuth, principalCheck(), controller.orderStatus.pushWms); + // 外部打单平台同步发货(配送后把发货结果同步回店管家):数量统计 / 批量重试 + router.get('/api/external-send/counts', jwtAuth, principalCheck(), controller.externalSendSync.counts); + router.post('/api/external-send/retry', jwtAuth, principalCheck(), controller.externalSendSync.retry); + // 以下资源均归属某个主体,需做主体校验与数据隔离,防止跨主体操作 // 商品批量导入:模板下载与导入接口需在 resources 之前注册,避免被 /:id 误匹配 router.get('/api/products/import-template', jwtAuth, principalCheck(), controller.product.importTemplate); @@ -242,6 +246,13 @@ module.exports = app => { router.get('/api/export-tasks/:id', jwtAuth, principalCheck({ model: 'ExportTask' }), controller.exportTask.progress); router.get('/api/export-tasks/:id/download', jwtAuth, principalCheck({ model: 'ExportTask' }), controller.exportTask.download); + // 拉单任务(异步任务池):一键拉取外部打单平台店铺订单,定时任务逐店执行,前端轮询进度 + // 注意:/running 必须在 /:id 之前注册,避免被当成任务ID + router.post('/api/order-sync-tasks', jwtAuth, principalCheck(), controller.orderSyncTask.submit); + router.get('/api/order-sync-tasks', jwtAuth, principalCheck(), controller.orderSyncTask.index); + router.get('/api/order-sync-tasks/running', jwtAuth, principalCheck(), controller.orderSyncTask.running); + router.get('/api/order-sync-tasks/:id', jwtAuth, principalCheck({ model: 'OrderSyncTask' }), controller.orderSyncTask.progress); + // 文件资源:check/upload 需登录并按主体隔离;raw 为公开读取(URL 含内容 hash,不可枚举) // raw 通配路由需在 resources('files') 之前注册,避免被 /api/files/:id 误匹配 router.post('/api/files/check', jwtAuth, principalCheck(), controller.file.check); diff --git a/backend/app/schedule/externalSendSyncWorker.js b/backend/app/schedule/externalSendSyncWorker.js new file mode 100644 index 0000000..53d5379 --- /dev/null +++ b/backend/app/schedule/externalSendSyncWorker.js @@ -0,0 +1,35 @@ +'use strict'; + +/** + * 同步外部打单平台发货:每 2 分钟扫描一次「待同步 / 失败待重试」的配送单。 + * + * 失败逐单累计次数,达到上限(3 次)转「异常」等人工批量重试; + * 用模块级 running 标记避免同进程叠加执行(单批最多 50 单,平台调用是网络请求)。 + */ +let running = false; + +module.exports = { + schedule: { + cron: '0 */2 * * * *', + type: 'worker', + disable: false, + }, + + /** + * 执行一轮 + * @param {Egg.Context} ctx egg context + * @return {Promise} 无返回值 + */ + async task(ctx) { + if (running) return; + running = true; + try { + const result = await ctx.service.externalSendSync.syncPending({ limit: 50 }); + if (result.total) ctx.logger.info('[external-send] 本轮同步结果 %j', result); + } catch (err) { + ctx.logger.error('[external-send] 调度执行失败', err); + } finally { + running = false; + } + }, +}; diff --git a/backend/app/schedule/fetchExternalShopOrders.js b/backend/app/schedule/fetchExternalShopOrders.js index be4a216..46e71d9 100644 --- a/backend/app/schedule/fetchExternalShopOrders.js +++ b/backend/app/schedule/fetchExternalShopOrders.js @@ -95,11 +95,13 @@ module.exports = { shop, now, `自动拉取成功:${result.orders} 单(新增 ${result.created},更新 ${result.updated}),明细 ${result.items} 条` + - `,跳过平台已发货 ${result.skipped || 0} 单,自动作废 ${result.voided || 0} 单` + `,跳过平台已发货 ${result.skipped || 0} 单,自动作废 ${result.voided || 0} 单` + + (result.voidedMissing ? `(其中平台已查不到 ${result.voidedMissing} 单)` : '') ); fetched++; ctx.logger.info( - `[external-order-fetch] 店铺 ${shop.id} 拉单成功:订单 ${result.orders},明细 ${result.items},跳过已发货 ${result.skipped || 0},作废 ${result.voided || 0}` + `[external-order-fetch] 店铺 ${shop.id} 拉单成功:订单 ${result.orders},明细 ${result.items},跳过已发货 ${result.skipped || 0},` + + `作废 ${result.voided || 0}(已发货 ${result.voidedShipped || 0}、查不到 ${result.voidedMissing || 0})` ); } catch (err) { await ctx.service.externalPrintOrder.markShopSynced(shop, now, `自动拉取失败:${err.message}`); diff --git a/backend/app/schedule/orderSyncWorker.js b/backend/app/schedule/orderSyncWorker.js new file mode 100644 index 0000000..8e8de8b --- /dev/null +++ b/backend/app/schedule/orderSyncWorker.js @@ -0,0 +1,34 @@ +'use strict'; + +/** + * 拉单异步任务消费者:每 10 秒运行一次,认领并执行一条「待处理」任务。 + * + * type: 'worker' 保证集群中仅由单一 worker 执行,配合行锁实现「逐个店铺串行拉取」; + * 单个任务执行时间可能较长(逐店请求平台),用模块级 running 标记避免同进程叠加执行。 + */ +let running = false; + +module.exports = { + schedule: { + cron: '*/10 * * * * *', + type: 'worker', + disable: false, + }, + + /** + * 执行一轮 + * @param {Egg.Context} ctx egg context + * @return {Promise} 无返回值 + */ + async task(ctx) { + if (running) return; + running = true; + try { + await ctx.service.orderSyncTask.processPending(); + } catch (err) { + ctx.logger.error('[order-sync-worker] 调度执行失败', err); + } finally { + running = false; + } + }, +}; diff --git a/backend/app/service/externalPrintExpressInterface.js b/backend/app/service/externalPrintExpressInterface.js index eff9d66..135803b 100644 --- a/backend/app/service/externalPrintExpressInterface.js +++ b/backend/app/service/externalPrintExpressInterface.js @@ -99,6 +99,7 @@ class ExternalPrintExpressInterfaceService extends Service { shop_id: item.shop_id || null, shop_name: item.shop_name || null, dbname: item.dbname || null, + cai_niao_auth_info_id: item.cai_niao_auth_info_id || null, platform_updated_at: item.platform_updated_at || null, synced_at: now, status: 1, diff --git a/backend/app/service/externalPrintOrder.js b/backend/app/service/externalPrintOrder.js index 5abb1cd..7c34d61 100644 --- a/backend/app/service/externalPrintOrder.js +++ b/backend/app/service/externalPrintOrder.js @@ -41,6 +41,18 @@ function buildProductInfo(lines) { })); } +/** + * 时间文本(用于自动作废备注,形如 2026-11-01 00:00) + * @param {Date} date 时间 + * @return {string} 文本 + */ +function formatTimeText(date) { + const value = new Date(date); + if (Number.isNaN(value.getTime())) return '-'; + const pad = num => String(num).padStart(2, '0'); + return `${value.getFullYear()}-${pad(value.getMonth() + 1)}-${pad(value.getDate())} ${pad(value.getHours())}:${pad(value.getMinutes())}`; +} + /** * 明细行转平台原样快照:绑定系统商品/组合商品时明细字段会被覆盖或拆分,解绑时按此还原 * @param {Object} line 平台明细 @@ -51,6 +63,9 @@ function buildPlatformSnapshot(line, lineNo) { return buildSnapshot(line, lineNo); } +/** 平台「查不到」的最大回看天数:平台对久远订单返回不可靠,避免把老单误判为消失 */ +const MISSING_CHECK_MAX_DAYS = 45; + /** * 外部打单平台订单拉取服务 * @@ -114,14 +129,27 @@ class ExternalPrintOrderService extends Service { } const saved = await this.saveOrders(shop, account, result.list); - // 平台侧已发货/已终结、但本地仍停留在待审核的副本:自动作废,避免脏单积压在待审核 - const voided = await this.voidFinishedOrders(shop, result.finished || []); + + // 平台侧已发货/已终结、但本地仍停留在待审核的副本:自动作废(备注写清具体依据) + const shipped = await this.voidUnavailableOrders(shop, (result.finished || []).map(item => ({ + external_order_id: item.external_order_id, + platform_status: item.platform_status || null, + reason_code: 'shipped', + reason: item.reason ? `店管家侧已发货或已终结(${item.reason})` : '店管家侧已发货或已终结', + }))); + + // 本次拉取窗口内本地仍是待审核、但平台已查不到的订单:也作废,并注明是「查不到」而非「已发货」 + const missingItems = await this.findMissingOrders(shop, result, { startTime, endTime }); + const missing = await this.voidUnavailableOrders(shop, missingItems); + return { startTime, endTime, orders: result.total, skipped: result.skipped || 0, - voided, + voided: shipped.count + missing.count, + voidedShipped: shipped.count, + voidedMissing: missing.count, created: saved.created, updated: saved.updated, items: saved.items, @@ -132,29 +160,153 @@ class ExternalPrintOrderService extends Service { } /** - * 作废本地仍处于「待审核」、但平台侧已发货/已终结的订单。 - * 已审核(待推送/委外中/…)的订单不受影响:那些订单的库存与仓库动作已经发生,交由人工处理。 + * 找出「本次拉取窗口内本地仍是待审核、但平台返回结果里没有」的订单 + * + * 用于区分「平台已发货」与「平台已查不到」两种消失原因: + * - 候选范围严格限定为「本店铺 + 待审核 + 下单时间落在本次查询窗口内」; + * - 窗口最长回看 MISSING_CHECK_MAX_DAYS 天(平台对久远订单的返回不可靠,避免误作废); + * - 本次没有成功命中任何分区(hosts 为空)时不判定,避免平台异常导致整批误作废; + * - 可用 AUTO_VOID_MISSING_ORDER=0 关闭该能力。 * @param {Object} shop 店铺实例 - * @param {Array<{external_order_id: string, platform_status: string}>} finished 平台侧已处理的订单 - * @return {Promise} 作废数量 + * @param {Object} result 平台返回(list / finished / hosts) + * @param {Object} range 本次查询时间窗 + * @param {Date} range.startTime 开始时间 + * @param {Date} range.endTime 结束时间 + * @return {Promise} 待作废项(含 reason_code=missing) */ - async voidFinishedOrders(shop, finished) { + async findMissingOrders(shop, result, { startTime, endTime }) { + const { ctx } = this; + if (String(process.env.AUTO_VOID_MISSING_ORDER || '1') === '0') return []; + if (!Array.isArray(result.hosts) || !result.hosts.length) return []; + + const Op = this.app.Sequelize.Op; + const end = new Date(endTime); + const floor = new Date(end.getTime() - MISSING_CHECK_MAX_DAYS * 24 * 3600 * 1000); + const start = new Date(Math.max(new Date(startTime).getTime(), floor.getTime())); + + const known = new Set(); + for (const row of result.list || []) { + if (row && row.external_order_id) known.add(String(row.external_order_id)); + } + for (const row of result.finished || []) { + if (row && row.external_order_id) known.add(String(row.external_order_id)); + } + + const candidates = await ctx.model.OrderStatusPending.findAll({ + where: { + principal_id: shop.principal_id, + shop_id: shop.id, + place_order_time: { [Op.between]: [ start, end ] }, + }, + attributes: [ 'id', 'order_no', 'parent_order_no', 'place_order_time', 'source_platform_code', 'oaid_order_source_code' ], + raw: true, + }); + + return candidates + .filter(row => row.parent_order_no && !known.has(String(row.parent_order_no))) + .map(row => ({ + external_order_id: String(row.parent_order_no), + platform_status: null, + reason_code: 'missing', + reason: `店管家侧已查不到该订单(${formatTimeText(start)} 至 ${formatTimeText(end)} 的拉取结果中没有该单,可能已删除、合并或转出本店铺)`, + })); + } + + /** + * 审核/推送前校验:平台侧是否已发货或已终结(只读) + * + * 场景:订单昨天已在店管家发货,OMS 今天才审核 → 不该再推仓库。 + * 平台查询失败按「放行」处理(只告警),避免平台抖动把审核全卡住。 + * @param {Object} order 订单明细(状态表行,需 shop_id / source_platform_code / extend_props) + * @param {Object} index 订单索引行(order_no / parent_order_no) + * @param {number} principalId 主体ID + * @return {Promise<{applicable: boolean, finished: boolean, status: string, reason: string, row: Object|null}>} 校验结果 + */ + async checkPlatformFinished(order, index, principalId) { + const { ctx } = this; + const result = { applicable: false, finished: false, status: '', reason: '', row: null }; + if (!order || !order.shop_id) return result; + + const shop = await ctx.model.Shop.findByPk(order.shop_id, { + attributes: [ 'id', 'type', 'external_print_account_id' ], + }); + if (!shop || Number(shop.type) !== 2 || !shop.external_print_account_id) return result; + + const platformCode = String(order.source_platform_code || '').trim(); + if (!platformCode) return result; + + const account = await ctx.model.ExternalPrintAccount.findByPk(shop.external_print_account_id, { + include: [{ model: ctx.model.ExternalPrintPlatform, as: 'platform' }], + }); + if (!account || !account.platform) return result; + + const service = this.createPlatformService(account); + const resolvePlatformType = service.constructor && service.constructor.resolvePlatformType; + if (typeof resolvePlatformType !== 'function' || typeof service.fetchPlatformOrder !== 'function') return result; + + // 平台类型 / 分区库优先取已同步的快递接口记录(无需额外接口) + const template = await ctx.model.ExternalPrintExpressInterface.findOne({ + where: { principal_id: principalId, account_id: account.id, platform_code: platformCode, status: 1 }, + attributes: [ 'id', 'platform_type', 'dbname' ], + order: [[ 'id', 'ASC' ]], + }); + const platformType = template ? template.platform_type : resolvePlatformType(platformCode); + if (!platformType) return result; + + result.applicable = true; + const row = await service.fetchPlatformOrder({ + platformType, + dbname: template ? template.dbname : '', + logicalOrderId: String((index && (index.parent_order_no || index.order_no)) || order.parent_order_no || order.order_no || ''), + platformOrderId: String((order.extend_props && order.extend_props.platform_order_no) || order.oaid_order_source_code || ''), + placeOrderTime: order.place_order_time || order.pay_time || order.created_at, + }); + if (!row) return result; + + const describe = service.constructor.describeFinishedOrder; + const detail = typeof describe === 'function' ? describe(row) : { finished: false, reason: '' }; + result.row = row; + result.status = String(row.ErpState || ''); + result.finished = detail.finished; + result.reason = detail.finished + ? `店管家侧已发货或已终结(${detail.reason || `ErpState=${result.status || '-'}`})` + : ''; + return result; + } + + /** + * 作废「本地仍是待审核、但平台侧不应再处理」的订单(已发货/已终结,或平台已查不到)。 + * + * 已审核(待推送/委外中/…)的订单不受影响:那些订单的库存与仓库动作已经发生,交由人工处理。 + * **作废备注按每个订单的真实原因写入**(已发货的具体依据 / 平台查不到),便于事后区分。 + * @param {Object} shop 店铺实例 + * @param {Array<{external_order_id: string, platform_status: string, reason: string, reason_code: string}>} items 待作废项 + * @return {Promise<{count: number, orders: Array}>} 作废数量与明细 + */ + async voidUnavailableOrders(shop, items) { const { ctx } = this; const Op = this.app.Sequelize.Op; - const list = (finished || []).filter(item => item && item.external_order_id); - if (!list.length) return 0; + const list = (items || []).filter(item => item && item.external_order_id); + if (!list.length) return { count: 0, orders: [] }; + + const reasonMap = new Map(); + const statusMap = new Map(); + for (const item of list) { + const key = String(item.external_order_id); + reasonMap.set(key, item.reason || '平台侧已不可处理'); + statusMap.set(key, item.platform_status || null); + } - const statusMap = new Map(list.map(item => [ String(item.external_order_id), item.platform_status || null ])); const indexRows = await ctx.model.OrderIndex.findAll({ where: { principal_id: shop.principal_id, - parent_order_no: { [Op.in]: Array.from(statusMap.keys()) }, + parent_order_no: { [Op.in]: Array.from(reasonMap.keys()) }, current_status: ORDER_STATUS.PENDING, }, attributes: [ 'id', 'order_no', 'parent_order_no' ], raw: true, }); - if (!indexRows.length) return 0; + if (!indexRows.length) return { count: 0, orders: [] }; // 先刷新订单头里的平台状态,作废后仍能看到平台侧最终状态 for (const row of indexRows) { @@ -164,32 +316,69 @@ class ExternalPrintOrderService extends Service { ); } - const reason = '平台侧已发货或已终结,系统自动作废'; - let result; - try { - result = await ctx.service.orderStatus.voidOrder({ - ids: indexRows.map(row => Number(row.id)), - void_reason: reason, - principalId: shop.principal_id, - }); - } catch (err) { - this.ctx.logger.warn('[externalPrintOrder] 自动作废平台已发货订单失败:%s', err.message); - return 0; + // 按原因分组作废:voidOrder 一次只接受一个原因,分组后每单的备注才是准确的 + const groups = new Map(); + for (const row of indexRows) { + const reason = reasonMap.get(String(row.parent_order_no)) || '平台侧已不可处理'; + if (!groups.has(reason)) groups.set(reason, []); + groups.get(reason).push(row); } - await ctx.service.operationLog.recordMany( - indexRows.map(row => ({ - principalId: shop.principal_id, - targetType: 'order', - targetId: Number(row.id), - action: 'void', - title: `平台已发货自动作废:${row.order_no}`, - detail: { reason, platform_status: statusMap.get(String(row.parent_order_no)) || null, shop_id: shop.id }, - })), - { source: 'sync' } - ); + let count = 0; + const voidedOrders = []; + for (const [ reason, rows ] of groups) { + try { + const result = await ctx.service.orderStatus.voidOrder({ + ids: rows.map(row => Number(row.id)), + void_reason: `${reason},系统自动作废`, + principalId: shop.principal_id, + }); + count += result.count || rows.length; + } catch (err) { + ctx.logger.warn('[externalPrintOrder] 自动作废失败(%s):%s', reason, err.message); + continue; + } - return result.count || indexRows.length; + for (const row of rows) { + voidedOrders.push({ id: Number(row.id), order_no: row.order_no, reason, platform_status: statusMap.get(String(row.parent_order_no)) || null }); + } + } + + if (voidedOrders.length) { + await ctx.service.operationLog.recordMany( + voidedOrders.map(row => ({ + principalId: shop.principal_id, + targetType: 'order', + targetId: row.id, + action: 'void', + title: `拉单自动作废:${row.order_no}`, + detail: { + reason: `${row.reason},系统自动作废`, + platform_status: row.platform_status, + shop_id: shop.id, + }, + })), + { source: 'sync' } + ); + } + + return { count, orders: voidedOrders }; + } + + /** + * 作废本地仍处于「待审核」、但平台侧已发货/已终结的订单(保留旧方法名,内部走统一实现) + * @param {Object} shop 店铺实例 + * @param {Array<{external_order_id: string, platform_status: string, reason: string}>} finished 平台侧已处理的订单 + * @return {Promise} 作废数量 + */ + async voidFinishedOrders(shop, finished) { + const result = await this.voidUnavailableOrders(shop, (finished || []).map(item => ({ + external_order_id: item.external_order_id, + platform_status: item.platform_status || null, + reason_code: 'shipped', + reason: item.reason ? `店管家侧已发货或已终结(${item.reason})` : '店管家侧已发货或已终结', + }))); + return result.count; } /** diff --git a/backend/app/service/externalSendSync.js b/backend/app/service/externalSendSync.js new file mode 100644 index 0000000..0cc8fbd --- /dev/null +++ b/backend/app/service/externalSendSync.js @@ -0,0 +1,349 @@ +'use strict'; + +const Service = require('egg').Service; + +/** 外部发货同步状态 */ +const SEND_STATUS = { + PENDING: 0, + SYNCED: 1, + RETRY: 2, + EXCEPTION: 3, +}; + +/** 状态文案 */ +const SEND_STATUS_LABELS = { + 0: '待同步', + 1: '已同步', + 2: '同步失败待重试', + 3: '同步异常', +}; + +/** 失败重试上限:达到后流转为「异常」,等人工批量重试 */ +const MAX_SEND_TIMES = 3; + +/** + * 截断字符串,避免超出表字段长度 + * @param {*} value 原始值 + * @param {number} max 最大长度 + * @return {string} 截断后的字符串 + */ +function truncateText(value, max) { + return String(value == null ? '' : value).slice(0, max); +} + +/** + * 是否为平台登录态失效类错误(分区接口统一返回「登录信息过期,请重新登录」) + * @param {Error} err 异常 + * @return {boolean} 是否需要重新登录 + */ +function isSessionExpiredError(err) { + const message = String((err && err.message) || ''); + return /登录信息过期|登录已失效|token is invalid|未登录|缺少 token/i.test(message); +} + +/** + * 同步外部打单平台发货(店管家 `NewOrder/OnlineSendBatch`) + * + * 触发链路: + * - WMS 回传 `deliveryorder.confirm` → 订单流转到「配送」时把状态置为「待同步」(`markPending`); + * - 定时任务 `externalSendSyncWorker` 扫描「待同步 / 失败待重试」的配送单,逐单调平台发货接口; + * - 失败累加次数,达到 3 次转「异常」;人工在列表里批量重试(`retry`)会把次数清零重新排队。 + */ +class ExternalSendSyncService extends Service { + /** + * 订单流转到配送后标记「待同步」 + * + * 非外部打单订单(店铺不是 type=2 / 没有打单账号)直接标记为「已同步」,避免污染异常统计。 + * @param {number[]} ids 订单ID(order_index.id) + * @param {number} principalId 主体ID + * @return {Promise} 无返回值 + */ + async markPending(ids, principalId) { + const { ctx } = this; + const idList = (Array.isArray(ids) ? ids : [ ids ]).map(Number).filter(Boolean); + if (!idList.length) return; + const Op = ctx.app.Sequelize.Op; + const rows = await ctx.model.OrderStatusDelivery.findAll({ + where: { principal_id: principalId, id: { [Op.in]: idList } }, + }); + for (const row of rows) { + const applicable = await this.isExternalPrintOrder(row); + await row.update(applicable + ? { external_send_status: SEND_STATUS.PENDING, external_send_times: 0, external_send_error: '' } + : { + external_send_status: SEND_STATUS.SYNCED, + external_send_times: 0, + external_send_error: '', + external_send_at: new Date(), + external_sent_at: new Date(), + }); + } + } + + /** + * 是否外部打单平台订单(店铺 type=2 且挂了打单账号) + * @param {Object} order 配送表订单行 + * @return {Promise} 是否需要同步 + */ + async isExternalPrintOrder(order) { + const { ctx } = this; + if (!order || !order.shop_id) return false; + const shop = await ctx.model.Shop.findByPk(order.shop_id, { + attributes: [ 'id', 'type', 'external_print_account_id' ], + }); + return !!(shop && Number(shop.type) === 2 && shop.external_print_account_id); + } + + /** + * 同步单个订单的发货结果到外部打单平台 + * @param {Object} order 配送表订单行(Sequelize 实例) + * @param {Object} [options] 参数 + * @param {string} [options.trigger] 触发来源(schedule / manual) + * @return {Promise<{ok: boolean, message: string, skipped?: boolean}>} 同步结果 + */ + async syncOrder(order, { trigger = 'schedule' } = {}) { + const { ctx } = this; + const now = new Date(); + try { + const target = await this.resolveTarget(order); + if (!target) { + await order.update({ + external_send_status: SEND_STATUS.SYNCED, + external_send_error: '', + external_send_at: now, + external_sent_at: now, + }); + return { ok: true, skipped: true, message: '非外部打单订单,无需同步' }; + } + + const { service, platformType, dbname, platformCode } = target; + const host = service.constructor.resolveOrderHost(platformType); + const row = await service.findPlatformOrderRow(host, { + traceId: await this.resolveTraceId(service), + dbname, + logicalOrderId: String(order.parent_order_no || order.order_no || ''), + platformOrderId: String((order.extend_props && order.extend_props.platform_order_no) || order.oaid_order_source_code || ''), + placeOrderTime: order.place_order_time || order.pay_time || order.created_at, + }); + if (!row) { + throw new Error(`外部打单平台未找到该订单(平台 ${platformCode},系统编号 ${order.parent_order_no || order.order_no})`); + } + + await service.sendOrders(host, { + traceId: await this.resolveTraceId(service), + dbname, + rows: [ row ], + }); + + await order.update({ + external_send_status: SEND_STATUS.SYNCED, + external_send_error: '', + external_send_at: now, + external_sent_at: now, + }); + ctx.logger.info('[external-send] 同步外部发货成功 %s(%s)', order.order_no, trigger); + return { ok: true, message: 'ok' }; + } catch (err) { + // 登录态失效:重新登录后重试一次 + if (isSessionExpiredError(err)) { + try { + const target = await this.resolveTarget(order); + if (target) { + await target.service.loginByPassword(); + const host = target.service.constructor.resolveOrderHost(target.platformType); + const row = await target.service.findPlatformOrderRow(host, { + traceId: await this.resolveTraceId(target.service), + dbname: target.dbname, + logicalOrderId: String(order.parent_order_no || order.order_no || ''), + platformOrderId: String((order.extend_props && order.extend_props.platform_order_no) || order.oaid_order_source_code || ''), + placeOrderTime: order.place_order_time || order.pay_time || order.created_at, + }); + if (!row) throw new Error('外部打单平台未找到该订单'); + await target.service.sendOrders(host, { + traceId: await this.resolveTraceId(target.service), + dbname: target.dbname, + rows: [ row ], + }); + await order.update({ + external_send_status: SEND_STATUS.SYNCED, + external_send_error: '', + external_send_at: now, + external_sent_at: now, + }); + ctx.logger.info('[external-send] 重新登录后同步成功 %s', order.order_no); + return { ok: true, message: 'ok' }; + } + } catch (retryErr) { + return await this.recordFailure(order, retryErr, now); + } + } + return await this.recordFailure(order, err, now); + } + } + + /** + * 记录一次失败:累加次数,达到上限转「异常」 + * @param {Object} order 配送表订单行 + * @param {Error} err 异常 + * @param {Date} now 当前时间 + * @return {Promise<{ok: boolean, message: string}>} 结果 + */ + async recordFailure(order, err, now) { + const { ctx } = this; + const times = Number(order.external_send_times || 0) + 1; + const exception = times >= MAX_SEND_TIMES; + const message = truncateText(err && err.message ? err.message : '同步失败', 500); + await order.update({ + external_send_status: exception ? SEND_STATUS.EXCEPTION : SEND_STATUS.RETRY, + external_send_times: times, + external_send_error: message, + external_send_at: now, + }); + ctx.logger.warn('[external-send] 同步外部发货失败 %s(第 %d 次%s):%s', + order.order_no, times, exception ? ',转异常' : '', message); + return { ok: false, message }; + } + + /** + * 定位同步目标(打单账号 / 平台服务 / 分区) + * @param {Object} order 配送表订单行 + * @return {Promise} 目标信息;非外部打单订单返回 null + */ + async resolveTarget(order) { + const { ctx } = this; + if (!order || !order.shop_id) return null; + const shop = await ctx.model.Shop.findByPk(order.shop_id, { + attributes: [ 'id', 'type', 'external_print_account_id' ], + }); + if (!shop || Number(shop.type) !== 2 || !shop.external_print_account_id) return null; + + const account = await ctx.model.ExternalPrintAccount.findByPk(shop.external_print_account_id, { + include: [{ model: ctx.model.ExternalPrintPlatform, as: 'platform' }], + }); + if (!account || !account.platform) return null; + + const platformCode = String(order.source_platform_code || '').trim(); + const service = ctx.service.externalPrintOrder.createPlatformService(account); + const resolvePlatformType = service.constructor && service.constructor.resolvePlatformType; + const template = await ctx.model.ExternalPrintExpressInterface.findOne({ + where: { principal_id: order.principal_id, account_id: account.id, platform_code: platformCode, status: 1 }, + attributes: [ 'id', 'platform_type', 'dbname' ], + order: [[ 'id', 'ASC' ]], + }); + const platformType = template ? template.platform_type : (typeof resolvePlatformType === 'function' ? resolvePlatformType(platformCode) : ''); + if (!platformType) return null; + return { service, account, platformType, dbname: template ? template.dbname : '', platformCode }; + } + + /** + * 取平台登录上下文 traceId(失败不阻断) + * @param {Object} service 平台服务实例 + * @return {Promise} traceId + */ + async resolveTraceId(service) { + try { + const info = await service.getUserInfo(); + return (info.data && info.data.TraceId) || ''; + } catch (err) { + return ''; + } + } + + /** + * 扫描并同步待同步 / 可重试的配送单(定时任务入口) + * @param {Object} [options] 参数 + * @param {number} [options.limit] 单批上限 + * @return {Promise} 统计结果 + */ + async syncPending({ limit = 50 } = {}) { + const { ctx } = this; + const Op = ctx.app.Sequelize.Op; + const rows = await ctx.model.OrderStatusDelivery.findAll({ + where: { + external_send_status: { [Op.in]: [ SEND_STATUS.PENDING, SEND_STATUS.RETRY ] }, + external_send_times: { [Op.lt]: MAX_SEND_TIMES }, + }, + order: [[ 'external_send_at', 'ASC' ]], + limit, + }); + + let success = 0; + let failed = 0; + let exception = 0; + for (const row of rows) { + const result = await this.syncOrder(row, { trigger: 'schedule' }); + if (result.ok) success += 1; + else if (row.external_send_status === SEND_STATUS.EXCEPTION) exception += 1; + else failed += 1; + } + return { total: rows.length, success, failed, exception }; + } + + /** + * 各状态数量(前端快速查看异常数量) + * @param {number} principalId 主体ID + * @return {Promise} { pending, retry, exception, synced, total } + */ + async counts(principalId) { + const { ctx } = this; + const Sequelize = ctx.app.Sequelize; + const rows = await ctx.model.OrderStatusDelivery.findAll({ + where: { principal_id: principalId }, + attributes: [ 'external_send_status', [ Sequelize.fn('COUNT', Sequelize.col('id')), 'cnt' ]], + group: [ 'external_send_status' ], + raw: true, + }); + const result = { pending: 0, retry: 0, exception: 0, synced: 0, total: 0 }; + for (const row of rows) { + const count = Number(row.cnt) || 0; + result.total += count; + if (Number(row.external_send_status) === SEND_STATUS.PENDING) result.pending += count; + else if (Number(row.external_send_status) === SEND_STATUS.RETRY) result.retry += count; + else if (Number(row.external_send_status) === SEND_STATUS.EXCEPTION) result.exception += count; + else if (Number(row.external_send_status) === SEND_STATUS.SYNCED) result.synced += count; + } + return result; + } + + /** + * 批量重试同步(人工处理异常单) + * + * 把状态重置为「待同步」并把次数清零,随后立刻跑一批,避免等定时任务。 + * @param {Object} p 参数 + * @param {number[]} [p.ids] 指定订单ID;为空时按状态筛选 + * @param {number} [p.principalId] 主体ID + * @param {number[]} [p.statuses] 状态筛选(默认异常 + 待重试) + * @return {Promise} { reset, result } + */ + async retry({ ids, principalId, statuses = [ SEND_STATUS.EXCEPTION, SEND_STATUS.RETRY ] } = {}) { + const { ctx } = this; + const Op = ctx.app.Sequelize.Op; + const idList = (Array.isArray(ids) ? ids : []).map(Number).filter(Boolean); + const where = { principal_id: principalId }; + if (idList.length) where.id = { [Op.in]: idList }; + else where.external_send_status = { [Op.in]: statuses }; + + const rows = await ctx.model.OrderStatusDelivery.findAll({ where }); + for (const row of rows) { + await row.update({ + external_send_status: SEND_STATUS.PENDING, + external_send_times: 0, + external_send_error: '', + }); + } + + let success = 0; + let failed = 0; + for (const row of rows) { + const result = await this.syncOrder(row, { trigger: 'manual' }); + if (result.ok) success += 1; + else failed += 1; + } + return { reset: rows.length, success, failed }; + } +} + +module.exports = ExternalSendSyncService; +module.exports.SEND_STATUS = SEND_STATUS; +module.exports.SEND_STATUS_LABELS = SEND_STATUS_LABELS; +module.exports.MAX_SEND_TIMES = MAX_SEND_TIMES; diff --git a/backend/app/service/orderItemResolve.js b/backend/app/service/orderItemResolve.js index 0b4935e..fa7dcb3 100644 --- a/backend/app/service/orderItemResolve.js +++ b/backend/app/service/orderItemResolve.js @@ -153,16 +153,23 @@ class OrderItemResolveService extends Service { const Op = this.app.Sequelize.Op; const statuses = options.statuses || [ ORDER_STATUS.PENDING, ORDER_STATUS.EXCEPTION ]; + const transaction = options.transaction || await ctx.model.transaction(); + const ownedTransaction = !options.transaction; + + // 必须在事务内查索引行:首次拉单建单时 OrderIndex 与明细在同一事务里刚写入, + // 事务外读不到 → 会误判「无需重建」而保留平台原值(表现为已绑定却显示平台商品名) const indexRows = await ctx.model.OrderIndex.findAll({ where: { id: { [Op.in]: ids }, current_status: { [Op.in]: statuses } }, attributes: [ 'id' ], raw: true, + transaction, }); const targetIds = indexRows.map(row => Number(row.id)); - if (!targetIds.length) return 0; + if (!targetIds.length) { + if (ownedTransaction) await transaction.rollback(); + return 0; + } - const transaction = options.transaction || await ctx.model.transaction(); - const ownedTransaction = !options.transaction; let affected = 0; try { diff --git a/backend/app/service/orderStatus.js b/backend/app/service/orderStatus.js index 1c76e44..78fa5c6 100644 --- a/backend/app/service/orderStatus.js +++ b/backend/app/service/orderStatus.js @@ -18,6 +18,14 @@ const { const { resolveAccountName } = require('../lib/accountProfile'); const { validateReceiver } = require('../lib/orderReceiver'); const { validateItems } = require('../lib/orderDeliveryItems'); + +/** 外部发货同步状态文案(与 service/externalSendSync.js 的 SEND_STATUS 对齐) */ +const EXTERNAL_SEND_STATUS_LABELS = { + 0: '待同步外部', + 1: '已同步外部', + 2: '同步失败待重试', + 3: '同步异常', +}; const { notNullDefaultColumnNames } = require('../lib/orderFields'); const { lockOrderStock, releaseOrderStock, deductOrderStock } = require('../utils/orderStock'); @@ -355,6 +363,16 @@ class OrderStatusService extends Service { } } + // 外部发货同步状态筛选(配送视图用:0待同步 1已同步 2待重试 3异常;支持多选逗号分隔) + const externalSendStatus = trimOrNull(p.external_send_status); + if (externalSendStatus) { + const values = String(externalSendStatus) + .split(',') + .map(item => Number(item.trim())) + .filter(item => Number.isFinite(item)); + if (values.length) where.external_send_status = { [Op.in]: values }; + } + // 只列索引表里存在的订单:详情按 order_index 校验主体, // 若状态表存在没有索引记录的历史脏数据,列表会看得到却点不开,这里直接挡掉 where[Op.and] = [ @@ -406,6 +424,7 @@ class OrderStatusService extends Service { row.product_kind = Array.isArray(row.product_info) ? row.product_info.length : 0; // 平台拉取的订单店铺由平台决定,前端据此禁用「设置店铺」 row.is_external = this._isExternalPrintOrder(row); + row.external_send_status_label = EXTERNAL_SEND_STATUS_LABELS[Number(row.external_send_status || 0)] || ''; } // 无 product_info 快照(新建发货单走 items 明细、老数据搬迁)时,按明细表现算摘要, @@ -909,6 +928,7 @@ class OrderStatusService extends Service { } const detail = await this._model(row.current_status).findByPk(id); + await this._guardPlatformFinished(row, detail, principalId); const itemCount = await ctx.model.OrderStatusItem.count({ where: { order_id: id, principal_id: principalId } }); if (!itemCount) { const err = new Error(`订单 ${row.order_no} 无商品明细,无法审核`); @@ -966,6 +986,40 @@ class OrderStatusService extends Service { } } + /** + * 审核前守卫:外部打单订单若平台侧已发货/已终结,自动作废并拒绝审核 + * + * 背景:订单可能在店管家先发货、OMS 隔天才审核;若照常审核会推送一张平台已完成、 + * 仓库无法再取号的脏单。平台查询失败按放行处理(只告警),避免平台抖动卡住审核。 + * @param {Object} row 订单索引行 + * @param {Object} detail 订单明细(状态表行) + * @param {number} principalId 主体ID + * @return {Promise} 无返回值(命中时抛 400) + */ + async _guardPlatformFinished(row, detail, principalId) { + const { ctx } = this; + if (String(process.env.DGJ_AUDIT_PLATFORM_CHECK || '1') === '0') return; + let check; + try { + check = await ctx.service.externalPrintOrder.checkPlatformFinished(detail, row, principalId); + } catch (err) { + ctx.logger.warn('[order-audit] %s 平台状态校验失败(放行审核):%s', row.order_no, err.message); + return; + } + if (!check || !check.finished) return; + + const reason = `${check.reason},系统自动作废`; + try { + await this.voidOrder({ ids: [ Number(row.id) ], void_reason: reason, principalId }); + } catch (err) { + ctx.logger.warn('[order-audit] %s 自动作废失败:%s', row.order_no, err.message); + } + + const ex = new Error(`订单 ${row.order_no} ${check.reason},不能审核(已自动作废)`); + ex.status = 400; + throw ex; + } + /** * 手工标记推送结果(待推送 → 委外中 / 异常):无外部仓库时的流转入口,也可用于修正外部实际结果 * @param {Object} p { ids, outcome: 'success'|'failed', remark } diff --git a/backend/app/service/orderSyncTask.js b/backend/app/service/orderSyncTask.js new file mode 100644 index 0000000..932f74b --- /dev/null +++ b/backend/app/service/orderSyncTask.js @@ -0,0 +1,463 @@ +'use strict'; + +const { Service } = require('egg'); + +/** 任务状态:0待处理 1处理中 2已完成 3部分失败 4失败 */ +const STATUS = { PENDING: 0, PROCESSING: 1, COMPLETED: 2, PARTIAL: 3, FAILED: 4 }; + +/** 状态中文(前端直接用,避免枚举漂移) */ +const STATUS_LABELS = { + [STATUS.PENDING]: '待处理', + [STATUS.PROCESSING]: '处理中', + [STATUS.COMPLETED]: '已完成', + [STATUS.PARTIAL]: '部分失败', + [STATUS.FAILED]: '失败', +}; + +/** 拉单范围:当前仅外部打单平台店铺,后续新增来源在此登记 */ +const SCOPES = { + external_print: '外部打单平台店铺', +}; + +/** 回看天数的默认值与上限(0 表示「全部待处理」,不限下单时间) */ +const DEFAULT_LOOKBACK_DAYS = 3; +const MAX_LOOKBACK_DAYS = 120; +/** 「全部待处理」的起始时间(早于所有平台订单) */ +const ALL_PENDING_START = new Date('2018-01-01T00:00:00+08:00'); + +/** 处理中的任务超过该时长视为异常中断(进程退出),允许重新认领 */ +const STALE_MS = 30 * 60 * 1000; + +/** 单任务最多拉取的店铺数(防止误提交拖垮平台) */ +const MAX_SHOPS = 200; + +/** + * 拉单任务服务 + * + * 与导出任务同构:提交只落库,定时任务认领执行;区别是本服务按「店铺」维度推进, + * 逐店调用 externalPrintOrder.syncOrders(与手动/定时拉单完全同一条链路,入库口径一致)。 + */ +class OrderSyncTaskService extends Service { + /** @return {Object} 任务状态枚举 */ + get STATUS() { + return STATUS; + } + + /** @return {Object} 范围枚举 */ + get SCOPES() { + return SCOPES; + } + + /** + * 按范围解析可拉取的店铺 + * @param {string} scope 拉单范围 + * @param {number} principalId 主体ID + * @param {Array} [shopIds] 指定店铺ID + * @return {Promise} 店铺列表 + */ + async resolveShops(scope, principalId, shopIds) { + const Op = this.app.Sequelize.Op; + const where = { principal_id: principalId, status: 1 }; + if (scope === 'external_print') { + where.type = 2; + where.external_print_account_id = { [Op.ne]: null }; + } else { + return []; + } + const ids = (shopIds || []).map(Number).filter(id => Number.isInteger(id) && id > 0); + if (ids.length) where.id = { [Op.in]: ids }; + + return await this.ctx.model.Shop.findAll({ + where, + attributes: [ 'id', 'code', 'name', 'principal_id', 'type', 'external_print_account_id' ], + order: [[ 'id', 'ASC' ]], + limit: MAX_SHOPS, + }); + } + + /** + * 提交拉单任务:只落一条待处理记录,立即返回任务ID + * @param {Object} payload 提交参数 + * @param {Object} payload.scope 拉单范围(默认 external_print) + * @param {number} [payload.lookback_days] 回看天数(0=全部待处理) + * @param {Array} [payload.shop_ids] 指定店铺ID(空=全部) + * @param {number} principalId 主体ID + * @param {number} userId 提交人ID + * @return {Promise} 任务实例 + */ + async submit(payload, principalId, userId) { + const { ctx } = this; + const scope = String(payload.scope || 'external_print').trim(); + if (!SCOPES[scope]) { + const err = new Error(`不支持的拉单范围:${scope}`); + err.status = 400; + throw err; + } + + // 已有未完成任务时拒绝重复提交:拉单会真实请求平台,重复提交只会互相拖慢 + const running = await ctx.model.OrderSyncTask.findOne({ + where: { principal_id: principalId, status: { [ ctx.app.Sequelize.Op.in ]: [ STATUS.PENDING, STATUS.PROCESSING ] } }, + attributes: [ 'id', 'status' ], + order: [[ 'id', 'DESC' ]], + }); + if (running) { + const err = new Error(`已有拉单任务在排队/执行中(任务 #${running.id}),请等待完成后再提交`); + err.status = 409; + throw err; + } + + const shops = await this.resolveShops(scope, principalId, payload.shop_ids); + if (!shops.length) { + const err = new Error('没有可拉取的店铺:请先在「外部打单平台」同步商家并开启店铺状态'); + err.status = 400; + throw err; + } + + const lookbackDays = this.normalizeLookbackDays(payload.lookback_days); + const endTime = new Date(); + const startTime = this.resolveStartTime(lookbackDays, endTime); + + return await ctx.model.OrderSyncTask.create({ + principal_id: principalId, + scope, + status: STATUS.PENDING, + start_time: startTime, + end_time: endTime, + lookback_days: lookbackDays, + shop_ids: shops.map(shop => Number(shop.id)), + total_shops: shops.length, + progress: 0, + items: [], + created_by: userId || null, + }); + } + + /** + * 归一化回看天数:0 表示「全部待处理」,其余限制在 1~MAX_LOOKBACK_DAYS + * @param {*} value 原始值 + * @return {number} 天数 + */ + normalizeLookbackDays(value) { + if (value === undefined || value === null || value === '') return DEFAULT_LOOKBACK_DAYS; + const days = Number(value); + if (!Number.isFinite(days) || days < 0) return DEFAULT_LOOKBACK_DAYS; + if (days === 0) return 0; + return Math.min(MAX_LOOKBACK_DAYS, Math.max(1, Math.floor(days))); + } + + /** + * 按回看天数计算起始时间 + * @param {number} lookbackDays 天数(0=全部待处理) + * @param {Date} endTime 结束时间 + * @return {Date} 起始时间 + */ + resolveStartTime(lookbackDays, endTime) { + if (lookbackDays === 0) return ALL_PENDING_START; + return new Date(endTime.getTime() - lookbackDays * 24 * 3600 * 1000); + } + + /** + * 给任务补中文标签与汇总 + * @param {Object} task 任务实例/纯对象 + * @return {Object} 带标签的任务 + */ + decorate(task) { + const item = task && task.get ? task.get({ plain: true }) : { ...task }; + item.status_label = STATUS_LABELS[item.status] || String(item.status); + item.scope_label = SCOPES[item.scope] || item.scope; + const items = Array.isArray(item.items) ? item.items : []; + item.items = items; + item.failed_items = items.filter(row => !row.success); + return item; + } + + /** + * 任务进度 + * @param {number} id 任务ID + * @param {number} principalId 主体ID + * @return {Promise} 任务,不存在或跨主体为 null + */ + async progress(id, principalId) { + const task = await this.ctx.model.OrderSyncTask.findOne({ + where: { id, principal_id: principalId }, + }); + return task ? this.decorate(task) : null; + } + + /** + * 任务列表 + * @param {number} principalId 主体ID + * @param {Object} opts 查询参数 + * @param {number} opts.page 页码 + * @param {number} opts.pageSize 每页条数 + * @param {number} [opts.status] 状态筛选 + * @param {string} [opts.scope] 范围筛选 + * @return {Promise<{list: Array, total: number}>} 列表与总数 + */ + async list(principalId, { page, pageSize, status, scope }) { + const where = { principal_id: principalId }; + if (status !== undefined && status !== null && status !== '') where.status = Number(status); + if (scope) where.scope = String(scope).trim(); + + const { count, rows } = await this.ctx.model.OrderSyncTask.findAndCountAll({ + where, + offset: (Number(page) - 1) * Number(pageSize), + limit: Number(pageSize), + // 列表不返回逐店明细,避免大任务把列表拖慢(明细看进度接口) + attributes: { exclude: [ 'items' ] }, + order: [[ 'id', 'DESC' ]], + }); + return { list: rows.map(row => this.decorate(row)), total: count }; + } + + /** + * 当前是否有排队/执行中的任务(前端进入页面时用于恢复进度条) + * @param {number} principalId 主体ID + * @return {Promise} 最新未完成任务 + */ + async runningTask(principalId) { + const task = await this.ctx.model.OrderSyncTask.findOne({ + where: { + principal_id: principalId, + status: { [ this.app.Sequelize.Op.in ]: [ STATUS.PENDING, STATUS.PROCESSING ] }, + }, + order: [[ 'id', 'DESC' ]], + }); + return task ? this.decorate(task) : null; + } + + /** + * 认领并执行一条任务(行锁保证集群下同一任务只被一个 worker 执行) + * @return {Promise} 无返回值 + */ + async processPending() { + const ctx = this.ctx; + const Model = ctx.model.OrderSyncTask; + const Op = this.app.Sequelize.Op; + + // 先回收异常中断的任务(进程退出导致长期停在处理中):独立提交,避免被后续 rollback 抹掉 + try { + const stale = new Date(Date.now() - STALE_MS); + await Model.update( + { status: STATUS.PENDING, error_message: '上次执行中断,已重新排队' }, + { where: { status: STATUS.PROCESSING, updated_at: { [Op.lt]: stale } } } + ); + } catch (err) { + ctx.logger.warn('[order-sync-worker] 回收中断任务失败:%s', err.message); + } + + const transaction = await ctx.model.transaction(); + let task = null; + try { + task = await Model.findOne({ + where: { status: STATUS.PENDING }, + order: [[ 'id', 'ASC' ]], + lock: true, + transaction, + }); + if (!task) { + await transaction.rollback(); + return; + } + task.status = STATUS.PROCESSING; + task.started_at = new Date(); + await task.save({ transaction }); + await transaction.commit(); + } catch (err) { + await transaction.rollback().catch(() => {}); + ctx.logger.error('[order-sync-worker] 认领任务失败', err); + return; + } + + try { + await this.run(task); + } catch (err) { + ctx.logger.error(`[order-sync-worker] 任务失败 id=${task.id}`, err); + } + } + + /** + * 执行任务:逐店拉单并实时写回进度 + * @param {Object} task 任务实例 + * @return {Promise} 无返回值 + */ + async run(task) { + const { ctx } = this; + const Model = ctx.model.OrderSyncTask; + + let shops = []; + try { + shops = await this.resolveShops(task.scope, task.principal_id, task.shop_ids || []); + } catch (err) { + await Model.update( + { status: STATUS.FAILED, error_message: truncate(err.message, 500), finished_at: new Date(), progress: 100 }, + { where: { id: task.id } } + ); + return; + } + + if (!shops.length) { + await Model.update( + { status: STATUS.FAILED, error_message: '没有可拉取的店铺(店铺可能已被删除或停用)', finished_at: new Date(), progress: 100 }, + { where: { id: task.id } } + ); + return; + } + + // 店铺数可能因期间停用而变化,按实际可拉取数量校正 + await Model.update({ total_shops: shops.length }, { where: { id: task.id } }); + + const accounts = await this.loadAccounts(shops); + const items = []; + const summary = { processed: 0, failed: 0, created: 0, updated: 0, skipped: 0, voided: 0, voidedShipped: 0, voidedMissing: 0 }; + + for (const shop of shops) { + const item = await this.runShop(shop, accounts, task); + items.push(item); + summary.processed += 1; + if (!item.success) summary.failed += 1; + summary.created += item.created || 0; + summary.updated += item.updated || 0; + summary.skipped += item.skipped || 0; + summary.voided += item.voided || 0; + summary.voidedShipped += item.voided_shipped || 0; + summary.voidedMissing += item.voided_missing || 0; + + const total = shops.length; + await Model.update( + { + processed_shops: summary.processed, + failed_shops: summary.failed, + created_orders: summary.created, + updated_orders: summary.updated, + skipped_orders: summary.skipped, + voided_orders: summary.voided, + voided_shipped_orders: summary.voidedShipped, + voided_missing_orders: summary.voidedMissing, + progress: Math.min(99, Math.floor(summary.processed / total * 100)), + items, + }, + { where: { id: task.id } } + ); + } + + const finalStatus = summary.failed === 0 + ? STATUS.COMPLETED + : (summary.failed === shops.length ? STATUS.FAILED : STATUS.PARTIAL); + await Model.update( + { + status: finalStatus, + progress: 100, + processed_shops: summary.processed, + failed_shops: summary.failed, + created_orders: summary.created, + updated_orders: summary.updated, + skipped_orders: summary.skipped, + voided_orders: summary.voided, + voided_shipped_orders: summary.voidedShipped, + voided_missing_orders: summary.voidedMissing, + items, + finished_at: new Date(), + }, + { where: { id: task.id } } + ); + ctx.logger.info( + `[order-sync-worker] 任务完成 id=${task.id} 店铺 ${summary.processed}(失败 ${summary.failed})` + + ` 新增 ${summary.created} 更新 ${summary.updated} 跳过 ${summary.skipped}` + + ` 作废 ${summary.voided}(已发货 ${summary.voidedShipped}、查不到 ${summary.voidedMissing})` + ); + } + + /** + * 预加载店铺关联的打单账号(含平台配置),避免逐店重复查询 + * @param {Array} shops 店铺列表 + * @return {Promise>} 账号ID → 账号实例 + */ + async loadAccounts(shops) { + const { ctx } = this; + const accountIds = Array.from(new Set( + shops.map(shop => Number(shop.external_print_account_id)).filter(id => Number.isInteger(id) && id > 0) + )); + if (!accountIds.length) return new Map(); + + const accounts = await ctx.model.ExternalPrintAccount.findAll({ + where: { id: { [ ctx.app.Sequelize.Op.in ]: accountIds } }, + include: [ + { + model: ctx.model.ExternalPrintPlatform, + as: 'platform', + attributes: [ 'id', 'code', 'name', 'url', 'fetch_waybill_no' ], + }, + ], + }); + return new Map(accounts.map(account => [ Number(account.id), account ])); + } + + /** + * 拉取单个店铺(失败只记录,不中断整批) + * @param {Object} shop 店铺实例 + * @param {Map} accounts 账号映射 + * @param {Object} task 任务实例 + * @return {Promise} 该店铺结果 + */ + async runShop(shop, accounts, task) { + const { ctx } = this; + const base = { + shop_id: Number(shop.id), + shop_code: shop.code, + shop_name: shop.name, + account_id: Number(shop.external_print_account_id) || null, + start_time: task.start_time, + end_time: task.end_time, + }; + + const account = accounts.get(Number(shop.external_print_account_id)); + if (!account) { + const message = '店铺关联的打单账号不存在'; + await ctx.service.externalPrintOrder.markShopSynced(shop, new Date(), `拉单失败:${message}`); + return { ...base, success: false, message }; + } + + try { + const result = await ctx.service.externalPrintOrder.syncOrders(shop, account, { + startTime: new Date(task.start_time), + endTime: new Date(task.end_time), + }); + const message = `拉取成功:${result.orders} 单(新增 ${result.created},更新 ${result.updated})` + + `,跳过平台已发货 ${result.skipped || 0} 单,自动作废 ${result.voided || 0} 单` + + (result.voidedMissing ? `(其中平台已查不到 ${result.voidedMissing} 单)` : ''); + await ctx.service.externalPrintOrder.markShopSynced(shop, new Date(), message); + return { + ...base, + success: true, + message, + orders: result.orders || 0, + created: result.created || 0, + updated: result.updated || 0, + skipped: result.skipped || 0, + voided: result.voided || 0, + voided_shipped: result.voidedShipped || 0, + voided_missing: result.voidedMissing || 0, + items: result.items || 0, + }; + } catch (err) { + const message = `拉取失败:${err.message}`; + await ctx.service.externalPrintOrder.markShopSynced(shop, new Date(), message).catch(() => {}); + ctx.logger.warn(`[order-sync-worker] 店铺 ${shop.id} 拉单失败:${err.message}`); + return { ...base, success: false, message: err.message }; + } + } +} + +/** + * 截断文本 + * @param {string} value 文本 + * @param {number} max 最大长度 + * @return {string} 截断后的文本 + */ +function truncate(value, max) { + const text = String(value == null ? '' : value); + return text.length > max ? text.slice(0, max) : text; +} + +module.exports = OrderSyncTaskService; diff --git a/backend/app/service/orderWms.js b/backend/app/service/orderWms.js index 9b4cca1..e592028 100644 --- a/backend/app/service/orderWms.js +++ b/backend/app/service/orderWms.js @@ -55,14 +55,24 @@ class OrderWmsService extends Service { */ async resolveWmsItemIds(order, items) { const Op = this.app.Sequelize.Op; + const productIds = [ ...new Set((items || []).map(i => Number(i.product_id)).filter(id => Number.isInteger(id) && id > 0)) ]; const codes = [ ...new Set((items || []).map(i => i.item_code).filter(Boolean)) ]; - if (!codes.length) return { byProduct: {}, byItemCode: {} }; + if (!productIds.length && !codes.length) return { byProduct: {}, byItemCode: {}, productById: {} }; + + const where = { principal_id: order.principal_id }; + if (productIds.length && codes.length) { + where[Op.or] = [{ id: { [Op.in]: productIds } }, { item_code: { [Op.in]: codes } }]; + } else if (productIds.length) { + where.id = { [Op.in]: productIds }; + } else { + where.item_code = { [Op.in]: codes }; + } const products = await this.ctx.model.Product.findAll({ - where: { principal_id: order.principal_id, item_code: { [Op.in]: codes } }, - attributes: [ 'id', 'item_code' ], + where, + attributes: [ 'id', 'item_code', 'item_name' ], }); - if (!products.length) return { byProduct: {}, byItemCode: {} }; + if (!products.length) return { byProduct: {}, byItemCode: {}, productById: {} }; const links = await this.ctx.model.WarehouseProduct.findAll({ where: { @@ -77,11 +87,35 @@ class OrderWmsService extends Service { if (l.wms_item_id != null) byProduct[Number(l.product_id)] = Number(l.wms_item_id); } const byItemCode = {}; + // 明细上的商品编码 → 系统商品(推送报文优先用系统商品的编码/名称,避免平台原值下发) + const productById = {}; for (const p of products) { const wmsItemId = byProduct[Number(p.id)]; if (wmsItemId != null) byItemCode[p.item_code] = wmsItemId; + productById[Number(p.id)] = { item_code: p.item_code, item_name: p.item_name }; } - return { byProduct, byItemCode }; + return { byProduct, byItemCode, productById }; + } + + /** + * 推送前校验明细是否已完成「店铺商品 → 系统商品」转换 + * + * 外部打单订单的明细在拉单时可能是未绑定状态(保留了平台商品编码), + * 这类明细不能推给仓库:平台编码在 WMS 侧不存在,会建出脏商品或报错。 + * @param {Array} items 明细(order_status_items,已展开为最小单位) + * @return {string} 不通过原因,全部通过返回空串 + */ + validateConvertedItems(items) { + const list = Array.isArray(items) ? items : []; + if (!list.length) return ''; + const invalid = list.filter(item => !(Number(item.product_id) > 0) && !(Number(item.combo_product_id) > 0)); + if (!invalid.length) return ''; + const detail = invalid + .slice(0, 5) + .map(item => `第 ${item.order_line_no || '?'} 行 ${item.item_code || '(无编码)'}`) + .join('、'); + return `明细商品未绑定系统商品(${detail}${invalid.length > 5 ? ` 等 ${invalid.length} 行` : ''}),无法推送:` + + '请先在「店铺商品」把对应商品绑定到系统商品/组合商品(重新绑定会自动重建订单明细)'; } /** @@ -275,6 +309,17 @@ class OrderWmsService extends Service { const client = new QimenWmsClient(api, this.app); const items = itemRows.map(item => item.get({ plain: true })); + + // 明细必须已完成「店铺商品 → 系统商品」转换,否则推给仓库的会是平台商品编码 + const unconverted = this.validateConvertedItems(items); + if (unconverted) { + await order.update({ + wms_push_result: { ...base, success: false, failureKind: 'unbound_items', message: unconverted }, + }); + ctx.logger.warn(`[order-wms] ${order.order_no} 推送中止:${unconverted}`); + return { ok: false, retry: false, fatal: true, message: unconverted, attempts }; + } + const wmsItemIds = await this.resolveWmsItemIds(order, items); const view = this.adaptOrder(order, warehouse); // 请求根节点参数:外部打单平台订单按平台配置决定是否回 OMS 取号 @@ -286,6 +331,8 @@ class OrderWmsService extends Service { warehouse: view.warehouse, wmsItemIdByProduct: wmsItemIds.byProduct, wmsItemIdByItemCode: wmsItemIds.byItemCode, + // 报文里的商品编码/名称以系统商品为准(明细可能是拉单时的平台原值) + productById: wmsItemIds.productById, }); } catch (err) { // 超时 / 网络异常 / 非法响应:可重试 diff --git a/backend/database/migrations/20261104030000-create-order-sync-tasks.js b/backend/database/migrations/20261104030000-create-order-sync-tasks.js new file mode 100644 index 0000000..12a57c1 --- /dev/null +++ b/backend/database/migrations/20261104030000-create-order-sync-tasks.js @@ -0,0 +1,80 @@ +'use strict'; + +/** + * 拉单任务表(异步任务池):一键拉取全部外部打单平台店铺 / 后续其它来源的订单。 + * + * 与 export_tasks 的设计一致:提交只落一条「待处理」记录并立即返回任务ID, + * 由定时任务(orderSyncWorker)认领后逐个店铺拉单,进度与逐店结果写回本表,前端轮询展示。 + * + * - scope:任务范围,当前只有 external_print(外部打单平台店铺),后续可扩展其它来源 + * - shop_ids:null/空 表示按 scope 匹配全部可拉取店铺;否则仅拉取指定店铺 + * - items:逐店结果 JSON 数组(店铺名 / 时间窗 / 订单数 / 新增 / 更新 / 跳过 / 作废 / 失败原因) + */ +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.createTable('order_sync_tasks', { + id: { type: Sequelize.BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' }, + principal_id: { type: Sequelize.BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID(按主体隔离)' }, + scope: { + type: Sequelize.STRING(30), + allowNull: false, + defaultValue: 'external_print', + comment: '拉单范围:external_print=外部打单平台店铺(后续可扩展其它来源)', + }, + status: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 0, + comment: '状态:0待处理 1处理中 2已完成 3部分失败 4失败', + }, + start_time: { type: Sequelize.DATE, allowNull: true, comment: '拉单起始时间(按平台下单时间过滤)' }, + end_time: { type: Sequelize.DATE, allowNull: true, comment: '拉单结束时间' }, + lookback_days: { type: Sequelize.INTEGER, allowNull: true, comment: '回看天数(0=全部待处理)' }, + shop_ids: { type: Sequelize.JSON, allowNull: true, comment: '指定店铺ID数组;空表示按范围匹配全部' }, + total_shops: { type: Sequelize.INTEGER, allowNull: false, defaultValue: 0, comment: '待拉取店铺数' }, + processed_shops: { type: Sequelize.INTEGER, allowNull: false, defaultValue: 0, comment: '已处理店铺数' }, + failed_shops: { type: Sequelize.INTEGER, allowNull: false, defaultValue: 0, comment: '失败店铺数' }, + created_orders: { type: Sequelize.INTEGER, allowNull: false, defaultValue: 0, comment: '新增订单数' }, + updated_orders: { type: Sequelize.INTEGER, allowNull: false, defaultValue: 0, comment: '更新订单数' }, + skipped_orders: { type: Sequelize.INTEGER, allowNull: false, defaultValue: 0, comment: '跳过(平台已发货)订单数' }, + voided_orders: { type: Sequelize.INTEGER, allowNull: false, defaultValue: 0, comment: '自动作废订单数(合计)' }, + voided_shipped_orders: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '自动作废中「平台已发货/已终结」的订单数', + }, + voided_missing_orders: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '自动作废中「平台已查不到」的订单数', + }, + progress: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 0, comment: '进度百分比 0-100' }, + items: { type: Sequelize.JSON, allowNull: true, comment: '逐店结果 JSON 数组' }, + error_message: { type: Sequelize.STRING(500), allowNull: true, comment: '整体失败原因' }, + created_by: { type: Sequelize.BIGINT.UNSIGNED, allowNull: true, comment: '提交人ID' }, + started_at: { type: Sequelize.DATE, allowNull: true, comment: '开始执行时间' }, + finished_at: { type: Sequelize.DATE, allowNull: true, comment: '执行结束时间' }, + created_at: { type: Sequelize.DATE, allowNull: true, comment: '创建时间' }, + updated_at: { type: Sequelize.DATE, allowNull: true, comment: '更新时间' }, + }); + + await queryInterface.addIndex('order_sync_tasks', [ 'principal_id', 'status' ], { + name: 'idx_order_sync_task_principal_status', + }); + await queryInterface.addIndex('order_sync_tasks', [ 'status' ], { + name: 'idx_order_sync_task_status', + }); + await queryInterface.addIndex('order_sync_tasks', [ 'created_at' ], { + name: 'idx_order_sync_task_created', + }); + }, + + async down(queryInterface) { + await queryInterface.removeIndex('order_sync_tasks', 'idx_order_sync_task_created'); + await queryInterface.removeIndex('order_sync_tasks', 'idx_order_sync_task_status'); + await queryInterface.removeIndex('order_sync_tasks', 'idx_order_sync_task_principal_status'); + await queryInterface.dropTable('order_sync_tasks'); + }, +}; diff --git a/backend/database/migrations/20261104040000-create-waybill-fetch-records.js b/backend/database/migrations/20261104040000-create-waybill-fetch-records.js new file mode 100644 index 0000000..2e19ec9 --- /dev/null +++ b/backend/database/migrations/20261104040000-create-waybill-fetch-records.js @@ -0,0 +1,129 @@ +'use strict'; + +/** + * 取号明细记录表。 + * + * `deliveryorder.getwaybill` 每次向打单平台取号(含「复用平台已有运单号」与失败)都落一条, + * 目的是把**平台原始返回**留存下来,便于: + * - 核对 WMS 该拿什么格式回写(printinfo / signature 原样透传); + * - 面单重复、号码不变、模板异常等问题复盘(不用再靠日志里截断的响应); + * - 与 `openapi_request_idempotency` 的请求级幂等对齐(同一次请求的所有单据可按 request_id 串起来)。 + * + * 与订单表的关系:**不写订单表**(取号与订单暂不关联),本表只做留痕,可随时清理。 + */ +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.createTable('waybill_fetch_records', { + id: { + type: Sequelize.BIGINT.UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键', + }, + principal_id: { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: false, + comment: '主体ID(来自 app_key)', + }, + warehouse_id: { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: true, + comment: '仓库ID(来自 app_key)', + }, + request_id: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '调用方 request_id(同一次批量取号共用)', + }, + delivery_order_code: { + type: Sequelize.STRING(100), + allowNull: false, + comment: 'OMS 发货单号(WMS 传入的 deliveryOrderCode)', + }, + express_code: { + type: Sequelize.STRING(50), + allowNull: true, + comment: '本次取号的快递编码(报文传入)', + }, + platform_code: { + type: Sequelize.STRING(50), + allowNull: true, + comment: '订单来源平台编码', + }, + account_id: { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: true, + comment: '外部打单账号ID', + }, + template_id: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '面单模板ID(平台侧)', + }, + status: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 0, + comment: '状态:1成功 0失败', + }, + waybill_source: { + type: Sequelize.STRING(20), + allowNull: true, + comment: '运单号来源:express_print=本次取号 platform_last=复用平台已有运单号', + }, + waybill_code: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '主运单号', + }, + waybill_codes: { + type: Sequelize.TEXT, + allowNull: true, + comment: '全部运单号(JSON 数组,多包裹场景)', + }, + printinfo: { + type: Sequelize.TEXT('medium'), + allowNull: true, + comment: '面单打印数据(平台原样返回,透传给 WMS)', + }, + signature: { + type: Sequelize.TEXT('medium'), + allowNull: true, + comment: '面单签名(平台原样返回,透传给 WMS)', + }, + raw_response: { + type: Sequelize.TEXT('medium'), + allowNull: true, + comment: '平台原始返回(JSON,调试用)', + }, + error_message: { + type: Sequelize.TEXT, + allowNull: true, + comment: '失败原因', + }, + created_at: { type: Sequelize.DATE, allowNull: true, comment: '创建时间' }, + updated_at: { type: Sequelize.DATE, allowNull: true, comment: '更新时间' }, + }); + + await queryInterface.addIndex('waybill_fetch_records', [ 'delivery_order_code' ], { + name: 'idx_waybill_fetch_order_code', + }); + await queryInterface.addIndex('waybill_fetch_records', [ 'waybill_code' ], { + name: 'idx_waybill_fetch_waybill_code', + }); + await queryInterface.addIndex('waybill_fetch_records', [ 'request_id' ], { + name: 'idx_waybill_fetch_request_id', + }); + await queryInterface.addIndex('waybill_fetch_records', [ 'created_at' ], { + name: 'idx_waybill_fetch_created', + }); + }, + + async down(queryInterface) { + await queryInterface.removeIndex('waybill_fetch_records', 'idx_waybill_fetch_created'); + await queryInterface.removeIndex('waybill_fetch_records', 'idx_waybill_fetch_request_id'); + await queryInterface.removeIndex('waybill_fetch_records', 'idx_waybill_fetch_waybill_code'); + await queryInterface.removeIndex('waybill_fetch_records', 'idx_waybill_fetch_order_code'); + await queryInterface.dropTable('waybill_fetch_records'); + }, +}; diff --git a/backend/database/migrations/20261104050000-add-external-send-fields-to-order-status.js b/backend/database/migrations/20261104050000-add-external-send-fields-to-order-status.js new file mode 100644 index 0000000..52e9088 --- /dev/null +++ b/backend/database/migrations/20261104050000-add-external-send-fields-to-order-status.js @@ -0,0 +1,69 @@ +'use strict'; + +/** + * 状态表 / 历史表增加「同步外部发货」状态字段。 + * + * 配送后需要把发货结果同步回外部打单平台(店管家 `NewOrder/OnlineSendBatch`): + * - 逐单记录状态与尝试次数,失败自动重试,超过上限转异常(等人工批量重试); + * - 订单流转时按字段定义整体搬运,所以所有状态表 + 历史表都要有这几列。 + */ + +const TABLES = [ + 'order_status_pending', + 'order_status_queued', + 'order_status_exception', + 'order_status_outsourcing', + 'order_status_delivery', + 'order_status_void', + 'order_status_canceled', + 'order_status_history', +]; + +module.exports = { + async up(queryInterface, Sequelize) { + for (const table of TABLES) { + await queryInterface.addColumn(table, 'external_send_status', { + type: Sequelize.TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '同步外部发货状态:0待同步 1已同步 2同步失败待重试 3异常(重试超限)', + }); + await queryInterface.addColumn(table, 'external_send_times', { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '同步外部发货已尝试次数', + }); + await queryInterface.addColumn(table, 'external_send_error', { + type: Sequelize.STRING(500), + allowNull: true, + comment: '最近一次同步失败原因', + }); + await queryInterface.addColumn(table, 'external_send_at', { + type: Sequelize.DATE, + allowNull: true, + comment: '最近一次同步尝试时间', + }); + await queryInterface.addColumn(table, 'external_sent_at', { + type: Sequelize.DATE, + allowNull: true, + comment: '同步成功时间', + }); + } + + await queryInterface.addIndex('order_status_delivery', [ 'principal_id', 'external_send_status' ], { + name: 'idx_delivery_external_send_status', + }); + }, + + async down(queryInterface) { + await queryInterface.removeIndex('order_status_delivery', 'idx_delivery_external_send_status'); + for (const table of TABLES) { + await queryInterface.removeColumn(table, 'external_sent_at'); + await queryInterface.removeColumn(table, 'external_send_at'); + await queryInterface.removeColumn(table, 'external_send_error'); + await queryInterface.removeColumn(table, 'external_send_times'); + await queryInterface.removeColumn(table, 'external_send_status'); + } + }, +}; diff --git a/backend/database/migrations/20261104050100-backfill-external-send-status.js b/backend/database/migrations/20261104050100-backfill-external-send-status.js new file mode 100644 index 0000000..af18f50 --- /dev/null +++ b/backend/database/migrations/20261104050100-backfill-external-send-status.js @@ -0,0 +1,20 @@ +'use strict'; + +/** + * 回填历史配送单的外部发货同步状态。 + * + * 新增 `external_send_status` 时默认值是 0(待同步),但历史配送单的发货结果早已同步过 + * (或者本来就不需要同步),如果不回填,定时任务会把**存量订单全部重新通知平台发货**, + * 造成误发货。这里把当前存量统一标记为「已同步」,只有上线之后新流转到配送的订单才会自动同步。 + */ +module.exports = { + async up(queryInterface) { + await queryInterface.sequelize.query( + 'UPDATE `order_status_delivery` SET `external_send_status` = 1, `external_sent_at` = NOW() WHERE `external_send_status` = 0' + ); + }, + + async down() { + // 回填不可逆(也无法区分哪些是历史数据),无需回退 + }, +}; diff --git a/backend/database/migrations/20261104060000-add-cai-niao-auth-info-id-to-express-interfaces.js b/backend/database/migrations/20261104060000-add-cai-niao-auth-info-id-to-express-interfaces.js new file mode 100644 index 0000000..41a81b5 --- /dev/null +++ b/backend/database/migrations/20261104060000-add-cai-niao-auth-info-id-to-express-interfaces.js @@ -0,0 +1,36 @@ +'use strict'; + +/** + * 快递接口(面单模板)增加菜鸟授权网点ID独立字段。 + * + * 平台模板列表里 `CaiNiaoAuthInfoId` 表示该模板绑定的菜鸟授权网点(同平台下不同网点取值不同), + * 之前只存在 `raw` JSON 里;独立出来便于: + * - 取号时回传给 WMS(WMS 需要按网点归集/对账); + * - 后续多网点取号、按网点筛选。 + */ +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('external_print_express_interfaces', 'cai_niao_auth_info_id', { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: true, + comment: '菜鸟授权网点ID(平台模板 CaiNiaoAuthInfoId)', + }); + + // 从已有 raw 回填(JSON 里的值可能是字符串或数字) + await queryInterface.sequelize.query(` + UPDATE \`external_print_express_interfaces\` + SET \`cai_niao_auth_info_id\` = CAST(JSON_UNQUOTE(JSON_EXTRACT(\`raw\`, '$.CaiNiaoAuthInfoId')) AS UNSIGNED) + WHERE JSON_EXTRACT(\`raw\`, '$.CaiNiaoAuthInfoId') IS NOT NULL + AND JSON_UNQUOTE(JSON_EXTRACT(\`raw\`, '$.CaiNiaoAuthInfoId')) REGEXP '^[0-9]+$' + `); + + await queryInterface.addIndex('external_print_express_interfaces', [ 'cai_niao_auth_info_id' ], { + name: 'idx_express_interface_cai_niao_auth', + }); + }, + + async down(queryInterface) { + await queryInterface.removeIndex('external_print_express_interfaces', 'idx_express_interface_cai_niao_auth'); + await queryInterface.removeColumn('external_print_express_interfaces', 'cai_niao_auth_info_id'); + }, +}; diff --git a/backend/scripts/dgj-waybill-probe.js b/backend/scripts/dgj-waybill-probe.js new file mode 100644 index 0000000..473059c --- /dev/null +++ b/backend/scripts/dgj-waybill-probe.js @@ -0,0 +1,320 @@ +'use strict'; + +/** + * 店管家取号手工验证脚本(不参与线上流程) + * + * 默认只做「只读」步骤:查订单 → 查绑定 → 调店管家订单列表接口回读订单行 → 打印将要发送的取号报文。 + * 只有显式加「--execute」才会真正调用 ExpressPrint(会消耗面单并产生费用); + * 真实取号默认开启,如需禁止(DGJ_WAYBILL_ENABLE=0)则脚本会拒绝执行。 + * + * 用法: + * node scripts/dgj-waybill-probe.js --order dgj-10000266092590 --express STO + * node scripts/dgj-waybill-probe.js --order dgj-10000266092590 --express STO --execute + * node scripts/dgj-waybill-probe.js --order dgj-10000266092590 --express STO --execute --package-count 2 + */ + +const fs = require('fs'); +const path = require('path'); +const mm = require('egg-mock'); +const { ORDER_TABLE_BY_STATUS } = require('../app/lib/orderStatus'); + +function readArg(name) { + const index = process.argv.indexOf(`--${name}`); + if (index > -1) return process.argv[index + 1]; + const inline = process.argv.find(item => item.startsWith(`--${name}=`)); + return inline ? inline.slice(name.length + 3) : ''; +} + +(async () => { + const orderNo = readArg('order'); + const expressCode = readArg('express'); + const execute = process.argv.includes('--execute'); + const pkgIndexArg = readArg('pkg-index'); + const packageCount = Number(readArg('package-count') || 0) || 0; + + if (!orderNo || !expressCode) { + console.error('用法:node scripts/dgj-waybill-probe.js --order --express <快递编码> [--execute] [--pkg-index N] [--package-count N]'); + process.exit(1); + } + // 包裹序号(0 基):默认取单号尾部 `_N`(N-1),显式传 --pkg-index 时以传参为准 + const packageIndex = pkgIndexArg === '' ? null : Number(pkgIndexArg); + + const app = mm.app(); + await app.ready(); + const ctx = app.mockContext(); + + const index = await ctx.model.OrderIndex.findOne({ where: { order_no: orderNo } }); + if (!index) throw new Error(`未找到订单:${orderNo}`); + const order = await ctx.model[orderTableModel(app, index.current_status)].findByPk(index.id); + if (!order) throw new Error(`订单状态行不存在:${orderNo}(${index.current_status})`); + + const shop = order.shop_id ? await ctx.model.Shop.findByPk(order.shop_id) : null; + if (!shop || Number(shop.type) !== 2 || !shop.external_print_account_id) { + throw new Error('订单店铺不是外部打单平台商家,无法取号'); + } + const account = await ctx.model.ExternalPrintAccount.findByPk(shop.external_print_account_id, { + include: [{ model: ctx.model.ExternalPrintPlatform, as: 'platform' }], + }); + if (!account || !account.platform) throw new Error('打单账号或平台配置不存在'); + + const platformCode = String(order.source_platform_code || '').trim(); + const template = await ctx.service.externalPrintExpressInterface.resolveByCode( + account.id, + { platformCode, expressCode }, + order.principal_id + ); + + console.log('==== 订单 / 账号 / 绑定 ===='); + console.log({ + order_no: order.order_no, + parent_order_no: order.parent_order_no, + status: index.current_status, + platform_code: platformCode, + shop: { id: shop.id, name: shop.name, type: shop.type }, + account: { id: account.id, account: account.account, platform: account.platform.code, fetch_waybill_no: account.platform.fetch_waybill_no }, + express_code: expressCode, + template: template + ? { + id: template.id, + template_id: template.template_id, + template_name: template.template_name, + platform_type: template.platform_type, + dbname: template.dbname, + express_company: `${template.express_company_code}(${template.express_company_name})`, + } + : null, + }); + + if (!template) { + console.log('\n❌ 该编码没有绑定快递接口,无法取号(先到「外部打单平台 → 快递接口」绑定)'); + process.exit(0); + } + + const service = ctx.service.externalPrintOrder.createPlatformService(account); + const detail = template.get ? template.get({ plain: true }) : template; + + // 只读步骤:回读店管家订单行(不消耗面单) + let traceId = ''; + try { + const info = await service.getUserInfo(); + traceId = (info.data && info.data.TraceId) || ''; + } catch (err) { + console.log(`⚠️ 获取 traceId 失败(不阻断):${err.message}`); + } + + const logicalOrderId = String(order.parent_order_no || orderNo.replace(/^[^-]+-/, '')); + const platformOrderId = String((order.extend_props && order.extend_props.platform_order_no) || order.oaid_order_source_code || ''); + console.log('\n==== 回读店管家订单行(只读) ===='); + console.log({ logicalOrderId, platformOrderId, traceId: traceId ? '已获取' : '空' }); + + let row = null; + try { + row = await service.findPlatformOrderRow(service.constructor.resolveOrderHost(detail.platform_type), { + traceId, + dbname: detail.dbname, + logicalOrderId, + platformOrderId, + placeOrderTime: order.place_order_time || order.pay_time || order.created_at, + }); + } catch (err) { + console.log(`❌ 回读订单行失败:${err.message}`); + } + + if (!row) { + console.log('❌ 店管家未返回该订单行,取号会失败(检查系统编号/分区 dbname/登录态)'); + process.exit(0); + } + + console.log({ + Id: row.Id, + LogicOrderId: row.LogicOrderId, + PlatformOrderId: row.PlatformOrderId, + ShopId: row.ShopId, + FxUserId: row.FxUserId, + ErpState: row.ErpState, + PrintState: row.PrintState, + ExpressPrintTimes: row.ExpressPrintTimes, + ExpressPrintTime: row.ExpressPrintTime, + LastWaybillCode: row.LastWaybillCode, + WaybillCodes: Array.isArray(row.WaybillCodes) ? `[] (${row.WaybillCodes.length} 个)` : row.WaybillCodes, + IsMultiPack: row.IsMultiPack, + SumPackageCount: row.SumPackageCount, + SubOrders: Array.isArray(row.SubOrders) ? row.SubOrders.length : 0, + }); + + // 组装「将要发送」的报文,方便手工核对(不发送) + const host = service.constructor.resolveOrderHost(detail.platform_type); + console.log('\n==== 平台已有运单号 ===='); + console.log(row.LastWaybillCode + ? `平台订单行已有运单号 ${row.LastWaybillCode}(仅用于对比:OMS 不再复用,真实取号会调 ExpressPrint 换新号)` + : '(平台无运单号,真实取号会调用 ExpressPrint,消耗面单)'); + console.log(`打印状态 PrintState=${row.PrintState}、已打印 ${row.ExpressPrintTimes || 0} 次、` + + `WaybillCodes=${Array.isArray(row.WaybillCodes) ? row.WaybillCodes.length : 0} 个、IsMultiPack=${row.IsMultiPack}`); + if (Array.isArray(row.WaybillCodes) && row.WaybillCodes.length) { + console.log('WaybillCodes 明细:', JSON.stringify(row.WaybillCodes.map(code => ({ + WaybillCode: code.WaybillCode, + WaybillCodeId: code.WaybillCodeId, + TemplateId: code.TemplateId, + CreateTime: code.CreateTime || code.WaybillCodeCreateDate, + })))); + } + console.log('(取号统一走「新单号打印」:PrintMethod=NewPrint + IsIgnoreWaybillRepeat=false,每次分配新号)'); + + const buildForm = service.constructor.buildForm; + const effectivePkgIndex = packageIndex === null + ? (String(orderNo).match(/_(\d+)$/) ? Math.max(Number(String(orderNo).match(/_(\d+)$/)[1]) - 1, 0) : 0) + : packageIndex; + console.log(`\n包裹序号 = ${effectivePkgIndex}(仅留痕,不下发给平台:每次取号都会分配新号);PackageCount = ${packageCount || 1}`); + const checkForm = buildCheckForm(buildForm, detail.template_id, [ row ]); + const printForm = buildPrintForm(buildForm, detail.template_id, [ row ], { DateNow: '', DayPrintBatchNumber: '' }, packageCount || 1); + console.log('\n==== 将发送的 CheckTemplateAvaliable(只读接口) ===='); + console.log(`POST https://${host}/TemplateSet/CheckTemplateAvaliable`); + console.log(checkForm); + console.log('\n==== 将发送的 ExpressPrint(会消耗面单) ===='); + console.log(`POST https://${host}/NewOrder/ExpressPrint`); + console.log(printForm); + + if (!execute) { + console.log('\n✅ 已完成只读校验,未调用取号接口。需要真实取号时执行:'); + console.log(`node scripts/dgj-waybill-probe.js --order ${orderNo} --express ${expressCode} --execute [--package-count N]`); + process.exit(0); + } + + if (!service.constructor.isWaybillEnabled()) { + console.log('\n❌ 当前已用 DGJ_WAYBILL_ENABLE=0 关闭真实取号,脚本拒绝执行;去掉该环境变量后再试'); + process.exit(1); + } + + console.log('\n⚠️ 即将真实取号(消耗面单)...'); + const result = await service.fetchWaybillNo(order.get({ plain: true }), { + template: detail, + expressCode, + platformCode, + packageIndex: effectivePkgIndex, + packageCount: packageCount || 1, + }); + + const dir = path.join(__dirname, '..', 'tmp'); + fs.mkdirSync(dir, { recursive: true }); + const file = path.join(dir, `dgj-expressprint-${orderNo}-${Date.now()}.json`); + fs.writeFileSync(file, JSON.stringify(result.raw, null, 2), 'utf8'); + + console.log('==== 取号结果 ===='); + console.log({ + waybill_code: result.waybill_code, + waybill_codes: result.waybill_codes, + previous_code: result.previous_code || '', + printinfo_len: (result.printinfo || '').length, + printinfo_head: (result.printinfo || '').slice(0, 120), + signature: result.signature ? '已返回' : '无', + raw: file, + }); + if (result.previous_code && result.previous_code === result.waybill_code) { + console.log(`⚠️ 本次调用 ExpressPrint,但平台仍返回原运单号 ${result.previous_code}(平台未换号)`); + } +})(); + +/** + * 状态 → 模型名 + * @param {Object} app egg application + * @param {string} status 订单状态 + * @return {string} 模型名 + */ +function orderTableModel(app, status) { + const map = { + pending: 'OrderStatusPending', + queued: 'OrderStatusQueued', + exception: 'OrderStatusException', + outsourcing: 'OrderStatusOutsourcing', + delivery: 'OrderStatusDelivery', + void: 'OrderStatusVoid', + }; + if (!map[status]) throw new Error(`未知订单状态:${status}(表 ${ORDER_TABLE_BY_STATUS[status] || '-'})`); + return map[status]; +} + +/** + * 组装 CheckTemplateAvaliable 表单(与 dgj.checkTemplateAvailable 同口径) + * @param {Object} buildForm 平台服务的表单构造器(PHP http_build_query 口径) + * @param {string} templateId 模板ID + * @param {Array} rows 平台订单行 + * @return {string} 表单字符串 + */ +function buildCheckForm(buildForm, templateId, rows) { + return buildForm({ + templateId: String(templateId), + printCount: String(rows.length), + needCheck: 'true', + orders: rows.map(row => ({ + SourceShopId: row.ShopId, + UpFxUserId: row.FxUserId, + SourceFxUserId: row.FxUserId, + LogicOrderId: row.LogicOrderId, + PlatformOrderId: row.LogicOrderId, + IsAllowNegativeStock: 'false', + SendType: row.SendState, + DataFlag: row.IsCold, + Items: (row.SubOrders || []).map(sub => ({ + OrderItemCode: sub.OrderItemCode, + LogicOrderItemId: sub.OrderItemId, + Quantity: '1', + })), + })), + isResend: '', + pirntMethod: 'Normal', + IsContinueForStock: 'false', + IsCustomerOrder: 'false', + FxPageType: '2', + }).toString(); +} + +/** + * 组装 ExpressPrint 表单(仅用于打印核对) + * @param {Object} buildForm 平台服务的表单构造器(PHP http_build_query 口径) + * @param {string} templateId 模板ID + * @param {Array} rows 平台订单行 + * @param {Object} checkData CheckTemplateAvaliable 的 Data + * @param {number} [packageCount] 包裹张数(>1 时把订单行重复 N 份,用于多包裹试验) + * @return {string} 表单字符串 + */ +function buildPrintForm(buildForm, templateId, rows, checkData, packageCount = 1) { + const repeat = Number(packageCount) > 1 ? Math.floor(Number(packageCount)) : 1; + const sourceRows = []; + for (let i = 0; i < repeat; i += 1) sourceRows.push(...(rows || [])); + return buildForm({ + TemplateId: String(templateId), + PackageCount: String(repeat), + PackageDesc: '', + GoodsDesc: '', + PrintMethod: 'Normal', + IsIgnoreWaybillRepeat: 'true', + PrinterName: '默认打印机', + IsPreview: 'false', + IsContinueForStock: 'false', + PackageLength: '', + PackageWidth: '', + PackageHeight: '', + ExpressSustenance: { name: '', desc: '' }, + Branches: '', + Orders: sourceRows.map((row, index) => ({ + WaybillCodeId: '', + Index: index + 1, + Id: row.Id, + LogicOrderId: row.LogicOrderId, + PlatformOrderId: row.LogicOrderId, + CustomerOrderId: row.PlatformOrderId, + ShopId: row.ShopId, + PathFlowCode: row.PathFlowCode, + FxUserId: row.FxUserId, + WaybillCode: '', + Items: (row.SubOrders || []).map(sub => ({ + OrderItemId: sub.OrderItemId, + OrderItemCode: sub.OrderItemCode, + Quantity: '1', + })), + })), + RequestBatchNumber: `1/1/${checkData.DateNow || ''}${checkData.DayPrintBatchNumber || ''}`, + IsCustomerOrder: 'false', + FxPageType: '2', + }).toString(); +} diff --git a/backend/scripts/rebuild-order-items.js b/backend/scripts/rebuild-order-items.js index 5402b4c..782810e 100644 --- a/backend/scripts/rebuild-order-items.js +++ b/backend/scripts/rebuild-order-items.js @@ -5,10 +5,13 @@ * * 背景:平台订单明细需要按店铺商品绑定关系展开为最小单位(组合商品拆成子商品行), * 旧代码只把绑定结果写回明细、不做拆分,存量订单会残留组合行。 + * 另有存量问题:绑定系统商品后明细的 item_code/item_name 仍是平台原值(页面看起来"没转换"), + * 用 `--stale` 可只挑出这类不一致的订单重建。 * * 用法: * node scripts/rebuild-order-items.js # 重建全部外部打单平台订单 * node scripts/rebuild-order-items.js --order 226 # 只重建指定订单(可逗号分隔) + * node scripts/rebuild-order-items.js --stale # 只重建「已绑定但编码仍是平台值」的订单 * node scripts/rebuild-order-items.js --dry-run # 只统计不写库 */ const mm = require('egg-mock'); @@ -16,13 +19,14 @@ const mm = require('egg-mock'); /** * 解析命令行参数 * @param {Array} argv 进程参数(process.argv.slice(2)) - * @return {{orderIds: Array, dryRun: boolean}} 解析结果 + * @return {{orderIds: Array, dryRun: boolean, stale: boolean}} 解析结果 */ function parseArgs(argv) { - const args = { orderIds: [], dryRun: false }; + const args = { orderIds: [], dryRun: false, stale: false }; for (let i = 0; i < argv.length; i++) { const arg = argv[i]; if (arg === '--dry-run') args.dryRun = true; + else if (arg === '--stale') args.stale = true; else if (arg === '--order' || arg === '--orders') { const value = argv[i + 1] || ''; args.orderIds.push(...value.split(',').map(v => Number(v.trim())).filter(v => v > 0)); @@ -32,6 +36,46 @@ function parseArgs(argv) { return args; } +/** + * 找出「已绑定系统商品、但明细编码/名称仍是平台原值」的待审核/异常订单 + * (绑定后未重建明细的存量脏数据,推送会被拦截或用错编码) + * @param {Object} ctx egg context + * @return {Promise>} 订单ID列表 + */ +async function findStaleOrderIds(ctx) { + const Op = ctx.app.Sequelize.Op; + const rows = await ctx.model.OrderStatusItem.findAll({ + where: { + product_id: { [Op.ne]: null }, + parse_status: 1, + }, + attributes: [ 'order_id', 'product_id', 'item_code' ], + raw: true, + }); + if (!rows.length) return []; + + const products = await ctx.model.Product.findAll({ + where: { id: { [Op.in]: [ ...new Set(rows.map(r => Number(r.product_id))) ] } }, + attributes: [ 'id', 'item_code' ], + raw: true, + }); + const codeById = new Map(products.map(p => [ Number(p.id), String(p.item_code || '') ])); + + const staleOrderIds = new Set(); + for (const row of rows) { + const expected = codeById.get(Number(row.product_id)); + if (expected && expected !== String(row.item_code || '')) staleOrderIds.add(Number(row.order_id)); + } + if (!staleOrderIds.size) return []; + + const indexes = await ctx.model.OrderIndex.findAll({ + where: { id: { [Op.in]: [ ...staleOrderIds ] }, current_status: { [Op.in]: [ 'pending', 'exception' ] } }, + attributes: [ 'id' ], + raw: true, + }); + return indexes.map(row => Number(row.id)); +} + (async () => { const args = parseArgs(process.argv.slice(2)); const app = mm.app(); @@ -40,7 +84,11 @@ function parseArgs(argv) { let orderIds = args.orderIds; const Op = app.Sequelize.Op; - if (!orderIds.length) { + if (!orderIds.length && args.stale) { + orderIds = await findStaleOrderIds(ctx); + console.log(`发现明细编码与绑定商品不一致的订单 ${orderIds.length} 个`); + } + if (!orderIds.length && !args.stale) { // 只处理平台拉取的订单:老表 orders.external_order_id 有值 → 按 order_no 映射到订单索引表 const legacy = await ctx.model.Order.findAll({ where: { external_order_id: { [Op.ne]: null } }, diff --git a/frontend/src/api/externalSendSync.ts b/frontend/src/api/externalSendSync.ts new file mode 100644 index 0000000..592a818 --- /dev/null +++ b/frontend/src/api/externalSendSync.ts @@ -0,0 +1,49 @@ +import request from '@/utils/request' + +/** + * 外部打单平台「同步发货」相关接口 + * + * 配送后 OMS 需要把发货结果同步回店管家(NewOrder/OnlineSendBatch): + * 失败自动重试,3 次后转异常,人工可在配送视图批量重试。 + */ + +/** 各同步状态数量 */ +export interface ExternalSendCounts { + pending: number + retry: number + exception: number + synced: number + total: number +} + +/** 批量重试结果 */ +export interface ExternalSendRetryResult { + reset: number + success: number + failed: number +} + +/** 同步状态枚举(与后端 SEND_STATUS 对齐) */ +export const EXTERNAL_SEND_STATUS_OPTIONS = [ + { value: 0, label: '待同步' }, + { value: 1, label: '已同步' }, + { value: 2, label: '同步失败待重试' }, + { value: 3, label: '同步异常' }, +] + +/** + * 查询同步状态数量 + * @returns 各状态数量 + */ +export function getExternalSendCounts() { + return request.get<{ data: ExternalSendCounts }>('/external-send/counts') +} + +/** + * 批量重试同步外部发货 + * @param ids 订单ID数组(为空时按 statuses 筛选) + * @param statuses 状态筛选(默认 [2,3]:待重试 + 异常) + */ +export function retryExternalSend(ids?: number[], statuses?: number[]) { + return request.post<{ data: ExternalSendRetryResult }>('/external-send/retry', { ids, statuses }) +} diff --git a/frontend/src/api/orderStatus.ts b/frontend/src/api/orderStatus.ts index d6c3279..beb8df9 100644 --- a/frontend/src/api/orderStatus.ts +++ b/frontend/src/api/orderStatus.ts @@ -150,6 +150,13 @@ export interface OrderStatusItem { void_at?: string | null void_by?: number | null void_reason?: string | null + /** 同步外部打单平台发货:0待同步 1已同步 2待重试 3异常(重试超限) */ + external_send_status?: number | null + external_send_status_label?: string | null + external_send_times?: number | null + external_send_error?: string | null + external_send_at?: string | null + external_sent_at?: string | null /** 索引表记录的当前所在表 */ current_table?: OrderStage created_at?: string diff --git a/frontend/src/api/orderSyncTask.ts b/frontend/src/api/orderSyncTask.ts new file mode 100644 index 0000000..2f3e780 --- /dev/null +++ b/frontend/src/api/orderSyncTask.ts @@ -0,0 +1,98 @@ +import { get, post } from '@/utils/request' + +/** + * 拉单任务(异步任务池):一键拉取外部打单平台店铺订单。 + * + * 提交后立即返回任务ID,定时任务逐店执行;前端轮询进度接口展示 + * 「已处理店铺 / 总店铺」与逐店结果,供运营确认哪些店铺失败。 + */ + +/** 任务状态:0待处理 1处理中 2已完成 3部分失败 4失败 */ +export type OrderSyncStatus = 0 | 1 | 2 | 3 | 4 + +/** 拉单范围:目前仅外部打单平台店铺,后续可扩展其它来源 */ +export type OrderSyncScope = 'external_print' | string + +/** 逐店拉单结果 */ +export interface OrderSyncShopItem { + shop_id: number + shop_code: string + shop_name: string + account_id: number | null + success: boolean + message: string + orders?: number + created?: number + updated?: number + skipped?: number + voided?: number + voided_shipped?: number + voided_missing?: number + items?: number +} + +/** 拉单任务 */ +export interface OrderSyncTaskItem { + id: number + principal_id: number + scope: OrderSyncScope + scope_label?: string + status: OrderSyncStatus + status_label?: string + start_time: string | null + end_time: string | null + lookback_days: number | null + total_shops: number + processed_shops: number + failed_shops: number + created_orders: number + updated_orders: number + skipped_orders: number + voided_orders: number + progress: number + items?: OrderSyncShopItem[] + failed_items?: OrderSyncShopItem[] + error_message: string | null + created_at: string + started_at: string | null + finished_at: string | null +} + +/** 提交拉单任务的参数 */ +export interface OrderSyncSubmitPayload { + scope?: OrderSyncScope + /** 回看天数;0 表示「全部待处理」(不限下单时间) */ + lookback_days?: number + /** 指定店铺ID;不传表示该范围内全部店铺 */ + shop_ids?: number[] +} + +/** 提交拉单任务:立即返回任务ID */ +export function submitOrderSyncTask(payload: OrderSyncSubmitPayload) { + return post<{ + id: number + scope: OrderSyncScope + status: OrderSyncStatus + total_shops: number + start_time: string + end_time: string + }>('/order-sync-tasks', payload) +} + +/** 拉单任务列表 */ +export function getOrderSyncTasks(params?: object) { + return get<{ list: OrderSyncTaskItem[]; total: number; page: number; pageSize: number }>( + '/order-sync-tasks', + params, + ) +} + +/** 拉单任务进度(含逐店结果) */ +export function getOrderSyncTask(id: number) { + return get('/order-sync-tasks/' + id) +} + +/** 当前未完成的拉单任务(进入页面恢复进度用) */ +export function getRunningOrderSyncTask() { + return get('/order-sync-tasks/running') +} diff --git a/frontend/src/views/Order/OrderSyncDialog.vue b/frontend/src/views/Order/OrderSyncDialog.vue new file mode 100644 index 0000000..6452bef --- /dev/null +++ b/frontend/src/views/Order/OrderSyncDialog.vue @@ -0,0 +1,352 @@ + + + + + diff --git a/frontend/src/views/Order/StatusPanel.vue b/frontend/src/views/Order/StatusPanel.vue index 1bba315..4dd029e 100644 --- a/frontend/src/views/Order/StatusPanel.vue +++ b/frontend/src/views/Order/StatusPanel.vue @@ -6,7 +6,14 @@ import ExportButton from '@/components/ExportButton.vue' import ListPager from '@/components/ListPager.vue' import RecordPickerDialog from '@/components/RecordPickerDialog.vue' import OrderFormDialog from './OrderFormDialog.vue' +import OrderSyncDialog from './OrderSyncDialog.vue' import { getExpressCodeOptions } from '@/api/customExpressCode' +import { + EXTERNAL_SEND_STATUS_OPTIONS, + getExternalSendCounts, + retryExternalSend, + type ExternalSendCounts, +} from '@/api/externalSendSync' import { DEFAULT_PAGE_SIZE, useListPage } from '@/composables/useListPage' import { formatDateTime } from '@/utils/datetime' import { platformNameOf } from '@/constants/platform' @@ -54,6 +61,8 @@ const props = defineProps<{ status: OrderStage }>() const isHistory = computed(() => props.status === 'history') /** 异常视图:状态恒为「异常」,列表不再重复展示状态列,并把异常原因提到前面标红 */ const isException = computed(() => props.status === 'exception') +/** 配送视图:外卖打单订单需要把发货结果同步回平台,这里提供筛选 / 异常数量 / 批量重试 */ +const isDelivery = computed(() => props.status === 'delivery') const stageMeta = computed(() => ORDER_STAGE_META[props.status]) /* -------------------- 筛选条件(默认一行简单条件,可展开为完整条件) -------------------- */ @@ -68,10 +77,32 @@ const query = reactive({ receiver: '', address: '', remark: '', + external_send_status: '' as number | '', createdRange: [] as string[], archivedRange: [] as string[], }) +/** 外部发货同步数量(配送视图:异常数量快速查看) */ +const externalSendCounts = ref(null) + +async function fetchExternalSendCounts() { + if (!isDelivery.value) return + try { + const res = await getExternalSendCounts() + externalSendCounts.value = res.data.data + } catch { + // 统计失败不打断列表 + } +} + +/** 点异常数量 → 直接筛选异常订单 */ +function filterExternalSend(status: number) { + query.external_send_status = status + query.page = 1 + search() + fetchExternalSendCounts() +} + /** 「含未绑定商品订单」开关(默认关闭:不显示含未绑定商品的订单) */ const showUnboundOrders = ref(false) @@ -105,6 +136,9 @@ const { loading, list, total, elapsed, fetchList, search, handlePageChange, hand } // 待审核默认只看「商品都已绑定」的订单,开关打开才包含未绑定商品的订单 if (props.status === 'pending' && !showUnboundOrders.value) params.exclude_unbound = 1 + if (isDelivery.value && query.external_send_status !== '') { + params.external_send_status = query.external_send_status + } return getOrderStatusList(params as never) }, }) @@ -117,6 +151,7 @@ function reset() { query.receiver = '' query.address = '' query.remark = '' + query.external_send_status = '' query.createdRange = [] query.archivedRange = [] search() @@ -136,6 +171,7 @@ const exportFilters = computed(() => ({ archived_from: query.archivedRange[0], archived_to: query.archivedRange[1], exclude_unbound: props.status === 'pending' && !showUnboundOrders.value ? 1 : '', + external_send_status: isDelivery.value ? query.external_send_status : '', })) /* -------------------- 筛选项数据源(状态枚举 / 店铺 / 归档阈值) -------------------- */ @@ -173,6 +209,7 @@ type BatchKey = | 'restore' | 'change_warehouse' | 'change_logistics' + | 'resend_external' /** 批量操作按场景分布在各视图(店铺在创建时确定,不再提供批量设置店铺) */ const BATCH_ACTIONS: Record = { @@ -202,7 +239,7 @@ const BATCH_ACTIONS: Record(null) +/* -------------------- 一键拉取订单(异步任务) -------------------- */ +const syncDialogVisible = ref(false) + +/** 拉单任务结束:刷新列表并清空勾选(订单集合已变化) */ +async function refreshAfterSync() { + selectedIds.value = [] + await fetchList() +} + function openCreate() { formOrderId.value = null formVisible.value = true @@ -649,6 +711,7 @@ function expressCodesOf(row: OrderStatusItem): string[] { onMounted(async () => { await fetchFilters() await fetchList() + await fetchExternalSendCounts() }) @@ -658,6 +721,39 @@ onMounted(async () => {
{{ stageMeta.label }} + + { @change="onUnboundSwitchChange" /> + + 一键拉取订单 + 新建订单(发货单) @@ -708,6 +807,16 @@ onMounted(async () => { style="width: 230px" /> + + + + + 查询 重置 @@ -811,6 +920,21 @@ onMounted(async () => { - + + + @@ -947,6 +1071,9 @@ onMounted(async () => { @saved="handleFormSaved" /> + + + { font-size: 12px; color: var(--el-text-color-secondary); } +/* 外部发货同步数量标签:可点击直接筛出对应状态的订单 */ +.external-send-tag { + cursor: pointer; +} +/* 同步外部发货列:重试次数与失败原因 */ +.send-times { + margin-left: 4px; + font-size: 12px; +} +.send-error { + font-size: 12px; + color: var(--el-color-danger); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} .filter-bar { flex: 0 0 auto; margin-bottom: 0; diff --git a/店管家取号-旧系统提取.md b/店管家取号-旧系统提取.md new file mode 100644 index 0000000..e6b8138 --- /dev/null +++ b/店管家取号-旧系统提取.md @@ -0,0 +1,419 @@ +# 店管家取号:旧系统流程提取 & OMS 落地 + +> 来源:旧系统 `D:\ye4s.wms.gztbyc.com\application\index\controller\wms\Dianguanjia.php` +> (ThinkPHP,`ExpressPrint()` / `CheckTemplateAvaliable()` / `Print()` / `sendProxyRequest()` 等) +> 目标:把「分配快递号(取号)」的完整流程提取出来,供 OMS 实现 `dgj.fetchWaybillNo()`。 +> ⚠️ **ExpressPrint 会真实消耗面单并产生费用,任何真实订单测试必须由业务手工触发。** + +--- + +## 1. 结论(TL;DR) + +- 取号 = `POST /TemplateSet/CheckTemplateAvaliable`(校验/余额,只读)+ `POST /NewOrder/ExpressPrint`(取号 + 打印数据)。 +- 前提是先从 `POST /NewOrder/List` 拿到**平台订单行**(Id / LogicOrderId / ShopId / SubOrders…)。 +- **订单接口与模板接口不在同一域名**(踩坑点,见 §2)。 +- 旧系统在平台已有运单号(`LastWaybillCode`)时会直接复用;**OMS 不采用该判断**,每次都真实取号,去重只靠幂等表 `request_id`。 +- OMS 已实现(`backend/app/lib/printPlatform/dgj.js`),**默认开启真实取号**(会调用 ExpressPrint 消耗面单);需要只读联调时用 `DGJ_WAYBILL_ENABLE=0` 关闭,并提供手工验证脚本。 + +--- + +## 2. 关键坑:订单域名 ≠ 模板域名 + +旧系统 `$this->pingtais` 把「平台 ID → 域名」映射为: + +| 平台 | 旧系统域名 | 说明 | +|---|---|---| +| 淘宝 / 1688 / 视频号(WxVideo) / 小红书 / 快手 | `fxali.dgjapp.com` | 订单与取号都在这里 | +| 抖店(TouTiao) | `fxdd.dgjapp.com` | | +| 拼多多 | `fxpdd.dgjapp.com` | | +| 京东 | `fxjd.dgjapp.com` | | + +而**面单模板**接口走的是模板域名(OMS 现有 `TEMPLATE_PLATFORMS`:视频号模板在 `fxdd`)。 +实测:订单 `dgj-10000266092590`(视频号)在 `fxdd` 查不到,在 `fxali` 一次命中 —— 取号必须用**订单域名**。 + +OMS 实现:`resolveOrderHost(platformType)`(`dgj.js` 顶部 `ORDER_HOSTS`,兜底 `fxali`),与 `resolveTemplateHost` 分开。 + +--- + +## 2.1 发货接口:`POST /NewOrder/OnlineSendBatch`(同步发货) + +OMS 的订单被 WMS 回传 `deliveryorder.confirm` 流转到「配送」后,需要把发货结果**同步回店管家**,平台才会把订单状态推进为「已发货」。 +接口与取号同域(走订单域名,见上表),**不消耗面单**。 + +请求(旧系统 `Dianguanjia.php#OnlineSendBatch` 同口径,`buildPhpForm` 展开): + +``` +Orders[0][Id] / [Index] / [LogicOrderId] / [OrderCode] / [PlatformOrderId] / [PathFlowCode] +Orders[0][CustomerOrderId](= 平台单号)/ [PlatformType] / [PlatformStatus]=waitsellersend +Orders[0][WaybillCode](= LastWaybillCode)/ [ExpressCompanyCode](= WaybillCodes[0].ExpressCpCode) +Orders[0][WaybillCodeUniqueKey](= WaybillCodes[0].UniqueKey) +Orders[0][SubOrders] / [Items][n][OrderItemId/OrderItemCode/Quantity] / [OrderItems][n] +Orders[0][Receiver][toFullName/toMobile/toArea/toProvince/toCity/toCounty/toMaskAddress] +Orders[0][Sender][CompanyName] / [Buyer][BuyerWangWang] +IsCustomerOrder=false FxPageType=2 IsSendPreCheck=true IsContinueForStock=false NoLogisticsInfoModel= +``` + +OMS 实现: + +| 位置 | 作用 | +|---|---| +| `dgj.sendOrders(host, { traceId, dbname, rows })` | 组装并提交上面这份表单;`Success!==true` 抛「店管家发货同步失败:…」 || `service/externalSendSync.js` | 配送后同步的状态机(待同步 → 已同步 / 待重试 → 3 次转异常) | +| `schedule/externalSendSyncWorker.js` | 每 2 分钟扫描「待同步 / 待重试」的配送单并发货同步 | +| `POST /api/external-send/retry` | 人工批量重试(重置次数后立刻同步一批) | +| `GET /api/external-send/counts` | 待同步 / 待重试 / 异常 / 已同步数量 | + +状态字段(配送表 `order_status_delivery`,所有状态表 + 历史表同构): + +| 字段 | 说明 | +|---|---| +| `external_send_status` | 0待同步 1已同步 2同步失败待重试 3异常(重试超限) | +| `external_send_times` | 已尝试次数(≥3 转异常) | +| `external_send_error` | 最近一次失败原因 | +| `external_send_at` / `external_sent_at` | 最近尝试时间 / 同步成功时间 | + +> 存量配送单在迁移 `20261104050100` 里统一回填为「已同步」,避免上线后把历史订单重新通知平台发货。 + +--- + +## 3. 完整取号流程 + +``` +① POST /NewOrder/List 回读平台订单行(只读) + └─ 命中后拿到 Id / LogicOrderId / ShopId / FxUserId / SubOrders / LastWaybillCode + +② 已发货/已终结(isOrderFinished) → 直接失败:该单应作废/取消,不能再取号 + └─ 旧系统会「平台已有运单号就直接复用」;**OMS 不采用**: + 重复调用与否只由幂等表(request_id)决定,每次都真实取号,LastWaybillCode 仅用于事后对比是否换号 + +③ POST /TemplateSet/CheckTemplateAvaliable (只读) + └─ 返回 Data.Balance / PrintCount / DateNow / DayPrintBatchNumber / Branches + └─ Balance < PrintCount → 「余额不足」,旧系统发企业微信告警并中止 + +④ POST /NewOrder/ExpressPrint (!! 消耗面单) + └─ 返回 Data.WaybillCode[],逐单 IsError / PrintInfo(打印数据,内含 documentID = 运单号) +``` + +--- + +## 4. 各接口细节(照旧系统抄) + +### 4.1 公共约定 + +- query:`token=<账号 token>&traceId=<登录上下文 traceId>&dbname=<分区库>&dataFlag=` +- body:`application/x-www-form-urlencoded`,数组按 `Orders[0]=` 形式(PHP `http_build_query`) +- headers:`Cookie`、`X-Requested-With: XMLHttpRequest`、`Origin`、`Referer: https:///NewOrder/WaitOrder`、`User-Agent` +- 旧系统 dbname 写死 `wdJM8OZZiF4gKKxb82bFQlqydSPSQ9/W`(那是老账号的分区); + OMS 按店铺分区的 `dbname`(实测 `y/2wUDWCZOk=` 可用),两者不可混用。 + +### 4.2 订单行:`POST /NewOrder/List` + +- Filter(可精确命中,实测有效): + ``` + Filters[0][TableAlias]=o + Filters[0][FieldType]=string + Filters[0][TableName]=LogicOrder + Filters[0][Name]=LogicOrderId + Filters[0][Value]=10000266092590 + Filters[0][Contract]=in + ``` +- `PlatformOrderId` 过滤需要额外 `Filters[0][CustomQuery]=PlatformOrderIdSearch`(旧系统写法)。 +- 其余字段:`PageSize=20`、`PageIndex=1`、`OrderByField=o.CreateTime`、`requestUrl=https:///NewOrder/WaitOrder`、`FxPageType=2`。 +- 兜底:按 `CreateTime` 时间窗(±2 天)翻页扫描后本地匹配 `LogicOrderId`。 + +订单行关键字段: + +| 字段 | 用途 | +|---|---| +| `Id` / `LogicOrderId` | 取号请求的订单主键(两者实测相同) | +| `PlatformOrderId` | 平台单号(OMS `extend_props.platform_order_no`) | +| `ShopId` / `FxUserId` / `PathFlowCode` | 取号报文必填 | +| `SubOrders[].OrderItemId / OrderItemCode` | 取号明细(数量固定写 1) | +| `LastWaybillCode` | 平台已有运单号(旧系统据此复用;**OMS 只用于事后对比是否换号**)。注意:**它非空不代表已经出号给业务方**,见 §4.2.1 | +| `PrintState` / `ExpressPrintTimes` / `ExpressPrintTime` | `PrintState=1` 已打印;`ExpressPrintTimes` 是该单被打印/取号的次数,`ExpressPrintTime` 是最近一次时间 | +| `WaybillCodes` / `IsMultiPack` / `SumPackageCount` | 平台侧**已出号列表** / 是否多包裹 / 包裹数;单包裹单号场景下 `WaybillCodes` 常为空数组 | +| `CaiNiaoAuthInfoId` | **菜鸟授权网点ID**(模板绑定的授权网点;同平台不同网点取值不同)。OMS 已独立成列 `external_print_express_interfaces.cai_niao_auth_info_id`,并在取号结果里回传给 WMS | +| `ErpState` | `sended` 表示平台侧已发货;`waitsellersend` 待发货 | +| `ToName / ToPhone / ToProvince / ToCity / ToCounty / ToTown / ToAddress / ToFullAddress` | 收件人报文 | + +#### 4.2.1 `LastWaybillCode` ≠ 已出号(实测 2026-11-04) + +同一行的两次观测: + +``` +08:20 前:PrintState=1 ExpressPrintTimes=1 LastWaybillCode='772085297346161' WaybillCodes=[] +08:48 (取号 2 次后):PrintState=1 ExpressPrintTimes=4 LastWaybillCode='772085297346161' + WaybillCodes=[ + { WaybillCode:'772085302413126', WaybillCodeId:10000273932918, TemplateId:'10824270' }, + { WaybillCode:'772085257627038', WaybillCodeId:10000273851363, TemplateId:'10824270' } + ] + IsMultiPack=false SumPackageCount=1 SubOrders=1 +``` + +`ExpressPrint` 的响应里,每个运单号对应一条 `Data.WaybillCode[]`,关键字段: + +``` +WaybillCode='772085257627038' WaybillCodeId=10000273851363 +WaybillCodePid='10000267890142_0' ← 平台幂等键:_<包裹序号> +Index=0 +WaybillCodeCreateDate='2026-11-04 08:20:37' +``` + +结论: + +- `LastWaybillCode` 只是「最近一次打印用到的号」,`WaybillCodes` 才是平台确认的出号列表,两者可能不一致。 +- **平台自己的幂等键是 `WaybillCodePid = _<包裹序号>`**:同一序号重复调 `ExpressPrint` + 会拿回同一个 `WaybillCodeId` + 同一个号(我们的 08:20 / 08:39 两次就是这种情况,每次只新增一条打印历史 `PrintHistoryIds`), + 换序号才会分配新号。 +- `ExpressPrintTimes` 是打印次数,跟号码个数不是一回事(本单打印 4 次、只有 2 个号)。 +- 因此 OMS「按 `LastWaybillCode` 复用」是错的判断;是否重复取号由 **OMS 幂等表(request_id)** 决定, + 而**同一个包裹重复取号拿回同号**是平台行为,不是 bug。 + +> **多包裹 / 子单(已实测跑通,2026-11-04 09:28)** +> +> 平台「新单号打印」的判定完全靠这三个字段,其余与我们原来一致: +> +> | 字段 | 新单号打印(要新号) | 原单号打印(复用旧号) | +> |---|---|---| +> | `PrintMethod` | **`NewPrint`** | `Normal` | +> | `IsIgnoreWaybillRepeat` | **`false`** | `true` | +> | `PackageType` | `1` | 可不传 | +> | `Orders[0][PrintInfo]` | `[1];\n` | 空 | +> | `Orders[0][WaybillCode]` + `Orders[0][WaybillCodes][]` | 带上当前号(含 `WaybillCodeId` / `Pid`) | 可空 | +> +> 实测(同一订单 `10000267890142`,连续 3 次调用都拿到新号): +> +> ``` +> 09:22:14 → 772085315396234 WaybillCodeId=10000274161082 pid=63274907ebce8f6b_1_1 +> 09:22:46 → 772085293866221 WaybillCodeId=10000274129933 pid=63274907ebce8f6b_2_1 +> 09:28:xx → 772085311557965 WaybillCodeId=10000274191801 pid=63274907ebce8f6b_3_1 +> ``` +> +> 所以:**每次调用都分配新号,pid 第二段自增**;OMS 现在统一走这套参数,WMS 按包裹各调一次即可拿到各自的号。 +> 旧逻辑用的是 `Normal` + `IsIgnoreWaybillRepeat=true` → 平台按已有号复用,才出现「取子单号拿回原单号」。 +> +> ⚠️ 代价:每次取号都真实消耗一张面单(`ExpressPrintTimes` 累加),重试务必复用同一个 `request_id`。 + +### 4.3 模板校验:`POST /TemplateSet/CheckTemplateAvaliable` + +```json +{ + "templateId": "10824270", + "printCount": "1", + "needCheck": "true", + "isResend": "", + "pirntMethod": "Normal", // 注意:平台字段名就是 pirntMethod(拼写错误) + "IsContinueForStock": "false", + "IsCustomerOrder": "false", + "FxPageType": "2", + "orders[0]": { + "SourceShopId": 7319156, + "UpFxUserId": 1227061, + "SourceFxUserId": 1227061, + "LogicOrderId": "10000266092590", + "PlatformOrderId": "10000266092590", + "IsAllowNegativeStock": "false", + "SendType": 1, + "DataFlag": 1, + "Items": [{ "OrderItemCode": "10000289254637", "LogicOrderItemId": "10000289254637", "Quantity": "1" }] + } +} +``` + +响应 `Data`:`Balance`(面单余额)、`PrintCount`(本次张数)、`DateNow`、`DayPrintBatchNumber`、`Branches`(网点信息,需 null→''、true/false→字符串)。 + +### 4.4 取号:`POST /NewOrder/ExpressPrint` + +```json +{ + "TemplateId": "10824270", + "PackageCount": "1", + "PrintMethod": "Normal", + "IsIgnoreWaybillRepeat": "true", // 忽略重复校验,每次都取新号 + "PrinterName": "默认打印机", + "IsPreview": "false", + "IsContinueForStock": "false", + "PackageDesc": "", "GoodsDesc": "", "PackageLength": "", "PackageWidth": "", "PackageHeight": "", + "ExpressSustenance[name]": "", "ExpressSustenance[desc]": "", + "Branches[0]": { "...": "来自 CheckTemplateAvaliable" }, + "RequestBatchNumber": "1/1/202611045", // 1/1/ + "IsCustomerOrder": "false", + "FxPageType": "2", + "Orders[0]": { + "WaybillCodeId": "", + "Index": 1, + "Id": "10000266092590", + "PlatformOrderId": "10000266092590", // 旧系统传的是 LogicOrderId + "LogicOrderId": "10000266092590", + "PathFlowCode": "1000001370772", + "CustomerOrderId": "3740288268498815232", // 真正的平台单号 + "ShopId": 7319156, + "PrintInfo": "", + "OrderItems": ["10000289254637"], + "Items": [{ "OrderItemId": "...", "OrderItemCode": "...", "Quantity": "1", "ShortTitle": "...", "SkuCode": "...", "ProductCode": "..." }], + "WaybillCode": "", // 置空:号码复用/分配由平台按 _<包裹序号> 决定 + "ManyCodeSendIndex": "0", // 包裹序号(0 基),OMS 由发货单号尾部 _N 推导(N-1) + "IsManyCodeSend": "", + "SellerRemark": "", "BuyerRemark": "", + "FxUserId": 1227061, + "IsSelectAllNotPrintedItem": "1", + "SendType": "0", + "DataFlag": "...", + "Receiver": { + "toFullName": "...", "toMobile": "...", "toArea": "完整地址", + "toProvince": "...", "toCity": "...", "toCounty": "...", "toMaskAddress": "镇+详细地址" + }, + "Sender": { "CompanyName": "" }, + "Buyer": { "BuyerWangWang": "..." } + } +} +``` + +### 4.5 取号响应 + +旧系统只用到的两个字段: + +```php +foreach ($res["Data"]["WaybillCode"] as $WaybillCode) { + if ($WaybillCode["IsError"]) { + // 失败:$WaybillCode["OrderInfo"]["OrderInfo"]["OriginID"] 回查订单 + } +} +``` + +运单号本身旧系统是从**打印历史**取的: + +```php +// PrintHistory/LoadPrintData → Data[0].PrintHistoryData.PrintDataJson +$documentID = $PrintDataList["task"]["documents"][0]["documentID"]; // = 运单号 +``` + +因此 OMS 的解析顺序(防御式): + +1. `Data.WaybillCode[].WaybillCode / LogisticCode / MailNo / WaybillNo` +2. `Data.WaybillCode[].OrderInfo.OrderInfo.WaybillCode / LastWaybillCode` +3. `Data.WaybillCode[].PrintInfo / PrintData / PrintDataJson`(旧版返回) +4. **`Data.PrintDataList.task.documents[]`(实际口径)**: + - `documentID` = 运单号 + - **`printInfo` = 面单打印数据**(base64 编码的 URL-encoded JSON,WMS 打印端按原样塞进 `task.printInfo`,**不要再解码**) + - `contents[0].signature / encryptedData / ver` → OMS 的 `signature / encryptprintinfo / ver`(视频号自定义模板不返回 `contents`,这三项为空) + +> 第 1、2、3 项是按常见字段名兜底;**实测(2026-11-04)打印数据只在 `documents[].printInfo`**, +> 之前只读 `WaybillCode[].PrintInfo` 导致回给 WMS 的 `printinfo` 是空串。 +> +> **打印数据必须留痕**:`printinfo` / `signature` 会随逐单结果透传给 WMS(WMS 落 `order_express`), +> 同时整条平台原始返回写入 OMS 的 `waybill_fetch_records`(含 `raw_response`、`printinfo`、`waybill_source`), +> 出问题查表即可,不需要让 WMS 重放报文。表结构见 `WMS-OMS-取号对接.md` §4.7。 + +--- + +## 5. 旧系统的两个额外动作(OMS 暂不实现) + +| 动作 | 接口 | 说明 | +|---|---|---| +| 发货 | `POST /NewOrder/OnlineSendBatch` | 取号后通知平台发货;OMS 的发货由 WMS 回传 `deliveryorder.confirm` 处理,不在此调用 | +| 打印历史 | `POST /PrintHistory/LoadList` / `LoadPrintData` | 用于回捞运单号与打印数据;OMS 直接从 ExpressPrint 响应解析,暂不接入 | + +--- + +## 6. OMS 落地 + +### 6.1 代码位置 + +| 方法 | 作用 | +|---|---| +| `DgjService.fetchWaybillNo(order, { template })` | 取号主流程:回读订单行 → 已发货拦截 → 模板校验 → 取号 → 解析运单号/打印数据 | +| `DgjService.findPlatformOrderRow(host, {...})` | 按 `LogicOrderId` → `PlatformOrderId` → 时间窗兜底 找订单行 | +| `DgjService.fetchOrderRows(host, {...})` | `NewOrder/List` 精确过滤查询 | +| `DgjService.checkTemplateAvailable(host, {...})` | `CheckTemplateAvaliable` | +| `DgjService.expressPrint(host, {...})` | `ExpressPrint`(会消耗面单) | +| `resolveOrderHost(platformType)` | 订单域名(`fxali` / `fxdd` / `fxpdd` / `fxjd`) | + +### 6.2 真实取号开关 + +```bash +# 默认开启:每次取号都会真实调用 ExpressPrint(消耗面单) +# 需要「只读联调、绝不下单」时关闭: +DGJ_WAYBILL_ENABLE=0 # 0/false/off/no 视为关闭;不设置或其他值均为开启 +``` + +- 关闭后取号直接返回「店管家真实取号已关闭(DGJ_WAYBILL_ENABLE=0):…」(不再有「复用平台运单号」这种只读成功路径); +- **是否重复取号只看幂等表**:同一 `request_id` 的失败/部分失败可重试,成功则回放;清表或换 `request_id` 就会再取一次号。 + +### 6.3 自动作废的备注口径(区分「已发货」与「查不到」) + +拉单时发现的「本地仍是待审核、但平台不应再处理」的订单会自动作废,**作废备注按真实原因写入**: + +| 情形 | `void_reason` 示例 | +|---|---| +| 平台已发货/已终结 | `店管家侧已发货或已终结(平台订单状态 ErpState=sended、平台已有发货时间 2026-11-03 17:35:24、1 个面单包裹已发货、物流状态已推进(LogisticStatus=3)),系统自动作废` | +| 平台已查不到 | `店管家侧已查不到该订单(2026-11-01 07:00 至 2026-11-04 07:00 的拉取结果中没有该单,可能已删除、合并或转出本店铺),系统自动作废` | + +- 「已发货」的判定依据(`describeFinishedOrder`):`ErpState` 属已发货/已终结、有 `OnlineSendTime`、面单包裹 `IsSended`、`LogisticStatus>0`,命中项全部写进备注。 +- 「查不到」的判定:本地待审核单的下单时间落在**本次实际查询窗口**内,但平台返回的 `list + finished` 里都没有它。 + 为避免误判,限制:窗口最长回看 **45 天**、本次必须成功命中至少一个分区、`AUTO_VOID_MISSING_ORDER=0` 可整体关闭。 +- 操作日志同步记录 `reason` 与 `platform_status`;店铺「最近同步结果」与拉单任务结果都会显示「其中平台已查不到 N 单」。 + +### 6.4 审核前平台状态守卫(防「平台已发货的单被审核推送」) + +订单可能昨天已在店管家发货,OMS 今天才审核。`orderStatus._auditOne` 在审核前会: + +1. 判断是否「外部打单订单」(店铺 `type=2` + `external_print_account_id`); +2. 用已同步的快递接口记录拿 `platform_type/dbname`,实时回读店管家订单行(只读); +3. `isOrderFinished(row)` 为真(`ErpState` 已发货/已终结、有 `OnlineSendTime`、包裹 `IsSended`、`LogisticStatus>0`)时: + - **自动作废**该订单,作废备注写明命中的具体依据(如「店管家侧已发货或已终结(平台订单状态 ErpState=sended、平台已有发货时间 2026-11-03 17:35:24),系统自动作废」); + - 抛 400:`订单 xxx 店管家侧已发货或已终结(…),不能审核(已自动作废)`。 +4. 平台查询失败**放行**(只告警),避免平台抖动卡住审核。 + +关闭开关:`DGJ_AUDIT_PLATFORM_CHECK=0`(默认开启)。 + +> 审核现在会为外部打单订单增加 1 次只读的平台查询;批量审核按单串行执行。 + +### 6.5 取号时同样拦截 + +`fetchWaybillNo` 回读到平台订单行后: + +- `isOrderFinished(row)` 为真 → 直接抛错「订单在店管家已发货或已终结(ErpState=sended,平台运单号 …),取号失败:请作废或取消该单」; +- 否则**继续调 ExpressPrint**(不再判断 `LastWaybillCode`,也不复用)。若平台返回的号码与订单行原号码相同,响应 `message` 会注明「本次调用平台取号,但平台仍返回原运单号 X」。 + +### 6.6 手工验证脚本 + +```bash +cd backend + +# 只读校验:查订单 → 查绑定 → 回读平台订单行 → 打印将发送的报文(不调用取号) +node scripts/dgj-waybill-probe.js --order dgj-10000266092590 --express STO + +# 真实取号(会消耗面单;需显式加 --execute;原始响应落到 backend/tmp/*.json) +node scripts/dgj-waybill-probe.js --order dgj-10000266092590 --express STO --execute +``` + +实测输出(2026-11-04,只读): + +``` +Id: '10000266092590' LogicOrderId: '10000266092590' PlatformOrderId: '3740288268498815232' +ShopId: 7319156 FxUserId: 1227061 ErpState: 'sended' PrintState: 1 +LastWaybillCode: '772085250163045' SubOrders: 1 +平台订单行已有运单号 772085250163045(仅用于对比:OMS 不再复用,真实取号会调 ExpressPrint 换新号) +``` + +> 这张测试单在店管家已取号并已发货,`isOrderFinished` 会直接拦成「请作废或取消该单」,不会走到取号。 + +--- + +## 7. 尚未真实验证的点(首次取号时确认) + +1. `ExpressPrint` 响应里运单号的确切字段(是否就是 `WaybillCode`,还是只在 `PrintInfo` 的 `documentID`)。 +2. `CheckTemplateAvaliable` 的 `Balance/PrintCount` 单位(张数)与「余额不足」实际返回码。 +3. `PlatformOrderId` 过滤是否必须带 `CustomQuery=PlatformOrderIdSearch`(`LogicOrderId` 实测可用,已作为首选)。 +4. `Branches` 结构(多网点时是否需要逐网点拆分取号)。 +5. 快手/小红书等平台是否仍与淘宝同域(旧系统映射都指向 `fxali`)。 +6. 多包裹订单(`SubOrders>1` / 需要多张面单)时的取号数量策略。 + +--- + +## 8. 安全提示 + +- `ExpressPrint` 会**真实消耗面单**并可能产生费用;`IsIgnoreWaybillRepeat=true` 表示每次都取新号,重复调用会重复取。 +- 因此:**每次请求都会真实取号**(不再复用平台已有运单号),去重只剩幂等表 `request_id` 这一道; + 联调/回归测试只用只读路径(订单行查询 + 报文字段核对),不要把真实订单反复取号。 +- 生产环境如需启用,应由业务指定测试单、确认余额后再开开关。