diff --git a/AI_METHOD_ROUTING.md b/AI_METHOD_ROUTING.md index 3d980b4..f3f7429 100644 --- a/AI_METHOD_ROUTING.md +++ b/AI_METHOD_ROUTING.md @@ -136,8 +136,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods | report.definition.delete | app/service/systemMethods/report/definition.js | delete | 需登录 | 需授权 | - 底层编排:`app/service/systems/report.js`(报表定义读取/类型注册表解析/工作簿生成,含 listRegisteredTypes/saveDefinition/listDefinitions/deleteDefinition 定义管理)、`app/service/systems/reportDelivery.js`(投递计划/记录 CRUD 与分钟级投递调度,含文本通知模板渲染与定向群/成员推送)、`app/lib/report/notifyTemplate.js`(标签白名单 {time}/{url}/{report_name}/{biz_date} 渲染) -- 配置与口径:`wms_report_definition` 极简配置(name/type/file_name/fields/is_enabled/remark,唯一性由主键 id 承担),注册类型与字段规格见 `app/service/systems/report/queries/index.js`(当前仅 stockFlow),详见 `docs/report-config-guide.md` -- 接口文档:`methods/system.json` 分组「通用报表模块」(module=report),变更记录见 `methods/changes/system.json` 版本 `2026.08.31-report-meta-removed`、`2026.08.30-report-delivery-plan-copy`、`2026.08.30-report-delivery-plan-name-field`、`2026.08.30-report-type-list-merge-into-definition`、`2026.08.30-report-definition-model-refactor`、`2026.08.29-report-config-driven-generate-delivery`、`2026.08.29-report-meta`、`2026.08.29-report-delivery-notify-template-targets`、`2026.08.29-report-delivery-channel-converge`、`2026.08.29-report-definition-management`、`2026.08.29-report-channel-normalize-doc-audit` +- 配置与口径:`wms_report_definition` 极简配置(name/type/file_name/fields/is_enabled/remark,唯一性由主键 id 承担),注册类型与字段规格见 `app/service/systems/report/queries/index.js`(当前 stockFlow、interceptOrder),详见 `docs/report-config-guide.md` +- 接口文档:`methods/system.json` 分组「通用报表模块」(module=report),变更记录见 `methods/changes/system.json` 版本 `2026.09.10-report-intercept-order-type`、`2026.08.31-report-meta-removed`、`2026.08.30-report-delivery-plan-copy`、`2026.08.30-report-delivery-plan-name-field`、`2026.08.30-report-type-list-merge-into-definition`、`2026.08.30-report-definition-model-refactor`、`2026.08.29-report-config-driven-generate-delivery`、`2026.08.29-report-meta`、`2026.08.29-report-delivery-notify-template-targets`、`2026.08.29-report-delivery-channel-converge`、`2026.08.29-report-definition-management`、`2026.08.29-report-channel-normalize-doc-audit` - 接口移除(2026-08-31,破坏性变更):`report.meta` 已下线移除(免权限列元数据接口),前端获取注册字段/窗口参数改由 `report.definition.typeList` 提供、某报表定义勾选字段经 `report.definition.list` 的 `fields` 数组获取;代码层删除 `systemMethods/report.js` 的 `meta` 方法与 `systems/report.js` 的 `getMeta`,`methods/system.json` 条目同步移除,详见 `docs/report-config-guide.md` 第 7 节 - 报表定义模型重构(2026-08-30,破坏性变更):报表定义由 code 编码改为主键 id 关联,`report.generate`/`report.meta`/`report.deliveryPlan.save` 入参 `report_code` 改为 `report_id`(=报表定义ID,兼容 reportId 驼峰,前端需同步改);`code/scope` 与 `output_config/source_config/sheet_config` 三段 JSON 配置已随模型删除,列渲染由类型硬编码字段规格自动完成;`report.definition.save` 入参 `{id?,name,type,file_name/fileName,fields,is_enabled?,remark?}`(type 须命中注册表、fields 须为该类型注册字段子集),`report.definition.list` where 改 `{name,type,is_enabled}` + sort 白名单 id/name/type/is_enabled/created_at/updated_at,`report.definition.delete` 入参 id 且引用拦截按 report_definition_id 统计;`report.deliveryPlan.*`/`report.deliveryLog.list` 关联键改 report_definition_id(log 响应带 report_name 快照);新增免权限只读 `report.definition.typeList` 返回注册类型清单(由独立模块 report/type.js 并入 report/definition.js);详见 `docs/report-config-guide.md` 第 1/2/3/6/7/8 节 - 投递渠道收敛(2026-08-29):`report.deliveryPlan.save` 的 channel 仅支持 inbox(默认 inbox,wecom/link 已弃用,非法渠道报「投递渠道仅支持 inbox: 」);历史 wecom/link 计划投递时按 inbox 兜底;inbox 推送失败经 inbox.message.retry 自动重推一次,仍失败进入 failed 退避(MAX_RETRY=3) @@ -145,6 +145,9 @@ rg "class .*Service|module.exports" app/service/qimenMethods - 计划名称(2026-08-30):`report.deliveryPlan.save` 可选入参 `name`(string|null;未传不覆盖,null/空串/全空白清空,非空 trim 后 ≤100 超长报错「计划名称 name 长度不能超过 100 字符」),`save` 响应与 `report.deliveryPlan.list` 列表项新增 `name`(缺省 '');仅展示字段,不参与幂等/关联;详见 `docs/report-config-guide.md` 第 5 节 - 批量复制(2026-08-30):新增 `report.deliveryPlan.copy` 入参 `{id, store_ids}`(store_ids 非空正整数数组,自动去重,兼容 storeIds 驼峰),把源计划快速复制到多个目标货主;目标货主已存在同 report_definition_id 计划跳过不覆盖、货主不存在或状态异常跳过、与源计划货主相同跳过(reason 枚举见 methods/system.json);notify_group_ids/notify_member_ids 通知配置不复制(新计划置空)、enabled 原样复制(保持复制语义),其余字段(report_definition_id/schedule_times/channel/late_grace_minutes/name/remark/notify_template)原样复制;事务批量创建,唯一键冲突单条降级 skipped;需登录需鉴权(与 save/list 同口径) - 渲染规则(2026-08-30):无 sheet_config,列由 `app/lib/report/render.js` `renderSheetByType` 按类型硬编码字段规格生成(string 静态列、number 统一 zeroToDash、boolean 统一 yesNo、array 窗口展开列);asText 由类型字段规格硬编码(item_code/barcode),渲染层输出 textColumns(0 基列索引)由 excel.js 落地文本单元格(长数字串防科学计数法);详见 `docs/report-config-guide.md` 第 3 节 +- 注册类型新增(2026-09-10):`interceptOrder`(库内确定拦截订单明细)——以配送表 `dispath_time`(订单迁移进配送表的时间)为时间基准,统计**昨日自然日**([昨日 00:00:00, 今日 00:00:00) 本地时区半开区间;可用 `params.bizDate` 覆盖为更早的统计日,**今天及以后一律回落昨日**——今天发出去的报表不含今天数据)内 `intercept_status='intercepted_at_warehouse'` 的库内确定拦截订单,按商品明细展开(一个商品一行),列与 `order.export`(export_mode=item)一致仅去掉「商品图片」列,并附 3 列(`source_order_codes` 平台交易单号=配送表同名字段、`intercept_notice_time` 通知拦截时间=配送表 intercept_time(为空时回落操作日志 ORDER_INTERCEPT_REQUEST 最早一条)、`intercept_confirm_time` 库内确定拦截时间=配送表 dispath_time),共 49 列全为 string 静态列,无展开列;报表定义 `type` 填 `interceptOrder` 即可使用,`report.generate`/`report.deliveryPlan` 链路无需变更;详见 `docs/report-config-guide.md` 第 2 节 +- 文件名占位符(2026-09-10):`file_name` 支持 `{date}`(数据日期 params.bizDate,缺省服务器当天,语义不变)/ `{time}`(生成时刻 HHmmss)/ `{datetime}`(数据日期_生成时刻)/ `{timestamp}`(毫秒时间戳),实现 `systems/report.js buildFilename`;同一天多次投递/手动导出同一报表时建议模板带 `{time}`(如 `interceptOrder_{date}_{time}`),避免 COS 同名覆盖与 CDN 旧内容回源;详见 `docs/report-config-guide.md` 第 4 节 +- 拦截时间口径变更(2026-09-10,随 interceptOrder 报表一并调整):`wms_order_delivery.intercept_time` 统一为「最近一次发起拦截的通知时刻」——发起/通知拦截**首次写入**(重复发起不覆盖,工具 `app/lib/intercept_time.js` 的 buildNoticeTimePatch/pickNoticeTimeOrderIds);库内拦截确认(`order.recheckOrder.confirmIntercept`、`order.recheckOrder.interceptScan`、定时自动确认)与退回入库(returned)**不再写该字段**;取消/解除拦截(`order.pendingOrder.batchUnintercept`)与订单克隆重置**置空 null**;库内确定拦截时刻改用配送表 `dispath_time`(订单迁移进配送表的时间)。写入点:`app/service/qimenMethods/order.js`、`app/service/openapiMethods/order.js`、`app/service/inbox/functions.js`、`app/service/systemMethods/order/pendingOrder.js`(发起拦截)、`app/service/systems/intercept_auto_confirm.js`、`app/service/systemMethods/order/recheckOrder.js`、`app/service/systems/return_received.js`(确认/退回);回归测试 `test/intercept_time_lifecycle.cjs` - 授权提示:需授权接口已登记 isNeedAuth=true,后续用 `npm run permission:sync:system-api -- --dry-run` 预演并按标准流程授权(不扩大任何角色授权) ## 5.2 inbox.group(站内信群管理)能力速查 @@ -197,6 +200,60 @@ rg "class .*Service|module.exports" app/service/qimenMethods - 语义:入参 `token`(ye4s 登录临时码,对应 ye4s 库 ye4s_user 表 tmp_code 字段)查询用户;命中返回 flag=success、code=200 与 real_name(用户真实姓名)、wms_account_id(WMS 账号 ID,未绑定为 null);未命中返回 code=404「用户不存在」;数据库异常返回 code=500;token 为空返回 code=400「token 不能为空」 - 接口文档:`methods/system.json` 分组「基础模块」(module=index),变更记录见 `methods/changes/system.json` 版本 `2026.09.06-index.queryUserByToken` +## 5.5 openapi.stockout(开放 API 出库单)能力速查 + +| method | 实现文件 | 函数 | 登录 | 鉴权/权限 | +|---|---|---|---|---| +| stockout.create | app/service/openapiMethods/stockout.js → app/service/systems/stockout_order.js | create / create | 免登录 | 免方法级权限(/openapi 入口按 app_key 合约 + 签名校验,合约须绑定货主) | +| stockout.query | app/service/openapiMethods/stockout.js → app/service/systems/stockout_order.js | query / query | 免登录 | 同上 | + +- 语义:开放 API 出库单创建/查询,与奇门 `stockout.create` / `stockout.query` 共用同一份领域实现(`app/service/systems/stockout_order.js`),差异只在来源标识:开放 API 落库 `wms_order_stockout.source_type=API`(回传走 OpenAPI 回调 `event=stockout.confirm`),奇门落库 `source_type=QM`(回传调用 `taobao.qimen.stockout.confirm`) +- 入参:开放 API 为扁平结构 `body.deliveryOrder` / `body.orderLines.orderLine` / `body.deliveryOrderCode`;奇门为 `request.deliveryOrder` / `request.orderLines.orderLine`。字段口径详见 `methods/openapi.json` 分组「出库单模块」(module=stockout) +- 库存:创建时事务内按 `planQty` 锁定库存(锁标记 `QM_STOCKOUT`,与 `storage.stockout.cancel/confirm/toOrder` 释放口径一致);非订单出库单能力另见 `storage.stockout.*` +- 接口文档:`methods/openapi.json` 分组「出库单模块」(module=stockout),变更记录见 `methods/changes/openapi.json` 版本 `2026.09.12-openapi-stockout-create-query` + +## 5.6 OpenAPI 出站回调 method 规范(2026-09-12 / 2026-09-13 破坏性变更) + +> 破坏性协议变更(2026-09-12):OpenAPI 出站回调的 `method`(query)由 snake_case 事件名统一改为 `模块.动作`(与奇门 method 去掉 `taobao.qimen.` 前缀后对齐)。旧事件名已全部废弃,无新旧兼容、无双发,接收方必须同步改造。 +> +> 破坏性协议变更(2026-09-13):报文体由 `{ event, data, metadata }` 改为奇门同层级的 `{ request: {...} }`,发送端不再发送数据/元数据,`event` 仅出现在 query 的 `method`;`deliveryorder.confirm` 由一次批量汇总通知改为逐单发送(仅对 `syncResults` 中 `status==='success'` 的订单,成功 N 单 = N 次回调)。接收方必须按新报文结构改造。 + +### 5.6.1 method 命名规范 +- 格式:`模块.动作`(如 `entryorder.confirm`、`stockout.confirm`) +- 与 `/openapi` 入站入口校验一致:`app/service/openapiEntry.js#validateOpenapiParams` 要求 `method` 必须包含 `.`,否则 400「参数缺失或错误: method/v/timestamp」 +- 与奇门的对应关系(注册表已声明的):`entryorder.confirm` ↔ `taobao.qimen.entryorder.confirm`、`stockout.confirm` ↔ `taobao.qimen.stockout.confirm`(见 `app/service/openapi/callbackRegistry.js` 描述) + +### 5.6.2 method 映射表(旧事件名 → 新 method → 触发场景 → 实现文件) + +| 旧(事件名,已废弃) | 新(method) | 触发场景 | 实现文件 | +|---|---|---|---| +| `entry_order_direct_inbound_completed` | `entryorder.confirm` | 直入入库(API 来源,`source_type=API`)完成后回传 | `app/service/systems/inbound_direct_log.js`(`qimenEntrySync` → `_sendOpenApiCallback`,约 1470 行) | +| `entry_order_receiving_matched` | `entryorder.match` | 入库单匹配收货单完成后回传(API 来源) | `app/service/systems/receiving_entry_match.js`(`_sendCallback` → `_sendOpenApiCallback`,约 1864 行) | +| `order_completed` | `deliveryorder.confirm` | API 渠道订单同步(出库)完成后逐单触发(仅对 `syncResults` 中 `status==='success'` 的订单,成功 N 单 = N 次回调;fire-and-forget,失败仅 warn) | `app/service/systems/order_async.js`(`finalizeLocalChannelOrdersInternal` → `notifyApiDeliveryOrderConfirmsInternal`) | +| `stockout_completed` | `stockout.confirm` | 出库单确认回传(API 来源,`source_type=API`) | `app/service/systems/order_async.js`(`notifyStockoutExternalInternal` → `buildStockoutConfirmDataInternal`) | +| `order_cancelled` | `deliveryorder.cancel` | 订单取消成功后触发(fire-and-forget;出站事件名与入站方法 `order.cancel` 区分,避免 `callback_url` 误指向 `/openapi` 时被路由到取消单据接口;**无奇门对应接口**,按 `deliveryOrder` 节点约定自定义,`status` 固定 `CANCELED`) | `app/service/openapiMethods/order.js`(`cancel`,约 296 行) | + +### 5.6.3 协议要点 +- 出站请求:`POST {callbackUrl}?method={模块.动作}&v=1.0×tamp={timestamp}&app_key={selfAppKey}&sign={md5}` + - `timestamp` 为**秒级(10 位字符串)规范值**:`String(Math.floor(Date.now()/1000))`,发送端(`callback.js#sendWithRetry`)与回调调试页(`openapiCallback.js#nowTimestamp`)已统一;与 `/openapi` 入站时效校验一致(`openapiEntry.js`,秒级 ±600 秒窗口)。此前「毫秒/秒口径不一致、待统一」的已知问题已修复 +- 请求头:`Content-Type: application/json` +- 请求体:`{ "request": {…} }`(奇门同层级);`event` 不出现在报文体内,仅拼入 query 的 `method`;发送端固定包装 `body = { request: request || {} }`(`app/service/openapi/callback.js#sendWithRetry`) +- 5 个事件的 `request` 顶层结构速查表: + +| method | `request` 顶层结构 | 组装实现 | +|---|---|---| +| `entryorder.confirm` | `{ entryOrder: {…}, orderLines: […] }` | `app/service/systems/inbound_direct_log.js#buildEntryOrderConfirmRequest`(QM/API 共用) | +| `entryorder.match` | `{ entryOrder: {…}, orderLines: […] }`(`outBizCode` 前缀 `RECEIVING_MATCH_`,`remark` 为「匹配收货单{收货单号}自动回传」) | `app/service/systems/receiving_entry_match.js#buildEntryOrderConfirmRequest`(QM/API 共用) | +| `deliveryorder.confirm` | `{ deliveryOrder: {…}, packages: {package:[…]}, orderLines: […] }`(逐单发送) | `app/service/systems/order_async.js#buildQimenDeliveryOrderConfirmDataInternal` | +| `stockout.confirm` | `{ deliveryOrder: {…}, packages: {package:[…]}, orderLines: […] }` | `app/service/systems/order_async.js#buildStockoutConfirmDataInternal` | +| `deliveryorder.cancel` | `{ deliveryOrder: { deliveryOrderCode, orderType, status: 'CANCELED' } }`(无奇门对应接口,自定义约定) | `app/service/openapiMethods/order.js#cancel` | + +各层字段口径详见 `methods/openapi_callback.json` / `docs/openapi-callback-events.md`(与 `callbackRegistry.js` 的 `request` 模板一致) +- 签名(`app/lib/api_sign.js#signRequest`):`sign = md5(canonicalQuery + selfAppSecret + md5(stableStringify(body)))`;`canonicalQuery` 为除 `sign`/`signature` 外 query 按 key 字母序 `key=value&…` 拼接(签名用未 URL 编码原值,实际 URL 中 `method`/`app_key` 做 `encodeURIComponent`);`bodySign` 基于 `{ request }` 完整报文 +- 重试(`app/service/openapi/callback.js#sendWithRetry`):非 2xx 或网络错误最多重试 3 次(`MAX_RETRY=3`),间隔 2s → 5s → 15s,单次超时 30s;每次尝试写 `[OpenapiCallback]` 日志(`logCallback`) +- 事件注册表:`app/service/openapi/callbackRegistry.js#CALLBACK_EVENTS`(5 条,每条含 `name`/`label`/`description`/`request`,`request` 为奇门同层级报文模板),回调调试页 `GET /docs/api/openapi/callback-test`(`app/controller/openapiCallback.js`)直接消费该注册表,并按注册表自动预填完整报文体 `{ request: {...} }` +- 完整协议文档:`docs/openapi-callback-events.md` + ## method结束 ## 6. 全量 Service Method 能力清单(自动扫描) @@ -208,10 +265,10 @@ rg "class .*Service|module.exports" app/service/qimenMethods - 临时清单输出:temp/tmp-service-method-inventory.md -自动生成时间: 2026-09-07T13:11:46.995Z +自动生成时间: 2026-09-12T11:41:21.651Z 扫描范围: app/service/**/*.js -文件数: 204 +文件数: 210 - app/service/api.js (1) - callMethod @@ -267,6 +324,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods - echo - app/service/openapiMethods/singleitem.js (2) - synchronize, query +- app/service/openapiMethods/stockout.js (2) + - create, query - app/service/pda.js (3) - callMethod, validateParams, saveLog - app/service/qimen.js (12) @@ -303,6 +362,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods - list - app/service/systemMethods/dashboard.js (17) - storeStats, storeSideStoreStats, queryWarehouseStats, mergeStoreStats, emptyStoreStats, warehouseStats, hot_order_rank, express_ratio, storeSideExpressRatio, queryWarehouseExpressRatio, mergeChartData, formatChartData, emptyChartData, platform_distribution, storeSidePlatformDistribution, queryWarehousePlatformDistribution, order_trend +- app/service/systemMethods/frontConfig.js (1) + - getByDomain - app/service/systemMethods/inbox.js (13) - group, message, after_sales, bindCode, groupList, groupQuickList, groupMembers, groupDisable, groupUpdate, groupReset, groupMessages, retry, reply - app/service/systemMethods/index.js (58) @@ -329,14 +390,14 @@ rg "class .*Service|module.exports" app/service/qimenMethods - list, detail, reverseReviewOrder, assertOrdersWithoutWaybill, syncWavesAfterReverseReview, allocateStorage, allocateStorageProgress, normalizeAllocateStorageTaskProgress, normalizeAllocateStorageTaskCount, normalizeAllocateStorageTaskCounts, normalizeAllocateStorageRequestId, getAllocateStorageTaskCacheKey, setAllocateStorageTaskProgress, getAllocateStorageTaskProgress, getAllocateExpressTaskCacheKey, normalizeAllocateExpressTaskId, setAllocateExpressTaskProgress, getAllocateExpressTaskProgress, getSyncOrderIdsTaskCacheKey, normalizeSyncOrderIdsRequestId, setSyncOrderIdsTaskProgress, getSyncOrderIdsTaskProgress, cancelAllocateStorage, syncOrderIds, syncOrderIdsProgress, allocateExpressCode, allocateExpressCodeTaskProgress, markPendingOutboundOrder, cancelOrder, normalizePendingOutboundOrderIds, normalizePendingCancelOrderIds, isCancelablePendingOrder, updateOrderPlatform, updateOrderExpress, updateAddress, updateRemark, cloneOrder, parseAddress, _parseAddressBatchOneShot, _parseSingleAddress, catch - app/service/systemMethods/order/print.js (4) - getWavePlatformPrintData, getOrderPrintData, getPrintDataByWaybillCodes, unlockWavePlatformPrintDataByGroup -- app/service/systemMethods/order/recheckOrder.js (58) - - scanOrder, scanTask, buildSingleWaveScanView, buildSingleWaveView, buildGroupWaveList, getPickModeByWaveId, getTaskIdByWaveId, getWaveOrdersBasic, batchQueryPackageMaterialRecommendation, enrichOrdersWithStock, getPickerInfoByWaveId, getPickerInfoByTaskId, getWaveStrategyInfo, scanWaybill, confirmRecheck, confirmRecheckByWaveId, _writeRecheckActionLog, updateTaskOrderReviewAndTryUnbindCart, _resolveTaskIdByWaveFallback, _checkTaskOrdersAllReviewed, updateTaskOrdersReviewBatch, unbindCartForTask, resolveOrderId, resolveScanKeyword, pickOrderMatchByKeyword, pickOrderIdByWaybill, pickOrderIdByCartCode, pickWaveMatchContextByWaveNo, pickCartMatchContextByCartCode, getTableColumnSet, resolvePickModeName, buildWaveMatchView, buildCartMatchView, flattenCartMatchOrders, enrichTaskOrderRows, groupTaskOrdersByWaveId, groupTaskOrdersByPickStatus, groupTaskOrdersByBoxNo, groupTaskOrders, buildRecheckReviewNo, assertOrderCanRecheck, recheckOrderList, queryRecheckOrderSingleList, queryRecheckOrderGroupList, resolveModelTableName, confirmIntercept, interceptScan, batchQuickRecheck, normalizeWaveIds, batchQuickRecheckByWave, _completePickForOrder, _markRecheckForOrder, _tryCompleteWaveIfAllOrdersRechecked, _tryCompleteWaveInTransaction, removeUnprintedInterceptedOrdersFromWave, _updateTaskOrderReviewInTransaction, _unbindCartForTaskInTransaction, _writeRecheckActionLogInTransaction +- app/service/systemMethods/order/recheckOrder.js (60) + - scanOrder, NOW, markWaveRecheckStart, scanTask, buildSingleWaveScanView, buildSingleWaveView, buildGroupWaveList, getPickModeByWaveId, getTaskIdByWaveId, getWaveOrdersBasic, batchQueryPackageMaterialRecommendation, enrichOrdersWithStock, getPickerInfoByWaveId, getPickerInfoByTaskId, getWaveStrategyInfo, scanWaybill, confirmRecheck, confirmRecheckByWaveId, _writeRecheckActionLog, updateTaskOrderReviewAndTryUnbindCart, _resolveTaskIdByWaveFallback, _checkTaskOrdersAllReviewed, updateTaskOrdersReviewBatch, unbindCartForTask, resolveOrderId, resolveScanKeyword, pickOrderMatchByKeyword, pickOrderIdByWaybill, pickOrderIdByCartCode, pickWaveMatchContextByWaveNo, pickCartMatchContextByCartCode, getTableColumnSet, resolvePickModeName, buildWaveMatchView, buildCartMatchView, flattenCartMatchOrders, enrichTaskOrderRows, groupTaskOrdersByWaveId, groupTaskOrdersByPickStatus, groupTaskOrdersByBoxNo, groupTaskOrders, buildRecheckReviewNo, assertOrderCanRecheck, recheckOrderList, queryRecheckOrderSingleList, queryRecheckOrderGroupList, resolveModelTableName, confirmIntercept, interceptScan, batchQuickRecheck, normalizeWaveIds, batchQuickRecheckByWave, _completePickForOrder, _markRecheckForOrder, _tryCompleteWaveIfAllOrdersRechecked, _tryCompleteWaveInTransaction, removeUnprintedInterceptedOrdersFromWave, _updateTaskOrderReviewInTransaction, _unbindCartForTaskInTransaction, _writeRecheckActionLogInTransaction - app/service/systemMethods/order/reviewOrder.js (2) - list, reviewOrder - app/service/systemMethods/order/storageAllocation.js (0) - -- app/service/systemMethods/order/wave.js (226) - - buildBatchAllocateExpressTraceId, buildOrderOperationLogRows, batchCreateOrderOperationLogs, buildMachineStructureToken, parseMachineStructureToken, getOrderItemPart, getDefaultWaveQuantity, getMinGroupOrderFetchQuantity, getGroupWavePrefix, getSingleFetchByIdsWavePrefix, getWarehouseSubjectConfig, getWarehouseSubjectConfigValue, normalizeFetchStructureRequests, generateWaveId, getCurrentDatePart, VALUES, getNextWaveNoSequence, buildWaveNo, id, getWaveCreator, extractInsertId, extractLastInsertId, isDuplicateEntryError, resolveWaveScopeByWaveMeta, createWaveBatchReady, buildFetchWhere, fetchSingleStructure, normalizeBoolean, normalizePositiveInteger, normalizeRequiredPositiveInteger, normalizeIdsInput, normalizePagination, normalizeWaveStatusList, normalizeBatchListStorageAssignmentStatusFilter, normalizeBatchListExpressAssignmentStatusFilter, normalizeBatchListPrintAssignmentStatusFilter, normalizeBatchListReviewAssignmentStatusFilter, getBatchListAssignmentFilterSchema, normalizeBatchListAssignmentStatusFilterByType, normalizeBatchListAssignmentStatusFilter, getModelTableSqlName, buildBatchListStorageAssignmentFilterClause, buildBatchListExpressAssignmentFilterClause, buildBatchListPrintAssignmentFilterClause, buildBatchListReviewAssignmentFilterClause, buildBatchListAssignmentStatusFilterClauseByType, buildBatchListAssignmentStatusFilterClause, buildBatchListWhereClause, normalizeWavePickTaskListPagination, normalizeWavePickTaskListRequest, buildWavePickTaskListWhereClause, resolveAssignmentStatus, normalizeSkuText, normalizeShopName, parseItemSnapshot, normalizeOrderItemRow, mergeOrderItemDetails, buildItemSummary, buildOrderItemSnapshot, buildItemSnapshotKey, orderMatchesIncludeSku, buildCoarseGroupKey, buildStatusSummary, buildGroupKey, groupOrderFetchList, singleOrderFetchList, waveStrategyList, getWaveStrategyNextFetchOrderCountMap, getWaveStrategyDebugFetchOrderListMap, previewWaveStrategyNextFetchOrderCount, getWaveStrategyMatchedOrderCountFilteredMap, waveStrategyCreate, waveStrategyUpdate, bumpWaveStrategyVersionAndInvalidateCache, getWaveStrategyModel, normalizeWaveStrategyId, normalizeWaveStrategyUpsertPayload, normalizeWaveStrategyWavePrefix, resolveWaveStrategyFetchWavePrefix, patchWaveStrategyIntegerField, validateWaveStrategyAllowedOwners, validateWaveStrategyAllowedExpresses, getWaveStrategyAvailableOwnerSet, getWaveStrategyAvailableExpressSet, applyWaveStrategyMaxSameStructureConstraint, normalizeWaveStrategyFallbackOrderListWhere, resolveWaveStrategyFallbackTrackingNo, resolveWaveStrategyFallbackStoreName, resolveWaveStrategyFallbackSysLogisticsName, buildWaveStrategyFallbackOrderListItem, waveStrategyFallbackOrderList, resolveWaveBatchOwnerStoreNameMap, batchList, wavePickTaskList, batchCancel, batchCancelTaskProgress, batchAllocateExpress, batchAllocateExpressTaskProgress, batchAllocateStorage, batchAllocateStorageTaskProgress, submitWaveStrategyQuickScanForWarehouse, waveStrategyQuickScan, waveStrategyQuickScanTaskProgress, buildWaveStrategyQuickScanOrderWhere, getWaveStrategyQuickScanStrategyRows, getWaveStrategyQuickScanMatchModel, syncWaveStrategyQuickScanMatchedStrategies, cleanupWaveStrategyQuickScanMatchedStrategies, cleanupWaveStrategyQuickScanMatchedStrategiesByOrderIds, enqueueWaveStrategyQuickScanPostOrderChange, executeWaveStrategyQuickScan, runWaveStrategyQuickScanTask, batchUpdateWaveStrategyQuickScanOrders, generateWaveStrategyQuickScanTaskId, normalizeWaveStrategyQuickScanTaskId, getWaveStrategyQuickScanTaskCacheKey, setWaveStrategyQuickScanTaskProgress, getWaveStrategyQuickScanTaskProgress, getWaveStrategyQuickScanWarehouseLockCacheKey, setWaveStrategyQuickScanWarehouseLock, getWaveStrategyQuickScanWarehouseLock, clearWaveStrategyQuickScanWarehouseLock, normalizeWaveStrategyQuickScanVersion, normalizeWaveStrategyQuickScanList, normalizeWaveStrategyQuickScanNumberOrNull, normalizeWaveStrategyQuickScanBoolean, normalizeWaveStrategyQuickScanStringList, getWaveStrategyQuickScanStructureKey, getWaveStrategyQuickScanExpressKey, filterCandidateOrdersByRequireSameExpress, isWaveStrategyQuickScanOrderMatched, getWaveStrategyQuickScanMatchedStrategyIds, isWaveStrategyQuickScanOrderMatchedSingleStrategy, isWaveStrategyQuickScanValueInRange, resolveGroupCandidateOrderIdsForSingleFetch, singleFetchByIds, batchRemoveOrders, resortWaveIndex, batchRemoveExceptionOrders, batchRemoveExceptionOrdersTaskProgress, generateBatchCancelTaskId, normalizeBatchCancelTaskId, generateBatchRemoveExceptionOrdersTaskId, normalizeBatchRemoveExceptionOrdersTaskId, normalizeBatchRemoveExceptionOrdersWaveIds, getBatchRemoveExceptionOrdersTaskCacheKey, setBatchRemoveExceptionOrdersTaskProgress, getBatchRemoveExceptionOrdersTaskProgress, isExceptionRemovableOrder, runBatchRemoveExceptionOrdersTask, normalizeBatchCancelWaveIds, getBatchCancelTaskCacheKey, setBatchCancelTaskProgress, getBatchCancelTaskProgress, runBatchCancelTask, generateBatchAllocateExpressTaskId, normalizeBatchAllocateExpressTaskId, normalizeBatchAllocateExpressWaveIds, getBatchAllocateExpressTaskCacheKey, setBatchAllocateExpressTaskProgress, getBatchAllocateExpressTaskProgress, generateBatchAllocateStorageTaskId, normalizeBatchAllocateStorageTaskId, normalizeBatchAllocateStorageWaveIds, normalizeBatchAllocateStorageTaskCount, buildBatchAllocateStorageRunningProgressPayload, normalizeBatchAllocateStorageOrderIds, getBatchAllocateStorageTaskCacheKey, getBatchAllocateStorageWarehouseLockKey, tryAcquireBatchAllocateStorageWarehouseLock, releaseBatchAllocateStorageWarehouseLock, setBatchAllocateStorageTaskProgress, getBatchAllocateStorageTaskProgress, isMissingBusinessKeyColumnError, runBatchAllocateExpressTask, runBatchAllocateStorageTask, batchAutoGrouping, batchFinishAutoGrouping, generateFetchTaskId, normalizeFetchTaskId, getFetchTaskCacheKey, setFetchTaskProgress, getFetchTaskProgress, fetchTaskProgress, runFetchTask, submitFetchTask, groupFetch, singleFetch, resolveWaveStrategyFetchPickMode, buildWaveStrategyFetchBoxAssignments, prepareWaveStrategyFetchPlan, in, ensureNoActiveWavePickTaskForOperator, normalizeWaveStrategyFetchCreatedBefore, buildWaveStrategyFetchTodayStart, getWaveStrategyFetchCandidateOrders, groupWaveStrategyFetchCandidateOrdersByStructure, buildWaveStrategyFetchOrderSkuMap, selectWaveStrategyFetchOrdersBySkuLimit, createWaveBatchByOrderIdsInTransaction, autoPopulateWaveStrategyFetchSelections, executeWaveStrategyDirectFetch, createWavePickTaskFromPlan, buildTaskCreatePayload, buildTaskWaveRows, buildTaskOrderRows, buildTaskSkuRows, buildTaskBoxRows, bindPickCartForTask, initTaskCheckpointAndLogs, ensurePickCartAvailable, generateWavePickTaskNo, createWavePickTaskWithRetry, isTaskNoDuplicateError, bulkInsertRows, parseWaveStrategyExistingTaskInfo, waveStrategyFetchPda, cancelWavePickTasksInternal, wavePickTaskCancel, wavePickTaskCancelSelf, waveStrategyFetchAdmin, deleteOrderWaveIndexByOrderIds, deleteOrderWaveIndexByWaveIds, rebuildOrderWaveIndex, replaceOrderWaveIndexByWaveIds, fetch +- app/service/systemMethods/order/wave.js (233) + - buildBatchAllocateExpressTraceId, buildOrderOperationLogRows, batchCreateOrderOperationLogs, buildMachineStructureToken, parseMachineStructureToken, getOrderItemPart, getDefaultWaveQuantity, getMinGroupOrderFetchQuantity, getGroupWavePrefix, getSingleFetchByIdsWavePrefix, getWarehouseSubjectConfig, getWarehouseSubjectConfigValue, normalizeFetchStructureRequests, generateWaveId, getCurrentDatePart, VALUES, getNextWaveNoSequence, buildWaveNo, id, getWaveCreator, extractInsertId, extractLastInsertId, isDuplicateEntryError, resolveWaveScopeByWaveMeta, createWaveBatchReady, buildFetchWhere, fetchSingleStructure, normalizeBoolean, normalizePositiveInteger, normalizeRequiredPositiveInteger, normalizeIdsInput, normalizePagination, normalizeWaveStatusList, normalizeBatchListStorageAssignmentStatusFilter, normalizeBatchListExpressAssignmentStatusFilter, normalizeBatchListPrintAssignmentStatusFilter, normalizeBatchListReviewAssignmentStatusFilter, getBatchListAssignmentFilterSchema, normalizeBatchListAssignmentStatusFilterByType, normalizeBatchListAssignmentStatusFilter, getModelTableSqlName, buildBatchListStorageAssignmentFilterClause, buildBatchListExpressAssignmentFilterClause, buildBatchListPrintAssignmentFilterClause, buildBatchListReviewAssignmentFilterClause, buildBatchListAssignmentStatusFilterClauseByType, buildBatchListAssignmentStatusFilterClause, isEmptyBatchListWhereValue, resolveBatchListFieldCondition, buildBatchListFieldConditionSql, normalizeBatchListDistinguishExpressValue, normalizeBatchListStoreIdCondition, buildBatchListWhereClause, normalizeWavePickTaskListPagination, normalizeWavePickTaskListRequest, buildWavePickTaskListWhereClause, resolveAssignmentStatus, normalizeSkuText, normalizeShopName, parseItemSnapshot, normalizeOrderItemRow, mergeOrderItemDetails, buildItemSummary, buildOrderItemSnapshot, buildItemSnapshotKey, orderMatchesIncludeSku, buildCoarseGroupKey, buildStatusSummary, buildGroupKey, groupOrderFetchList, singleOrderFetchList, waveStrategyList, getWaveStrategyNextFetchOrderCountMap, getWaveStrategyDebugFetchOrderListMap, previewWaveStrategyNextFetchOrderCount, getWaveStrategyMatchedOrderCountFilteredMap, getWaveStrategyMatchedOrderCountTotal, waveStrategyCreate, waveStrategyUpdate, bumpWaveStrategyVersionAndInvalidateCache, getWaveStrategyModel, normalizeWaveStrategyId, normalizeWaveStrategyUpsertPayload, normalizeWaveStrategyWavePrefix, resolveWaveStrategyFetchWavePrefix, patchWaveStrategyIntegerField, validateWaveStrategyAllowedOwners, validateWaveStrategyAllowedExpresses, getWaveStrategyAvailableOwnerSet, getWaveStrategyAvailableExpressSet, applyWaveStrategyMaxSameStructureConstraint, normalizeWaveStrategyFallbackOrderListWhere, resolveWaveStrategyFallbackTrackingNo, resolveWaveStrategyFallbackStoreName, resolveWaveStrategyFallbackSysLogisticsName, buildWaveStrategyFallbackOrderListItem, waveStrategyFallbackOrderList, resolveWaveBatchOwnerStoreNameMap, batchList, wavePickTaskList, batchCancel, batchCancelTaskProgress, batchAllocateExpress, batchAllocateExpressTaskProgress, batchAllocateStorage, batchAllocateStorageTaskProgress, submitWaveStrategyQuickScanForWarehouse, waveStrategyQuickScan, waveStrategyQuickScanTaskProgress, buildWaveStrategyQuickScanOrderWhere, getWaveStrategyQuickScanStrategyRows, getWaveStrategyQuickScanMatchModel, syncWaveStrategyQuickScanMatchedStrategies, cleanupWaveStrategyQuickScanMatchedStrategies, cleanupWaveStrategyQuickScanMatchedStrategiesByOrderIds, enqueueWaveStrategyQuickScanPostOrderChange, executeWaveStrategyQuickScan, runWaveStrategyQuickScanTask, batchUpdateWaveStrategyQuickScanOrders, generateWaveStrategyQuickScanTaskId, normalizeWaveStrategyQuickScanTaskId, getWaveStrategyQuickScanTaskCacheKey, setWaveStrategyQuickScanTaskProgress, getWaveStrategyQuickScanTaskProgress, getWaveStrategyQuickScanWarehouseLockCacheKey, setWaveStrategyQuickScanWarehouseLock, getWaveStrategyQuickScanWarehouseLock, clearWaveStrategyQuickScanWarehouseLock, normalizeWaveStrategyQuickScanVersion, normalizeWaveStrategyQuickScanList, normalizeWaveStrategyQuickScanNumberOrNull, normalizeWaveStrategyQuickScanBoolean, normalizeWaveStrategyQuickScanStringList, getWaveStrategyQuickScanStructureKey, getWaveStrategyQuickScanExpressKey, filterCandidateOrdersByRequireSameExpress, isWaveStrategyQuickScanOrderMatched, getWaveStrategyQuickScanMatchedStrategyIds, isWaveStrategyQuickScanOrderMatchedSingleStrategy, isWaveStrategyQuickScanValueInRange, resolveGroupCandidateOrderIdsForSingleFetch, singleFetchByIds, batchRemoveOrders, resortWaveIndex, batchRemoveExceptionOrders, batchRemoveExceptionOrdersTaskProgress, generateBatchCancelTaskId, normalizeBatchCancelTaskId, generateBatchRemoveExceptionOrdersTaskId, normalizeBatchRemoveExceptionOrdersTaskId, normalizeBatchRemoveExceptionOrdersWaveIds, getBatchRemoveExceptionOrdersTaskCacheKey, setBatchRemoveExceptionOrdersTaskProgress, getBatchRemoveExceptionOrdersTaskProgress, isExceptionRemovableOrder, runBatchRemoveExceptionOrdersTask, normalizeBatchCancelWaveIds, getBatchCancelTaskCacheKey, setBatchCancelTaskProgress, getBatchCancelTaskProgress, runBatchCancelTask, generateBatchAllocateExpressTaskId, normalizeBatchAllocateExpressTaskId, normalizeBatchAllocateExpressWaveIds, getBatchAllocateExpressTaskCacheKey, setBatchAllocateExpressTaskProgress, getBatchAllocateExpressTaskProgress, generateBatchAllocateStorageTaskId, normalizeBatchAllocateStorageTaskId, normalizeBatchAllocateStorageWaveIds, normalizeBatchAllocateStorageTaskCount, buildBatchAllocateStorageRunningProgressPayload, normalizeBatchAllocateStorageOrderIds, getBatchAllocateStorageTaskCacheKey, getBatchAllocateStorageWarehouseLockKey, tryAcquireBatchAllocateStorageWarehouseLock, releaseBatchAllocateStorageWarehouseLock, setBatchAllocateStorageTaskProgress, getBatchAllocateStorageTaskProgress, isMissingBusinessKeyColumnError, runBatchAllocateExpressTask, runBatchAllocateStorageTask, batchAutoGrouping, batchFinishAutoGrouping, generateFetchTaskId, normalizeFetchTaskId, getFetchTaskCacheKey, setFetchTaskProgress, getFetchTaskProgress, fetchTaskProgress, runFetchTask, submitFetchTask, groupFetch, singleFetch, resolveWaveStrategyFetchPickMode, buildWaveStrategyFetchBoxAssignments, prepareWaveStrategyFetchPlan, in, ensureNoActiveWavePickTaskForOperator, normalizeWaveStrategyFetchCreatedBefore, buildWaveStrategyFetchTodayStart, getWaveStrategyFetchCandidateOrders, groupWaveStrategyFetchCandidateOrdersByStructure, buildWaveStrategyFetchOrderSkuMap, selectWaveStrategyFetchOrdersBySkuLimit, createWaveBatchByOrderIdsInTransaction, mergeWaveStrategyFirstPoolSameStructureOrders, autoPopulateWaveStrategyFetchSelections, executeWaveStrategyDirectFetch, createWavePickTaskFromPlan, buildTaskCreatePayload, buildTaskWaveRows, buildTaskOrderRows, buildTaskSkuRows, buildTaskBoxRows, bindPickCartForTask, initTaskCheckpointAndLogs, ensurePickCartAvailable, generateWavePickTaskNo, createWavePickTaskWithRetry, isTaskNoDuplicateError, bulkInsertRows, parseWaveStrategyExistingTaskInfo, waveStrategyFetchPda, cancelWavePickTasksInternal, wavePickTaskCancel, wavePickTaskCancelSelf, waveStrategyFetchAdmin, deleteOrderWaveIndexByOrderIds, deleteOrderWaveIndexByWaveIds, rebuildOrderWaveIndex, replaceOrderWaveIndexByWaveIds, fetch - app/service/systemMethods/outbound.js (1) - autoOutbound - app/service/systemMethods/pick.js (14) @@ -383,8 +444,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods - callSystemRole, list, permission, add, delete, update - app/service/systemMethods/setting/store_warehouse.js (0) - -- app/service/systemMethods/setting/warehouse.js (3) - - getSettings, getFieldMeta, saveSettings +- app/service/systemMethods/setting/warehouse.js (6) + - getSettings, getFieldMeta, saveSettings, getFrontConfig, saveFrontConfig, saveFrontCert - app/service/systemMethods/shops.js (6) - callShopsSystem, list, add, del, edit, GetAuthorizeSessionKey - app/service/systemMethods/stock/combo.js (0) @@ -405,8 +466,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods - list, listStore, get, getStore, cancel, addItem, commit, removeItem, bindReceiving, unbindReceiving, quickInbound, getPrintData, receivingCompare, queryEntryLogs, getReceivingDetailsForBind, containerList, reviewEntry, export, exportTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress, storeExport, storeExportTaskProgress - app/service/systemMethods/storage/expiry.js (1) - list -- app/service/systemMethods/storage/inventory.js (14) - - transferLocation, transferByProduct, extractStockQueryVirtualFilter, list, listByStockId, quickPutaway, directPutaway, export, exportTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress +- app/service/systemMethods/storage/inventory.js (15) + - transferLocation, transferByProduct, extractStockQueryVirtualFilter, list, listByStockId, listBySpaceId, quickPutaway, directPutaway, export, exportTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress - app/service/systemMethods/storage/management.js (1) - replenishmentDemand - app/service/systemMethods/storage/receiving.js (29) @@ -451,8 +512,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods - list, detail, create, update, delete - app/service/systems/comboGoods.js (15) - fetchStockInfoMap, buildSimpleNotation, buildNameNotation, validateItems, getTargetStoreIdFromMap, checkCustomCodeUniqueForCreate, checkCustomCodeUniqueForUpdate, list, buildListWhere, create, update, delete, search, searchByIdOrCode, enrichComboList -- app/service/systems/delivery_order.js (52) - - getStoreSubjectConfigCacheKey, normalizeStoreSubjectConfig, getStoreSubjectConfig, findCodeOption, getOptionName, appendOrderOperationLog, getOrderLogOperator, getOrderLogWarehouseId, flushOrderOperationLogs, findPlatformOptionByCode, getPlatformSnapshotCode, getPlatformSnapshotName, resolvePlatformSnapshot, resolveExpressCodeFromSetting, resolveExpressSettingSnapshot, resolveEnableExternalExpressCode, resolveExpressSnapshot, addOrder, isPrimaryKeyDuplicate, formatOrderCreateError, resolveOrderStep, generateItemsHash, calculateCRC32, normalizeOrderFromKey, resolveOperatorName, prepareOrderData, addOrderLines, buildOrderItemSnapshot, safeParseFloat, withPatchedCtxUser, buildAsyncProcessContext, buildExpressAllocateRequest, enqueueAutoWaybillAllocation, buildStorageAllocateRequest, getStoreWarehousePolicyConfig, normalizePolicyFlag, resolveCutoffOrderConfig, isPastCutoffTime, Date, isAllocationWindowClosed, buildAutoGroupingStructure, findAutoGroupingWaveId, appendOrderToWave, countCandidateGroupOrders, createGroupingWave, markWaveAutoGrouping, finishAutoGroupingIfNeeded, runAutoGrouping, runAsyncProcessStep, findAutoExpressExcludedRemark, appendAutoExpressSkipLog, asyncProcessOrderCreated +- app/service/systems/delivery_order.js (54) + - getStoreSubjectConfigCacheKey, normalizeStoreSubjectConfig, getStoreSubjectConfig, findCodeOption, getOptionName, appendOrderOperationLog, getOrderLogOperator, getOrderLogWarehouseId, flushOrderOperationLogs, findPlatformOptionByCode, getPlatformSnapshotCode, getPlatformSnapshotName, resolvePlatformSnapshot, resolveExpressCodeFromSetting, resolveExpressSettingSnapshot, resolveEnableExternalExpressCode, resolveExpressSnapshot, addOrder, buildOrderStats, isRetryableLockError, isPrimaryKeyDuplicate, formatOrderCreateError, resolveOrderStep, generateItemsHash, calculateCRC32, normalizeOrderFromKey, resolveOperatorName, prepareOrderData, addOrderLines, buildOrderItemSnapshot, safeParseFloat, withPatchedCtxUser, buildAsyncProcessContext, buildExpressAllocateRequest, enqueueAutoWaybillAllocation, buildStorageAllocateRequest, getStoreWarehousePolicyConfig, normalizePolicyFlag, resolveCutoffOrderConfig, isPastCutoffTime, Date, isAllocationWindowClosed, buildAutoGroupingStructure, findAutoGroupingWaveId, appendOrderToWave, countCandidateGroupOrders, createGroupingWave, markWaveAutoGrouping, finishAutoGroupingIfNeeded, runAutoGrouping, runAsyncProcessStep, findAutoExpressExcludedRemark, appendAutoExpressSkipLog, asyncProcessOrderCreated - app/service/systems/entry_order.js (16) - addOrder, getLineCount, received, success, fail, findByOrderCode, findByStatus, getStatsByWarehouse, updateSyncStatus, updateOrderStatus, calculateReceivedQuantities, batchUpdateReceived, getOrderProgress, tryCreateEntryOrder, addItems, reviewEntry - app/service/systems/excel.js (26) @@ -533,10 +594,12 @@ rg "class .*Service|module.exports" app/service/qimenMethods - qimenClient, send, sendRequest - app/service/systems/receiving_entry_match.js (27) - matchAfterEntryCompleted, _bindEntryOrderReceiving, bindEntryOrderReceiving, _bindReceivingsWithStorageSync, _bindOneReceivingAndSyncStorage, max, _syncReceivingStorageByEntryItems, _parseLedgerMap, _serializeLedgerMap, min, _buildLegacyBaselineLedger, _bindingAllocationByStock, _recalcReceivingStorageStatus, _reconcileEntryReceivedQuantity, recordLedgerAllocation, setLedgerAllocation, rollbackEntryOrderBindings, _rollbackOneBindingStorage, _getRecentReceivingOrders, _findReceivingByRemark, _compareDetails, _sendCallback, _sendQimenCallback, _sendOpenApiCallback, _markReceivingPartialStorage, _commitBinding, unbindEntryOrderReceiving -- app/service/systems/report.js (16) - - getDefinition, parseFieldsField, definitionToView, resolveTypeEntry, resolveQuerier, listRegisteredTypes, validateTypeFields, resolveOrderedFields, buildFilename, buildWorkbookSheets, generate, generateBuffer, saveDefinition, findDefinitionById, listDefinitions, deleteDefinition +- app/service/systems/report.js (17) + - getDefinition, parseFieldsField, definitionToView, resolveTypeEntry, resolveQuerier, listRegisteredTypes, validateTypeFields, resolveOrderedFields, Date, buildFilename, buildWorkbookSheets, generate, generateBuffer, saveDefinition, findDefinitionById, listDefinitions, deleteDefinition - app/service/systems/report/queries/index.js (0) - +- app/service/systems/report/queries/interceptOrder.js (0) + - - app/service/systems/report/queries/sevenDayStockFlow.js (0) - - app/service/systems/reportDelivery.js (29) @@ -567,8 +630,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods - createError, getCurrentStoreId, getCurrentEmployeeId, toPositiveNumber, getEmployee, normalizeRoleIds, findAssignableRoles, clearEmployeeCache, getCurrentEmployeeRoleIds, collectDescendantRoleIds, buildRolePermissionMap, buildRoleTree, normalizeStoreScope, isRoleVisibleInScope, normalizePermissionIds, normalizePid, getManageableRole, validatePermissionSet, replaceRolePermissions, clearRoleUsersCache, list, permission, add, delete, update - app/service/systems/setting/store_warehouse.js (35) - createError, getCurrentStoreId, getCurrentAccountId, toPositiveNumber, normalizePage, normalizeStatusFlag, normalizeAuthStatus, normalizeNonNegativeInteger, normalizeText, normalizeDate, normalizeSignAction, normalizeTempCode, getTempCodeCacheKey, createTempCode, pickRemaskField, resolveRemaskValue, buildCurrentRemaskPatch, requireCurrentRemaskPatch, saveTempSignPayload, getTempSignPayload, clearTempSignPayload, buildTempSignView, getCurrentSubject, getCounterparty, buildListWhere, getRelationIncludes, resolvePairIds, serializeRelation, findScopedRelation, list, sign, trimContract, confirmSign, rename, unbind -- app/service/systems/setting/warehouse.js (12) - - getDefaultCodeFieldOptionsMap, normalizeWaveStrategyVersion, normalizeSubjectConfigInternalFields, sanitizeSubjectConfigForOutput, createError, getCurrentWarehouseId, deleteCacheByKey, clearWarehouseSettingCache, getFieldMeta, getSettings, validateDefaultLocation, saveSettings +- app/service/systems/setting/warehouse.js (30) + - getDefaultCodeFieldOptionsMap, normalizeWaveStrategyVersion, normalizeSubjectConfigInternalFields, sanitizeSubjectConfigForOutput, createError, getCurrentWarehouseId, deleteCacheByKey, clearWarehouseSettingCache, getFieldMeta, getSettings, validateDefaultLocation, saveSettings, normalizeFrontConfigText, normalizeFrontConfigTheme, assertFrontConfigDomainUnique, buildFrontConfigOutput, getFrontConfig, getFrontConfigDomainCacheKey, buildFrontConfigPublicOutput, clearFrontConfigDomainCache, getFrontConfigByDomain, normalizeFrontConfigPem, parseFrontConfigCertPem, assertFrontConfigCertValid, collectFrontConfigCertNames, frontConfigCertCoversDomain, validateFrontConfigKeyPem, assertFrontConfigWarehouseSubject, saveFrontConfig, saveFrontCert - app/service/systems/shops.js (20) - generatePendingShopName, createError, getCurrentWarehouseId, normalizeText, normalizeInteger, ensureShopPrintPlatformExists, getListWhereSpecialFieldMap, buildListWhere, normalizePagination, buildShopPrintPlatformInclude, formatShopRow, list, ensureShopNameUnique, add, findShopById, del, edit, generateAuthorizeRandomCode, createOrReuseAuthorizeReservation, getAuthorizeSessionKey - app/service/systems/sign.js (10) @@ -581,14 +644,16 @@ rg "class .*Service|module.exports" app/service/qimenMethods - normalizeInboundOrderId, isOrderOutboundTransaction, resolveOutboundOrderReference, create, list, _buildStorageTransactionWhere, _resolveKeywordToStockIds, queryList, exportList, exportStorageList - app/service/systems/stock_warehouse.js (3) - _buildStockDetailCacheKey, getStockDetails, invalidateStockDetailCache +- app/service/systems/stockout_order.js (3) + - resolveStockoutExpress, create, query - app/service/systems/storage/entry.js (25) - normalizeExpenseRecordValue, normalizeExpenseRecordCondition, normalizeFilterValues, buildEntryStockTransactionExistsCondition, buildHasReceivingCondition, preprocessEntryListWhere, list, get, IN, enrichItemsWithAvailableReceivingDetails, normalizeCancelEntryOrderIds, getOwnedEntryOrderById, cancel, _rollbackReceivingStorageStatus, addItem, commit, removeItem, getReceivingDetailsForBind, containerList, _applyReceivingInboundUsage, quickInbound, receivingCompare, _buildMergedComparison, exportEntryOrders, exportStoreEntryOrders - app/service/systems/storage/expiry.js (1) - list - app/service/systems/storage/index.js (15) - findByStockAndBatch, findBySpace, findAvailableByWarehouse, findExpiringSoon, updateQuantity, lockQuantity, unlockQuantity, allocateQuantity, interceptLockQuantity, interceptReceiveQuantity, interceptUnlockQuantity, min, offsetGapOnInbound, getStockSummary, getSpaceUsage -- app/service/systems/storage/inventory.js (13) - - createTransferStockTransactions, transferLocation, transferByProduct, resolveStockQueryToStockIds, getInventoryList, getStorageListByStockId, _aggregateStorageRowsBySpace, _loadInventoryWarningRanges, _formatBatchStorageRows, quickPutaway, directPutaway, exportInventoryList, _generateEntryOrderCode +- app/service/systems/storage/inventory.js (15) + - createTransferStockTransactions, transferLocation, transferByProduct, resolveStockQueryToStockIds, getInventoryList, getStorageListByStockId, getStorageListBySpaceId, _aggregateStorageRowsByStock, _aggregateStorageRowsBySpace, _loadInventoryWarningRanges, _formatBatchStorageRows, quickPutaway, directPutaway, exportInventoryList, _generateEntryOrderCode - app/service/systems/storage/management.js (1) - replenishmentDemand - app/service/systems/storage/receiving.js (44) @@ -603,8 +668,12 @@ rg "class .*Service|module.exports" app/service/qimenMethods - createError, getCurrentStoreId, getCurrentAccountId, toPositiveNumber, normalizePage, normalizeStatusFlag, normalizeAuthStatus, normalizeNonNegativeInteger, normalizeInteger, normalizeText, normalizeIntegerRange, normalizeEmail, getPolicyConfigFieldList, getPolicyConfigFieldMetaList, normalizePolicyConfig, getPolicyConfigCacheKey, hasPolicyConfigColumn, loadPolicyConfigByContractId, savePolicyConfigByContractId, getPolicyConfigDefaults, mergePolicyConfigWithDefaults, getEffectivePolicyConfigByContractId, ensureWarehouseSubject, getNoticeService, sendPrintQuantityAdjustNotice, resolveRelationId, normalizeDate, normalizeSignAction, normalizeTempCode, getTempCodeCacheKey, createTempCode, pickRemaskField, resolveRemaskValue, buildCurrentRemaskPatch, requireCurrentRemaskPatch, saveTempSignPayload, getTempSignPayload, clearTempSignPayload, buildTempSignView, getCurrentSubject, getCounterparty, buildListWhereByStoreId, buildListWhere, getRelationIncludes, getQimenContractCacheKey, clearQimenContractCache, getApiInterfaceType, getQimenInterfaceType, resolveQimenCustomerIdByAppKey, getQimenErpNameMapByAppKeys, serializeQimenConfig, getQimenConfigMap, getSingleQimenConfig, resolvePairIds, serializeRelation, findScopedRelation, buildListForStoreWhere, listForStore, exportListForStore, listForWarehouse, list, sign, trimContract, confirmSign, rename, adjustPrintQuantity, queryPrintQuantityLogs, exportPrintQuantityLogs, getPolicyConfigFields, getPolicyConfig, savePolicyConfig, listApiConfig, saveApiConfig, deleteQimenConfig, unbind, getContractConfigCacheKey, invalidateContractConfigCache, getContractConfig, openAccount, createUser - app/service/systems/store.js (22) - normalizeSubjectConfigInput, validateStoreData, checkCompanyNameExists, findByAccountId, findAllEnabled, findAllWarehouses, getStoreName, getStoreRemaskName, createStore, createWarehouse, joinStore, joinWarehouse, ensureEmployeeRoleBinding, assignAdminRoleToCreator, generateJoinToken, sendNotification, sendNotificationToAdmins, getStoreRoles, auditApply, loadStores, loadWarehouses, bindCode +- app/service/systems/system_log.js (3) + - findCleanupBoundaryId, deleteSystemLogsBatch, cleanupExpiredSystemLogs - app/service/systems/upload.js (18) - getTencentCloudConfig, getCosConfig, initCOS, getUploadParams, hash_hmac, generatePolicyAndSignature, resolveUploadMaxSizeBytes, validateFileInfo, generateFileName, parseSizeToBytes, formatFileSize, getFrontendConfig, uploadFile, validateFile, uploadSuccessNotify, getMimeType, createFileReference, handleUploadCallback +- app/service/systems/video_record_request.js (15) + - _getRecordingComputer, _isComputerOnline, _resetVideoRecords, _withinReuseWindow, _markFailed, requestPackVideo, requestUnpackVideo, requestFor, syncByVideos, settleStatuses, notifyResults, queryPackVideo, _buildResultMessage, _notifyManualHandling, _replyResult - app/service/systems/warehouseNotify.js (7) - truncateLogBody, getCallbackConfig, MD5, buildSignature, writeLog, push, pushSystemMessage - app/service/systems/wave_batch_closure.js (1) @@ -632,6 +701,16 @@ rg "class .*Service|module.exports" app/service/qimenMethods + + + + + + + + + + diff --git a/app/controller/docs.js b/app/controller/docs.js index 7967b14..f5c5d27 100644 --- a/app/controller/docs.js +++ b/app/controller/docs.js @@ -445,12 +445,14 @@ function normalizeGroups(docData) { /** * 解析文档对应的统一入口路径,优先使用文档内声明的 http.path。 + * 只要 http.path 是非空字符串就原样返回,允许 `{ApiApp.callback_url}` + * 这类出站回调占位符原样展示;http.path 为 null/空串时回落到模块默认入口。 * @param {object} docData 文档 JSON 数据。 * @return {string} 统一入口路径。 */ function resolveDocEntryPath(docData) { const httpPath = String(docData?.http?.path || '').trim(); - if (httpPath.startsWith('/')) { + if (httpPath) { return httpPath; } @@ -679,8 +681,9 @@ function renderHtmlPage({ entryPath, }) { const isOpenapi = docData.module === 'openapi'; + const isOpenapiCallback = docData.module === 'openapi_callback'; const isWarehouse = docData.module === 'warehouse' || docData.module === 'warehouse_notify'; - const isExternalApi = isOpenapi || isWarehouse; + const isExternalApi = isOpenapi || isOpenapiCallback || isWarehouse; const methodsCount = groups.reduce((sum, group) => sum + toArray(group.list).length, 0); const globalHeaders = toArray(docData.headers); const globalHeadersControls = renderGlobalHeadersControls(globalHeaders); @@ -1133,7 +1136,7 @@ function renderHtmlPage({
点击上方按钮后,可直接预览当前文档的变更记录或原文 JSON。
`} - ${isExternalApi ? (docData.module === 'warehouse_notify' ? `
+ ${isOpenapi || isWarehouse ? (docData.module === 'warehouse_notify' ? `

请求方式

POST {notify_url}?app_key={app_key}&method={方法名}&timestamp={时间戳}&sign={签名}
 Content-Type: application/json
@@ -1212,6 +1215,10 @@ Content-Type: application/json
         ${isOpenapi ? `

→ 回调测试工具 (模拟接收回调通知,验证回调链路) +

+

+ → 出站回调文档 + (WMS → 外部的回调事件定义,共 5 个)

` : ''}
`) : ''} @@ -2157,6 +2164,14 @@ class DocsController extends Controller { await this.renderDoc('openapi'); } + /** + * 渲染 OpenAPI 出站回调文档独立页面。 + * @return {Promise} 无返回值。 + */ + async openapiCallbackEvents() { + await this.renderDoc('openapi_callback'); + } + /** * 渲染仓库开放 API 文档独立页面。 * @return {Promise} 无返回值。 diff --git a/app/controller/openapiCallback.js b/app/controller/openapiCallback.js index e10ad8c..a0c4c89 100644 --- a/app/controller/openapiCallback.js +++ b/app/controller/openapiCallback.js @@ -9,7 +9,8 @@ const { CALLBACK_EVENTS } = require('../service/openapi/callbackRegistry'); class OpenapiCallbackController extends Controller { /** * 渲染回调测试页面。 - * 页面支持选择已注册的回调事件、填入测试 URL 和密钥, + * 页面支持选择已注册的回调事件,选中后自动填充与真实回调完全一致的 + * 完整报文体 { request: {...} }(奇门同层级,可编辑)、填入测试 URL 和密钥, * 前端计算 MD5 签名后 POST 到目标 URL 并展示完整请求/响应。 */ async testPage() { @@ -45,9 +46,11 @@ class OpenapiCallbackController extends Controller {

OpenAPI 回调测试

-

选择已注册的回调事件,填入测试 URL,模拟真实回调推送。

+

选择已注册的回调事件,自动填充与真实回调完全一致的完整报文体(奇门同层级 { request },可编辑),填入测试 URL 模拟推送。

← 返回 API 文档 +  |  + → 出站回调文档

@@ -72,8 +75,8 @@ class OpenapiCallbackController extends Controller { - - + + @@ -102,7 +105,9 @@ class OpenapiCallbackController extends Controller { var found = EVENTS.find(function(e) { return e.name === name; }); if (found) { eventDesc.textContent = found.description; - dataInput.value = JSON.stringify(found.sampleData, null, 2); + dataInput.value = JSON.stringify({ + request: found.request || {}, + }, null, 2); } else { eventDesc.textContent = ''; dataInput.value = '{}'; diff --git a/app/router.js b/app/router.js index b437fe3..438c229 100644 --- a/app/router.js +++ b/app/router.js @@ -39,6 +39,9 @@ module.exports = app => { // OpenAPI 回调测试 — 所有环境均可访问的独立调试页面 router.get('/docs/api/openapi/callback-test', controller.openapiCallback.testPage); + // OpenAPI 出站回调文档 — 所有环境均可访问 + router.get('/docs/api/openapi_callback', controller.docs.openapiCallbackEvents); + // 仅开发环境可访问的 docs 通配路由(静态文件),必须在 /docs/api/openapi 之后注册 if (app.config.env === 'local') { router.get('/docs/:relPath(.*)', controller.docs.docsFile); diff --git a/app/service/openapi/callback.js b/app/service/openapi/callback.js index 016a908..f8936d6 100644 --- a/app/service/openapi/callback.js +++ b/app/service/openapi/callback.js @@ -18,12 +18,13 @@ class OpenapiCallbackService extends Service { /** * 计算回调签名(与 OpenAPI 入口签名算法完全一致)。 + * 算法:md5(canonicalQuery + selfAppSecret + md5(stableStringify(body)))。 * @param {Object} options 签名参数。 - * @param {string} options.event 事件名,如 order_completed。 + * @param {string} options.event 回调 method(模块.动作,如 deliveryorder.confirm),仅用于 query 的 method。 * @param {string} options.appKey 应用 app_key。 * @param {string} options.selfAppSecret 应用密钥。 - * @param {Object} options.body 回调请求体数据。 - * @param {string} options.timestamp 毫秒时间戳。 + * @param {Object} options.body 完整回调报文体(奇门同层级 { request: {...} })。 + * @param {string} options.timestamp 秒级时间戳(10 位字符串,与 /openapi 入站时效校验一致)。 * @return {{ canonicalQuery: string, bodySign: string, sign: string }} 签名计算结果。 */ signCallback({ event, appKey, selfAppSecret, body, timestamp }) { @@ -39,21 +40,23 @@ class OpenapiCallbackService extends Service { /** * 发送回调请求(带自动重试)。 + * 报文体固定为奇门同层级结构 { request: {...} },event 仅拼入 query 的 method; * 非 2xx 响应或网络错误触发重试,最多重试 MAX_RETRY 次, - * 每次重试间隔递增(2s → 5s → 15s)。 + * 每次重试间隔递增(2s → 5s → 15s),请求超时 30 秒。 * @param {Object} options 回调选项。 * @param {string} options.callbackUrl 回调目标 URL。 * @param {string} options.appKey 应用 app_key。 * @param {string} options.selfAppSecret 应用密钥。 - * @param {string} options.event 事件名,如 order_completed。 - * @param {Object} options.data 回调数据。 - * @param {Object} [options.metadata] 额外元数据。 + * @param {string} options.event 回调 method(模块.动作,如 deliveryorder.confirm),仅用于 query 的 method。 + * @param {Object} options.request 奇门同层级业务报文内容(不含外层 request 包装,由发送端包装)。 * @return {Promise} 回调结果 { success, retryCount, response, error }。 */ - async sendWithRetry({ callbackUrl, appKey, selfAppSecret, event, data, metadata }) { + async sendWithRetry({ callbackUrl, appKey, selfAppSecret, event, request }) { const { ctx } = this; - const timestamp = String(Date.now()); - const body = { event, data, metadata: metadata || {} }; + // 秒级时间戳(10 位):与 /openapi 入站时效校验(±600 秒窗口)及回调调试页保持一致 + const timestamp = String(Math.floor(Date.now() / 1000)); + // 报文体固定为奇门同层级 { request }:event 只出现在 query 的 method 中 + const body = { request: request || {} }; const { sign } = this.signCallback({ event, appKey, selfAppSecret, body, timestamp }); const queryString = [ @@ -85,6 +88,8 @@ class OpenapiCallbackService extends Service { lastResponse = result; if (result.status >= 200 && result.status < 300) { + console.log(`[OpenapiCallback] event=${event} appKey=${appKey} retry=${attempt} url=${url} status=${result.status} success=true response=${this._formatResponsePayload(result.data)}`); + await this.logCallback({ appKey, event, @@ -104,6 +109,8 @@ class OpenapiCallbackService extends Service { lastError = new Error(`回调返回非 2xx 状态码: ${result.status}`); + console.log(`[OpenapiCallback] event=${event} appKey=${appKey} retry=${attempt} url=${url} status=${result.status} success=false response=${this._formatResponsePayload(result.data)}`); + await this.logCallback({ appKey, event, @@ -115,6 +122,9 @@ class OpenapiCallbackService extends Service { }); } catch (error) { lastError = error; + const availableResponse = lastResponse ? lastResponse.data : null; + + console.log(`[OpenapiCallback] event=${event} appKey=${appKey} retry=${attempt} url=${url} success=false error=${error.message} response=${this._formatResponsePayload(availableResponse)}`); await this.logCallback({ appKey, @@ -122,7 +132,7 @@ class OpenapiCallbackService extends Service { callbackUrl, success: false, retryCount: attempt, - response: null, + response: availableResponse, error: error.message, }); } @@ -143,14 +153,14 @@ class OpenapiCallbackService extends Service { /** * 根据 app_key 查询 api_app 获取 callback_url 与密钥,发送回调通知。 + * 报文体由 sendWithRetry 统一包装为奇门同层级 { request: {...} }。 * @param {Object} options 回调选项。 * @param {string} options.appKey 应用 app_key。 - * @param {string} options.event 事件名,如 order_completed。 - * @param {Object} options.data 回调数据。 - * @param {Object} [options.metadata] 额外元数据。 + * @param {string} options.event 回调 method(模块.动作,如 deliveryorder.confirm),仅用于 query 的 method。 + * @param {Object} options.request 奇门同层级业务报文内容(不含外层 request 包装,由发送端包装)。 * @return {Promise} 回调结果 { success, retryCount, response, error }。 */ - async sendByAppKey({ appKey, event, data, metadata }) { + async sendByAppKey({ appKey, event, request }) { const { ctx } = this; const normalizedAppKey = String(appKey || '').trim(); @@ -190,26 +200,65 @@ class OpenapiCallbackService extends Service { appKey: normalizedAppKey, selfAppSecret: appConfig.self_app_secret || '', event, - data, - metadata, + request, }); } + /** + * 将回调响应报文格式化为日志可输出的字符串。 + * 兼容对象、字符串、Buffer / ArrayBuffer / TypedArray 与 null / undefined, + * 超出最大长度时做截断处理,避免日志刷屏。 + * @param {*} response 回调响应报文,类型不限。 + * @return {string} 格式化后的报文字符串。 + */ + _formatResponsePayload(response) { + const MAX_PAYLOAD_LENGTH = 500; + let payload; + + if (response === null || response === undefined) { + payload = 'null'; + } else if (typeof response === 'string') { + payload = response; + } else if (Buffer.isBuffer(response)) { + payload = response.toString('utf8'); + } else if (response instanceof ArrayBuffer) { + payload = Buffer.from(response).toString('utf8'); + } else if (ArrayBuffer.isView(response)) { + // TypedArray 与 DataView:仅取视图对应的内存区间 + payload = Buffer.from(response.buffer, response.byteOffset, response.byteLength).toString('utf8'); + } else { + try { + payload = JSON.stringify(response); + } catch (error) { + // 循环引用等序列化异常时降级处理 + payload = String(response); + } + } + + if (payload.length > MAX_PAYLOAD_LENGTH) { + return `${payload.slice(0, MAX_PAYLOAD_LENGTH)}...(truncated)`; + } + + return payload; + } + /** * 记录回调日志。 - * 格式:[OpenapiCallback] event=xxx appKey=xxx url=xxx retry=N success=xxx + * 格式:[OpenapiCallback] event=xxx appKey=xxx url=xxx retry=N success=xxx response=xxx * @param {Object} options 日志选项。 * @param {string} options.appKey 应用 app_key。 * @param {string} options.event 事件名。 * @param {string} options.callbackUrl 回调目标 URL。 * @param {boolean} options.success 是否成功。 * @param {number} options.retryCount 重试次数。 + * @param {*} [options.response] 回调响应报文。 * @param {string} [options.error] 错误信息。 * @return {void} 无返回值。 */ - async logCallback({ appKey, event, callbackUrl, success, retryCount, error }) { + async logCallback({ appKey, event, callbackUrl, success, retryCount, response, error }) { const { ctx } = this; - const logMessage = `[OpenapiCallback] event=${event} appKey=${appKey} url=${callbackUrl} retry=${retryCount} success=${success}`; + const payload = this._formatResponsePayload(response); + const logMessage = `[OpenapiCallback] event=${event} appKey=${appKey} url=${callbackUrl} retry=${retryCount} success=${success} response=${payload}`; if (success) { ctx.logger.info(logMessage); diff --git a/app/service/openapi/callbackRegistry.js b/app/service/openapi/callbackRegistry.js index 35a95e8..d091c35 100644 --- a/app/service/openapi/callbackRegistry.js +++ b/app/service/openapi/callbackRegistry.js @@ -3,27 +3,192 @@ /** * OpenAPI 回调事件注册表。 * 每个事件包含 name(事件名)、label(展示名)、description(说明)、 - * sampleData(示例数据,与真实回调数据格式一致)。 + * request(奇门同层级报文模板,即 request 节点的内容,不含外层 request 包装; + * 真实回调报文结构统一为 { request: {...} },字段名与嵌套层级和真实调用点完全一致)。 + * 回调调试页 GET /docs/api/openapi/callback-test 直接消费本注册表。 */ const CALLBACK_EVENTS = [ { - name: 'order_completed', - label: '订单发货完成', - description: '订单同步(出库)完成后触发', - sampleData: { - orderIds: [ 1001, 1002 ], - status: 'completed', - successCount: 2, - failedCount: 0, + name: 'entryorder.confirm', + label: '入库单确认完成(直入)', + description: '直入入库(API 来源)完成后回传,对应奇门 taobao.qimen.entryorder.confirm', + request: { + entryOrder: { + entryOrderCode: 'RK20260912001', + ownerCode: 'OWNER-001', + warehouseCode: 'WH-100', + entryOrderId: 543, + entryOrderType: 'SCRK', + outBizCode: 'DIRECT_INBOUND_1726131400000', + confirmType: 0, + status: 'FULFILLED', + freight: 0, + operateTime: '2026-09-12 10:30:00', + remark: '导入/PDA直接入库提交', + }, + orderLines: [ + { + orderLineNo: 1, + ownerCode: 'OWNER-001', + itemCode: 'SKU-1', + itemId: '1001', + inventoryType: 'ZP', + planQty: 2, + actualQty: 2, + }, + ], }, }, { - name: 'order_cancelled', + name: 'entryorder.match', + label: '入库单匹配收货完成', + description: '入库单匹配收货单完成后回传(API 来源),对应奇门 taobao.qimen.entryorder.confirm', + request: { + entryOrder: { + entryOrderCode: 'RK20260912002', + ownerCode: 'OWNER-001', + warehouseCode: 'WH-100', + entryOrderId: 543, + entryOrderType: 'SCRK', + outBizCode: 'RECEIVING_MATCH_1726131400000', + confirmType: 0, + status: 'FULFILLED', + freight: 0, + operateTime: '2026-09-12 10:30:00', + remark: '匹配收货单RCV20260912001自动回传', + }, + orderLines: [ + { + orderLineNo: 1, + ownerCode: 'OWNER-001', + itemCode: 'SKU-1', + itemId: '1001', + inventoryType: 'ZP', + planQty: 2, + actualQty: 2, + }, + ], + }, + }, + { + name: 'deliveryorder.confirm', + label: '订单发货完成', + description: '订单同步(出库)完成后触发,对应奇门 taobao.qimen.deliveryorder.confirm', + request: { + deliveryOrder: { + totalOrderLines: 1, + deliveryOrderCode: 'DO20260912001', + deliveryOrderId: 123, + warehouseCode: 'WH-100', + orderType: 'JYCK', + status: 'DELIVERED', + outBizCode: 'DO20260912001', + confirmType: 0, + orderConfirmTime: '2026-09-12 10:30:00', + operatorCode: '', + operatorName: '', + storageFee: '0', + operateTime: '2026-09-12 10:30:00', + }, + packages: { + package: [ + { + logisticsCode: 'YTO', + logisticsName: '圆通速递', + expressCode: 'YT1234567890', + packageCode: 'DO20260912001', + invoiceNo: 'INV20260912001', + items: [ + { + itemCode: 'SKU-1', + itemId: 1001, + quantity: 2, + }, + ], + }, + ], + }, + orderLines: [ + { + orderLineNo: '1', + orderSourceCode: 'SO20260912001', + subSourceCode: '', + ownerCode: 'OWNER-001', + itemCode: 'SKU-1', + itemId: 1001, + itemName: '测试商品1', + extCode: '', + planQty: 2, + actualQty: 2, + retailPrice: 0, + actualPrice: 0, + discountAmount: '0', + inventoryType: 'ZP', + snList: [], + qrCode: '', + }, + ], + }, + }, + { + name: 'stockout.confirm', + label: '出库单确认完成', + description: '出库单确认回传(API 来源),对应奇门 taobao.qimen.stockout.confirm', + request: { + deliveryOrder: { + totalOrderLines: 1, + deliveryOrderCode: 'SO20260912001', + deliveryOrderId: 5001, + warehouseCode: 'WH-100', + orderType: 'PTCK', + status: 'DELIVERED', + outBizCode: 'SO20260912001', + confirmType: 0, + orderConfirmTime: '2026-09-12 10:30:00', + operatorCode: '', + operatorName: '', + }, + packages: { + package: [ + { + logisticsCode: 'YTO', + logisticsName: '圆通速递', + expressCode: 'YT1234567890', + packageCode: 'SO20260912001', + items: [ + { + itemCode: 'SKU-1', + itemId: 1001, + quantity: 2, + }, + ], + }, + ], + }, + orderLines: [ + { + orderLineNo: '1', + ownerCode: 'OWNER-001', + itemCode: 'SKU-1', + itemId: 1001, + itemName: '测试商品1', + planQty: 2, + actualQty: 2, + inventoryType: 'ZP', + }, + ], + }, + }, + { + name: 'deliveryorder.cancel', label: '订单已取消', - description: '订单取消成功后触发', - sampleData: { - orderCode: 'TEST-ORDER-001', - status: 'cancelled', + description: '订单取消成功后触发(出站回调事件名 deliveryorder.cancel,与入站方法 order.cancel 区分,避免回调误路由到取消单据接口;无奇门对应接口,按 deliveryOrder 节点约定自定义)', + request: { + deliveryOrder: { + deliveryOrderCode: 'TEST-ORDER-001', + orderType: 'JYCK', + status: 'CANCELED', + }, }, }, ]; diff --git a/app/service/openapiMethods/callback.js b/app/service/openapiMethods/callback.js index 0ee4cd7..40bc8ab 100644 --- a/app/service/openapiMethods/callback.js +++ b/app/service/openapiMethods/callback.js @@ -44,21 +44,20 @@ class OpenapiCallbackMethodService extends MainService { * 模拟发送回调通知(测试用)。 * 通过 app_key 查找回调配置并发送一次回调请求。 * @param {Object} [payload={}] 调用参数。 - * @param {Object} [payload.body={}] 请求体数据,可指定 event 与 data。 + * @param {Object} [payload.body={}] 请求体数据,可指定 event 与 request(奇门同层级业务报文,不含外层 request 包装)。 * @param {Object} [payload.query={}] 请求 query 数据,需包含 app_key。 * @return {Promise} 回调测试结果。 */ async test(payload = {}) { const { body = {}, query = {} } = payload; - const { event = 'order_completed', data = {} } = body; + const { event = 'deliveryorder.confirm', request = {} } = body; try { const info = await this.resolveAppInfo(query.app_key); const result = await this.ctx.service.openapi.callback.sendByAppKey({ appKey: info.appKey, event, - data, - metadata: { test: true }, + request, }); if (result.success) { diff --git a/app/service/systems/inbound_direct_log.js b/app/service/systems/inbound_direct_log.js index cd69f89..52d1a6c 100644 --- a/app/service/systems/inbound_direct_log.js +++ b/app/service/systems/inbound_direct_log.js @@ -1392,16 +1392,53 @@ class InboundDirectLogService extends Service { return lines; } + /** + * 组装 entryorder.confirm 业务报文(与奇门 taobao.qimen.entryorder.confirm 同层级)。 + * 返回 { entryOrder, orderLines },不包含外层 request 包装, + * 字段与取值逻辑以奇门分支为唯一基准,奇门与 OpenAPI 回传共用。 + * @param {Object} entryOrder 入库单对象 + * @param {Array} orderLines 入库明细行数组 + * @param {Object} [options] 可选配置 + * @param {string} [options.outBizCode] 外部业务编码,缺省时自动生成 DIRECT_INBOUND_时间戳 + * @param {boolean} [options.isFin=true] 是否最终确认(confirmType 0=最终 / 1=部分,status FULFILLED / PARTFULFILLED) + * @param {string} [options.remark] 备注 + * @return {{ entryOrder: Object, orderLines: Array }} 组装后的业务报文 + */ + buildEntryOrderConfirmRequest(entryOrder, orderLines, options = {}) { + const { app } = this; + const { outBizCode, isFin = true, remark } = options; + + return { + entryOrder: { + entryOrderCode: entryOrder.entry_order_code, + ownerCode: entryOrder.qimen_owner_code || '', + warehouseCode: entryOrder.qimen_warehouse_code || '', + entryOrderId: entryOrder.id, + entryOrderType: entryOrder.order_type, + outBizCode: outBizCode || `DIRECT_INBOUND_${Date.now()}`, + confirmType: isFin ? 0 : 1, + status: isFin ? 'FULFILLED' : 'PARTFULFILLED', + freight: 0, + operateTime: app.formatDate(new Date()), + remark: remark || '', + }, + orderLines, + }; + } + /** * OpenAPI 回传:查询 ApiApp 回调地址并 POST 回传。 + * 报文体与奇门同层级({ request: { entryOrder, orderLines } },外层 request 由发送端自动包裹), + * 与奇门分支共用 buildEntryOrderConfirmRequest 组装。 * @param {Object} entryOrder 入库单 * @param {Object} [options] 可选配置 + * @param {Object} options.request 奇门同层级业务报文 { entryOrder, orderLines }(由 buildEntryOrderConfirmRequest 组装) * @param {boolean} [options.throwOnError=false] 失败时是否向外抛出异常 * @return {Promise} 返回回传结果 { success, error?, statusCode?, body? },异常时返回 null */ async _sendOpenApiCallback(entryOrder, options = {}) { const { ctx, app } = this; - const { throwOnError = false } = options; + const { request, throwOnError = false } = options; try { const storeWarehouse = await ctx.model.StoreWarehouse.findOne({ @@ -1449,30 +1486,19 @@ class InboundDirectLogService extends Service { return null; } - const callbackData = { - entryOrderId: entryOrder.id, - entryOrderCode: entryOrder.entry_order_code, - completedAt: new Date().toISOString(), - inboundType: 'direct', - }; - console.log('[quickInbound] _sendOpenApiCallback 发送前:', { entryOrderId: entryOrder.id, callbackUrl: apiApp.callback_url, appKey: apiApp.self_app_key, - callbackData, + request, }); const result = await ctx.service.openapi.callback.sendWithRetry({ callbackUrl: apiApp.callback_url, appKey: apiApp.self_app_key, selfAppSecret: apiApp.self_app_secret || '', - event: 'entry_order_direct_inbound_completed', - data: callbackData, - metadata: { - source: 'inbound_direct_log', - entryOrderId: entryOrder.id, - }, + event: 'entryorder.confirm', + request, }); console.log('[quickInbound] _sendOpenApiCallback 响应:', { @@ -1566,22 +1592,11 @@ class InboundDirectLogService extends Service { // 3. 构造 queryData 并发请求(事务外) if (sourceType === 'QM') { const queryData = { - request: { - entryOrder: { - entryOrderCode: entryOrder.entry_order_code, - ownerCode: entryOrder.qimen_owner_code || '', - warehouseCode: entryOrder.qimen_warehouse_code || '', - entryOrderId: entryOrder.id, - entryOrderType: entryOrder.order_type, - outBizCode: outBizCode || `DIRECT_INBOUND_${Date.now()}`, - confirmType: isFin ? 0 : 1, - status: isFin ? 'FULFILLED' : 'PARTFULFILLED', - freight: 0, - operateTime: app.formatDate(new Date()), - remark: remark || '', - }, - orderLines, - }, + request: this.buildEntryOrderConfirmRequest(entryOrder, orderLines, { + outBizCode, + remark, + isFin, + }), }; console.log('[qimenEntrySync] 奇门请求发送前:', { @@ -1667,7 +1682,14 @@ class InboundDirectLogService extends Service { let apiResult; try { - apiResult = await this._sendOpenApiCallback(entryOrder, { throwOnError: true }); + apiResult = await this._sendOpenApiCallback(entryOrder, { + throwOnError: true, + request: this.buildEntryOrderConfirmRequest(entryOrder, orderLines, { + outBizCode, + remark, + isFin, + }), + }); } catch (err) { apiResult = { success: false, error: err.message }; } diff --git a/app/service/systems/order_async.js b/app/service/systems/order_async.js index 8601dba..58dc38c 100644 --- a/app/service/systems/order_async.js +++ b/app/service/systems/order_async.js @@ -857,6 +857,108 @@ async function processManualOrderInternal(service, orderModel, orderItemsModel, }; } +/** + * 逐单发送 API 渠道订单确认回调(deliveryorder.confirm)。 + * + * 复用 buildQimenDeliveryOrderConfirmDataInternal 组装与奇门 + * taobao.qimen.deliveryorder.confirm 完全一致的 request 报文, + * 每个同步成功的订单发送一次 OpenAPI 回调;单订单组装/发送失败 + * 仅记录 warn 日志,不影响其他订单与主流程。 + * + * @param {Object} service 订单异步服务实例。 + * @param {Object} options 通知参数。 + * @param {string} options.appKey 应用 app_key。 + * @param {number} options.warehouseId 仓库 ID。 + * @param {Object} options.context 同步上下文(透传给报文组装)。 + * @param {Array} options.successResults 同步成功结果列表。 + * @param {Map} options.orderMap 订单 ID 到主表记录的映射。 + * @param {Map>} options.itemsByOrderId 订单 ID 到明细列表的映射。 + * @return {Promise} 无返回值,失败仅记录 warn 日志。 + */ +async function notifyApiDeliveryOrderConfirmsInternal(service, options = {}) { + const { + appKey, + warehouseId, + context = {}, + successResults = [], + orderMap = new Map(), + itemsByOrderId = new Map(), + } = options; + const callbackService = service.ctx.service.openapi && service.ctx.service.openapi.callback; + if (!callbackService || typeof callbackService.sendByAppKey !== 'function') { + return; + } + + const successOrderIds = successResults + .map(item => Number(item && item.order_id)) + .filter(orderId => Number.isFinite(orderId) && orderId > 0); + if (successOrderIds.length === 0) { + return; + } + + // 一次性批量读取运单号(单次查询,避免逐单 N+1), + // 与 syncQmOrdersInternal 的加载方式保持一致 + const waybillCodeMap = await buildOrderWaybillCodeMapInternal(service, successOrderIds, warehouseId); + + for (const syncResult of successResults) { + const orderId = Number(syncResult && syncResult.order_id); + + try { + const orderRow = orderMap.get(orderId); + if (!orderRow) { + service.ctx.logger.warn(`[OrderAsyncService] deliveryorder.confirm 回调跳过:订单记录缺失 orderId=${orderId}`); + continue; + } + + const orderItems = itemsByOrderId.get(orderId) || []; + const waybillCodes = waybillCodeMap.get(orderId) || []; + const requestData = await buildQimenDeliveryOrderConfirmDataInternal(service, orderRow, orderItems, { + ...context, + packageExpressCode: Array.isArray(waybillCodes) ? waybillCodes[0] : '', + packageExpressCodes: waybillCodes, + }); + + // 报文组装数据缺失(如缺奇门货主编码)时跳过该订单,与 QM 分支口径一致 + if (!requestData || !requestData.ownerCode || !requestData.request) { + service.ctx.logger.warn(`[OrderAsyncService] deliveryorder.confirm 回调跳过:报文组装数据缺失 orderId=${orderId}`, { + deliveryOrderCode: String(orderRow.delivery_order_code || '').trim(), + ownerCode: requestData && requestData.ownerCode, + }); + continue; + } + + const callbackResult = await callbackService.sendByAppKey({ + appKey, + event: 'deliveryorder.confirm', + request: requestData.request, + }); + + if (!callbackResult || callbackResult.success !== true) { + service.ctx.logger.warn(`[OrderAsyncService] deliveryorder.confirm 回调失败 orderId=${orderId}`, { + deliveryOrderCode: String(orderRow.delivery_order_code || '').trim(), + error: callbackResult && callbackResult.error, + }); + } + } catch (error) { + service.ctx.logger.warn(`[OrderAsyncService] deliveryorder.confirm 回调异常 orderId=${orderId}`, { + message: String((error && error.message) || error || '').trim(), + }); + } + } +} + +/** + * 本地渠道(MANUAL / API)订单同步收尾: + * 逐单锁定扣减库存并推进订单同步状态,统计成功/失败数量; + * API 渠道在存在成功订单时,逐单触发 OpenAPI deliveryorder.confirm 回调(fire-and-forget)。 + * + * @param {Object} service 订单异步服务实例。 + * @param {string} createChannel 创建渠道(MANUAL / API)。 + * @param {Object} [groupedOrder] 分组后的订单(含 order_ids / order_count / orders)。 + * @param {Object} [context] 同步上下文(含 warehouseId / appKey / request_id)。 + * @param {string} [syncTarget] 同步目标(internal / api)。 + * @return {Promise} 同步结果(含 success_count / failed_count / sync_results 等)。 + */ async function finalizeLocalChannelOrdersInternal(service, createChannel, groupedOrder = {}, context = {}, syncTarget = 'internal') { const orderIds = Array.isArray(groupedOrder.order_ids) ? groupedOrder.order_ids.map(orderId => Number(orderId)).filter(orderId => Number.isFinite(orderId) && orderId > 0) @@ -934,7 +1036,20 @@ async function finalizeLocalChannelOrdersInternal(service, createChannel, groupe } } - void orderItemRows; + // 订单明细按 order_id 建索引,供逐单回调组装奇门报文复用(与 syncQmOrdersInternal 一致) + const itemsByOrderId = new Map(); + for (const orderItem of Array.isArray(orderItemRows) ? orderItemRows : []) { + const itemOrderId = Number(orderItem && orderItem.order_id); + if (!Number.isFinite(itemOrderId) || itemOrderId <= 0) { + continue; + } + + if (!itemsByOrderId.has(itemOrderId)) { + itemsByOrderId.set(itemOrderId, []); + } + + itemsByOrderId.get(itemOrderId).push(orderItem); + } // dispatch前最终去重,防止同一orderId在列表中重复导致并发双扣 const uniqueOrderIds = [ ...new Set(orderIds) ]; @@ -974,20 +1089,17 @@ async function finalizeLocalChannelOrdersInternal(service, createChannel, groupe const appKey = String(context.appKey || '').trim(); if (appKey) { - callbackService.sendByAppKey({ + // 逐单发送 deliveryorder.confirm:只对同步成功的订单发送, + // 报文与奇门 taobao.qimen.deliveryorder.confirm 的 request 节点完全一致 + const successResults = syncResults.filter(item => item.status === 'success'); + + notifyApiDeliveryOrderConfirmsInternal(service, { appKey, - event: 'order_completed', - data: { - orderIds, - status: 'completed', - successCount, - failedCount, - }, - metadata: { - warehouseId, - createChannel, - syncTarget, - }, + warehouseId, + context, + successResults, + orderMap, + itemsByOrderId, }).catch(err => { service.ctx.logger.warn(`[OrderAsyncService] OpenAPI 回调忽略失败: ${err.message}`); }); @@ -1100,7 +1212,7 @@ function buildStockoutConfirmDataInternal(service, stockoutOrder, orderRow, stoc * 通知外部出库单确认结果(按出库单 source_type 分流)。 * * - QM:奇门 taobao.qimen.stockout.confirm,flag=success 视为成功; - * - API:OpenAPI 签名回调(event=stockout_completed); + * - API:OpenAPI 签名回调(event=stockout.confirm,报文为与奇门同层级的 request 节点); * - 其他(WMS 等内部来源):无需通知外部,直接视为成功。 * * @param {Object} service 服务实例 @@ -1159,19 +1271,11 @@ async function notifyStockoutExternalInternal(service, stockoutOrder, requestDat } try { + // requestData 即奇门 request 节点内容,OpenAPI 回调按同层级 request 发送 const callbackResult = await callbackService.sendByAppKey({ appKey, - event: 'stockout_completed', - data: { - stockoutOrderCode: stockoutOrder.stockout_order_code, - status: 'completed', - ...requestData, - }, - metadata: { - warehouseId: Number(stockoutOrder.warehouse_id) || 0, - storeId: Number(stockoutOrder.store_id) || 0, - sourceType, - }, + event: 'stockout.confirm', + request: requestData, }); if (callbackResult && callbackResult.success === true) { diff --git a/app/service/systems/receiving_entry_match.js b/app/service/systems/receiving_entry_match.js index 2819b6e..abf7bbf 100644 --- a/app/service/systems/receiving_entry_match.js +++ b/app/service/systems/receiving_entry_match.js @@ -20,13 +20,16 @@ const RECEIVING_CACHE_KEY_PREFIX = 'cache:receiving_orders:warehouse:'; * 3. 对比入库单明细与收货单明细(SKU + 数量) * 4. 匹配成功后写入 wms_entry_order_receiving 绑定关系,CREATED 状态转 PENDING * 5. 覆盖场景标记收货单为"部分入库" + * 6. 新建绑定时按来源回传外部系统(奇门 confirm / OpenAPI entryorder.match) */ class ReceivingEntryMatchService extends Service { /** * 入库单创建后的异步匹配入口:根据备注匹配收货单,写入绑定关系并在必要时转换状态。 * 匹配到收货单后写入 wms_entry_order_receiving 绑定关系; - * 如果入库单当前状态为 CREATED,同步更新为 PENDING。 + * 如果入库单当前状态为 CREATED,同步更新为 PENDING; + * 仅在本次确实新建绑定时按来源回传外部系统(奇门 / OpenAPI), + * 回传失败仅记录日志,不影响绑定与状态更新结果。 * 不阻塞主流程,所有错误仅记录日志。 * * @param {number} entryOrderId 入库单 ID @@ -94,8 +97,8 @@ class ReceivingEntryMatchService extends Service { // 5. 根据对比结果写入绑定关系 if (comparisonResult.type === 'full_match' || comparisonResult.type === 'receiving_covers_entry') { - // 匹配成功 → 写入 wms_entry_order_receiving 绑定关系 - await this._bindEntryOrderReceiving(entryOrderId, matchedReceiving.id); + // 匹配成功 → 写入 wms_entry_order_receiving 绑定关系,返回本次是否新建绑定 + const bindResult = await this._bindEntryOrderReceiving(entryOrderId, matchedReceiving.id); // 若入库单当前状态是 CREATED,更新为 PENDING if (entryOrder.order_status === 'CREATED') { @@ -113,6 +116,27 @@ class ReceivingEntryMatchService extends Service { if (comparisonResult.type === 'receiving_covers_entry') { await this._markReceivingPartialStorage(matchedReceiving.id, comparisonResult, warehouseId); } + + // 6. 按来源回传外部系统(奇门 / OpenAPI)。 + // 仅当本次确实新建了绑定关系才回传:重复触发时绑定已存在(created=false), + // 不会重复通知外部;回传失败仅记录 warn 日志,不影响绑定与状态更新结果。 + if (bindResult && bindResult.created) { + try { + const callbackResult = await this._sendCallback(entryOrder, matchedReceiving, 'auto_match'); + if (!callbackResult || !callbackResult.success) { + ctx.logger.warn( + `[ReceivingEntryMatch] 回传失败(不影响绑定结果) entryOrderId=${entryOrderId} ` + + `receivingId=${matchedReceiving.id} ` + + `sourceType=${callbackResult ? callbackResult.sourceType : 'N/A'}` + ); + } + } catch (callbackError) { + ctx.logger.warn( + `[ReceivingEntryMatch] 回传异常(不影响绑定结果) entryOrderId=${entryOrderId} ` + + `receivingId=${matchedReceiving.id}: ${callbackError.message}` + ); + } + } } else { // 其他情况(entry 有 receiving 没有的明细,或完全不匹配)→ 不做处理 ctx.logger.info( @@ -130,11 +154,12 @@ class ReceivingEntryMatchService extends Service { /** * 写入入库单与收货单的主表级绑定关系。 - * 使用 upsert 策略避免重复写入;绑定记录为软删除模型,已删除的历史记录会被恢复。 + * 幂等策略:先查(含软删除)——已存在未删除 → 跳过;已软删除 → 恢复;不存在 → 新建(唯一索引兜底并发)。 + * 仅当本次确实新建绑定行时返回 created=true,调用方据此判断是否需要回传外部系统。 * * @param {number} entryOrderId 入库单 ID * @param {number} receivingId 收货单 ID - * @return {Promise} + * @return {Promise<{created: boolean}>} 本次是否新建了绑定行;已存在/恢复/并发冲突/写入失败时均为 false */ async _bindEntryOrderReceiving(entryOrderId, receivingId) { const { ctx } = this; @@ -158,7 +183,7 @@ class ReceivingEntryMatchService extends Service { `[ReceivingEntryMatch] 绑定关系已存在,跳过 entryOrderId=${entryOrderId} receivingId=${receivingId}` ); } - return; + return { created: false }; } await ctx.model.EntryOrderReceiving.create({ @@ -171,18 +196,20 @@ class ReceivingEntryMatchService extends Service { ctx.logger.info( `[ReceivingEntryMatch] 写入绑定关系成功 entryOrderId=${entryOrderId} receivingId=${receivingId}` ); + return { created: true }; } catch (error) { // 唯一索引冲突时忽略(并发场景) if (error.name === 'SequelizeUniqueConstraintError') { ctx.logger.warn( `[ReceivingEntryMatch] 绑定关系已存在(并发写入) entryOrderId=${entryOrderId} receivingId=${receivingId}` ); - return; + return { created: false }; } ctx.logger.error( `[ReceivingEntryMatch] 写入绑定关系失败 entryOrderId=${entryOrderId} receivingId=${receivingId}: ${error.message}`, error.stack ); + return { created: false }; } } @@ -1678,6 +1705,71 @@ class ReceivingEntryMatchService extends Service { }; } + /** + * 加载入库单明细并组装为奇门 orderLines 数组(行号从 1 递增)。 + * ownerCode / itemCode / itemId 缺省为空字符串,inventoryType 缺省为 ZP, + * planQty 取计划数量、actualQty 取已入库数量,缺省为 0。 + * @param {Object} entryOrder 入库单实例 + * @return {Promise|null>} 明细行数组;无明细时返回 null + */ + async _queryEntryOrderLines(entryOrder) { + const { ctx } = this; + + // 重新加载入库单明细 + const items = await ctx.model.EntryItems.findAll({ + where: { order_id: entryOrder.id }, + attributes: [ 'item_code', 'item_id', 'count', 'inventory_type', 'owner_code', 'received_quantity' ], + raw: true, + }); + + if (!items || items.length === 0) { + return null; + } + + return items.map((item, index) => ({ + orderLineNo: index + 1, + ownerCode: item.owner_code || '', + itemCode: item.item_code || '', + itemId: item.item_id || '', + inventoryType: item.inventory_type || 'ZP', + planQty: item.count || 0, + actualQty: item.received_quantity || 0, + })); + } + + /** + * 组装 entryorder.confirm 业务报文(与奇门 taobao.qimen.entryorder.confirm 同层级)。 + * 返回 { entryOrder, orderLines },不包含外层 request 包装, + * 字段与取值逻辑以奇门分支为唯一基准,奇门与 OpenAPI 回传共用。 + * @param {Object} entryOrder 入库单实例 + * @param {Array} orderLines 入库明细行数组 + * @param {Object} [options] 可选配置 + * @param {string} [options.outBizCode] 外部业务编码,缺省时自动生成 RECEIVING_MATCH_时间戳 + * @param {string} [options.remark] 备注 + * @return {{ entryOrder: Object, orderLines: Array }} 组装后的业务报文 + */ + buildEntryOrderConfirmRequest(entryOrder, orderLines, options = {}) { + const { app } = this; + const { outBizCode, remark } = options; + + return { + entryOrder: { + entryOrderCode: entryOrder.entry_order_code, + ownerCode: entryOrder.qimen_owner_code || '', + warehouseCode: entryOrder.qimen_warehouse_code || '', + entryOrderId: entryOrder.id, + entryOrderType: entryOrder.order_type, + outBizCode: outBizCode || `RECEIVING_MATCH_${Date.now()}`, + confirmType: 0, // 0 = 最终确认 + status: 'FULFILLED', + freight: 0, + operateTime: app.formatDate(new Date()), + remark: remark || '', + }, + orderLines, + }; + } + /** * 根据入库单来源发送回传。 * - QM(奇门)→ 调用奇门入库单确认接口回传 @@ -1722,51 +1814,23 @@ class ReceivingEntryMatchService extends Service { const { ctx, app } = this; try { - // 重新加载入库单明细 - const items = await ctx.model.EntryItems.findAll({ - where: { order_id: entryOrder.id }, - attributes: [ 'item_code', 'item_id', 'count', 'inventory_type', 'owner_code', 'received_quantity' ], - raw: true, - }); + // 重新加载入库单明细并组装为奇门 orderLines + const orderLines = await this._queryEntryOrderLines(entryOrder); - if (!items || items.length === 0) { + if (!orderLines) { ctx.logger.warn(`[ReceivingEntryMatch] 奇门回传:入库单无明细 entryOrderId=${entryOrder.id}`); return { success: false, error: '入库单无明细' }; } - const orderLines = items.map((item, index) => ({ - orderLineNo: index + 1, - ownerCode: item.owner_code || '', - itemCode: item.item_code || '', - itemId: item.item_id || '', - inventoryType: item.inventory_type || 'ZP', - planQty: item.count || 0, - actualQty: item.received_quantity || 0, - })); - - const queryData = { - request: { - entryOrder: { - entryOrderCode: entryOrder.entry_order_code, - ownerCode: entryOrder.qimen_owner_code || '', - warehouseCode: entryOrder.qimen_warehouse_code || '', - entryOrderId: entryOrder.id, - entryOrderType: entryOrder.order_type, - outBizCode: `RECEIVING_MATCH_${Date.now()}`, - confirmType: 0, // 0 = 最终确认 - status: 'FULFILLED', - freight: 0, - operateTime: app.formatDate(new Date()), - remark: `匹配收货单${receivingOrder.receiving_number}自动回传`, - }, - orderLines, - }, - }; + const request = this.buildEntryOrderConfirmRequest(entryOrder, orderLines, { + outBizCode: `RECEIVING_MATCH_${Date.now()}`, + remark: `匹配收货单${receivingOrder.receiving_number}自动回传`, + }); const result = await app.qimenClient.send( 'taobao.qimen.entryorder.confirm', entryOrder.qimen_owner_code, - queryData, + { request }, { ctx } ); @@ -1794,10 +1858,12 @@ class ReceivingEntryMatchService extends Service { /** * OpenAPI 回传:查询 ApiApp 回调地址,通过签名鉴权 POST 回传。 + * 报文体与奇门同层级({ request: { entryOrder, orderLines } },外层 request 由发送端自动包裹), + * 与 _sendQimenCallback 共用同一份报文组装。 * * @param {Object} entryOrder 入库单实例 * @param {Object} receivingOrder 匹配到的收货单 - * @param {string} [matchType='auto_match'] 匹配类型标识 + * @param {string} [matchType='auto_match'] 匹配类型标识(仅用于日志,奇门报文无对应位置,不回传) * @return {Promise<{success: boolean, error?: string, retryCount?: number}>} 回传结果 */ async _sendOpenApiCallback(entryOrder, receivingOrder, matchType = 'auto_match') { @@ -1846,40 +1912,40 @@ class ReceivingEntryMatchService extends Service { return { success: false, error: '未找到有效ApiApp配置' }; } - // 构建回传数据 - const callbackData = { - entryOrderId: entryOrder.id, - entryOrderCode: entryOrder.entry_order_code, - receivingNumber: receivingOrder.receiving_number, - receivingId: receivingOrder.id, - matchType, - completedAt: new Date().toISOString(), - }; + // 组装与奇门同层级的业务报文(entryorder.match 与奇门 entryorder.confirm 共用同一份组装) + const orderLines = await this._queryEntryOrderLines(entryOrder); - // 使用 OpenAPI 回调服务发送 + if (!orderLines) { + ctx.logger.warn( + '[ReceivingEntryMatch] OpenAPI回传:入库单无明细 ' + + `entryOrderId=${entryOrder.id} receivingNumber=${receivingOrder.receiving_number}` + ); + return { success: false, error: '入库单无明细' }; + } + + const request = this.buildEntryOrderConfirmRequest(entryOrder, orderLines, { + remark: `匹配收货单${receivingOrder.receiving_number}自动回传`, + }); + + // 使用 OpenAPI 回调服务发送(matchType 仅保留在日志中,不塞入奇门报文) const result = await ctx.service.openapi.callback.sendWithRetry({ callbackUrl: apiApp.callback_url, appKey: apiApp.self_app_key, selfAppSecret: apiApp.self_app_secret || '', - event: 'entry_order_receiving_matched', - data: callbackData, - metadata: { - source: 'receiving_entry_match', - entryOrderId: entryOrder.id, - receivingId: receivingOrder.id, - }, + event: 'entryorder.match', + request, }); if (result.success) { ctx.logger.info( `[ReceivingEntryMatch] OpenAPI回传成功 entryOrderId=${entryOrder.id} ` + - `callbackUrl=${apiApp.callback_url} retryCount=${result.retryCount}` + `callbackUrl=${apiApp.callback_url} matchType=${matchType} retryCount=${result.retryCount}` ); return { success: true, retryCount: result.retryCount }; } ctx.logger.warn( `[ReceivingEntryMatch] OpenAPI回传失败 entryOrderId=${entryOrder.id} ` + - `error=${result.error} retryCount=${result.retryCount}` + `matchType=${matchType} error=${result.error} retryCount=${result.retryCount}` ); return { success: false, error: result.error, retryCount: result.retryCount }; } catch (error) { diff --git a/docs/api-doc-update-spec.example.json b/docs/api-doc-update-spec.example.json new file mode 100644 index 0000000..30e8c9b --- /dev/null +++ b/docs/api-doc-update-spec.example.json @@ -0,0 +1,49 @@ +{ + "docName": "example", + "newDoc": { + "module": "example", + "description": "示例文档(由 docs/api-doc-update-spec.example.json 复制而来,正式使用时请按需修改 docName/newDoc/group/methods/change)", + "http": { "path": "/example", "method": "POST" }, + "headers": [ + { "name": "Content-Type", "type": "string", "required": true, "description": "application/json" } + ] + }, + "docMeta": { + "version": "0.1.0", + "updatedAt": "2026-09-12" + }, + "group": { + "groupName": "示例分组", + "module": "example" + }, + "methods": [ + { + "method": "example.ping", + "description": "示例方法:演示固定 spec 的最小结构。", + "isNeedAuth": true, + "isNeedLogin": false, + "headers": [], + "params": [ + { "name": "name", "type": "string", "required": true, "source": "query", "description": "示例入参" } + ], + "response": [ + { "name": "ok", "type": "boolean", "required": true, "description": "是否成功" } + ], + "errors": [ + { "code": 400, "message": "参数错误" } + ], + "notes": [ + "params 允许 source(query/body);headers/response 不写 source;response 项必须含 boolean 的 required" + ] + } + ], + "deleteMethods": [], + "change": { + "version": "2026.09.12-example-init", + "date": "2026-09-12", + "type": "added", + "summary": "示例变更记录。", + "methods": [ "example.ping" ], + "notes": [ "正式使用时请替换为真实的 version/summary/methods/notes,并确保 version 不重复" ] + } +} diff --git a/docs/api-doc-update-workflow.md b/docs/api-doc-update-workflow.md new file mode 100644 index 0000000..d8473c2 --- /dev/null +++ b/docs/api-doc-update-workflow.md @@ -0,0 +1,190 @@ +# API 文档更新工作流(`script/update-api-doc.cjs`) + +> 本文档说明 `methods/*.json`(接口文档 SSOT)与 `methods/changes/*.json`(变更记录)的**唯一合规写入方式**: +> 通过 `npm run doc:api:update -- --spec=` 执行,禁止直接手写这两个目录下的 JSON。 +> 内容以 `script/update-api-doc.cjs` 实际实现为准;回归测试见 `test/scripts/update_api_doc.test.cjs`(13 用例)。 + +## 1. 命令用法 + +```powershell +npm run doc:api:update -- --spec= # 正式写入(主文档 + 变更记录) +npm run doc:api:update -- --spec= --dry-run # 只校验并打印计划,不写任何文件 +npm run doc:api:update -- --spec= --doc-only # 只写 methods/.json,跳过变更记录 +npm run doc:api:update -- --help # 打印用法、选项与 spec.newDoc 说明(-h 等价) +``` + +- `--spec=`:必填;相对路径按项目根目录(`process.cwd()`)解析。缺省报 `Missing required --spec= argument.`;文件不存在报 `Spec file not found: `。 +- 脚本底层等价于 `node ./script/update-api-doc.cjs --spec=`,npm 层需要 `--` 分隔符传递参数。 + +## 2. spec 结构(固定 spec JSON) + +```json +{ + "docName": "system", + "docMeta": { "version": "1.2.0", "updatedAt": "2026-09-12" }, + "group": { "groupName": "分组展示名", "module": "分组 module" }, + "methods": [ { "method": "...", "description": "...", "isNeedAuth": true, "isNeedLogin": false, "headers": [], "params": [], "response": [], "errors": [], "notes": [] } ], + "deleteMethods": [ "要删除的.method" ], + "change": { "version": "唯一版本号", "date": "2026-09-12", "type": "updated", "summary": "...", "methods": [ "..." ], "notes": [ "..." ] } +} +``` + +| 字段 | 必填 | 说明 | +|---|---|---| +| `docName` | 是 | 目标文档名;仅允许字母、数字、下划线、横线(`^[a-z0-9_-]+$`)。对应 `methods/.json` 与 `methods/changes/.json` | +| `docMeta` | 否 | `{ version, updatedAt, description }` 均可选;写入后覆盖主文档根部的 `version` / `updatedAt` / `description`(`description` 为字符串时生效,可用于更正根说明文案) | +| `group` | 是 | `{ groupName, module }` 均为非空字符串。定位已有分组时**先按 `module` 匹配,再按 `groupName`**;找不到则新建分组 | +| `methods` | 是 | 至少 1 条 method 文档;按 `group` + `method` 做 upsert,不覆盖其它分组/方法 | +| `deleteMethods` | 否 | 要删除的 method 名数组;不能与 `methods` 中的 method 重名,否则报 `Method conflict` | +| `change` | 否 | 变更记录对象(`--doc-only` 模式下可省略)。详见第 5 节 | + +### 2.1 method 文档条目(`methods[]` 每一条) + +- 必填键:`method` / `description` / `isNeedAuth`(boolean)/ `isNeedLogin`(boolean)/ `headers`(数组)/ `params`(数组)/ `response`(数组)/ `errors`(数组)。 +- `notes` 可选(字符串数组,写入后保留在 method 文档内)。 + +### 2.2 upsert 语义 + +- method 不存在 → `inserted`(追加到目标分组 list 尾部)。 +- method 已存在且在同一分组 → `updated`(整条覆盖)。 +- method 已存在但在其它分组 → `moved`(从原分组移除后写入目标分组)。 +- `deleteMethods` 命中 → `deleted`;未命中 → `delete-not-found`(不报错,仅提示)。 +- 脚本逐条打印 `inserted:` / `updated:` / `moved:` / `deleted:` / `delete-not-found:` 行。 + +## 3. 字段级硬性校验(报错即拒绝写入) + +| 校验点 | 规则 | +|---|---| +| `docName` | 非空字符串,仅字母/数字/下划线/横线 | +| `docMeta.description`(可选) | 若提供必须为字符串(可为空串,表示清空根说明);非字符串报 `spec.docMeta.description must be a string.` | +| `group.groupName` / `group.module` | 非空字符串 | +| `methods[].method` / `description` | 非空字符串;spec 内 method 名不允许重复(`Duplicate method in spec.methods`) | +| `methods[].isNeedAuth` / `isNeedLogin` | **必须为 boolean** | +| `methods[].headers` / `params` / `response` / `errors` | 必须为数组 | +| `headers[]` / `params[]` / `response[]` 每一项 | `name` / `type` / `description` 非空字符串;**`required` 必须为 boolean**(非布尔报 `xxx.required must be a boolean`) | +| `source` 字段 | **仅 `params[]` 允许**(`allowSource=true`,如 `query` / `body`);`headers[]` / `response[]` 不校验 `source`,因此不要在这两处写 `source` | +| 可选 `list` 字段 | 必须是数组,且每一项必须含 `value` 键 | +| `errors[]` 每一项 | 必须含 `code` 键(数字或字符串均可,如 `400` / `5xx`)+ 非空字符串 `message` | +| `deleteMethods[]` | 字符串数组;与 `methods[]` 中的 method 重名时报 `Method conflict` | +| `change` | 见第 5 节 | + +## 4. 新增文档能力(`spec.newDoc`,2026-09-12 新增) + +目标 `methods/.json` **不存在**时,spec 必须提供 `newDoc`,脚本自动生成文档骨架后再应用 `group` / `methods`;否则报: + +``` +Target doc file not found: (provide spec.newDoc to create it) +``` + +### 4.1 `newDoc` 字段与规则 + +| 字段 | 规则 | +|---|---| +| `module` | **必填**,非空字符串 → 新文档根 `module` | +| `description` | 可选,string;缺省 `""` | +| `http` | 可选,object;缺省 `{ "path": "", "method": "POST" }` | +| `headers` | 可选,array;缺省 `[]` | +| `version` / `updatedAt` / `methods` | **保留键**:由骨架统一管理(`version`/`updatedAt` 取自 `docMeta`,`methods` 固定为 `{ groups: [] }`),写在 `newDoc` 里不生效、不参与透传,也不报错 | +| 其它未知字段 | 仅接受 plain JSON 值(null/字符串/数字/布尔/对象/数组,递归校验),**原样透传**到新文档根(供未来扩展) | + +### 4.2 骨架与落盘行为 + +- 新文档骨架:`{ module, description, version, updatedAt, http, headers, methods: { groups: [] } }`;`version` 取 `docMeta.version`(缺省 `0.0.0`),`updatedAt` 取 `docMeta.updatedAt`(缺省本地今天 `YYYY-MM-DD`)。 +- `methods/changes/.json` 不存在时视为空数组,正式写入时自动创建(目录递归创建),内容为仅含本次 `change` 的数组。 +- **新建文件统一为 2 空格缩进 + LF**;已存在的文件保留原缩进与 EOL 风格(最小 diff)。 +- doc **已存在**时 `spec.newDoc` 被忽略(与不传 `newDoc` 落盘结果逐字节一致,有测试覆盖)。 +- dry-run 对将要新建的文件打印 `created: <相对路径>` 计划行,但不写盘。 + +### 4.3 示例(一次完成新建 + 写入) + +```powershell +npm run doc:api:update -- --spec=temp/api-doc-create.json --dry-run +npm run doc:api:update -- --spec=temp/api-doc-create.json +``` + +## 5. 变更记录(`methods/changes/.json`) + +- `change` 必填键:`version`(非空字符串,**不得与既有记录重复**,重复报 `Duplicate change version detected`)/ `date` / `summary` / `methods`(字符串数组)/ `notes`(字符串数组)。 +- `type` 可选(如 `added` / `updated`)。 +- 新记录**插入数组头部**(`unshift`),与现有约定一致;历史记录不回改。 +- 建议记录至少包含:`version`、`date`、`summary`、`methods`、`notes`。 + +## 6. 推荐流程 + +1. 核对代码与调用链(`controller / systemMethods / systems / model / test`),确定 method、参数、响应、错误码的真实口径。 +2. 在 `temp/apiDoc/` 下先备份对应时间点的 `methods/.json` 与 `methods/changes/.json`(自动归档与人工回档都在该目录)。 +3. 组织固定 spec JSON(可从已有 spec 或 `docs/api-doc-update-spec.example.json` 复制后编辑)。 +4. 先执行 dry-run 校验并查看 `inserted:` / `updated:` / `deleted:` / `created:` 计划行。 +5. 确认无误后正式执行写入。 +6. 校验落盘文件:`JSON.parse` 可解析、缩进/EOL 与写入前一致(新建文件为 2 空格 + LF)。 +7. 再同步 `docs/*.md` / `README.md` 等解释性文档。 + +## 7. `--doc-only` 的适用场景 + +- 仅修补 `methods/.json` 本身、**不追加变更记录**时使用(例如变更记录 `version` 与既有记录重复且只想修正主文档,慎用)。 +- `--doc-only` 下 spec 可省略 `change`;若提供了 `change` 仍会做字段校验(不写 changes 文件)。 +- 注意:`--doc-only` 属于旁路,正式接口变更仍应走完整流程(主文档 + 变更记录)。 + +## 8. 环境变量钩子(仅测试用) + +- `WMS_API_DOC_METHODS_DIR`:覆盖主文档目录(默认 `methods/`)。 +- `WMS_API_DOC_CHANGES_DIR`:覆盖变更记录目录(默认 `methods/changes/`)。 +- 脚本在**模块加载时**读取这两个变量(`path.resolve` 解析)。仅用于测试目录隔离(如 `test/scripts/update_api_doc.test.cjs` 注入临时目录),业务运行不要设置。 + +## 9. 输出样例 + +dry-run(新建场景): + +``` +docName: sample +group: sample (示例分组) +inserted: sample.echo +updated: - +moved: - +deleted: - +delete-not-found: - +change version: 2026.09.12-sample +created: methods/sample.json +created: methods/changes/sample.json +dry-run: validated successfully, no files were written. +``` + +正式写入(既有文档): + +``` +docName: openapi_callback +group: callback (出站回调事件) +inserted: deliveryorder.cancel +updated: entryorder.confirm, entryorder.match, deliveryorder.confirm, stockout.confirm +moved: - +deleted: order.cancel +delete-not-found: - +change version: 2026.09.12-openapi-callback-protocol-align +wrote: methods/openapi_callback.json +wrote: methods/changes/openapi_callback.json +``` + +## 10. 常见坑(校验报错对照) + +| 报错 / 现象 | 原因与处理 | +|---|---| +| `Missing required --spec= argument.` | 未传 `--spec=`(npm 调用需加 `--` 分隔符) | +| `Spec file not found: ` | spec 路径不存在或相对路径解析基准不对(按项目根解析) | +| `spec.docName must contain only letters, numbers, underscore, or dash.` | `docName` 含非法字符 | +| `spec.methods must contain at least one method doc.` | `methods` 为空数组 | +| `spec.methods[0].response[0].required must be a boolean.` | `required` 不是布尔(写了字符串 `"true"` 等) | +| `Duplicate method in spec.methods: xxx` | spec 内 method 名重复 | +| `Method conflict: xxx appears in both spec.methods and spec.deleteMethods.` | 同一 method 同时出现在增改与删除列表 | +| `Target doc file not found: (provide spec.newDoc to create it)` | 目标文档不存在且未提供 `spec.newDoc` | +| `spec.newDoc.module must be a non-empty string.` | `newDoc` 缺 `module` 或为空白字符串 | +| `spec.newDoc.custom must be a plain JSON value.` | `newDoc` 未知透传字段不是 plain JSON 值(如函数) | +| `Duplicate change version detected: xxx` | changes 中已有同 `version` 记录;更换 version,或确认只想补主文档时用 `--doc-only` | +| 变更记录里方法名带 `spec.` 前缀报错 | 字段路径为 spec 内路径提示,指向的仍是 method 文档字段本身 | + +## 11. 回归测试 + +```powershell +node test/scripts/update_api_doc.test.cjs +``` + +覆盖 13 用例:`spec.newDoc` 新建骨架、保留键不透传、doc 已存在时 `newDoc` 被忽略、changes 自动创建、`--doc-only` 不建 changes、dry-run 不写盘、`--help` 输出、新建文件 2 空格 + LF 等。 diff --git a/docs/openapi-callback-events.md b/docs/openapi-callback-events.md new file mode 100644 index 0000000..df5c794 --- /dev/null +++ b/docs/openapi-callback-events.md @@ -0,0 +1,384 @@ +# OpenAPI 出站回调事件说明 + +> 状态:2026-09-13 破坏性协议变更已落代码(报文体 `{ event, data, metadata }` → `{ request }`;`deliveryorder.confirm` 改为逐单发送)。 +> 本文档描述 WMS 主动向外部系统推送的 **OpenAPI 出站回调**(出站 HTTP 回调)协议。 +> 与 `methods/openapi.json` 描述的**入站** OpenAPI method(`POST /openapi`)方向相反;本文档不属于 `methods/*.json` 的 SSOT 范围。 + +## 1. 破坏性变更说明 + +### 1.1 2026-09-13:报文体改为奇门同层级 `{ request }` + +- 报文体由 `{ event, data, metadata }` 改为奇门同层级的 `{ request: {...} }`;发送端不再发送数据/元数据,`event` 仅出现在 query 的 `method`。 +- 5 个事件的 `request` 结构与奇门对应接口的 `request` 节点同层级(字段口径见第 3 节,与注册表 `request` 模板一致)。 +- `deliveryorder.confirm` 通知对象口径变化:改动前一次回调携带整批 `orderIds`(含失败/跳过);改后仅对 `syncResults` 中 `status==='success'` 的订单逐单发送(成功 N 单 = N 次回调),详见 3.3。 +- 旧报文结构(`{ event, data, metadata }`)已全部废弃:无新旧兼容、无双发,接收方必须同步改造。 + +### 1.2 2026-09-12:事件名改为 模块.动作(历史,仍有效) + +- 出站回调的 `method`(query 参数)原先使用 snake_case 事件名(如 `stockout_completed`),现统一改为 `模块.动作`(如 `stockout.confirm`),与奇门 method 去掉 `taobao.qimen.` 前缀后对齐。 +- 旧事件名已**全部废弃**:无新旧兼容、无双发。接收方必须同步改造;仅当接收方按 `模块.动作` 校验 method 时,新协议可正常通过(此前会报 400「参数缺失或错误: method(需为 模块.动作,如 index.ping)」)。 +- 回调事件 `order.cancel` 更名为 `deliveryorder.cancel`:与 `/openapi` 入站方法 `order.cancel`(取消单据接口,见 `methods/openapi.json`)同名,若接收方将 `callback_url` 误指向 WMS `/openapi` 会被路由到真正的取消单据接口;不做兼容、不双发,旧名 `order.cancel`(出站方向)已废弃。 + +| 旧(事件名,已废弃) | 新(method) | 触发场景 | 实现位置 | +|---|---|---|---| +| `entry_order_direct_inbound_completed` | `entryorder.confirm` | 直入入库(API 来源)完成 | `app/service/systems/inbound_direct_log.js` | +| `entry_order_receiving_matched` | `entryorder.match` | 入库单匹配收货单完成 | `app/service/systems/receiving_entry_match.js` | +| `order_completed` | `deliveryorder.confirm` | 订单同步(出库)完成(逐单发送) | `app/service/systems/order_async.js` | +| `stockout_completed` | `stockout.confirm` | 出库单确认完成 | `app/service/systems/order_async.js` | +| `order_cancelled` | `deliveryorder.cancel` | 订单取消成功(旧 method 名 `order.cancel` 已废弃) | `app/service/openapiMethods/order.js` | + +事件注册表:`app/service/openapi/callbackRegistry.js#CALLBACK_EVENTS`(5 条,每条含 `name` / `label` / `description` / `request`,`request` 为奇门同层级报文模板),回调调试页 `GET /docs/api/openapi/callback-test`(`app/controller/openapiCallback.js`)直接消费该注册表,并按注册表自动预填完整报文体 `{ request: {...} }`(可编辑)。 + +## 2. 协议说明 + +### 2.1 出站请求与 query 参数 + +``` +POST {callbackUrl}?method={模块.动作}&v=1.0×tamp={timestamp}&app_key={selfAppKey}&sign={sign} +``` + +`callbackUrl` 来自 `api_app` 表(`callback_url` 字段,要求 `is_enabled=1` 且 `callback_url` 非空)。 + +| query 参数 | 类型 | 必填 | 说明 | +|---|---|---|---| +| `method` | string | 是 | 回调 method,`模块.动作` 格式(与奇门对应接口对应;报文体不再携带 `event` 字段);URL 中做 `encodeURIComponent` | +| `v` | string | 是 | 协议版本,固定 `1.0` | +| `timestamp` | string | 是 | 时间戳,秒级(10 位字符串),见第 4 节 | +| `app_key` | string | 是 | 应用标识(`api_app.self_app_key`);URL 中做 `encodeURIComponent` | +| `sign` | string | 是 | 签名,算法见 2.4 | + +### 2.2 请求头 + +``` +Content-Type: application/json +``` + +### 2.3 请求体结构 + +```json +{ + "request": { "…": "…" } +} +``` + +- `request` 为奇门同层级业务报文,结构按事件不同,口径见第 3 节(与注册表 `request` 模板一致)。 +- `event` 不出现在报文体内,仅拼入 query 的 `method`。 +- 构造位置:`app/service/openapi/callback.js#sendWithRetry`(`body = { request: request || {} }`);`sendByAppKey` 将 `request` 原样透传给 `sendWithRetry`。 + +### 2.4 签名算法 + +实现:`app/lib/api_sign.js#signRequest`(与 OpenAPI 入口验签算法一致)。 + +1. `canonicalQuery`:query 中除 `sign` / `signature`(大小写不敏感)外、值非 `undefined` 的参数,按 key 字母序升序,拼为 `key=value&key2=value2`。值为原始字符串(**不 URL 编码**);对象值经 `stableStringify`。 +2. `bodySign = md5(stableStringify(body))`;`stableStringify` 对对象键做字母序排序后 JSON 序列化;`body` 即完整报文 `{ request: {...} }`。 +3. `sign = md5(canonicalQuery + selfAppSecret + bodySign)`,小写十六进制。 + +注意: + +- 参与签名的是**未 URL 编码的原值**;实际 URL 中仅 `method`、`app_key` 做了 `encodeURIComponent`。 +- `selfAppSecret` 为 `api_app.self_app_secret`(`signRequest` 内部会 `trim`)。 + +canonicalQuery 示例(`method=entryorder.confirm`): + +``` +app_key=APP2024011514301234&method=entryorder.confirm×tamp=1758047400&v=1.0 +``` + +### 2.5 重试策略 + +实现:`app/service/openapi/callback.js#sendWithRetry`。 + +- 最多重试 `MAX_RETRY=3` 次(即最多共 4 次尝试)。 +- 间隔:`[2000, 5000, 15000]` 毫秒(2s → 5s → 15s)。 +- 触发条件:非 2xx 响应或网络错误(异常 catch)。 +- 单次请求超时:30s(`ctx.curl` `timeout: 30000`)。 +- 每次尝试经 `logCallback` 记录日志:`[OpenapiCallback] event=… appKey=… url=… retry=N success=… response=…`(成功 info、中途失败 warn、最终失败 error)。 + +### 2.6 发送途径与配置解析 + +| 途径 | 配置解析 | 使用的事件 | +|---|---|---| +| `sendByAppKey` | 按 `app_key` 查 `ApiApp`(`self_app_key=appKey, is_enabled=1`),取 `self_app_secret` 与 `callback_url` | `deliveryorder.confirm`、`stockout.confirm`、`deliveryorder.cancel` | +| `sendWithRetry` 直调 | 按 `StoreWarehouse`(`store_id/warehouse_id, auth_status=2`)→ `ApiApp`(`contract_id=storeWarehouse.id, is_enabled=1, callback_url` 非空)定位 | `entryorder.confirm`、`entryorder.match` | + +调试/测试工具: + +- 调试页:`GET /docs/api/openapi/callback-test`(`app/controller/openapiCallback.js`,路由见 `app/router.js`),按注册表渲染事件下拉,选中事件后自动预填与真实回调一致的完整报文体 `{ request: {...} }`(可编辑),前端算签名后 POST。 +- 模拟发送(入站):`openapiMethods/callback.js#test`(method=`callback.test`,body 为 `{ event, request }`,`event` 缺省 `deliveryorder.confirm`,按 `app_key` 走真实发送链路)。 + +## 3. 事件逐个说明 + +> 说明:以下触发实现中的行号为 2026-09-12 代码快照值,行号可能漂移;定位请以方法名 grep 为准。 + +### 3.1 entryorder.confirm + +- label:入库单确认完成(直入) +- description:直入入库(API 来源)完成后回传,对应奇门 `taobao.qimen.entryorder.confirm` +- 触发实现:`app/service/systems/inbound_direct_log.js#qimenEntrySync` 的 API 分支(`source_type=API`)→ `_sendOpenApiCallback`(`event: 'entryorder.confirm'`);回传成功才执行本地回调,`throwOnError=true` +- 发送途径:`sendWithRetry` 直调(见 2.6) +- `request` 结构(注册表 `request` 模板口径;以 QM 分支为唯一基准,QM/API 共用 `buildEntryOrderConfirmRequest` 组装): + +```json +{ + "entryOrder": { + "entryOrderCode": "RK20260912001", + "ownerCode": "OWNER-001", + "warehouseCode": "WH-100", + "entryOrderId": 543, + "entryOrderType": "SCRK", + "outBizCode": "DIRECT_INBOUND_1726131400000", + "confirmType": 0, + "status": "FULFILLED", + "freight": 0, + "operateTime": "2026-09-12 10:30:00", + "remark": "导入/PDA直接入库提交" + }, + "orderLines": [ + { + "orderLineNo": 1, + "ownerCode": "OWNER-001", + "itemCode": "SKU-1", + "itemId": "1001", + "inventoryType": "ZP", + "planQty": 2, + "actualQty": 2 + } + ] +} +``` + +- `entryOrder` 字段口径:`outBizCode` 缺省自动生成 `DIRECT_INBOUND_时间戳`;`confirmType` 0=最终确认 / 1=部分确认;`status` `FULFILLED` / `PARTFULFILLED`;`freight` 固定 0;`operateTime` 为 `app.formatDate(new Date())`;`remark` 为业务备注。 + +### 3.2 entryorder.match + +- label:入库单匹配收货完成 +- description:入库单匹配收货单完成后回传(API 来源),对应奇门 `taobao.qimen.entryorder.confirm` +- 触发实现:`app/service/systems/receiving_entry_match.js#matchAfterEntryCompleted`:匹配成功写入绑定关系且**本次确实新建绑定**(`bindResult.created === true`)时,调用 `_sendCallback(entryOrder, matchedReceiving, 'auto_match')`;`_sendCallback` 按 `source_type` 分流(QM→奇门,API→OpenAPI → `_sendOpenApiCallback`,`event: 'entryorder.match'`)。重复触发时绑定已存在(`created === false`),不会重复回传;回传失败仅记录 warn,不影响绑定与入库单状态更新。 +- 发送途径:`sendWithRetry` 直调(见 2.6) +- `matchType`:仅保留在日志中(自动/手动匹配类型标识),不塞入回传报文 +- `outBizCode` / `remark` 口径:`outBizCode` 缺省自动生成 `RECEIVING_MATCH_时间戳`;`remark` 固定「匹配收货单{收货单号}自动回传」(如 `匹配收货单RCV20260912001自动回传`);`confirmType` 固定 0、`status` 固定 `FULFILLED` +- `request` 结构(注册表 `request` 模板口径;QM/API 共用 `buildEntryOrderConfirmRequest` 组装): + +```json +{ + "entryOrder": { + "entryOrderCode": "RK20260912002", + "ownerCode": "OWNER-001", + "warehouseCode": "WH-100", + "entryOrderId": 543, + "entryOrderType": "SCRK", + "outBizCode": "RECEIVING_MATCH_1726131400000", + "confirmType": 0, + "status": "FULFILLED", + "freight": 0, + "operateTime": "2026-09-12 10:30:00", + "remark": "匹配收货单RCV20260912001自动回传" + }, + "orderLines": [ + { + "orderLineNo": 1, + "ownerCode": "OWNER-001", + "itemCode": "SKU-1", + "itemId": "1001", + "inventoryType": "ZP", + "planQty": 2, + "actualQty": 2 + } + ] +} +``` + +### 3.3 deliveryorder.confirm + +- label:订单发货完成 +- description:订单同步(出库)完成后触发,对应奇门 `taobao.qimen.deliveryorder.confirm` +- 触发实现:`app/service/systems/order_async.js#finalizeLocalChannelOrdersInternal`(`syncApiOrders` 处理链,触发条件不变:`createChannel=API` 且 `successCount>0`)→ `notifyApiDeliveryOrderConfirmsInternal`(fire-and-forget,失败仅 warn) +- 发送途径:`sendByAppKey`(按 `app_key` 解析) +- **逐单发送语义(2026-09-13 变化)**: + +| 维度 | 改动前 | 改动后 | +|---|---|---| +| 通知对象 | 一次回调携带整批 `orderIds`(含失败/跳过) | 仅对 `syncResults` 中 `status==='success'` 的订单逐单发送 | +| 回调次数 | 每批次 1 次 | 成功 N 单 = N 次回调 | +| 报文内容 | 批次汇总 `{ orderIds, status, successCount, failedCount }` | 每单独立奇门同层级 `request` 报文(`buildQimenDeliveryOrderConfirmDataInternal` 组装) | +| 失败处理 | 不阻塞主流程 | 单订单组装/发送失败仅 warn,不影响其他订单与主流程 | + +- 查询开销:复用原有主表+明细查询,新增 1 次运单号批量查询(`buildOrderWaybillCodeMapInternal`,强制同仓校验,无 N+1) +- `request` 结构(注册表 `request` 模板口径): + +```json +{ + "deliveryOrder": { + "totalOrderLines": 1, + "deliveryOrderCode": "DO20260912001", + "deliveryOrderId": 123, + "warehouseCode": "WH-100", + "orderType": "JYCK", + "status": "DELIVERED", + "outBizCode": "DO20260912001", + "confirmType": 0, + "orderConfirmTime": "2026-09-12 10:30:00", + "operatorCode": "", + "operatorName": "", + "storageFee": "0", + "operateTime": "2026-09-12 10:30:00" + }, + "packages": { + "package": [ + { + "logisticsCode": "YTO", + "logisticsName": "圆通速递", + "expressCode": "YT1234567890", + "packageCode": "DO20260912001", + "invoiceNo": "INV20260912001", + "items": [ + { + "itemCode": "SKU-1", + "itemId": 1001, + "quantity": 2 + } + ] + } + ] + }, + "orderLines": [ + { + "orderLineNo": "1", + "orderSourceCode": "SO20260912001", + "subSourceCode": "", + "ownerCode": "OWNER-001", + "itemCode": "SKU-1", + "itemId": 1001, + "itemName": "测试商品1", + "extCode": "", + "planQty": 2, + "actualQty": 2, + "retailPrice": 0, + "actualPrice": 0, + "discountAmount": "0", + "inventoryType": "ZP", + "snList": [], + "qrCode": "" + } + ] +} +``` + +### 3.4 stockout.confirm + +- label:出库单确认完成 +- description:出库单确认回传(API 来源),对应奇门 `taobao.qimen.stockout.confirm` +- 触发实现:`app/service/systems/order_async.js#notifyStockoutExternalInternal` 的 API 分支(`source_type=API`,`event: 'stockout.confirm'`);`request` 即 `buildStockoutConfirmDataInternal` 的返回结构 `{ deliveryOrder, packages, orderLines }`(**不再有原先 `data.stockoutOrderCode`/`status` 薄包装**,报文与奇门请求体同层级) +- 发送途径:`sendByAppKey`(按 `app_key` 解析) +- `request` 结构(注册表 `request` 模板口径): + +```json +{ + "deliveryOrder": { + "totalOrderLines": 1, + "deliveryOrderCode": "SO20260912001", + "deliveryOrderId": 5001, + "warehouseCode": "WH-100", + "orderType": "PTCK", + "status": "DELIVERED", + "outBizCode": "SO20260912001", + "confirmType": 0, + "orderConfirmTime": "2026-09-12 10:30:00", + "operatorCode": "", + "operatorName": "" + }, + "packages": { + "package": [ + { + "logisticsCode": "YTO", + "logisticsName": "圆通速递", + "expressCode": "YT1234567890", + "packageCode": "SO20260912001", + "items": [ + { + "itemCode": "SKU-1", + "itemId": 1001, + "quantity": 2 + } + ] + } + ] + }, + "orderLines": [ + { + "orderLineNo": "1", + "ownerCode": "OWNER-001", + "itemCode": "SKU-1", + "itemId": 1001, + "itemName": "测试商品1", + "planQty": 2, + "actualQty": 2, + "inventoryType": "ZP" + } + ] +} +``` + +### 3.5 deliveryorder.cancel + +- label:订单已取消 +- description:订单取消成功后触发(出站事件名 `deliveryorder.cancel`) +- 触发实现:`app/service/openapiMethods/order.js#cancel` 取消成功后 fire-and-forget(`event: 'deliveryorder.cancel'`) +- 改名原因:出站回调事件名与 `/openapi` 入站方法 `order.cancel`(取消单据接口,见 `methods/openapi.json`)同名,若接收方将 `callback_url` 误指向 WMS `/openapi` 会被路由到真正的取消单据接口;故改为 `deliveryorder.cancel`,不做兼容、不双发 +- **自定义约定(2026-09-13)**:**无奇门对应接口**,按 `deliveryOrder` 节点约定自定义;`status` 为自定义约定值 `CANCELED`(风格与奇门 `deliveryOrder.status` 家族枚举一致);`orderType` 为 `body.orderType` 大写归一化结果(`String(body.orderType || 'JYCK').trim().toUpperCase()`) +- 发送途径:`sendByAppKey`(按 `app_key` 解析) +- `request` 结构(注册表 `request` 模板口径): + +```json +{ + "deliveryOrder": { + "deliveryOrderCode": "TEST-ORDER-001", + "orderType": "JYCK", + "status": "CANCELED" + } +} +``` + +## 4. timestamp 规范(2026-09-12 已统一为秒) + +`timestamp` 已统一为**秒级(10 位字符串)**规范值:`String(Math.floor(Date.now() / 1000))`。 + +| 位置 | 取值 | 单位 | +|---|---|---| +| 出站发送 `app/service/openapi/callback.js#sendWithRetry` | `String(Math.floor(Date.now() / 1000))` | **秒(10 位)** | +| 回调调试页 `app/controller/openapiCallback.js`(`nowTimestamp`) | `Math.floor(Date.now() / 1000)` | **秒(10 位)** | + +- 与 `/openapi` 入站入口 `app/service/openapiEntry.js` 的时间戳时效校验一致(秒级窗口,±600 秒),可作为规范值对外承诺。 +- 历史背景:此前发送端用 `String(Date.now())`(毫秒)与调试页(秒)口径不一致(`methods/changes/openapi_callback.json` 版本 `2026.09.12-openapi-callback-init` 的「已知问题」备注),已在本批次修复;接收方请按秒级(10 位)实现校验,勿再按毫秒。 + +## 5. 相关文件索引 + +- 事件注册表:`app/service/openapi/callbackRegistry.js` +- 发送与重试:`app/service/openapi/callback.js` +- 签名算法:`app/lib/api_sign.js` +- 调试页控制器:`app/controller/openapiCallback.js`(路由 `app/router.js`) +- 入站方法路由文档:`AI_METHOD_ROUTING.md` 5.6 节 +- 触发实现:`app/service/systems/inbound_direct_log.js`、`app/service/systems/receiving_entry_match.js`、`app/service/systems/order_async.js`、`app/service/openapiMethods/order.js` +- 接口文档 SSOT:`methods/openapi_callback.json`(5 个 method) +- 变更记录:`methods/changes/openapi_callback.json` +- 文档站页面:`/docs/api/openapi_callback`(OpenAPI 出站回调文档页) +- 入口来源:`/docs/api/openapi` 页面头部的「→ 出站回调文档」链接 + +调试工具 `GET /docs/api/openapi/callback-test` 已在第 1 节与 2.6 节说明,此处不重复。 + +**三份资料的定位与先后关系**: + +| 资料 | 定位 | +|---|---| +| `methods/openapi_callback.json` | 出站回调**接口文档 SSOT**(5 个 method 的 params / response / errors),文档站 `/docs/api/openapi_callback` 页面消费 | +| `app/service/openapi/callbackRegistry.js#CALLBACK_EVENTS` | **事件注册表**(name / label / description / request,`request` 为奇门同层级报文模板),运行时数据源;回调调试页 `/docs/api/openapi/callback-test` 消费注册表并预填完整报文体 `{ request: {...} }` | +| `docs/openapi-callback-events.md`(本文) | **协议说明与背景**(触发链路、签名算法、重试策略、时间戳规范),非 SSOT,仅作解释性补充 | + +先后关系:事件或字段变化时,先改代码(`callbackRegistry.js` 注册表与发送实现)→ 再经 `script/update-api-doc.cjs` 更新接口文档 SSOT `methods/openapi_callback.json` 并追加 `methods/changes/openapi_callback.json` → 最后同步本文与文档站文案。调试页内容以注册表为准,文档站页面以 SSOT 为准。 + +## 6. 与 methods/*.json 的关系 + +- 出站回调**不写入** `methods/openapi.json`:该文件是**入站** method 的 SSOT(`POST /openapi`),`script/update-api-doc.cjs` 的 spec 结构(modules→list→method→params/response/errors)不适合表达出站回调,写入会污染文档与文档 UI 语义。 +- 出站回调现已独立成接口文档 `methods/openapi_callback.json`(module=`openapi_callback`,5 个 method,当前版本 1.2.0);变更记录写入 `methods/changes/openapi_callback.json`(首条 version `2026.09.12-openapi-callback-init`,type `added`;本次 version `2026.09.13-openapi-callback-request-protocol`,type `updated`)。 +- 本次无入站接口契约变更:`methods/openapi.json`、`methods/system.json`、`methods/qimen.json` 均未改动。 +- `methods/changes/*.json` 中历史记录提及的旧事件名(`stockout_completed`、`entry_order_direct_inbound_completed`、`entry_order_receiving_matched` 等)为追加式历史,保持原样,不回改。 diff --git a/methods/changes/openapi_callback.json b/methods/changes/openapi_callback.json new file mode 100644 index 0000000..6bbe05e --- /dev/null +++ b/methods/changes/openapi_callback.json @@ -0,0 +1,66 @@ +[ + { + "version": "2026.09.13-openapi-callback-request-protocol", + "date": "2026-09-13", + "type": "updated", + "summary": "破坏性协议变更:OpenAPI 出站回调报文体由 { event, data, metadata } 改为奇门同层级的 { request: {...} },发送端不再发送数据/元数据;event 仅保留在 query 的 method;5 个事件的 request 结构按 callbackRegistry.js 的 request 模板重写;deliveryorder.confirm 由一次批量汇总通知改为逐单发送(仅对 status='success' 的订单,成功 N 单 = N 次回调);deliveryorder.cancel 按 deliveryOrder 节点约定自定义(status 固定 CANCELED,无奇门对应接口);回调调试页预填完整报文体 { request }。文档版本 1.1.0 → 1.2.0。", + "methods": [ + "entryorder.confirm", + "entryorder.match", + "deliveryorder.confirm", + "stockout.confirm", + "deliveryorder.cancel" + ], + "notes": [ + "破坏性协议变更:body 不再有 event/data/metadata,发送端统一发送 { request: request || {} }(app/service/openapi/callback.js#sendWithRetry / sendByAppKey);event 仅用于 query 的 method", + "5 个事件 request 结构:entryorder.confirm { entryOrder, orderLines }(inbound_direct_log.js#buildEntryOrderConfirmRequest,QM/API 共用);entryorder.match { entryOrder, orderLines }(receiving_entry_match.js#buildEntryOrderConfirmRequest,QM/API 共用,outBizCode 前缀 RECEIVING_MATCH_、remark=匹配收货单{收货单号}自动回传);deliveryorder.confirm { deliveryOrder, packages{package[]}, orderLines }(order_async.js#buildQimenDeliveryOrderConfirmDataInternal);stockout.confirm { deliveryOrder, packages{package[]}, orderLines }(order_async.js#buildStockoutConfirmDataInternal,删除原先 data.stockoutOrderCode/status 薄包装);deliveryorder.cancel { deliveryOrder: { deliveryOrderCode, orderType, status:'CANCELED' } }(openapiMethods/order.js#cancel,无奇门对应接口)", + "deliveryorder.confirm 逐单语义:改动前一次回调携带整批 orderIds(含失败/跳过);改后仅对 syncResults 中 status==='success' 的订单逐单发送(成功 N 单 = N 次回调),fire-and-forget、失败仅 warn;复用原有主表+明细查询并新增 1 次运单号批量查询,无 N+1", + "事件注册表 callbackRegistry.js 由 { name, label, description, sampleData, metadata } 改为 { name, label, description, request };回调调试页 GET /docs/api/openapi/callback-test 预填完整报文体 { request: {...} }(此前预填三层 { event, data, metadata })", + "同步 docs/openapi-callback-events.md 与 AI_METHOD_ROUTING.md 5.6 节" + ] + }, + { + "version": "2026.09.12-openapi-callback-protocol-align", + "date": "2026-09-12", + "type": "updated", + "module": "callback", + "summary": "methods/openapi_callback.json 同步 2026-09-12 出站回调代码改动:回调方法 order.cancel 更名为 deliveryorder.cancel(与 /openapi 入站方法 order.cancel 区分,不做兼容、不双发);5 个事件的 timestamp 统一为秒级(10 位)规范值(原「毫秒/秒不一致待统一」已知问题已修复);补齐 metadata 字段说明;entryorder.match 由「已实现待接入」改为已接入(matchAfterEntryCompleted 绑定成功且本次新建绑定时回传,matchType 固定 auto_match);调试页按真实 { event, data, metadata } 三层预填。", + "methods": [ + "entryorder.confirm", + "entryorder.match", + "deliveryorder.confirm", + "stockout.confirm", + "deliveryorder.cancel" + ], + "notes": [ + "order.cancel 为出站回调旧方法名,本次删除(不做兼容、不双发);入站方法 order.cancel 仍属于 methods/openapi.json,不受影响", + "timestamp 统一:app/service/openapi/callback.js#sendWithRetry 改为 String(Math.floor(Date.now()/1000)),与 /openapi 入站 ±600 秒时效校验及回调调试页一致", + "entryorder.match 接入点:app/service/systems/receiving_entry_match.js#matchAfterEntryCompleted 绑定成功且 bindResult.created===true 时调用 _sendCallback(...,'auto_match');重复触发不重复回传,回传失败仅 warn 不影响绑定", + "metadata:entryorder.confirm {source:'inbound_direct_log',entryOrderId};entryorder.match {source:'receiving_entry_match',entryOrderId,receivingId};deliveryorder.confirm {warehouseId,createChannel:'API',syncTarget};stockout.confirm {warehouseId,storeId,sourceType:'API'};deliveryorder.cancel 真实调用点未传(报文内 {})", + "回调调试页 GET /docs/api/openapi/callback-test 按注册表自动预填真实三层报文体 { event, data, metadata }(此前把 sampleData 直接当整个 body)", + "同步 docs/openapi-callback-events.md 与 AI_METHOD_ROUTING.md 5.6 节;新建 docs/api-doc-update-workflow.md", + "文档版本 1.0.0 → 1.1.0" + ] + }, + { + "version": "2026.09.12-openapi-callback-init", + "date": "2026-09-12", + "type": "added", + "module": "callback", + "summary": "新增 methods/openapi_callback.json:OpenAPI 出站回调(WMS → 外部)接口文档,登记 5 个出站回调事件 entryorder.confirm / entryorder.match / deliveryorder.confirm / stockout.confirm / order.cancel(event 与 query method 同值);协议口径与 docs/openapi-callback-events.md 及 app/service/openapi/callbackRegistry.js#CALLBACK_EVENTS 一致;入站接口仍以 methods/openapi.json 为准。", + "methods": [ + "entryorder.confirm", + "entryorder.match", + "deliveryorder.confirm", + "stockout.confirm", + "order.cancel" + ], + "notes": [ + "触发实现与发送途径:entryorder.confirm(inbound_direct_log.js#qimenEntrySync API 分支,sendWithRetry 直调,throwOnError=true);entryorder.match(receiving_entry_match.js#_sendCallback API 分支,sendWithRetry 直调,当前无调用方);deliveryorder.confirm(order_async.js#finalizeLocalChannelOrdersInternal,sendByAppKey);stockout.confirm(order_async.js#notifyStockoutExternalInternal API 分支,sendByAppKey);order.cancel(openapiMethods/order.js#cancel,sendByAppKey)", + "协议:POST {ApiApp.callback_url}?method=&v=1.0×tamp=&app_key=&sign=;body 统一 { event, data, metadata };sign = md5(canonicalQuery + selfAppSecret + md5(stableStringify(body)));非 2xx/网络错误重试至多 3 次(间隔 2s→5s→15s,单次超时 30s)", + "已知问题如实记录:timestamp 口径不一致(sendWithRetry 毫秒 vs 调试页秒),统一前不作为规范值;entryorder.match 触发函数 _sendCallback 无调用方(已实现待接入)", + "本文件为出站方向文档(版本 0.0.0 -> 1.0.0),不修改 methods/openapi.json(入站)", + "写入通过 script/update-api-doc.cjs(先 --dry-run 校验)" + ] + } +] diff --git a/methods/openapi_callback.json b/methods/openapi_callback.json new file mode 100644 index 0000000..500855f --- /dev/null +++ b/methods/openapi_callback.json @@ -0,0 +1,1329 @@ +{ + "module": "openapi_callback", + "description": "开放 API 出站回调定义(出站方向:WMS → 外部)。WMS 在业务完成后按 ApiApp 配置的 callback_url 主动推送事件通知:query 携带 method/v/timestamp/app_key/sign,报文体统一为奇门同层级的 { request: {...} }(event 仅出现在 query 的 method),使用 MD5 签名鉴权。入站接口请参阅 openapi.json。", + "version": "1.2.0", + "updatedAt": "2026-09-13", + "http": { + "path": "{ApiApp.callback_url}", + "method": "POST" + }, + "headers": [ + { + "name": "Content-Type", + "type": "string", + "required": true, + "description": "application/json" + } + ], + "methods": { + "groups": [ + { + "groupName": "出站回调事件", + "module": "callback", + "list": [ + { + "method": "entryorder.confirm", + "description": "入库单确认完成(直入)出站回调。直入入库(API 来源,source_type=API)完成后,WMS 向外部回传入库完成信息(对应奇门 taobao.qimen.entryorder.confirm)。触发实现:app/service/systems/inbound_direct_log.js#qimenEntrySync 的 API 分支 → _sendOpenApiCallback(throwOnError=true,回传成功才执行本地回调)。request 报文由 buildEntryOrderConfirmRequest 组装,奇门(QM)与 OpenAPI(API)共用。", + "isNeedAuth": true, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "回调 method(模块.动作,如 entryorder.confirm),由 WMS 计算后发出(不是接收方入参);event 仅出现在 query 的 method,报文体不再携带 event 字段;URL 中做 encodeURIComponent" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "协议版本,由 WMS 发出,固定 1.0" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "时间戳,由 WMS 发出,统一为秒级(10 位字符串,String(Math.floor(Date.now()/1000)));与 /openapi 入站时效校验(±600 秒窗口,Math.floor(Date.now()/1000))及回调调试页(nowTimestamp)口径一致,可作为规范值对外承诺" + }, + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "应用标识(api_app.self_app_key),由 WMS 发出;URL 中做 encodeURIComponent" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "MD5 签名,由 WMS 计算后发出;sign = md5(canonicalQuery + selfAppSecret + md5(stableStringify(body))),小写十六进制" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "奇门同层级业务报文 { entryOrder, orderLines }(不含外层 request 包装,发送端统一包装为 body = { request });口径与 callbackRegistry.js 的 request 模板一致,结构见下方 request.* 子字段" + }, + { + "name": "request.entryOrder", + "type": "object", + "required": true, + "source": "body", + "description": "入库单头信息" + }, + { + "name": "request.entryOrder.entryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "入库单编码(wms_entry_order.entry_order_code)" + }, + { + "name": "request.entryOrder.ownerCode", + "type": "string", + "required": true, + "source": "body", + "description": "奇门货主编码(wms_entry_order.qimen_owner_code)" + }, + { + "name": "request.entryOrder.warehouseCode", + "type": "string", + "required": true, + "source": "body", + "description": "奇门仓库编码(wms_entry_order.qimen_warehouse_code)" + }, + { + "name": "request.entryOrder.entryOrderId", + "type": "number", + "required": true, + "source": "body", + "description": "入库单 ID(wms_entry_order.id)" + }, + { + "name": "request.entryOrder.entryOrderType", + "type": "string", + "required": true, + "source": "body", + "description": "入库单类型(wms_entry_order.order_type,如 SCRK)" + }, + { + "name": "request.entryOrder.outBizCode", + "type": "string", + "required": true, + "source": "body", + "description": "外部业务编码,缺省自动生成 DIRECT_INBOUND_时间戳(毫秒)" + }, + { + "name": "request.entryOrder.confirmType", + "type": "number", + "required": true, + "source": "body", + "description": "确认类型:0=最终确认 / 1=部分确认(isFin)" + }, + { + "name": "request.entryOrder.status", + "type": "string", + "required": true, + "source": "body", + "description": "FULFILLED(最终确认)/ PARTFULFILLED(部分确认)" + }, + { + "name": "request.entryOrder.freight", + "type": "number", + "required": true, + "source": "body", + "description": "运费,固定 0" + }, + { + "name": "request.entryOrder.operateTime", + "type": "string", + "required": true, + "source": "body", + "description": "操作时间(app.formatDate(new Date()))" + }, + { + "name": "request.entryOrder.remark", + "type": "string", + "required": true, + "source": "body", + "description": "备注(如「导入/PDA直接入库提交」)" + }, + { + "name": "request.orderLines", + "type": "array", + "required": true, + "source": "body", + "description": "入库明细行数组:[ { orderLineNo, ownerCode, itemCode, itemId, inventoryType, planQty, actualQty } ]" + }, + { + "name": "request.orderLines[].orderLineNo", + "type": "number", + "required": true, + "source": "body", + "description": "行号(从 1 递增)" + }, + { + "name": "request.orderLines[].ownerCode", + "type": "string", + "required": true, + "source": "body", + "description": "货主编码" + }, + { + "name": "request.orderLines[].itemCode", + "type": "string", + "required": true, + "source": "body", + "description": "商品编码" + }, + { + "name": "request.orderLines[].itemId", + "type": "string", + "required": true, + "source": "body", + "description": "商品 ID" + }, + { + "name": "request.orderLines[].inventoryType", + "type": "string", + "required": true, + "source": "body", + "description": "库存类型(如 ZP)" + }, + { + "name": "request.orderLines[].planQty", + "type": "number", + "required": true, + "source": "body", + "description": "计划数量" + }, + { + "name": "request.orderLines[].actualQty", + "type": "number", + "required": true, + "source": "body", + "description": "实际入库数量" + } + ], + "response": [ + { + "name": "http_status", + "type": "number", + "required": true, + "description": "接收方应返回任意 2xx 状态码(200 ≤ status < 300,如 200/201/204);WMS 仅按 HTTP 状态码判定成功,响应体内容不参与判定" + }, + { + "name": "response_body", + "type": "object", + "required": false, + "description": "响应体无约定格式;WMS 不校验业务码,返回 2xx 即视为成功,非 2xx 或网络错误进入重试(至多 3 次,间隔 2s→5s→15s)" + } + ], + "errors": [ + { + "code": 400, + "message": "接收方返回 400(如参数/验签不通过):WMS 视为回调失败,进入重试,至多 3 次(间隔 2s→5s→15s),全部失败后判定最终失败" + }, + { + "code": 401, + "message": "接收方返回 401(鉴权失败):处理同 400,重试至多 3 次后判定最终失败" + }, + { + "code": 403, + "message": "接收方返回 403(拒绝访问):处理同 400,重试至多 3 次后判定最终失败" + }, + { + "code": "5xx", + "message": "接收方返回 5xx(服务端错误):处理同 400,重试至多 3 次后判定最终失败" + }, + { + "code": "NETWORK_ERROR", + "message": "网络错误或单次请求超时(30s):处理同非 2xx,重试至多 3 次后判定最终失败" + } + ], + "notes": [ + "本文件描述出站方向(WMS → 外部)回调;入站接口请参阅 methods/openapi.json", + "签名算法:sign = md5(canonicalQuery + selfAppSecret + md5(stableStringify(body))),小写十六进制;canonicalQuery 为 query 中除 sign/signature 外、值非 undefined 的参数按 key 升序拼成的 key=value&… 串(值为原始字符串,不 URL 编码),selfAppSecret 为 api_app.self_app_secret", + "重试策略:非 2xx 响应或网络错误触发重试,至多重试 3 次(即最多 4 次尝试),间隔 2s→5s→15s,单次请求超时 30s;全部失败后判定回调失败", + "报文体统一为奇门同层级的 { request: {...} }(发送端统一包装 body = { request: request || {} }),event 仅出现在 query 的 method", + "事件注册表:app/service/openapi/callbackRegistry.js#CALLBACK_EVENTS;调试页:GET /docs/api/openapi/callback-test(app/controller/openapiCallback.js 按注册表自动预填完整报文体 { request: {...} },可编辑后发送)", + "发送途径:sendWithRetry 直调(按 StoreWarehouse auth_status=2 → ApiApp contract_id/is_enabled=1/callback_url 非空 定位)", + "回传成功才执行本地回调(throwOnError=true,失败抛出并写 QUICK_INBOUND_FAILED 操作日志)" + ] + }, + { + "method": "entryorder.match", + "description": "入库单匹配收货完成出站回调。入库单匹配收货单完成后(API 来源,source_type=API),WMS 向外部回传匹配完成信息(对应奇门 taobao.qimen.entryorder.confirm)。触发实现:app/service/systems/receiving_entry_match.js#matchAfterEntryCompleted 在绑定成功且本次确实新建绑定(bindResult.created === true)时调用 _sendCallback(entryOrder, matchedReceiving, 'auto_match') 的 API 分支 → _sendOpenApiCallback(event=entryorder.match);重复触发时绑定已存在(created=false)不会重复回传;回传失败仅记录 warn,不影响绑定与入库单状态更新。request 报文由 buildEntryOrderConfirmRequest 组装,奇门(QM)与 OpenAPI(API)共用。", + "isNeedAuth": true, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "回调 method(模块.动作,如 entryorder.match),由 WMS 计算后发出(不是接收方入参);event 仅出现在 query 的 method,报文体不再携带 event 字段;URL 中做 encodeURIComponent" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "协议版本,由 WMS 发出,固定 1.0" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "时间戳,由 WMS 发出,统一为秒级(10 位字符串,String(Math.floor(Date.now()/1000)));与 /openapi 入站时效校验(±600 秒窗口,Math.floor(Date.now()/1000))及回调调试页(nowTimestamp)口径一致,可作为规范值对外承诺" + }, + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "应用标识(api_app.self_app_key),由 WMS 发出;URL 中做 encodeURIComponent" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "MD5 签名,由 WMS 计算后发出;sign = md5(canonicalQuery + selfAppSecret + md5(stableStringify(body))),小写十六进制" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "奇门同层级业务报文 { entryOrder, orderLines }(不含外层 request 包装,发送端统一包装为 body = { request });口径与 callbackRegistry.js 的 request 模板一致,结构见下方 request.* 子字段" + }, + { + "name": "request.entryOrder", + "type": "object", + "required": true, + "source": "body", + "description": "入库单头信息" + }, + { + "name": "request.entryOrder.entryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "入库单编码(wms_entry_order.entry_order_code)" + }, + { + "name": "request.entryOrder.ownerCode", + "type": "string", + "required": true, + "source": "body", + "description": "奇门货主编码(wms_entry_order.qimen_owner_code)" + }, + { + "name": "request.entryOrder.warehouseCode", + "type": "string", + "required": true, + "source": "body", + "description": "奇门仓库编码(wms_entry_order.qimen_warehouse_code)" + }, + { + "name": "request.entryOrder.entryOrderId", + "type": "number", + "required": true, + "source": "body", + "description": "入库单 ID(wms_entry_order.id)" + }, + { + "name": "request.entryOrder.entryOrderType", + "type": "string", + "required": true, + "source": "body", + "description": "入库单类型(wms_entry_order.order_type,如 SCRK)" + }, + { + "name": "request.entryOrder.outBizCode", + "type": "string", + "required": true, + "source": "body", + "description": "外部业务编码,缺省自动生成 RECEIVING_MATCH_时间戳(毫秒)" + }, + { + "name": "request.entryOrder.confirmType", + "type": "number", + "required": true, + "source": "body", + "description": "确认类型,固定 0(最终确认)" + }, + { + "name": "request.entryOrder.status", + "type": "string", + "required": true, + "source": "body", + "description": "固定 FULFILLED" + }, + { + "name": "request.entryOrder.freight", + "type": "number", + "required": true, + "source": "body", + "description": "运费,固定 0" + }, + { + "name": "request.entryOrder.operateTime", + "type": "string", + "required": true, + "source": "body", + "description": "操作时间(app.formatDate(new Date()))" + }, + { + "name": "request.entryOrder.remark", + "type": "string", + "required": true, + "source": "body", + "description": "备注,固定「匹配收货单{收货单号}自动回传」(如 匹配收货单RCV20260912001自动回传)" + }, + { + "name": "request.orderLines", + "type": "array", + "required": true, + "source": "body", + "description": "入库明细行数组:[ { orderLineNo, ownerCode, itemCode, itemId, inventoryType, planQty, actualQty } ]" + }, + { + "name": "request.orderLines[].orderLineNo", + "type": "number", + "required": true, + "source": "body", + "description": "行号(从 1 递增)" + }, + { + "name": "request.orderLines[].ownerCode", + "type": "string", + "required": true, + "source": "body", + "description": "货主编码" + }, + { + "name": "request.orderLines[].itemCode", + "type": "string", + "required": true, + "source": "body", + "description": "商品编码" + }, + { + "name": "request.orderLines[].itemId", + "type": "string", + "required": true, + "source": "body", + "description": "商品 ID" + }, + { + "name": "request.orderLines[].inventoryType", + "type": "string", + "required": true, + "source": "body", + "description": "库存类型,缺省 ZP" + }, + { + "name": "request.orderLines[].planQty", + "type": "number", + "required": true, + "source": "body", + "description": "计划数量(wms_entry_items.count)" + }, + { + "name": "request.orderLines[].actualQty", + "type": "number", + "required": true, + "source": "body", + "description": "实际入库数量(wms_entry_items.received_quantity)" + } + ], + "response": [ + { + "name": "http_status", + "type": "number", + "required": true, + "description": "接收方应返回任意 2xx 状态码(200 ≤ status < 300,如 200/201/204);WMS 仅按 HTTP 状态码判定成功,响应体内容不参与判定" + }, + { + "name": "response_body", + "type": "object", + "required": false, + "description": "响应体无约定格式;WMS 不校验业务码,返回 2xx 即视为成功,非 2xx 或网络错误进入重试(至多 3 次,间隔 2s→5s→15s)" + } + ], + "errors": [ + { + "code": 400, + "message": "接收方返回 400(如参数/验签不通过):WMS 视为回调失败,进入重试,至多 3 次(间隔 2s→5s→15s),全部失败后判定最终失败" + }, + { + "code": 401, + "message": "接收方返回 401(鉴权失败):处理同 400,重试至多 3 次后判定最终失败" + }, + { + "code": 403, + "message": "接收方返回 403(拒绝访问):处理同 400,重试至多 3 次后判定最终失败" + }, + { + "code": "5xx", + "message": "接收方返回 5xx(服务端错误):处理同 400,重试至多 3 次后判定最终失败" + }, + { + "code": "NETWORK_ERROR", + "message": "网络错误或单次请求超时(30s):处理同非 2xx,重试至多 3 次后判定最终失败" + } + ], + "notes": [ + "本文件描述出站方向(WMS → 外部)回调;入站接口请参阅 methods/openapi.json", + "签名算法:sign = md5(canonicalQuery + selfAppSecret + md5(stableStringify(body))),小写十六进制;canonicalQuery 为 query 中除 sign/signature 外、值非 undefined 的参数按 key 升序拼成的 key=value&… 串(值为原始字符串,不 URL 编码),selfAppSecret 为 api_app.self_app_secret", + "重试策略:非 2xx 响应或网络错误触发重试,至多重试 3 次(即最多 4 次尝试),间隔 2s→5s→15s,单次请求超时 30s;全部失败后判定回调失败", + "报文体统一为奇门同层级的 { request: {...} }(发送端统一包装 body = { request: request || {} }),event 仅出现在 query 的 method", + "事件注册表:app/service/openapi/callbackRegistry.js#CALLBACK_EVENTS;调试页:GET /docs/api/openapi/callback-test(app/controller/openapiCallback.js 按注册表自动预填完整报文体 { request: {...} },可编辑后发送)", + "发送途径:sendWithRetry 直调(按 StoreWarehouse auth_status=2 → ApiApp contract_id/is_enabled=1/callback_url 非空 定位)", + "已接入:matchAfterEntryCompleted 在绑定成功且本次新建绑定(bindResult.created === true)时调用 _sendCallback(entryOrder, matchedReceiving, 'auto_match');重复触发不重复回传;回传失败仅 warn 不影响绑定" + ] + }, + { + "method": "deliveryorder.confirm", + "description": "订单发货完成出站回调(逐单发送)。API 渠道订单同步(出库)完成(createChannel=API 且 successCount>0)后,WMS 对每个同步成功的订单各发送一次回调(成功 N 单 = N 次回调),仅对 syncResults 中 status==='success' 的订单发送;fire-and-forget,失败仅 warn,不阻塞主流程。触发实现:app/service/systems/order_async.js#finalizeLocalChannelOrdersInternal → notifyApiDeliveryOrderConfirmsInternal(复用 buildQimenDeliveryOrderConfirmDataInternal 组装与奇门 taobao.qimen.deliveryorder.confirm 完全一致的 request 报文;复用原有主表+明细查询,新增 1 次运单号批量查询,无 N+1)。", + "isNeedAuth": true, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "回调 method(模块.动作,如 deliveryorder.confirm),由 WMS 计算后发出(不是接收方入参);event 仅出现在 query 的 method,报文体不再携带 event 字段;URL 中做 encodeURIComponent" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "协议版本,由 WMS 发出,固定 1.0" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "时间戳,由 WMS 发出,统一为秒级(10 位字符串,String(Math.floor(Date.now()/1000)));与 /openapi 入站时效校验(±600 秒窗口,Math.floor(Date.now()/1000))及回调调试页(nowTimestamp)口径一致,可作为规范值对外承诺" + }, + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "应用标识(api_app.self_app_key),由 WMS 发出;URL 中做 encodeURIComponent" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "MD5 签名,由 WMS 计算后发出;sign = md5(canonicalQuery + selfAppSecret + md5(stableStringify(body))),小写十六进制" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "奇门同层级业务报文 { deliveryOrder, packages, orderLines }(不含外层 request 包装,发送端统一包装为 body = { request });口径与 callbackRegistry.js 的 request 模板一致,结构见下方 request.* 子字段" + }, + { + "name": "request.deliveryOrder", + "type": "object", + "required": true, + "source": "body", + "description": "发货单头信息" + }, + { + "name": "request.deliveryOrder.totalOrderLines", + "type": "number", + "required": true, + "source": "body", + "description": "明细行数(orderLines.length)" + }, + { + "name": "request.deliveryOrder.deliveryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "发货单编码(wms_order.delivery_order_code)" + }, + { + "name": "request.deliveryOrder.deliveryOrderId", + "type": "number", + "required": true, + "source": "body", + "description": "订单 ID(wms_order.id)" + }, + { + "name": "request.deliveryOrder.warehouseCode", + "type": "string", + "required": true, + "source": "body", + "description": "仓库编码" + }, + { + "name": "request.deliveryOrder.orderType", + "type": "string", + "required": true, + "source": "body", + "description": "单据类型(wms_order.order_type,如 JYCK)" + }, + { + "name": "request.deliveryOrder.status", + "type": "string", + "required": true, + "source": "body", + "description": "固定 DELIVERED" + }, + { + "name": "request.deliveryOrder.outBizCode", + "type": "string", + "required": true, + "source": "body", + "description": "外部业务编码,同 deliveryOrderCode" + }, + { + "name": "request.deliveryOrder.confirmType", + "type": "number", + "required": true, + "source": "body", + "description": "固定 0(最终确认)" + }, + { + "name": "request.deliveryOrder.orderConfirmTime", + "type": "string", + "required": true, + "source": "body", + "description": "确认时间(app.formatDate(new Date()))" + }, + { + "name": "request.deliveryOrder.operatorCode", + "type": "string", + "required": true, + "source": "body", + "description": "操作员编码,固定空字符串" + }, + { + "name": "request.deliveryOrder.operatorName", + "type": "string", + "required": true, + "source": "body", + "description": "操作员名称,固定空字符串" + }, + { + "name": "request.deliveryOrder.storageFee", + "type": "string", + "required": true, + "source": "body", + "description": "仓储费(wms_order.storage_fee,字符串)" + }, + { + "name": "request.deliveryOrder.operateTime", + "type": "string", + "required": true, + "source": "body", + "description": "操作时间(app.formatDate(new Date()))" + }, + { + "name": "request.packages", + "type": "object", + "required": true, + "source": "body", + "description": "包裹信息对象 { package: [...] }" + }, + { + "name": "request.packages.package", + "type": "array", + "required": true, + "source": "body", + "description": "包裹数组(每个运单号一条)" + }, + { + "name": "request.packages.package[].logisticsCode", + "type": "string", + "required": true, + "source": "body", + "description": "物流公司编码(wms_order.logistics_code)" + }, + { + "name": "request.packages.package[].logisticsName", + "type": "string", + "required": true, + "source": "body", + "description": "物流公司名称(wms_order.logistics_name)" + }, + { + "name": "request.packages.package[].expressCode", + "type": "string", + "required": true, + "source": "body", + "description": "运单号(wms_order_express 批量查询,同仓校验)" + }, + { + "name": "request.packages.package[].packageCode", + "type": "string", + "required": true, + "source": "body", + "description": "包裹编码(package_code 缺省同 deliveryOrderCode)" + }, + { + "name": "request.packages.package[].invoiceNo", + "type": "string", + "required": true, + "source": "body", + "description": "发票号(wms_order.invoice_no)" + }, + { + "name": "request.packages.package[].items", + "type": "array", + "required": true, + "source": "body", + "description": "包裹内商品行:[ { itemCode, itemId, quantity } ]" + }, + { + "name": "request.packages.package[].items[].itemCode", + "type": "string", + "required": true, + "source": "body", + "description": "商品编码" + }, + { + "name": "request.packages.package[].items[].itemId", + "type": "string", + "required": true, + "source": "body", + "description": "商品 ID" + }, + { + "name": "request.packages.package[].items[].quantity", + "type": "number", + "required": true, + "source": "body", + "description": "数量" + }, + { + "name": "request.orderLines", + "type": "array", + "required": true, + "source": "body", + "description": "发货明细行数组" + }, + { + "name": "request.orderLines[].orderLineNo", + "type": "string", + "required": true, + "source": "body", + "description": "行号(字符串)" + }, + { + "name": "request.orderLines[].orderSourceCode", + "type": "string", + "required": true, + "source": "body", + "description": "订单来源编码(source_order_code)" + }, + { + "name": "request.orderLines[].subSourceCode", + "type": "string", + "required": true, + "source": "body", + "description": "子来源编码(sub_source_order_code)" + }, + { + "name": "request.orderLines[].ownerCode", + "type": "string", + "required": true, + "source": "body", + "description": "货主编码" + }, + { + "name": "request.orderLines[].itemCode", + "type": "string", + "required": true, + "source": "body", + "description": "商品编码" + }, + { + "name": "request.orderLines[].itemId", + "type": "string", + "required": true, + "source": "body", + "description": "商品 ID" + }, + { + "name": "request.orderLines[].itemName", + "type": "string", + "required": true, + "source": "body", + "description": "商品名称" + }, + { + "name": "request.orderLines[].extCode", + "type": "string", + "required": true, + "source": "body", + "description": "扩展编码(ext_code)" + }, + { + "name": "request.orderLines[].planQty", + "type": "number", + "required": true, + "source": "body", + "description": "计划数量" + }, + { + "name": "request.orderLines[].actualQty", + "type": "number", + "required": true, + "source": "body", + "description": "实际发货数量" + }, + { + "name": "request.orderLines[].retailPrice", + "type": "number", + "required": true, + "source": "body", + "description": "零售价" + }, + { + "name": "request.orderLines[].actualPrice", + "type": "number", + "required": true, + "source": "body", + "description": "实际价" + }, + { + "name": "request.orderLines[].discountAmount", + "type": "string", + "required": true, + "source": "body", + "description": "优惠金额(字符串)" + }, + { + "name": "request.orderLines[].inventoryType", + "type": "string", + "required": true, + "source": "body", + "description": "库存类型(如 ZP)" + }, + { + "name": "request.orderLines[].snList", + "type": "array", + "required": true, + "source": "body", + "description": "序列号列表(无序列号时为空数组 [])" + }, + { + "name": "request.orderLines[].qrCode", + "type": "string", + "required": true, + "source": "body", + "description": "二维码(qr_code)" + } + ], + "response": [ + { + "name": "http_status", + "type": "number", + "required": true, + "description": "接收方应返回任意 2xx 状态码(200 ≤ status < 300,如 200/201/204);WMS 仅按 HTTP 状态码判定成功,响应体内容不参与判定" + }, + { + "name": "response_body", + "type": "object", + "required": false, + "description": "响应体无约定格式;WMS 不校验业务码,返回 2xx 即视为成功,非 2xx 或网络错误进入重试(至多 3 次,间隔 2s→5s→15s)" + } + ], + "errors": [ + { + "code": 400, + "message": "接收方返回 400(如参数/验签不通过):WMS 视为回调失败,进入重试,至多 3 次(间隔 2s→5s→15s),全部失败后判定最终失败" + }, + { + "code": 401, + "message": "接收方返回 401(鉴权失败):处理同 400,重试至多 3 次后判定最终失败" + }, + { + "code": 403, + "message": "接收方返回 403(拒绝访问):处理同 400,重试至多 3 次后判定最终失败" + }, + { + "code": "5xx", + "message": "接收方返回 5xx(服务端错误):处理同 400,重试至多 3 次后判定最终失败" + }, + { + "code": "NETWORK_ERROR", + "message": "网络错误或单次请求超时(30s):处理同非 2xx,重试至多 3 次后判定最终失败" + } + ], + "notes": [ + "本文件描述出站方向(WMS → 外部)回调;入站接口请参阅 methods/openapi.json", + "签名算法:sign = md5(canonicalQuery + selfAppSecret + md5(stableStringify(body))),小写十六进制;canonicalQuery 为 query 中除 sign/signature 外、值非 undefined 的参数按 key 升序拼成的 key=value&… 串(值为原始字符串,不 URL 编码),selfAppSecret 为 api_app.self_app_secret", + "重试策略:非 2xx 响应或网络错误触发重试,至多重试 3 次(即最多 4 次尝试),间隔 2s→5s→15s,单次请求超时 30s;全部失败后判定回调失败", + "报文体统一为奇门同层级的 { request: {...} }(发送端统一包装 body = { request: request || {} }),event 仅出现在 query 的 method", + "事件注册表:app/service/openapi/callbackRegistry.js#CALLBACK_EVENTS;调试页:GET /docs/api/openapi/callback-test(app/controller/openapiCallback.js 按注册表自动预填完整报文体 { request: {...} },可编辑后发送)", + "发送途径:sendByAppKey(按 app_key 查 ApiApp,is_enabled=1,取 self_app_secret 与 callback_url)", + "逐单发送语义(破坏性变更):改动前一次回调携带整批 orderIds(含失败/跳过);改后仅对 syncResults 中 status==='success' 的订单逐单发送,成功 N 单 = N 次回调;组装/发送失败仅 warn,不影响其他订单与主流程", + "fire-and-forget 触发:回调结果不影响订单同步主流程" + ] + }, + { + "method": "stockout.confirm", + "description": "出库单确认完成出站回调。出库单确认(API 来源,source_type=API)后,WMS 向外部回传出库确认信息(对应奇门 taobao.qimen.stockout.confirm)。触发实现:app/service/systems/order_async.js#notifyStockoutExternalInternal 的 API 分支(event=stockout.confirm);request 即 buildStockoutConfirmDataInternal 的返回结构 { deliveryOrder, packages, orderLines },与奇门请求体同层级。", + "isNeedAuth": true, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "回调 method(模块.动作,如 stockout.confirm),由 WMS 计算后发出(不是接收方入参);event 仅出现在 query 的 method,报文体不再携带 event 字段;URL 中做 encodeURIComponent" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "协议版本,由 WMS 发出,固定 1.0" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "时间戳,由 WMS 发出,统一为秒级(10 位字符串,String(Math.floor(Date.now()/1000)));与 /openapi 入站时效校验(±600 秒窗口,Math.floor(Date.now()/1000))及回调调试页(nowTimestamp)口径一致,可作为规范值对外承诺" + }, + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "应用标识(api_app.self_app_key),由 WMS 发出;URL 中做 encodeURIComponent" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "MD5 签名,由 WMS 计算后发出;sign = md5(canonicalQuery + selfAppSecret + md5(stableStringify(body))),小写十六进制" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "奇门同层级业务报文 { deliveryOrder, packages, orderLines }(即 buildStockoutConfirmDataInternal 的返回结构,不含外层 request 包装,发送端统一包装为 body = { request });口径与 callbackRegistry.js 的 request 模板一致,结构见下方 request.* 子字段" + }, + { + "name": "request.deliveryOrder", + "type": "object", + "required": true, + "source": "body", + "description": "出库单头信息" + }, + { + "name": "request.deliveryOrder.totalOrderLines", + "type": "number", + "required": true, + "source": "body", + "description": "明细行数(wms_order_stockout.total_order_lines 或 orderLines.length)" + }, + { + "name": "request.deliveryOrder.deliveryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "出库单号(wms_order_stockout.stockout_order_code)" + }, + { + "name": "request.deliveryOrder.deliveryOrderId", + "type": "number", + "required": true, + "source": "body", + "description": "出库单 ID(wms_order_stockout.id)" + }, + { + "name": "request.deliveryOrder.warehouseCode", + "type": "string", + "required": true, + "source": "body", + "description": "奇门仓库编码(wms_order_stockout.qimen_warehouse_code)" + }, + { + "name": "request.deliveryOrder.orderType", + "type": "string", + "required": true, + "source": "body", + "description": "单据类型(如 PTCK)" + }, + { + "name": "request.deliveryOrder.status", + "type": "string", + "required": true, + "source": "body", + "description": "固定 DELIVERED" + }, + { + "name": "request.deliveryOrder.outBizCode", + "type": "string", + "required": true, + "source": "body", + "description": "外部业务编码,同出库单号" + }, + { + "name": "request.deliveryOrder.confirmType", + "type": "number", + "required": true, + "source": "body", + "description": "固定 0(最终确认)" + }, + { + "name": "request.deliveryOrder.orderConfirmTime", + "type": "string", + "required": true, + "source": "body", + "description": "确认时间(app.formatDate(new Date()))" + }, + { + "name": "request.deliveryOrder.operatorCode", + "type": "string", + "required": true, + "source": "body", + "description": "操作员编码,固定空字符串" + }, + { + "name": "request.deliveryOrder.operatorName", + "type": "string", + "required": true, + "source": "body", + "description": "操作员名称,固定空字符串" + }, + { + "name": "request.packages", + "type": "object", + "required": true, + "source": "body", + "description": "包裹信息对象 { package: [...] }" + }, + { + "name": "request.packages.package", + "type": "array", + "required": true, + "source": "body", + "description": "包裹数组(每个运单号一条;STOCKOUT 渠道运单号只认 wms_order_express 表)" + }, + { + "name": "request.packages.package[].logisticsCode", + "type": "string", + "required": true, + "source": "body", + "description": "物流公司编码(订单 sys_logistics_code → logistics_code → 出库单 express_code,缺省 OTHER)" + }, + { + "name": "request.packages.package[].logisticsName", + "type": "string", + "required": true, + "source": "body", + "description": "物流公司名称(订单 sys_logistics_name → logistics_name → 出库单 express_name,缺省 OTHER)" + }, + { + "name": "request.packages.package[].expressCode", + "type": "string", + "required": true, + "source": "body", + "description": "运单号(wms_order_express 表)" + }, + { + "name": "request.packages.package[].packageCode", + "type": "string", + "required": true, + "source": "body", + "description": "包裹编码(package_code 缺省同出库单号)" + }, + { + "name": "request.packages.package[].items", + "type": "array", + "required": true, + "source": "body", + "description": "包裹内商品行:[ { itemCode, itemId, quantity } ]" + }, + { + "name": "request.packages.package[].items[].itemCode", + "type": "string", + "required": true, + "source": "body", + "description": "商品编码" + }, + { + "name": "request.packages.package[].items[].itemId", + "type": "string", + "required": true, + "source": "body", + "description": "商品 ID" + }, + { + "name": "request.packages.package[].items[].quantity", + "type": "number", + "required": true, + "source": "body", + "description": "数量(actualQty)" + }, + { + "name": "request.orderLines", + "type": "array", + "required": true, + "source": "body", + "description": "出库明细行数组:[ { orderLineNo, ownerCode, itemCode, itemId, itemName, planQty, actualQty, inventoryType } ]" + }, + { + "name": "request.orderLines[].orderLineNo", + "type": "string", + "required": true, + "source": "body", + "description": "行号(字符串)" + }, + { + "name": "request.orderLines[].ownerCode", + "type": "string", + "required": true, + "source": "body", + "description": "货主编码(item.owner_code 或出库单 qimen_owner_code)" + }, + { + "name": "request.orderLines[].itemCode", + "type": "string", + "required": true, + "source": "body", + "description": "商品编码" + }, + { + "name": "request.orderLines[].itemId", + "type": "string", + "required": true, + "source": "body", + "description": "商品 ID" + }, + { + "name": "request.orderLines[].itemName", + "type": "string", + "required": true, + "source": "body", + "description": "商品名称" + }, + { + "name": "request.orderLines[].planQty", + "type": "number", + "required": true, + "source": "body", + "description": "计划数量" + }, + { + "name": "request.orderLines[].actualQty", + "type": "number", + "required": true, + "source": "body", + "description": "实际数量(缺省同 planQty)" + }, + { + "name": "request.orderLines[].inventoryType", + "type": "string", + "required": true, + "source": "body", + "description": "库存类型,缺省 ZP" + } + ], + "response": [ + { + "name": "http_status", + "type": "number", + "required": true, + "description": "接收方应返回任意 2xx 状态码(200 ≤ status < 300,如 200/201/204);WMS 仅按 HTTP 状态码判定成功,响应体内容不参与判定" + }, + { + "name": "response_body", + "type": "object", + "required": false, + "description": "响应体无约定格式;WMS 不校验业务码,返回 2xx 即视为成功,非 2xx 或网络错误进入重试(至多 3 次,间隔 2s→5s→15s)" + } + ], + "errors": [ + { + "code": 400, + "message": "接收方返回 400(如参数/验签不通过):WMS 视为回调失败,进入重试,至多 3 次(间隔 2s→5s→15s),全部失败后判定最终失败" + }, + { + "code": 401, + "message": "接收方返回 401(鉴权失败):处理同 400,重试至多 3 次后判定最终失败" + }, + { + "code": 403, + "message": "接收方返回 403(拒绝访问):处理同 400,重试至多 3 次后判定最终失败" + }, + { + "code": "5xx", + "message": "接收方返回 5xx(服务端错误):处理同 400,重试至多 3 次后判定最终失败" + }, + { + "code": "NETWORK_ERROR", + "message": "网络错误或单次请求超时(30s):处理同非 2xx,重试至多 3 次后判定最终失败" + } + ], + "notes": [ + "本文件描述出站方向(WMS → 外部)回调;入站接口请参阅 methods/openapi.json", + "签名算法:sign = md5(canonicalQuery + selfAppSecret + md5(stableStringify(body))),小写十六进制;canonicalQuery 为 query 中除 sign/signature 外、值非 undefined 的参数按 key 升序拼成的 key=value&… 串(值为原始字符串,不 URL 编码),selfAppSecret 为 api_app.self_app_secret", + "重试策略:非 2xx 响应或网络错误触发重试,至多重试 3 次(即最多 4 次尝试),间隔 2s→5s→15s,单次请求超时 30s;全部失败后判定回调失败", + "报文体统一为奇门同层级的 { request: {...} }(发送端统一包装 body = { request: request || {} }),event 仅出现在 query 的 method", + "事件注册表:app/service/openapi/callbackRegistry.js#CALLBACK_EVENTS;调试页:GET /docs/api/openapi/callback-test(app/controller/openapiCallback.js 按注册表自动预填完整报文体 { request: {...} },可编辑后发送)", + "发送途径:sendByAppKey(按 app_key 查 ApiApp,is_enabled=1,取 self_app_secret 与 callback_url)", + "仅 API 来源(source_type=API)出库单回传;QM 来源走奇门 taobao.qimen.stockout.confirm" + ] + }, + { + "method": "deliveryorder.cancel", + "description": "订单取消出站回调(出站事件名 deliveryorder.cancel,与 /openapi 入站方法 order.cancel 区分,避免 callback_url 误指向 WMS /openapi 时被路由到真正的取消单据接口;不做兼容、不双发)。订单取消成功后,WMS 向外部回传取消结果(fire-and-forget,不阻塞主流程)。触发实现:app/service/openapiMethods/order.js#cancel(event=deliveryorder.cancel)。无奇门对应接口,按 deliveryOrder 节点约定自定义报文。", + "isNeedAuth": true, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "回调 method(模块.动作,如 deliveryorder.cancel),由 WMS 计算后发出(不是接收方入参);event 仅出现在 query 的 method,报文体不再携带 event 字段;URL 中做 encodeURIComponent" + }, + { + "name": "v", + "type": "string", + "required": true, + "source": "query", + "description": "协议版本,由 WMS 发出,固定 1.0" + }, + { + "name": "timestamp", + "type": "string", + "required": true, + "source": "query", + "description": "时间戳,由 WMS 发出,统一为秒级(10 位字符串,String(Math.floor(Date.now()/1000)));与 /openapi 入站时效校验(±600 秒窗口,Math.floor(Date.now()/1000))及回调调试页(nowTimestamp)口径一致,可作为规范值对外承诺" + }, + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "应用标识(api_app.self_app_key),由 WMS 发出;URL 中做 encodeURIComponent" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "MD5 签名,由 WMS 计算后发出;sign = md5(canonicalQuery + selfAppSecret + md5(stableStringify(body))),小写十六进制" + }, + { + "name": "request", + "type": "object", + "required": true, + "source": "body", + "description": "奇门同层级业务报文 { deliveryOrder }(不含外层 request 包装,发送端统一包装为 body = { request });口径与 callbackRegistry.js 的 request 模板一致,结构见下方 request.* 子字段" + }, + { + "name": "request.deliveryOrder", + "type": "object", + "required": true, + "source": "body", + "description": "被取消订单信息(自定义约定,无奇门对应接口)" + }, + { + "name": "request.deliveryOrder.deliveryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "被取消的订单编码(normalizedOrderCode)" + }, + { + "name": "request.deliveryOrder.orderType", + "type": "string", + "required": true, + "source": "body", + "description": "单据类型,取 body.orderType 大写归一化结果(String(body.orderType || 'JYCK').trim().toUpperCase())" + }, + { + "name": "request.deliveryOrder.status", + "type": "string", + "required": true, + "source": "body", + "description": "固定 CANCELED(自定义约定值;无奇门对应接口,风格与奇门 deliveryOrder.status 家族枚举一致)" + } + ], + "response": [ + { + "name": "http_status", + "type": "number", + "required": true, + "description": "接收方应返回任意 2xx 状态码(200 ≤ status < 300,如 200/201/204);WMS 仅按 HTTP 状态码判定成功,响应体内容不参与判定" + }, + { + "name": "response_body", + "type": "object", + "required": false, + "description": "响应体无约定格式;WMS 不校验业务码,返回 2xx 即视为成功,非 2xx 或网络错误进入重试(至多 3 次,间隔 2s→5s→15s)" + } + ], + "errors": [ + { + "code": 400, + "message": "接收方返回 400(如参数/验签不通过):WMS 视为回调失败,进入重试,至多 3 次(间隔 2s→5s→15s),全部失败后判定最终失败" + }, + { + "code": 401, + "message": "接收方返回 401(鉴权失败):处理同 400,重试至多 3 次后判定最终失败" + }, + { + "code": 403, + "message": "接收方返回 403(拒绝访问):处理同 400,重试至多 3 次后判定最终失败" + }, + { + "code": "5xx", + "message": "接收方返回 5xx(服务端错误):处理同 400,重试至多 3 次后判定最终失败" + }, + { + "code": "NETWORK_ERROR", + "message": "网络错误或单次请求超时(30s):处理同非 2xx,重试至多 3 次后判定最终失败" + } + ], + "notes": [ + "本文件描述出站方向(WMS → 外部)回调;入站接口请参阅 methods/openapi.json", + "签名算法:sign = md5(canonicalQuery + selfAppSecret + md5(stableStringify(body))),小写十六进制;canonicalQuery 为 query 中除 sign/signature 外、值非 undefined 的参数按 key 升序拼成的 key=value&… 串(值为原始字符串,不 URL 编码),selfAppSecret 为 api_app.self_app_secret", + "重试策略:非 2xx 响应或网络错误触发重试,至多重试 3 次(即最多 4 次尝试),间隔 2s→5s→15s,单次请求超时 30s;全部失败后判定回调失败", + "报文体统一为奇门同层级的 { request: {...} }(发送端统一包装 body = { request: request || {} }),event 仅出现在 query 的 method", + "事件注册表:app/service/openapi/callbackRegistry.js#CALLBACK_EVENTS;调试页:GET /docs/api/openapi/callback-test(app/controller/openapiCallback.js 按注册表自动预填完整报文体 { request: {...} },可编辑后发送)", + "发送途径:sendByAppKey(按 app_key 查 ApiApp,is_enabled=1,取 self_app_secret 与 callback_url)", + "fire-and-forget 触发:回调结果不影响订单取消主流程", + "改名说明:出站回调事件名由 order.cancel 改为 deliveryorder.cancel(不做兼容、不双发),与 /openapi 入站方法 order.cancel(取消单据接口)区分,避免 callback_url 误指向 /openapi 时被路由到取消单据接口" + ] + } + ] + } + ] + } +} diff --git a/script/update-api-doc.cjs b/script/update-api-doc.cjs index af9e431..be907c8 100644 --- a/script/update-api-doc.cjs +++ b/script/update-api-doc.cjs @@ -2,8 +2,13 @@ const fs = require('fs'); const path = require('path'); const ROOT = process.cwd(); -const METHODS_DIR = path.join(ROOT, 'methods'); -const CHANGES_DIR = path.join(METHODS_DIR, 'changes'); +// 测试覆盖钩子:允许通过环境变量覆盖目标目录(未设置时保持原有 methods/ 与 methods/changes/ 默认值不变) +const METHODS_DIR = process.env.WMS_API_DOC_METHODS_DIR + ? path.resolve(process.env.WMS_API_DOC_METHODS_DIR) + : path.join(ROOT, 'methods'); +const CHANGES_DIR = process.env.WMS_API_DOC_CHANGES_DIR + ? path.resolve(process.env.WMS_API_DOC_CHANGES_DIR) + : path.join(METHODS_DIR, 'changes'); function parseArgs(argv) { const args = { @@ -43,6 +48,9 @@ function parseArgs(argv) { return args; } +/** + * 打印脚本帮助文案(用法、选项、spec.newDoc 字段说明与新建文档示例命令) + */ function printHelp() { console.log([ 'Usage:', @@ -54,6 +62,19 @@ function printHelp() { ' --spec= Path to the fixed update spec JSON file.', ' --dry-run Validate and print the planned changes without writing files.', ' --doc-only Update methods/.json only and skip methods/changes/.json.', + '', + 'spec.newDoc (optional spec field, only used when methods/.json does not exist):', + ' module Required, non-empty string. New doc root "module".', + ' description Optional string, default "".', + ' http Optional object, default { "path": "", "method": "POST" }.', + ' headers Optional array, default [].', + ' Other fields are passed through for future use (plain JSON values only).', + ' Ignored when methods/.json already exists.', + '', + 'Examples:', + ' Create a new doc skeleton and write group/methods in one shot:', + ' npm run doc:api:update -- --spec=temp/api-doc-create.json --dry-run', + ' npm run doc:api:update -- --spec=temp/api-doc-create.json', ].join('\n')); } @@ -88,6 +109,16 @@ function detectEol(raw) { return raw.includes('\r\n') ? '\r\n' : '\n'; } +/** + * 返回本地时区的今天日期(YYYY-MM-DD,如 2026-09-12) + * @return {string} 今天日期字符串 + */ +function formatLocalDate() { + const now = new Date(); + const pad = value => String(value).padStart(2, '0'); + return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`; +} + function writeJsonFile(filePath, value, indent, eol) { const formatted = JSON.stringify(value, null, indent).replace(/\n/g, eol); fs.writeFileSync(filePath, `${formatted}${eol}`, 'utf8'); @@ -110,6 +141,25 @@ function ensureStringArray(value, fieldPath) { value.forEach((item, index) => ensureString(item, `${fieldPath}[${index}]`)); } +/** + * 校验值必须是可 JSON 序列化的 plain 值(null / 字符串 / 数字 / 布尔 / plain 对象 / 数组,递归校验) + * @param {*} value 待校验值 + * @param {string} fieldPath 字段路径(用于报错文案) + */ +function ensurePlainJson(value, fieldPath) { + if (value === null || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + return; + } + + if (Array.isArray(value)) { + value.forEach((item, index) => ensurePlainJson(item, `${fieldPath}[${index}]`)); + return; + } + + assert(isPlainObject(value), `${fieldPath} must be a plain JSON value.`); + Object.keys(value).forEach(key => ensurePlainJson(value[key], `${fieldPath}.${key}`)); +} + function validateListOption(option, fieldPath) { assert(isPlainObject(option), `${fieldPath} must be an object.`); const hasValue = Object.prototype.hasOwnProperty.call(option, 'value'); @@ -179,6 +229,71 @@ function validateCurrentChanges(changes, fieldPath) { ensureArray(changes, fieldPath); } +// spec.newDoc 保留键:module/description/http/headers 由骨架消费,version/updatedAt/methods 由骨架统一管理,不参与透传 +const NEW_DOC_RESERVED_KEYS = new Set([ 'module', 'description', 'http', 'headers', 'version', 'updatedAt', 'methods' ]); + +/** + * 校验 spec.newDoc(仅当目标文档不存在、需要自动创建骨架时调用) + * @param {object} newDoc 新建文档骨架配置 + * @param {string} fieldPath 字段路径(用于报错文案) + */ +function validateNewDoc(newDoc, fieldPath) { + assert(isPlainObject(newDoc), `${fieldPath} must be an object.`); + ensureString(newDoc.module, `${fieldPath}.module`); + + if (Object.prototype.hasOwnProperty.call(newDoc, 'description')) { + assert(typeof newDoc.description === 'string', `${fieldPath}.description must be a string.`); + } + + if (Object.prototype.hasOwnProperty.call(newDoc, 'http')) { + assert(isPlainObject(newDoc.http), `${fieldPath}.http must be an object.`); + } + + if (Object.prototype.hasOwnProperty.call(newDoc, 'headers')) { + ensureArray(newDoc.headers, `${fieldPath}.headers`); + } + + // 未来扩展字段:跳过保留键,其余字段仅接受 plain JSON 值并原样透传 + Object.keys(newDoc).forEach(key => { + if (!NEW_DOC_RESERVED_KEYS.has(key)) { + ensurePlainJson(newDoc[key], `${fieldPath}.${key}`); + } + }); +} + +/** + * 依据 spec.newDoc 与 spec.docMeta 生成新文档骨架(module/description/version/updatedAt/http/headers/methods.groups) + * @param {object} newDoc 已校验的 spec.newDoc + * @param {object} docMeta 已校验的 spec.docMeta(未提供时为 {}) + * @return {object} 新文档骨架对象 + */ +function buildNewDoc(newDoc, docMeta) { + const doc = { + module: newDoc.module, + description: newDoc.description || '', + version: (docMeta && docMeta.version) || '0.0.0', + updatedAt: (docMeta && docMeta.updatedAt) || formatLocalDate(), + http: newDoc.http || { path: '', method: 'POST' }, + headers: newDoc.headers || [], + methods: { groups: [] }, + }; + + // 未来扩展字段原样透传(保留键除外,已在校验阶段限制为 plain JSON 值) + Object.keys(newDoc).forEach(key => { + if (!NEW_DOC_RESERVED_KEYS.has(key)) { + doc[key] = cloneJson(newDoc[key]); + } + }); + + return doc; +} + +/** + * 校验并规范化更新 spec(含新建文档 spec.newDoc 的判定与校验),返回执行计划所需的结构化信息 + * @param {object} spec 更新 spec 对象 + * @param {object} args 命令行参数(dryRun / docOnly) + * @return {object} 规范化结果(docName/docPath/changePath/docExists/changeExists/docMeta/group/methods/deleteMethods/change/newDoc) + */ function validateSpec(spec, args) { assert(isPlainObject(spec), 'Spec root must be an object.'); ensureString(spec.docName, 'spec.docName'); @@ -187,11 +302,18 @@ function validateSpec(spec, args) { const docPath = path.join(METHODS_DIR, `${spec.docName}.json`); const changePath = path.join(CHANGES_DIR, `${spec.docName}.json`); - assert(fs.existsSync(docPath), `Target doc file not found: ${docPath}`); - if (!args.docOnly) { - assert(fs.existsSync(changePath), `Target change file not found: ${changePath}`); + const docExists = fs.existsSync(docPath); + if (!docExists) { + // 目标文档不存在时必须提供 spec.newDoc,否则给出可操作提示 + assert( + Object.prototype.hasOwnProperty.call(spec, 'newDoc'), + `Target doc file not found: ${docPath} (provide spec.newDoc to create it)` + ); + validateNewDoc(spec.newDoc, 'spec.newDoc'); } + const changeExists = fs.existsSync(changePath); + if (Object.prototype.hasOwnProperty.call(spec, 'docMeta')) { assert(isPlainObject(spec.docMeta), 'spec.docMeta must be an object.'); if (Object.prototype.hasOwnProperty.call(spec.docMeta, 'updatedAt')) { @@ -200,6 +322,9 @@ function validateSpec(spec, args) { if (Object.prototype.hasOwnProperty.call(spec.docMeta, 'version')) { ensureString(spec.docMeta.version, 'spec.docMeta.version'); } + if (Object.prototype.hasOwnProperty.call(spec.docMeta, 'description')) { + assert(typeof spec.docMeta.description === 'string', 'spec.docMeta.description must be a string.'); + } } assert(isPlainObject(spec.group), 'spec.group must be an object.'); @@ -234,11 +359,14 @@ function validateSpec(spec, args) { docName: spec.docName, docPath, changePath, + docExists, + changeExists, docMeta: spec.docMeta || {}, group: spec.group, methods: spec.methods, deleteMethods, change: spec.change || null, + newDoc: spec.newDoc || null, }; } @@ -331,6 +459,10 @@ function applyDocUpdate(doc, groupSpec, methods, docMeta, deleteMethods = []) { doc.version = docMeta.version; } + if (typeof docMeta.description === 'string') { + doc.description = docMeta.description; + } + return summary; } @@ -341,6 +473,10 @@ function appendChange(changes, change) { changes.unshift(cloneJson(change)); } +/** + * 主流程:解析参数 → 校验 spec → 读取既有文档或按 spec.newDoc 生成骨架 → 应用更新 → 输出计划 → 写盘 + * 新建场景:目标文档不存在时依据 spec.newDoc 生成骨架(2 空格缩进 + LF);变更文件不存在时视为空数组并自动创建 + */ function main() { const args = parseArgs(process.argv.slice(2)); if (args.help) { @@ -354,12 +490,18 @@ function main() { const spec = JSON.parse(specRaw); const normalized = validateSpec(spec, args); - const docState = readJsonFile(normalized.docPath); + // 目标文档不存在:依据 spec.newDoc 生成骨架(默认 2 空格缩进 + LF,与 methods/ 下多数文件风格一致) + const docState = normalized.docExists + ? readJsonFile(normalized.docPath) + : { json: buildNewDoc(normalized.newDoc, normalized.docMeta), indent: ' ', eol: '\n' }; validateCurrentDoc(docState.json, normalized.docPath); let changeState = null; if (!args.docOnly) { - changeState = readJsonFile(normalized.changePath); + // 变更文件不存在:视为空数组,正式写入阶段自动创建(默认 2 空格缩进 + LF) + changeState = normalized.changeExists + ? readJsonFile(normalized.changePath) + : { json: [], indent: ' ', eol: '\n' }; validateCurrentChanges(changeState.json, normalized.changePath); } @@ -386,16 +528,35 @@ function main() { } if (args.dryRun) { + // dry-run 只打印计划(created 行标识将要新建的文件),绝不写盘 + if (!normalized.docExists) { + console.log(`created: ${path.relative(ROOT, normalized.docPath)}`); + } + if (!args.docOnly && !normalized.changeExists) { + console.log(`created: ${path.relative(ROOT, normalized.changePath)}`); + } console.log('dry-run: validated successfully, no files were written.'); return; } - writeJsonFile(normalized.docPath, docNext, docState.indent, docState.eol); - console.log(`wrote: ${path.relative(ROOT, normalized.docPath)}`); + if (normalized.docExists) { + writeJsonFile(normalized.docPath, docNext, docState.indent, docState.eol); + console.log(`wrote: ${path.relative(ROOT, normalized.docPath)}`); + } else { + writeJsonFile(normalized.docPath, docNext, docState.indent, docState.eol); + console.log(`created: ${path.relative(ROOT, normalized.docPath)}`); + } if (!args.docOnly) { - writeJsonFile(normalized.changePath, changeNext, changeState.indent, changeState.eol); - console.log(`wrote: ${path.relative(ROOT, normalized.changePath)}`); + if (normalized.changeExists) { + writeJsonFile(normalized.changePath, changeNext, changeState.indent, changeState.eol); + console.log(`wrote: ${path.relative(ROOT, normalized.changePath)}`); + } else { + // 变更文件不存在:兜底递归创建目录后新建文件 + fs.mkdirSync(path.dirname(normalized.changePath), { recursive: true }); + writeJsonFile(normalized.changePath, changeNext, changeState.indent, changeState.eol); + console.log(`created: ${path.relative(ROOT, normalized.changePath)}`); + } } } @@ -410,6 +571,8 @@ if (require.main === module) { module.exports = { applyDocUpdate, + buildNewDoc, parseArgs, + validateNewDoc, validateSpec, }; diff --git a/test/app/controller/openapiCallback.test.js b/test/app/controller/openapiCallback.test.js new file mode 100644 index 0000000..72de240 --- /dev/null +++ b/test/app/controller/openapiCallback.test.js @@ -0,0 +1,51 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const OpenapiCallbackController = require('../../../app/controller/openapiCallback'); + +/** + * 创建回调调试页控制器纯桩实例。 + * @return {Object} 控制器实例(含 ctx 桩)。 + */ +function createController() { + const controller = Object.create(OpenapiCallbackController.prototype); + controller.ctx = { type: null, body: null }; + return controller; +} + +describe('test/app/controller/openapiCallback.test.js', () => { + it('调试页应输出完整报文体模板(奇门同层级 { request },可编辑)', async () => { + const controller = createController(); + + await controller.testPage(); + + assert.equal(controller.ctx.type, 'text/html; charset=utf-8'); + assert.ok(typeof controller.ctx.body === 'string', '应返回 HTML 字符串'); + + const html = controller.ctx.body; + + // 文案与出站回调文档入口链接 + assert.ok(html.includes('完整报文体(奇门同层级 { request },与真实回调一致,可编辑)'), '应包含完整报文体标签文案'); + assert.ok(html.includes('/docs/api/openapi_callback'), '应包含出站回调文档入口链接'); + + // 事件切换时自动填充 { request } 一层包装结构(奇门同层级) + assert.ok(html.includes('request: found.request || {}'), '模板应包含 request 字段'); + assert.ok(!html.includes('event: found.name'), '模板不应再包含 event 外层字段'); + assert.ok(!html.includes('data: found.sampleData'), '模板不应再包含 data 外层字段'); + assert.ok(!html.includes('metadata: found.metadata'), '模板不应再包含 metadata 外层字段'); + + // 注册表 5 个事件名均注入页面 + for (const name of [ + 'entryorder.confirm', + 'entryorder.match', + 'deliveryorder.confirm', + 'stockout.confirm', + 'deliveryorder.cancel', + ]) { + assert.ok(html.includes(name), `页面应包含事件名 ${name}`); + } + + // 页面仍为秒级时间戳(与发送侧统一) + assert.ok(html.includes('Math.floor(Date.now() / 1000)'), '调试页 timestamp 应为秒级'); + }); +}); diff --git a/test/app/service/openapi/callback.event.rename.test.js b/test/app/service/openapi/callback.event.rename.test.js new file mode 100644 index 0000000..49d04e3 --- /dev/null +++ b/test/app/service/openapi/callback.event.rename.test.js @@ -0,0 +1,619 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const InboundDirectLogService = require('../../../../app/service/systems/inbound_direct_log'); +const ReceivingEntryMatchService = require('../../../../app/service/systems/receiving_entry_match'); +const OpenapiOrderService = require('../../../../app/service/openapiMethods/order'); +const OpenapiCallbackMethodService = require('../../../../app/service/openapiMethods/callback'); +const { CALLBACK_EVENTS } = require('../../../../app/service/openapi/callbackRegistry'); + +/** 项目根目录(test/app/service/openapi 上溯 4 级) */ +const PROJECT_ROOT = path.join(__dirname, '..', '..', '..', '..'); + +/** + * 读取项目内源码文件全文。 + * @param {string} relativePath 相对于项目根目录的文件路径。 + * @return {string} 源码文本。 + */ +function readSource(relativePath) { + return fs.readFileSync(path.join(PROJECT_ROOT, relativePath), 'utf8'); +} + +/** + * 递归收集对象/数组结构中的所有字段名(数组取其元素对象合并后的键集)。 + * @param {*} value 任意结构值。 + * @return {Set} 字段名集合。 + */ +function collectFieldNames(value) { + const names = new Set(); + + if (Array.isArray(value)) { + for (const item of value) { + for (const name of collectFieldNames(item)) { + names.add(name); + } + } + return names; + } + + if (value && typeof value === 'object') { + for (const [ key, child ] of Object.entries(value)) { + names.add(key); + for (const name of collectFieldNames(child)) { + names.add(name); + } + } + } + + return names; +} + +/** + * 创建静默 logger 桩。 + * @return {Object} logger 桩。 + */ +function createLogger() { + return { + info() {}, + warn() {}, + error() {}, + }; +} + +/** + * 临时静默 console.log,避免被测代码调试输出刷屏。 + * @param {Function} fn 执行体。 + * @return {Promise<*>} fn 的返回值。 + */ +async function withSilentConsole(fn) { + const original = console.log; + console.log = () => {}; + try { + return await fn(); + } finally { + console.log = original; + } +} + +/** + * 创建直入入库回传服务桩。 + * @param {Object} [options] 可选配置。 + * @return {{ service: Object, sendWithRetryCalls: Array, noticeCalls: Array }} 服务实例与调用记录。 + */ +function createInboundDirectService(options = {}) { + const sendWithRetryCalls = []; + const noticeCalls = []; + const ctx = { + logger: createLogger(), + user: null, + model: { + StoreWarehouse: { + async findOne() { + return { id: 1 }; + }, + }, + ApiApp: { + async findOne() { + return { + self_app_key: 'APP-KEY-1', + self_app_secret: 'SEC-1', + callback_url: 'http://cb.example.com/openapi', + }; + }, + }, + }, + service: { + openapi: { + callback: { + async sendWithRetry(callOptions) { + sendWithRetryCalls.push(callOptions); + if (typeof options.onSendWithRetry === 'function') { + return await options.onSendWithRetry(callOptions); + } + + return { success: true }; + }, + }, + }, + systems: { + notice: { + async send(payload) { + noticeCalls.push(payload); + return { success: true }; + }, + }, + }, + }, + }; + + const service = Object.create(InboundDirectLogService.prototype); + service.ctx = ctx; + service.app = { + Sequelize: { Op: { and: 'AND', ne: 'NE' } }, + formatDate() { + return '2026-09-12 10:00:00'; + }, + }; + // 通知文案明细查询降级为空,避免依赖模型层 + service._queryCompletedEntryItems = async () => []; + + return { service, sendWithRetryCalls, noticeCalls }; +} + +/** + * 创建入库单匹配收货回传服务桩。 + * @return {{ service: Object, sendWithRetryCalls: Array }} 服务实例与调用记录。 + */ +function createReceivingEntryMatchService() { + const sendWithRetryCalls = []; + const ctx = { + logger: createLogger(), + model: { + StoreWarehouse: { + async findOne() { + return { id: 9 }; + }, + }, + ApiApp: { + async findOne() { + return { + self_app_key: 'APP-KEY-2', + self_app_secret: 'SEC-2', + callback_url: 'http://cb2.example.com/openapi', + }; + }, + }, + EntryItems: { + async findAll() { + return [ + { item_code: 'SKU-1', item_id: '1001', count: 2, inventory_type: 'ZP', owner_code: 'OWNER-001', received_quantity: 2 }, + ]; + }, + }, + }, + service: { + openapi: { + callback: { + async sendWithRetry(callOptions) { + sendWithRetryCalls.push(callOptions); + return { success: true }; + }, + }, + }, + }, + }; + + const service = Object.create(ReceivingEntryMatchService.prototype); + service.ctx = ctx; + service.app = { + Sequelize: { Op: { and: 'AND', ne: 'NE' } }, + formatDate() { + return '2026-09-12 10:00:00'; + }, + }; + + return { service, sendWithRetryCalls }; +} + +/** + * 创建 openapi order.cancel 服务桩。 + * @return {{ service: Object, callbackCalls: Array, orderUpdates: Array }} 服务实例与调用记录。 + */ +function createOpenapiOrderService() { + const callbackCalls = []; + const orderUpdates = []; + const commitCalls = []; + const rollbackCalls = []; + const ctx = { + app: { config: {} }, + logger: createLogger(), + user: null, + model: { + async transaction() { + return { + LOCK: { UPDATE: 'UPDATE' }, + async commit() { commitCalls.push(1); }, + async rollback() { rollbackCalls.push(1); }, + }; + }, + OrderDeliveryFactory: { + async getCurrentModel() { + return { + async findOne() { + return { + id: 123, + delivery_order_code: 'TEST-ORDER-001', + wave_id: 0, + pick_status: 'none', + print_status: 'none', + async update(values, updateOptions) { + orderUpdates.push({ values, options: updateOptions }); + }, + }; + }, + }; + }, + }, + }, + service: { + openapi: { + callback: { + async sendByAppKey(callOptions) { + callbackCalls.push(callOptions); + return { success: true }; + }, + }, + }, + systemMethods: { + order: { + wave: {}, + }, + }, + systems: { + stockoutOrder: { + async cancel() { + return { code: 200, message: '取消出库单成功' }; + }, + }, + }, + }, + }; + + const service = new OpenapiOrderService(ctx); + service.setInfo(1000000, 100000, 'APP-KEY-1'); + // 储位锁定释放走桩,隔离模型依赖 + service.releaseStockLockForCancel = async () => {}; + + return { service, callbackCalls, orderUpdates, commitCalls }; +} + +/** + * 创建 openapi 回调测试方法服务桩。 + * @return {{ service: Object, callbackCalls: Array }} 服务实例与调用记录。 + */ +function createOpenapiCallbackMethodService() { + const callbackCalls = []; + const ctx = { + app: { config: {} }, + logger: createLogger(), + model: { + ApiApp: { + async findOne() { + return { self_app_key: 'APP-KEY-3' }; + }, + }, + }, + service: { + openapi: { + callback: { + async sendByAppKey(callOptions) { + callbackCalls.push(callOptions); + return { success: true }; + }, + }, + }, + }, + }; + + const service = new OpenapiCallbackMethodService(ctx); + + return { service, callbackCalls }; +} + +describe('test/app/service/openapi/callback.event.rename.test.js', () => { + it('inbound_direct_log 回传 method 应为 entryorder.confirm(request 对齐奇门报文)', async () => { + await withSilentConsole(async () => { + const { service, sendWithRetryCalls } = createInboundDirectService(); + const entryOrder = { + id: 543, + entry_order_code: 'RK-1', + store_id: 1000000, + warehouse_id: 100000, + }; + // 与 buildEntryOrderConfirmRequest 组装结果同层级:{ entryOrder, orderLines } + const request = { + entryOrder: { + entryOrderCode: 'RK-1', + ownerCode: '', + warehouseCode: '', + entryOrderId: 543, + entryOrderType: undefined, + outBizCode: 'DIRECT_INBOUND_1726131400000', + confirmType: 0, + status: 'FULFILLED', + freight: 0, + operateTime: '2026-09-12 10:00:00', + remark: '导入/PDA直接入库提交', + }, + orderLines: [ + { + orderLineNo: 1, + ownerCode: '', + itemCode: 'SKU-1', + itemId: '1001', + inventoryType: 'ZP', + planQty: 2, + actualQty: 2, + }, + ], + }; + + const result = await service._sendOpenApiCallback(entryOrder, { request }); + + assert.equal(result.success, true); + assert.equal(sendWithRetryCalls.length, 1); + assert.equal(sendWithRetryCalls[0].event, 'entryorder.confirm'); + assert.equal(sendWithRetryCalls[0].callbackUrl, 'http://cb.example.com/openapi'); + // 报文对齐奇门 request 层级,由发送端包装为 { request },不再携带 data/metadata + assert.deepEqual(sendWithRetryCalls[0].request, request); + assert.equal(Object.prototype.hasOwnProperty.call(sendWithRetryCalls[0], 'data'), false); + assert.equal(Object.prototype.hasOwnProperty.call(sendWithRetryCalls[0], 'metadata'), false); + }); + }); + + it('receiving_entry_match 回传 method 应为 entryorder.match(request 对齐奇门报文)', async () => { + const { service, sendWithRetryCalls } = createReceivingEntryMatchService(); + // 明细行桩与 EntryItems 模型桩解耦,避免并行修改时相互影响 + service._queryEntryOrderLines = async () => [ + { + orderLineNo: 1, + ownerCode: 'OWNER-001', + itemCode: 'SKU-1', + itemId: '1001', + inventoryType: 'ZP', + planQty: 2, + actualQty: 2, + }, + ]; + const entryOrder = { + id: 543, + entry_order_code: 'RK-2', + order_type: 'SCRK', + qimen_owner_code: 'OWNER-001', + qimen_warehouse_code: 'WH-100', + store_id: 1000000, + warehouse_id: 100000, + }; + const receivingOrder = { + id: 88, + receiving_number: 'RCV-88', + }; + + const result = await service._sendOpenApiCallback(entryOrder, receivingOrder, 'auto_match'); + + assert.equal(result.success, true); + assert.equal(sendWithRetryCalls.length, 1); + assert.equal(sendWithRetryCalls[0].event, 'entryorder.match'); + assert.equal(sendWithRetryCalls[0].callbackUrl, 'http://cb2.example.com/openapi'); + // 报文对齐奇门 request 层级,由发送端包装为 { request },不再携带 data/metadata + assert.equal(Object.prototype.hasOwnProperty.call(sendWithRetryCalls[0], 'data'), false); + assert.equal(Object.prototype.hasOwnProperty.call(sendWithRetryCalls[0], 'metadata'), false); + assert.deepEqual(sendWithRetryCalls[0].request, { + entryOrder: { + entryOrderCode: 'RK-2', + ownerCode: 'OWNER-001', + warehouseCode: 'WH-100', + entryOrderId: 543, + entryOrderType: 'SCRK', + outBizCode: sendWithRetryCalls[0].request.entryOrder.outBizCode, + confirmType: 0, + status: 'FULFILLED', + freight: 0, + operateTime: '2026-09-12 10:00:00', + remark: '匹配收货单RCV-88自动回传', + }, + orderLines: [ + { + orderLineNo: 1, + ownerCode: 'OWNER-001', + itemCode: 'SKU-1', + itemId: '1001', + inventoryType: 'ZP', + planQty: 2, + actualQty: 2, + }, + ], + }); + // outBizCode 动态生成,固定前缀 RECEIVING_MATCH_ + assert.match(sendWithRetryCalls[0].request.entryOrder.outBizCode, /^RECEIVING_MATCH_\d+$/); + }); + + it('openapi order.cancel 回调 method 应为 deliveryorder.cancel(与入站 order.cancel 区分)', async () => { + const { service, callbackCalls, orderUpdates, commitCalls } = createOpenapiOrderService(); + + const result = await service.cancel({ + body: { + orderCode: 'TEST-ORDER-001', + orderType: 'JYCK', + }, + query: { + app_key: 'APP-KEY-1', + }, + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.message, '取消订单成功'); + assert.equal(callbackCalls.length, 1); + assert.equal(callbackCalls[0].event, 'deliveryorder.cancel'); + assert.equal(callbackCalls[0].appKey, 'APP-KEY-1'); + assert.deepEqual(callbackCalls[0].request, { + deliveryOrder: { + deliveryOrderCode: 'TEST-ORDER-001', + orderType: 'JYCK', + status: 'CANCELED', + }, + }); + // 报文对齐奇门 request 层级:不再携带 data/metadata + assert.equal(Object.prototype.hasOwnProperty.call(callbackCalls[0], 'data'), false); + assert.equal(Object.prototype.hasOwnProperty.call(callbackCalls[0], 'metadata'), false); + assert.equal(commitCalls.length, 1); + assert.equal(orderUpdates.length, 1); + assert.equal(orderUpdates[0].values.status, 'cancel'); + }); + + it('openapiMethods/callback 测试方法默认 method 应为 deliveryorder.confirm', async () => { + const { service, callbackCalls } = createOpenapiCallbackMethodService(); + + const result = await service.test({ + body: { + request: { orderIds: [ 1 ] }, + }, + query: { + app_key: 'APP-KEY-3', + }, + }); + + assert.equal(result.flag, 'success'); + assert.equal(callbackCalls.length, 1); + assert.equal(callbackCalls[0].event, 'deliveryorder.confirm'); + assert.equal(callbackCalls[0].appKey, 'APP-KEY-3'); + // 去掉 data/metadata:只透传 request,由发送端包装为 { request } + assert.deepEqual(callbackCalls[0].request, { orderIds: [ 1 ] }); + assert.equal(Object.prototype.hasOwnProperty.call(callbackCalls[0], 'data'), false); + assert.equal(Object.prototype.hasOwnProperty.call(callbackCalls[0], 'metadata'), false); + }); + + it('notice 通道事件名 entry_order_completed 未被误改', async () => { + const { service, noticeCalls } = createInboundDirectService(); + + const result = await service.notifyEntryOrderCompleted({ + id: 543, + entry_order_code: 'RK-1', + warehouse_id: 100000, + store_id: 1000000, + }); + + assert.equal(noticeCalls.length, 1); + assert.equal(noticeCalls[0].event, 'entry_order_completed'); + assert.equal(noticeCalls[0].businessName, 'entry_order'); + assert.equal(noticeCalls[0].channel, 'warehouse'); + assert.equal(result.success, true); + }); + + it('CALLBACK_EVENTS 应包含 5 条且字段为 { name, label, description, request }', () => { + const names = CALLBACK_EVENTS.map(item => item.name); + assert.deepEqual(names, [ + 'entryorder.confirm', + 'entryorder.match', + 'deliveryorder.confirm', + 'stockout.confirm', + 'deliveryorder.cancel', + ]); + + for (const item of CALLBACK_EVENTS) { + assert.ok(item.name, '事件缺少 name'); + assert.ok(item.label, `${item.name} 缺少 label`); + assert.ok(item.description, `${item.name} 缺少 description`); + assert.ok(item.request && typeof item.request === 'object', `${item.name} 缺少 request`); + assert.equal( + Object.prototype.hasOwnProperty.call(item, 'sampleData'), + false, + `${item.name} 不应再有 sampleData 字段` + ); + assert.equal( + Object.prototype.hasOwnProperty.call(item, 'metadata'), + false, + `${item.name} 不应再有 metadata 字段` + ); + } + + const entryorderConfirm = CALLBACK_EVENTS.find(item => item.name === 'entryorder.confirm'); + assert.deepEqual(entryorderConfirm.request, { + entryOrder: { + entryOrderCode: 'RK20260912001', + ownerCode: 'OWNER-001', + warehouseCode: 'WH-100', + entryOrderId: 543, + entryOrderType: 'SCRK', + outBizCode: 'DIRECT_INBOUND_1726131400000', + confirmType: 0, + status: 'FULFILLED', + freight: 0, + operateTime: '2026-09-12 10:30:00', + remark: '导入/PDA直接入库提交', + }, + orderLines: [ + { + orderLineNo: 1, + ownerCode: 'OWNER-001', + itemCode: 'SKU-1', + itemId: '1001', + inventoryType: 'ZP', + planQty: 2, + actualQty: 2, + }, + ], + }); + }); + + it('各事件 request 顶层节点应与奇门报文同层级', () => { + const byName = Object.fromEntries(CALLBACK_EVENTS.map(item => [ item.name, item ])); + + // 奇门 taobao.qimen.entryorder.confirm:request 节点为 { entryOrder, orderLines } + assert.deepEqual(Object.keys(byName['entryorder.confirm'].request).sort(), [ 'entryOrder', 'orderLines' ]); + assert.deepEqual(Object.keys(byName['entryorder.match'].request).sort(), [ 'entryOrder', 'orderLines' ]); + + // 奇门 taobao.qimen.deliveryorder.confirm / stockout.confirm:request 节点为 { deliveryOrder, packages, orderLines } + assert.deepEqual( + Object.keys(byName['deliveryorder.confirm'].request).sort(), + [ 'deliveryOrder', 'orderLines', 'packages' ] + ); + assert.deepEqual( + Object.keys(byName['stockout.confirm'].request).sort(), + [ 'deliveryOrder', 'orderLines', 'packages' ] + ); + + // 无奇门对应接口:按 deliveryOrder 节点约定自定义 + assert.deepEqual(Object.keys(byName['deliveryorder.cancel'].request).sort(), [ 'deliveryOrder' ]); + assert.deepEqual(Object.keys(byName['deliveryorder.cancel'].request.deliveryOrder).sort(), [ + 'deliveryOrderCode', + 'orderType', + 'status', + ]); + }); + + it('各事件 request 字段名应与真实调用点源码一致', () => { + const sourceExpectations = [ + { + name: 'entryorder.confirm', + file: 'app/service/systems/inbound_direct_log.js', + }, + { + name: 'entryorder.match', + file: 'app/service/systems/receiving_entry_match.js', + }, + { + name: 'deliveryorder.confirm', + file: 'app/service/systems/order_async.js', + }, + { + name: 'stockout.confirm', + file: 'app/service/systems/order_async.js', + }, + { + // 无奇门对应接口:字段按 deliveryOrder 家族节点约定自定义, + // 已与真实调用点 app/service/openapiMethods/order.js 对齐 + name: 'deliveryorder.cancel', + file: 'app/service/openapiMethods/order.js', + }, + ]; + + const byName = Object.fromEntries(CALLBACK_EVENTS.map(item => [ item.name, item ])); + + for (const expectation of sourceExpectations) { + const event = byName[expectation.name]; + assert.ok(event, `注册表应存在事件 ${expectation.name}`); + + const source = readSource(expectation.file); + + for (const fieldName of collectFieldNames(event.request)) { + assert.ok( + source.includes(fieldName), + `${expectation.name}.request 字段 ${fieldName} 未在 ${expectation.file} 源码中出现` + ); + } + } + }); +}); diff --git a/test/app/service/openapi/callback.test.js b/test/app/service/openapi/callback.test.js new file mode 100644 index 0000000..726db36 --- /dev/null +++ b/test/app/service/openapi/callback.test.js @@ -0,0 +1,502 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const OpenapiCallbackService = require('../../../../app/service/openapi/callback'); + +/** + * 创建 OpenAPI 回调服务纯桩测试实例。 + * @param {Object} [options] 桩配置。 + * @param {Function} [options.curlImpl] ctx.curl 桩实现。 + * @param {Object} [options.loggerImpl] ctx.logger 桩实现。 + * @param {Function} [options.apiAppFindOne] ctx.model.ApiApp.findOne 桩实现。 + * @return {Object} 服务实例。 + */ +function createService({ curlImpl, loggerImpl, apiAppFindOne } = {}) { + const ctx = { + async curl(url, options) { + if (curlImpl) { + return await curlImpl(url, options); + } + + return { status: 200, data: {} }; + }, + logger: loggerImpl || { + info() {}, + warn() {}, + error() {}, + }, + model: { + ApiApp: { + async findOne() { + if (typeof apiAppFindOne === 'function') { + return await apiAppFindOne(); + } + + return null; + }, + }, + }, + }; + + const service = Object.create(OpenapiCallbackService.prototype); + service.ctx = ctx; + service.app = {}; + return service; +} + +/** + * 临时替换 console.log 并收集输出,执行完后恢复。 + * @param {Function} fn 执行体,入参为收集到的日志数组。 + * @return {*} fn 的返回值。 + */ +async function captureConsoleLog(fn) { + const logs = []; + const original = console.log; + console.log = (...args) => { + logs.push(args.map(String).join(' ')); + }; + try { + return await fn(logs); + } finally { + console.log = original; + } +} + +/** + * 临时将全局 setTimeout 降为 0 延迟,避免测试等待重试间隔。 + * @param {Function} fn 执行体。 + * @return {*} fn 的返回值。 + */ +async function withFastRetryDelay(fn) { + const originalSetTimeout = global.setTimeout; + global.setTimeout = (callback, ...args) => originalSetTimeout(callback, 0, ...args); + try { + return await fn(); + } finally { + global.setTimeout = originalSetTimeout; + } +} + +/** 默认回调入参 */ +const DEFAULT_OPTIONS = { + callbackUrl: 'http://callback.example.com/openapi', + appKey: 'WMS-TEST-APP-KEY', + selfAppSecret: 'test-secret', + event: 'entryorder.confirm', + request: { entryOrderId: 543 }, +}; + +describe('test/app/service/openapi/callback.test.js', () => { + describe('sendWithRetry 成功分支', () => { + it('2xx 时应打印成功日志且返回结构与重试次数不变', async () => { + await captureConsoleLog(async collected => { + const curlCalls = []; + const service = createService({ + curlImpl: async () => { + curlCalls.push(1); + return { status: 200, data: { code: 'OK', data: { accepted: true } } }; + }, + }); + + const result = await withFastRetryDelay(() => service.sendWithRetry(DEFAULT_OPTIONS)); + + assert.equal(curlCalls.length, 1); + assert.deepEqual(result, { + success: true, + retryCount: 0, + response: { code: 'OK', data: { accepted: true } }, + error: null, + }); + + const successLine = collected.find(line => line.includes('success=true')); + assert.ok(successLine, '应存在成功日志行'); + assert.match(successLine, /event=entryorder\.confirm/); + assert.match(successLine, /appKey=WMS-TEST-APP-KEY/); + assert.match(successLine, /retry=0/); + assert.match(successLine, /status=200/); + assert.match(successLine, /response=\{/); + }); + }); + }); + + describe('sendWithRetry 非 2xx 分支', () => { + it('400 且响应为 JSON 对象时应打印可解析的报文内容', async () => { + await captureConsoleLog(async collected => { + let curlCalls = 0; + const service = createService({ + curlImpl: async () => { + curlCalls += 1; + return { status: 400, data: { code: 400, message: '参数错误', field: 'entryOrderId' } }; + }, + }); + + const result = await withFastRetryDelay(() => service.sendWithRetry(DEFAULT_OPTIONS)); + + assert.equal(result.success, false); + assert.equal(result.retryCount, 3); + assert.equal(curlCalls, 4); + assert.deepEqual(result.response, { code: 400, message: '参数错误', field: 'entryOrderId' }); + assert.equal(result.error, '回调返回非 2xx 状态码: 400'); + + const failLine = collected.find(line => line.includes('status=400')); + assert.ok(failLine, '应存在非 2xx 日志行'); + assert.match(failLine, /success=false/); + + // 提取 response= 之后的内容并确认是合法 JSON + const payloadText = failLine.slice(failLine.indexOf('response=') + 'response='.length); + const parsed = JSON.parse(payloadText); + assert.deepEqual(parsed, { code: 400, message: '参数错误', field: 'entryOrderId' }); + }); + }); + + it('400 且响应为纯字符串时应原样打印报文', async () => { + await captureConsoleLog(async collected => { + let curlCalls = 0; + const service = createService({ + curlImpl: async () => { + curlCalls += 1; + return { status: 400, data: 'plain text error body' }; + }, + }); + + const result = await withFastRetryDelay(() => service.sendWithRetry(DEFAULT_OPTIONS)); + + assert.equal(result.success, false); + assert.equal(result.retryCount, 3); + assert.equal(curlCalls, 4); + + const failLine = collected.find(line => line.includes('status=400')); + assert.ok(failLine, '应存在非 2xx 日志行'); + assert.ok(failLine.includes('response=plain text error body'), `日志应原样包含纯字符串报文,实际: ${failLine}`); + }); + }); + }); + + describe('sendWithRetry 异常分支', () => { + it('curl 抛异常时应打印 url 与 error.message', async () => { + await captureConsoleLog(async collected => { + let curlCalls = 0; + const service = createService({ + curlImpl: async () => { + curlCalls += 1; + throw new Error('connect ECONNREFUSED 127.0.0.1:9999'); + }, + }); + + const result = await withFastRetryDelay(() => service.sendWithRetry(DEFAULT_OPTIONS)); + + assert.equal(result.success, false); + assert.equal(result.retryCount, 3); + assert.equal(curlCalls, 4); + assert.equal(result.error, 'connect ECONNREFUSED 127.0.0.1:9999'); + assert.equal(result.response, null); + + const failLine = collected.find(line => line.includes('connect ECONNREFUSED')); + assert.ok(failLine, '应存在异常日志行'); + assert.match(failLine, /url=http:\/\/callback\.example\.com\/openapi/); + assert.match(failLine, /success=false/); + assert.ok(failLine.includes('response=null')); + }); + }); + }); + + describe('_formatResponsePayload 类型兼容', () => { + it('对象 / 字符串 / null 均不抛异常且输出符合预期', () => { + const service = createService(); + + assert.equal(service._formatResponsePayload({ a: 1 }), '{"a":1}'); + assert.equal(service._formatResponsePayload('hello'), 'hello'); + assert.equal(service._formatResponsePayload(null), 'null'); + assert.equal(service._formatResponsePayload(undefined), 'null'); + assert.equal(service._formatResponsePayload(123), '123'); + }); + + it('Buffer / ArrayBuffer / TypedArray 应按 utf8 转换', () => { + const service = createService(); + + assert.equal(service._formatResponsePayload(Buffer.from('buf-body')), 'buf-body'); + assert.equal(service._formatResponsePayload(Uint8Array.from(Buffer.from('typed-body'))), 'typed-body'); + const arrayBuffer = Uint8Array.from(Buffer.from('ab-body')).buffer; + assert.equal(service._formatResponsePayload(arrayBuffer), 'ab-body'); + }); + + it('循环引用对象应降级为 String 而不抛异常', () => { + const service = createService(); + const circular = {}; + circular.self = circular; + + assert.doesNotThrow(() => service._formatResponsePayload(circular)); + assert.equal(service._formatResponsePayload(circular), '[object Object]'); + }); + + it('超长字符串应截断并追加标记', () => { + const service = createService(); + const longText = 'x'.repeat(800); + const formatted = service._formatResponsePayload(longText); + + assert.equal(formatted.length, 500 + '...(truncated)'.length); + assert.ok(formatted.startsWith('x'.repeat(500))); + assert.ok(formatted.endsWith('...(truncated)')); + assert.ok(!formatted.includes('x'.repeat(501))); + }); + }); + + describe('sendWithRetry 回调 URL 拼装', () => { + it('URL 中 method 应带 . 且 sign 基于新 query 重算', async () => { + await captureConsoleLog(async () => { + let capturedUrl = null; + let capturedBody = null; + const service = createService({ + curlImpl: async (url, options) => { + capturedUrl = url; + capturedBody = options.data; + return { status: 200, data: {} }; + }, + }); + + const result = await withFastRetryDelay(() => service.sendWithRetry(DEFAULT_OPTIONS)); + + assert.equal(result.success, true); + assert.ok(capturedUrl, '应捕获到回调 URL'); + assert.ok(capturedUrl.includes('method=entryorder.confirm'), `URL 的 method 应为新名并包含 .,实际: ${capturedUrl}`); + + const parsedUrl = new URL(capturedUrl); + const sign = parsedUrl.searchParams.get('sign'); + assert.ok(sign, 'URL 应包含 sign 参数'); + + // 不硬编码 sign:按 signCallback 对 { request } 新报文体重算并比对 + const { sign: expectedSign } = service.signCallback({ + event: DEFAULT_OPTIONS.event, + appKey: DEFAULT_OPTIONS.appKey, + selfAppSecret: DEFAULT_OPTIONS.selfAppSecret, + body: capturedBody, + timestamp: parsedUrl.searchParams.get('timestamp'), + }); + assert.equal(sign, expectedSign); + }); + }); + }); + + describe('sendWithRetry 报文体', () => { + it('发出的报文体恰为 { request: {...} },且不含 event/data/metadata 顶层键', async () => { + await captureConsoleLog(async () => { + let capturedBody = null; + const service = createService({ + curlImpl: async (url, options) => { + capturedBody = options.data; + return { status: 200, data: {} }; + }, + }); + + const result = await withFastRetryDelay(() => service.sendWithRetry(DEFAULT_OPTIONS)); + + assert.equal(result.success, true); + assert.deepEqual(capturedBody, { request: { entryOrderId: 543 } }); + assert.ok(Object.prototype.hasOwnProperty.call(capturedBody, 'request')); + assert.equal(Object.prototype.hasOwnProperty.call(capturedBody, 'event'), false); + assert.equal(Object.prototype.hasOwnProperty.call(capturedBody, 'data'), false); + assert.equal(Object.prototype.hasOwnProperty.call(capturedBody, 'metadata'), false); + }); + }); + + it('request 缺省时报文体应为 { request: {} }', async () => { + await captureConsoleLog(async () => { + let capturedBody = null; + const service = createService({ + curlImpl: async (url, options) => { + capturedBody = options.data; + return { status: 200, data: {} }; + }, + }); + + await withFastRetryDelay(() => service.sendWithRetry({ + callbackUrl: DEFAULT_OPTIONS.callbackUrl, + appKey: DEFAULT_OPTIONS.appKey, + selfAppSecret: DEFAULT_OPTIONS.selfAppSecret, + event: DEFAULT_OPTIONS.event, + })); + + assert.deepEqual(capturedBody, { request: {} }); + }); + }); + + it('遗留的 data/metadata 入参应被忽略,不做兼容', async () => { + await captureConsoleLog(async () => { + let capturedBody = null; + const service = createService({ + curlImpl: async (url, options) => { + capturedBody = options.data; + return { status: 200, data: {} }; + }, + }); + + await withFastRetryDelay(() => service.sendWithRetry({ + ...DEFAULT_OPTIONS, + data: { legacy: true }, + metadata: { legacy: true }, + })); + + assert.deepEqual(capturedBody, { request: { entryOrderId: 543 } }); + assert.equal(Object.prototype.hasOwnProperty.call(capturedBody, 'data'), false); + assert.equal(Object.prototype.hasOwnProperty.call(capturedBody, 'metadata'), false); + }); + }); + }); + + describe('sendByAppKey 报文体', () => { + it('经 ApiApp 解析后发出的报文体恰为 { request: {...} },sign 基于新 body 实时重算', async () => { + await captureConsoleLog(async () => { + let capturedUrl = null; + let capturedBody = null; + const service = createService({ + apiAppFindOne: async () => ({ + self_app_key: 'WMS-TEST-APP-KEY', + self_app_secret: 'test-secret', + callback_url: 'http://callback.example.com/openapi', + }), + curlImpl: async (url, options) => { + capturedUrl = url; + capturedBody = options.data; + return { status: 200, data: {} }; + }, + }); + + const result = await withFastRetryDelay(() => service.sendByAppKey({ + appKey: 'WMS-TEST-APP-KEY', + event: 'deliveryorder.confirm', + request: { deliveryOrder: { deliveryOrderCode: 'DO-1', status: 'DELIVERED' } }, + })); + + assert.equal(result.success, true); + assert.deepEqual(capturedBody, { + request: { deliveryOrder: { deliveryOrderCode: 'DO-1', status: 'DELIVERED' } }, + }); + assert.equal(Object.prototype.hasOwnProperty.call(capturedBody, 'event'), false); + assert.equal(Object.prototype.hasOwnProperty.call(capturedBody, 'data'), false); + assert.equal(Object.prototype.hasOwnProperty.call(capturedBody, 'metadata'), false); + + const parsedUrl = new URL(capturedUrl); + assert.ok(parsedUrl.searchParams.get('method') === 'deliveryorder.confirm'); + + const { sign: expectedSign } = service.signCallback({ + event: 'deliveryorder.confirm', + appKey: 'WMS-TEST-APP-KEY', + selfAppSecret: 'test-secret', + body: capturedBody, + timestamp: parsedUrl.searchParams.get('timestamp'), + }); + assert.equal(parsedUrl.searchParams.get('sign'), expectedSign); + }); + }); + + it('缺少 appKey 时应返回失败且不访问模型', async () => { + const service = createService(); + + const result = await service.sendByAppKey({ + appKey: ' ', + event: 'deliveryorder.confirm', + request: {}, + }); + + assert.equal(result.success, false); + assert.equal(result.error, '缺少 appKey'); + assert.equal(result.retryCount, 0); + assert.equal(result.response, null); + }); + + it('未找到有效回调配置时应返回失败', async () => { + const service = createService({ + apiAppFindOne: async () => null, + }); + + const result = await service.sendByAppKey({ + appKey: 'WMS-TEST-APP-KEY', + event: 'deliveryorder.confirm', + request: {}, + }); + + assert.equal(result.success, false); + assert.equal(result.error, '未找到有效的回调配置'); + assert.equal(result.retryCount, 0); + }); + }); + + describe('sendWithRetry 时间戳', () => { + it('timestamp 应为 10 位秒级字符串且与当前服务器秒数一致', async () => { + await captureConsoleLog(async () => { + let capturedUrl = null; + const service = createService({ + curlImpl: async url => { + capturedUrl = url; + return { status: 200, data: {} }; + }, + }); + + const beforeSeconds = Math.floor(Date.now() / 1000); + await withFastRetryDelay(() => service.sendWithRetry(DEFAULT_OPTIONS)); + const afterSeconds = Math.floor(Date.now() / 1000); + + assert.ok(capturedUrl, '应捕获到回调 URL'); + const timestamp = new URL(capturedUrl).searchParams.get('timestamp'); + assert.match(timestamp, /^\d{10}$/, 'timestamp 应为 10 位数字字符串'); + const ts = Number(timestamp); + assert.ok( + ts >= beforeSeconds && ts <= afterSeconds, + `timestamp=${ts} 应落在 [${beforeSeconds}, ${afterSeconds}] 区间内(秒级)` + ); + }); + }); + }); + + describe('logCallback 报文输出', () => { + it('成功分支应输出响应报文', async () => { + const records = []; + const service = createService({ + loggerImpl: { + info(line) { records.push({ level: 'info', line }); }, + warn() {}, + error() {}, + }, + }); + + await service.logCallback({ + appKey: 'WMS-TEST-APP-KEY', + event: 'deliveryorder.confirm', + callbackUrl: 'http://callback.example.com/openapi', + success: true, + retryCount: 0, + response: { ok: true }, + }); + + assert.equal(records.length, 1); + assert.equal(records[0].level, 'info'); + assert.match(records[0].line, /response=\{"ok":true\}/); + }); + + it('末次重试失败分支应输出报文与错误信息', async () => { + const records = []; + const service = createService({ + loggerImpl: { + info() {}, + warn() {}, + error(line) { records.push({ level: 'error', line }); }, + }, + }); + + await service.logCallback({ + appKey: 'WMS-TEST-APP-KEY', + event: 'deliveryorder.confirm', + callbackUrl: 'http://callback.example.com/openapi', + success: false, + retryCount: 3, + response: 'error body', + error: '回调返回非 2xx 状态码: 400', + }); + + assert.equal(records.length, 1); + assert.equal(records[0].level, 'error'); + assert.match(records[0].line, /response=error body/); + assert.match(records[0].line, /error=回调返回非 2xx 状态码: 400/); + }); + }); +}); diff --git a/test/app/service/openapiMethods/order.cancel.test.js b/test/app/service/openapiMethods/order.cancel.test.js new file mode 100644 index 0000000..4ccd0b3 --- /dev/null +++ b/test/app/service/openapiMethods/order.cancel.test.js @@ -0,0 +1,179 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const OpenapiOrderService = require('../../../../app/service/openapiMethods/order'); + +/** + * 创建 openapi order.cancel 测试桩(纯桩,不访问真实数据库)。 + * + * @param {Object} [options] 可选配置。 + * @param {Function} [options.onSendByAppKey] OpenAPI 回调桩实现。 + * @param {Object} [options.existingOrder] 已存在订单记录(raw)。 + * @return {Object} 服务实例与回调调用记录。 + */ +function createHarness(options = {}) { + const callbackCalls = []; + + const ctx = { + app: { + config: {}, + Sequelize: { + Op: { + ne: Symbol('ne'), + }, + }, + }, + model: { + async transaction() { + return { + LOCK: { UPDATE: Symbol('UPDATE') }, + async rollback() { + return undefined; + }, + async commit() { + return undefined; + }, + }; + }, + OrderDeliveryFactory: { + async getCurrentModel() { + return { + async findOne() { + return { + ...(options.existingOrder || { + id: 9001, + delivery_order_code: 'DO-CANCEL-1', + warehouse_id: 100000, + store_id: 1000000, + pick_status: 'none', + print_status: 'none', + wave_id: 0, + inspection_status: 'none', + weighing_weight: 0, + intercept_time: null, + }), + async update() { + return [ 1 ]; + }, + }; + }, + async update() { + return [ 1 ]; + }, + }; + }, + }, + OrderItemsFactory: { + async getCurrentModel() { + return { + async findAll() { + return []; + }, + }; + }, + }, + Picking: { + async findAll() { + return []; + }, + }, + OperationLog: { + async create() { + return {}; + }, + }, + }, + service: { + openapi: { + callback: { + async sendByAppKey(callOptions) { + callbackCalls.push(callOptions); + if (typeof options.onSendByAppKey === 'function') { + return await options.onSendByAppKey(callOptions); + } + + return { success: true }; + }, + }, + }, + systemMethods: { + order: { + wave: { + async deleteOrderWaveIndexByOrderIds() { + return undefined; + }, + async replaceOrderWaveIndexByWaveIds() { + return undefined; + }, + }, + }, + }, + systems: { + afterSale: { + async createInterceptWorkOrdersAndNotify() { + return undefined; + }, + }, + }, + }, + user: {}, + logger: { + info() {}, + warn() {}, + error() {}, + }, + }; + + const service = new OpenapiOrderService(ctx); + service.setInfo(1000000, 100000, 'APP-KEY-C', null, 'WH-100'); + + return { service, callbackCalls }; +} + +describe('test/app/service/openapiMethods/order.cancel.test.js', () => { + it('取消成功应发送 deliveryorder.cancel 回调,request.deliveryOrder 按约定组装', async () => { + const { service, callbackCalls } = createHarness(); + + const result = await service.cancel({ + body: { + orderCode: ' DO-CANCEL-1 ', + orderType: 'jyck', + }, + query: {}, + }); + + assert.equal(result.flag, 'success'); + assert.equal(callbackCalls.length, 1); + + const call = callbackCalls[0]; + assert.equal(call.event, 'deliveryorder.cancel'); + assert.equal(call.appKey, 'APP-KEY-C'); + assert.equal(call.data, undefined); + assert.equal(call.metadata, undefined); + assert.deepEqual(call.request, { + deliveryOrder: { + deliveryOrderCode: 'DO-CANCEL-1', + orderType: 'JYCK', + status: 'CANCELED', + }, + }); + }); + + it('回调发送失败不应影响取消主流程(fire-and-forget)', async () => { + const { service } = createHarness({ + onSendByAppKey() { + throw new Error('callback down'); + }, + }); + + const result = await service.cancel({ + body: { + orderCode: 'DO-CANCEL-1', + orderType: 'JYCK', + }, + query: {}, + }); + + assert.equal(result.flag, 'success'); + }); +}); diff --git a/test/app/service/systems/inbound_direct_log.callback.test.js b/test/app/service/systems/inbound_direct_log.callback.test.js new file mode 100644 index 0000000..aa9fc58 --- /dev/null +++ b/test/app/service/systems/inbound_direct_log.callback.test.js @@ -0,0 +1,412 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const InboundDirectLogService = require('../../../../app/service/systems/inbound_direct_log'); + +/** + * 构建入库单桩实例。 + * @param {Object} [overrides] 覆盖字段。 + * @param {Array} [updateLog] 收集 entryOrder.update 调用的数组。 + * @return {Object} 入库单桩实例。 + */ +function buildEntryOrder(overrides = {}, updateLog = []) { + return { + id: 1001, + entry_order_code: 'RK-1001', + source_type: 'API', + order_type: 'CGRK', + warehouse_id: 100000, + store_id: 1000000, + qimen_owner_code: 'OWNER-1', + qimen_warehouse_code: 'WH-1', + async update(values, options) { + updateLog.push({ values, options }); + return [ 1 ]; + }, + ...overrides, + }; +} + +/** + * 构建入库明细行(奇门 orderLines 结构)。 + * @return {Array} 明细行数组。 + */ +function buildOrderLines() { + return [ + { orderLineNo: 1, ownerCode: 'OWNER-1', itemCode: 'SKU-1', itemId: 'ITEM-1', inventoryType: 'ZP', planQty: 2, actualQty: 2 }, + { orderLineNo: 2, ownerCode: 'OWNER-1', itemCode: 'SKU-2', itemId: '', inventoryType: 'ZP', planQty: 1, actualQty: 0 }, + ]; +} + +/** + * 创建纯桩测试环境:不访问数据库、不依赖 Egg 上下文。 + * @param {Object} [options] 可选配置。 + * @param {Function} [options.onQimenSend] 奇门发送桩实现。 + * @param {Function} [options.onSendWithRetry] OpenAPI 回调桩实现。 + * @return {Object} 服务实例、上下文与各调用记录。 + */ +function createHarness(options = {}) { + const logs = { info: [], warn: [], error: [] }; + const sends = []; + const openApiSends = []; + const operationLogs = []; + const commits = []; + const rollbacks = []; + + const ctx = { + app: { + Sequelize: { + Op: { + in: Symbol('in'), + ne: Symbol('ne'), + and: Symbol('and'), + }, + }, + formatDate() { + return '2026-09-12 10:00:00'; + }, + qimenClient: { + async send(method, ownerCode, queryData, sendOptions) { + sends.push({ method, ownerCode, queryData, options: sendOptions }); + if (typeof options.onQimenSend === 'function') { + return await options.onQimenSend(method, ownerCode, queryData, sendOptions); + } + return { xmlArray: { response: { flag: 'success', message: 'ok' } } }; + }, + }, + }, + model: { + async transaction() { + return { + async commit() { commits.push(1); }, + async rollback() { rollbacks.push(1); }, + }; + }, + StoreWarehouse: { + async findOne() { + return { id: 1 }; + }, + }, + ApiApp: { + async findOne() { + return { + self_app_key: 'APP-KEY', + self_app_secret: 'SECRET', + callback_url: 'https://cb.example.com/hook', + }; + }, + }, + }, + service: { + openapi: { + callback: { + async sendWithRetry(payload) { + openApiSends.push(payload); + if (typeof options.onSendWithRetry === 'function') { + return await options.onSendWithRetry(payload); + } + return { success: true, retryCount: 0 }; + }, + }, + }, + systems: { + operationLog: { + async createOperationLog(payload) { + operationLogs.push(payload); + }, + }, + }, + }, + logger: { + info(...args) { + logs.info.push(args.join(' ')); + }, + warn(...args) { + logs.warn.push(args.join(' ')); + }, + error(...args) { + logs.error.push(args.join(' ')); + }, + }, + }; + + const service = new InboundDirectLogService(ctx); + + return { + service, + ctx, + logs, + sends, + openApiSends, + operationLogs, + commits, + rollbacks, + }; +} + +/** + * 临时静默 console.log,避免被测代码调试输出刷屏。 + * @param {Function} fn 执行体。 + * @return {Promise<*>} fn 的返回值。 + */ +async function withSilentConsole(fn) { + const original = console.log; + console.log = () => {}; + try { + return await fn(); + } finally { + console.log = original; + } +} + +describe('test/app/service/systems/inbound_direct_log.callback.test.js', () => { + it('QM 分支奇门报文逐字段不变(entryOrder + orderLines 快照一致)', async () => { + await withSilentConsole(async () => { + const harness = createHarness(); + const onSuccessCalls = []; + const entryOrder = buildEntryOrder({ source_type: 'QM' }); + const orderLines = buildOrderLines(); + + const result = await harness.service.qimenEntrySync({ + entryOrder, + orderLines, + outBizCode: 'DIRECT_INBOUND_12345', + remark: '导入/PDA直接入库提交', + isFin: true, + onSuccess: async eo => { + onSuccessCalls.push(eo); + }, + operator: { id: 1, name: '张三' }, + }); + + assert.equal(result.success, true); + assert.equal(result.message, '同步成功'); + assert.equal(onSuccessCalls.length, 1); + assert.equal(onSuccessCalls[0], entryOrder); + assert.equal(harness.openApiSends.length, 0); + assert.equal(harness.sends.length, 1); + + const sent = harness.sends[0]; + assert.equal(sent.method, 'taobao.qimen.entryorder.confirm'); + assert.equal(sent.ownerCode, 'OWNER-1'); + assert.equal(sent.options.ctx, harness.ctx); + assert.deepEqual(sent.queryData, { + request: { + entryOrder: { + entryOrderCode: 'RK-1001', + ownerCode: 'OWNER-1', + warehouseCode: 'WH-1', + entryOrderId: 1001, + entryOrderType: 'CGRK', + outBizCode: 'DIRECT_INBOUND_12345', + confirmType: 0, + status: 'FULFILLED', + freight: 0, + operateTime: '2026-09-12 10:00:00', + remark: '导入/PDA直接入库提交', + }, + orderLines, + }, + }); + }); + }); + + it('QM 部分确认 isFin=false 时 confirmType=1 且 status=PARTFULFILLED', async () => { + await withSilentConsole(async () => { + const harness = createHarness(); + const onSuccessCalls = []; + + const result = await harness.service.qimenEntrySync({ + entryOrder: buildEntryOrder({ source_type: 'QM' }), + orderLines: buildOrderLines(), + outBizCode: 'DIRECT_INBOUND_12345', + remark: '导入/PDA直接入库提交', + isFin: false, + onSuccess: async () => { + onSuccessCalls.push(1); + }, + operator: { id: 1, name: '张三' }, + }); + + assert.equal(result.success, true); + assert.equal(onSuccessCalls.length, 1); + assert.equal(harness.sends.length, 1); + assert.equal(harness.sends[0].queryData.request.entryOrder.confirmType, 1); + assert.equal(harness.sends[0].queryData.request.entryOrder.status, 'PARTFULFILLED'); + }); + }); + + it('QM 缺省 ownerCode/warehouseCode/outBizCode/remark 时按兜底写法组装,不查库', async () => { + await withSilentConsole(async () => { + const harness = createHarness(); + + await harness.service.qimenEntrySync({ + entryOrder: buildEntryOrder({ + source_type: 'QM', + qimen_owner_code: null, + qimen_warehouse_code: null, + }), + orderLines: buildOrderLines(), + onSuccess: async () => {}, + }); + + assert.equal(harness.sends.length, 1); + const entryOrder = harness.sends[0].queryData.request.entryOrder; + assert.equal(entryOrder.ownerCode, ''); + assert.equal(entryOrder.warehouseCode, ''); + assert.match(entryOrder.outBizCode, /^DIRECT_INBOUND_\d+$/); + assert.equal(entryOrder.remark, ''); + }); + }); + + it('API 分支回传 event=entryorder.confirm,request 结构与奇门同层级且无 data/metadata 顶层键', async () => { + await withSilentConsole(async () => { + const harness = createHarness(); + const onSuccessCalls = []; + const orderLines = buildOrderLines(); + + const result = await harness.service.qimenEntrySync({ + entryOrder: buildEntryOrder({ source_type: 'API' }), + orderLines, + outBizCode: 'DIRECT_INBOUND_12345', + remark: '导入/PDA直接入库提交', + isFin: true, + onSuccess: async () => { + onSuccessCalls.push(1); + }, + operator: { id: 1, name: '张三' }, + }); + + assert.equal(result.success, true); + assert.equal(onSuccessCalls.length, 1); + assert.equal(harness.sends.length, 0); + assert.equal(harness.openApiSends.length, 1); + + const sent = harness.openApiSends[0]; + assert.equal(sent.event, 'entryorder.confirm'); + assert.equal(sent.callbackUrl, 'https://cb.example.com/hook'); + assert.equal(sent.appKey, 'APP-KEY'); + assert.equal(sent.selfAppSecret, 'SECRET'); + assert.equal(sent.data, undefined); + assert.equal(sent.metadata, undefined); + assert.deepEqual(Object.keys(sent.request).sort(), [ 'entryOrder', 'orderLines' ]); + assert.deepEqual(sent.request.entryOrder, { + entryOrderCode: 'RK-1001', + ownerCode: 'OWNER-1', + warehouseCode: 'WH-1', + entryOrderId: 1001, + entryOrderType: 'CGRK', + outBizCode: 'DIRECT_INBOUND_12345', + confirmType: 0, + status: 'FULFILLED', + freight: 0, + operateTime: '2026-09-12 10:00:00', + remark: '导入/PDA直接入库提交', + }); + assert.deepEqual(sent.request.orderLines, orderLines); + }); + }); + + it('同一入参下 API 与 QM 的报文逐字段一致', async () => { + await withSilentConsole(async () => { + const harness = createHarness(); + const paramsBase = { + orderLines: buildOrderLines(), + outBizCode: 'DIRECT_INBOUND_12345', + remark: '导入/PDA直接入库提交', + isFin: true, + onSuccess: async () => {}, + }; + + await harness.service.qimenEntrySync({ + entryOrder: buildEntryOrder({ source_type: 'QM' }), + ...paramsBase, + }); + await harness.service.qimenEntrySync({ + entryOrder: buildEntryOrder({ source_type: 'API' }), + ...paramsBase, + }); + + assert.equal(harness.sends.length, 1); + assert.equal(harness.openApiSends.length, 1); + assert.deepEqual( + harness.openApiSends[0].request, + harness.sends[0].queryData.request + ); + }); + }); + + it('API 回传失败时返回失败并写 FAILED 状态与操作日志,不执行 onSuccess', async () => { + await withSilentConsole(async () => { + const harness = createHarness({ + onSendWithRetry: async () => ({ success: false, error: '回调被拒' }), + }); + const updateLog = []; + const onSuccessCalls = []; + + const result = await harness.service.qimenEntrySync({ + entryOrder: buildEntryOrder({ source_type: 'API' }, updateLog), + orderLines: buildOrderLines(), + outBizCode: 'DIRECT_INBOUND_12345', + remark: '导入/PDA直接入库提交', + isFin: true, + onSuccess: async () => { + onSuccessCalls.push(1); + }, + operator: { id: 1, name: '张三' }, + }); + + assert.equal(result.success, false); + assert.equal(result.message.includes('回调被拒'), true); + assert.equal(onSuccessCalls.length, 0); + assert.equal(updateLog.length, 1); + assert.equal(updateLog[0].values.sync_status, 'FAILED'); + assert.equal(JSON.parse(updateLog[0].values.sync_message).errorCode, 'API_FAILED'); + assert.equal(harness.operationLogs.length, 1); + assert.equal(harness.operationLogs[0].operationCode, 'QUICK_INBOUND_FAILED'); + assert.equal(harness.commits.length, 1); + assert.equal(harness.rollbacks.length, 0); + }); + }); + + it('行不能为空时直接返回失败,不发任何回传', async () => { + await withSilentConsole(async () => { + const harness = createHarness(); + const onSuccessCalls = []; + + const result = await harness.service.qimenEntrySync({ + entryOrder: buildEntryOrder({ source_type: 'QM' }), + orderLines: [], + onSuccess: async () => { + onSuccessCalls.push(1); + }, + }); + + assert.equal(result.success, false); + assert.equal(result.message, '行不能为空'); + assert.equal(onSuccessCalls.length, 0); + assert.equal(harness.sends.length, 0); + assert.equal(harness.openApiSends.length, 0); + }); + }); + + it('非 QM/API 来源跳过回传并直接执行回调', async () => { + await withSilentConsole(async () => { + const harness = createHarness(); + const onSuccessCalls = []; + + const result = await harness.service.qimenEntrySync({ + entryOrder: buildEntryOrder({ source_type: 'WMS' }), + orderLines: buildOrderLines(), + onSuccess: async () => { + onSuccessCalls.push(1); + }, + }); + + assert.equal(result.success, true); + assert.equal(onSuccessCalls.length, 1); + assert.equal(harness.sends.length, 0); + assert.equal(harness.openApiSends.length, 0); + }); + }); +}); diff --git a/test/app/service/systems/order_async.openapi.callback.test.js b/test/app/service/systems/order_async.openapi.callback.test.js new file mode 100644 index 0000000..327b16b --- /dev/null +++ b/test/app/service/systems/order_async.openapi.callback.test.js @@ -0,0 +1,500 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const OrderAsyncService = require('../../../../app/service/systems/order_async'); + +/** + * 轮询等待条件成立(fire-and-forget 回调为异步触发)。 + * + * @param {Function} predicate 条件函数。 + * @param {number} [timeoutMs] 超时时间(毫秒)。 + * @return {Promise} 条件成立或超时后返回。 + */ +async function waitFor(predicate, timeoutMs = 500) { + const startAt = Date.now(); + while (!predicate()) { + if (Date.now() - startAt > timeoutMs) { + return; + } + + await new Promise(resolve => setTimeout(resolve, 5)); + } +} + +/** + * 创建订单异步服务测试桩(覆盖 OpenAPI 回调与 notice 通道断言)。 + * @param {Object} [options] 可选配置。 + * @param {Array} [options.orderRows] 订单主表记录(raw)。 + * @param {Array} [options.orderItems] 订单明细记录(raw)。 + * @param {Array} [options.orderExpressRows] 运单号记录(raw)。 + * @param {Object} [options.stockoutOrder] 出库单主表记录(raw)。 + * @param {Function} [options.onSendByAppKey] OpenAPI 回调桩实现。 + * @param {Function} [options.onOutbound] 库存扣减桩实现(可模拟失败订单)。 + * @param {boolean} [options.omitNoticeService] 是否省略 notice 服务。 + * @return {Object} 服务实例与各调用记录。 + */ +function createHarness(options = {}) { + const callbackCalls = []; + const noticeCalls = []; + const outboundCalls = []; + const transactionCalls = []; + const stockoutUpdates = []; + const orderUpdates = []; + + const orderRows = Array.isArray(options.orderRows) + ? options.orderRows.map(item => ({ ...item })) + : [ + { + id: 1, + warehouse_id: 100000, + store_id: 1000000, + delivery_order_code: 'DO-1001', + warehouse_code: 'WH-100', + order_type: 'JYCK', + logistics_code: 'YTO', + logistics_name: '圆通速递', + express_code: '', + name: '测试客户', + mobile: '13800000000', + source_order_codes: 'SO-1001', + sync_status: 'pending', + }, + ]; + const orderItems = Array.isArray(options.orderItems) + ? options.orderItems.map(item => ({ ...item })) + : [ + { + id: 101, + order_id: 1, + order_line_no: '1', + source_order_code: 'SRC-1', + owner_code: 'OWNER-001', + item_code: 'SKU-1', + item_id: '1001', + item_name: '测试商品1', + plan_qty: 2, + actual_qty: 2, + inventory_type: 'ZP', + }, + ]; + const orderExpressRows = Array.isArray(options.orderExpressRows) + ? options.orderExpressRows + : [ + { + order_id: 1, + business_key: 9001, + waybill_code: 'WB-1001', + }, + ]; + + const ctx = { + app: { + Sequelize: { + Op: { + in: Symbol('in'), + ne: Symbol('ne'), + and: Symbol('and'), + }, + }, + formatDate() { + return '2026-09-12 10:00:00'; + }, + }, + model: { + async transaction(callback) { + const transaction = { + id: `tx-${transactionCalls.length + 1}`, + LOCK: { UPDATE: Symbol('UPDATE') }, + }; + transactionCalls.push({ transaction }); + return await callback(transaction); + }, + OrderDeliveryFactory: { + async getCurrentModel() { + return { + async findAll(query = {}) { + const inIds = query.where && query.where.id && query.where.id[ctx.app.Sequelize.Op.in]; + if (!Array.isArray(inIds)) { + return orderRows; + } + + const normalizedIds = inIds.map(item => Number(item)); + return orderRows.filter(row => normalizedIds.includes(Number(row.id))); + }, + async findOne(query = {}) { + const where = query.where || {}; + const targetId = Number(where.id); + const targetWarehouseId = Number(where.warehouse_id); + return orderRows.find(row => Number(row.id) === targetId && Number(row.warehouse_id) === targetWarehouseId) || null; + }, + async update(values, updateOptions) { + orderUpdates.push({ values, options: updateOptions }); + return [ 1 ]; + }, + }; + }, + }, + OrderItemsFactory: { + async getCurrentModel() { + return { + async findAll(query = {}) { + const inIds = query.where && query.where.order_id && query.where.order_id[ctx.app.Sequelize.Op.in]; + if (Array.isArray(inIds)) { + const normalizedIds = inIds.map(item => Number(item)); + return orderItems.filter(item => normalizedIds.includes(Number(item.order_id))); + } + + const singleOrderId = query.where && query.where.order_id; + if (singleOrderId !== undefined) { + return orderItems.filter(item => Number(item.order_id) === Number(singleOrderId)); + } + + return orderItems; + }, + }; + }, + }, + OrderExpress: { + async findAll(query = {}) { + const inIds = query.where && query.where.order_id && query.where.order_id[ctx.app.Sequelize.Op.in]; + if (!Array.isArray(inIds)) { + return orderExpressRows; + } + + const normalizedIds = inIds.map(item => Number(item)); + return orderExpressRows.filter(item => normalizedIds.includes(Number(item.order_id))); + }, + }, + OrderStockout: { + async findOne() { + return options.stockoutOrder || { + id: 5001, + stockout_order_code: 'SO-1001', + warehouse_id: 100000, + store_id: 1000000, + source_type: 'API', + sync_status: 'PENDING', + express_code: '', + express_name: '', + total_order_lines: 1, + order_type: 'PTCK', + qimen_owner_code: 'OWNER-001', + qimen_warehouse_code: 'WH-100', + }; + }, + async update(values, updateOptions) { + stockoutUpdates.push({ values, options: updateOptions }); + return [ 1 ]; + }, + }, + OrderStockoutItems: { + async findAll() { + return [ + { + id: 1, + order_id: 5001, + order_line_no: '1', + owner_code: 'OWNER-001', + item_code: 'SKU-1', + item_id: 1001, + item_name: '测试商品1', + plan_qty: 2, + actual_qty: 2, + inventory_type: 'ZP', + }, + ]; + }, + }, + }, + user: { + store_id: 1000000, + }, + service: { + openapi: { + callback: { + async sendByAppKey(callOptions) { + callbackCalls.push(callOptions); + if (typeof options.onSendByAppKey === 'function') { + return await options.onSendByAppKey(callOptions); + } + + return { success: true }; + }, + }, + }, + systems: { + stockStore: { + async outbound(itemId, quantity, transaction, meta) { + outboundCalls.push({ itemId, quantity, transaction, meta }); + if (typeof options.onOutbound === 'function') { + return await options.onOutbound({ itemId, quantity, transaction, meta }); + } + + return { success: true }; + }, + }, + ...(options.omitNoticeService ? {} : { + notice: { + async send(payload) { + noticeCalls.push(payload); + return { success: true }; + }, + }, + }), + storeWarehouse: { + async getContractConfig() { + return { + policy_config: { + notify_manual_sync: 1, + }, + }; + }, + }, + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + }; + + const service = new OrderAsyncService(ctx); + + return { + service, + ctx, + callbackCalls, + noticeCalls, + outboundCalls, + transactionCalls, + stockoutUpdates, + orderUpdates, + }; +} + +describe('test/app/service/systems/order_async.openapi.callback.test.js', () => { + it('API 订单同步完成应逐单发送 deliveryorder.confirm(request 对齐奇门报文,失败单不发送)', async () => { + const { service, callbackCalls } = createHarness({ + orderRows: [ + { + id: 1, + warehouse_id: 100000, + store_id: 1000000, + delivery_order_code: 'DO-1001', + warehouse_code: 'WH-100', + order_type: 'JYCK', + logistics_code: 'YTO', + logistics_name: '圆通速递', + express_code: '', + name: '测试客户', + mobile: '13800000000', + source_order_codes: 'SO-1001', + sync_status: 'pending', + }, + { + id: 2, + warehouse_id: 100000, + store_id: 1000000, + delivery_order_code: 'DO-1002', + warehouse_code: 'WH-100', + order_type: 'JYCK', + logistics_code: 'YTO', + logistics_name: '圆通速递', + express_code: '', + name: '测试客户2', + mobile: '13800000001', + source_order_codes: 'SO-1002', + sync_status: 'pending', + }, + { + id: 3, + warehouse_id: 100000, + store_id: 1000000, + delivery_order_code: 'DO-1003', + warehouse_code: 'WH-100', + order_type: 'JYCK', + logistics_code: 'YTO', + logistics_name: '圆通速递', + express_code: '', + name: '测试客户3', + mobile: '13800000002', + source_order_codes: 'SO-1003', + sync_status: 'pending', + }, + ], + orderItems: [ + { + id: 101, + order_id: 1, + order_line_no: '1', + source_order_code: 'SRC-1', + owner_code: 'OWNER-001', + item_code: 'SKU-1', + item_id: '1001', + item_name: '测试商品1', + plan_qty: 2, + actual_qty: 2, + inventory_type: 'ZP', + }, + { + id: 102, + order_id: 2, + order_line_no: '1', + source_order_code: 'SRC-2', + owner_code: 'OWNER-002', + item_code: 'SKU-2', + item_id: '1002', + item_name: '测试商品2', + plan_qty: 1, + actual_qty: 1, + inventory_type: 'ZP', + }, + { + id: 103, + order_id: 3, + order_line_no: '1', + source_order_code: 'SRC-3', + owner_code: 'OWNER-003', + item_code: 'SKU-3', + item_id: '1003', + item_name: '测试商品3', + plan_qty: 3, + actual_qty: 3, + inventory_type: 'ZP', + }, + ], + orderExpressRows: [ + { order_id: 1, business_key: 9001, waybill_code: 'WB-1001' }, + { order_id: 2, business_key: 9002, waybill_code: 'WB-1002' }, + { order_id: 3, business_key: 9003, waybill_code: 'WB-1003' }, + ], + onOutbound({ meta }) { + if (Number(meta.orderId) === 3) { + return { success: false, error: '库存不足' }; + } + + return { success: true }; + }, + }); + + const result = await service.syncApiOrders({ + create_channel: 'API', + order_ids: [ 1, 2, 3 ], + order_count: 3, + orders: [{ id: 1 }, { id: 2 }, { id: 3 }], + }, { + warehouseId: 100000, + appKey: 'APP-KEY-8', + }); + + assert.equal(result.success_count, 2); + assert.equal(result.failed_count, 1); + + // fire-and-forget 逐单回调:成功 2 单各发送一次,失败单不发送 + await waitFor(() => callbackCalls.length === 2); + + assert.equal(callbackCalls.length, 2); + const sentCodes = callbackCalls.map(call => call.request.deliveryOrder.deliveryOrderCode).sort(); + assert.deepEqual(sentCodes, [ 'DO-1001', 'DO-1002' ]); + + for (const call of callbackCalls) { + assert.equal(call.event, 'deliveryorder.confirm'); + assert.equal(call.appKey, 'APP-KEY-8'); + assert.equal(call.data, undefined); + assert.equal(call.metadata, undefined); + assert.ok(call.request.deliveryOrder); + assert.ok(call.request.packages); + assert.ok(Array.isArray(call.request.orderLines)); + assert.equal(call.request.deliveryOrder.status, 'DELIVERED'); + assert.equal(call.request.deliveryOrder.orderType, 'JYCK'); + // 请求报文不含 event / data / metadata 顶层键 + assert.equal(call.request.event, undefined); + assert.equal(call.request.data, undefined); + assert.equal(call.request.metadata, undefined); + } + + const firstCall = callbackCalls.find(call => call.request.deliveryOrder.deliveryOrderCode === 'DO-1001'); + assert.equal(firstCall.request.orderLines[0].itemCode, 'SKU-1'); + assert.equal(firstCall.request.packages.package[0].expressCode, 'WB-1001'); + }); + + it('API 订单同步成功 1 单时仍逐单发送(event 与 appKey 正确)', async () => { + const { service, callbackCalls } = createHarness(); + + const result = await service.syncApiOrders({ + create_channel: 'API', + order_ids: [ 1 ], + order_count: 1, + orders: [{ id: 1 }], + }, { + warehouseId: 100000, + appKey: 'APP-KEY-8', + }); + + assert.equal(result.status, 'success'); + assert.equal(result.success_count, 1); + + await waitFor(() => callbackCalls.length === 1); + + assert.equal(callbackCalls.length, 1); + assert.equal(callbackCalls[0].event, 'deliveryorder.confirm'); + assert.equal(callbackCalls[0].appKey, 'APP-KEY-8'); + assert.equal(callbackCalls[0].data, undefined); + assert.equal(callbackCalls[0].metadata, undefined); + assert.equal(callbackCalls[0].request.deliveryOrder.deliveryOrderCode, 'DO-1001'); + }); + + it('API 来源出库单回传 method 应为 stockout.confirm(request 为奇门同层级报文)', async () => { + const { service, callbackCalls } = createHarness(); + + const result = await service.syncStockoutOrders({ + create_channel: 'STOCKOUT', + order_ids: [ 1 ], + order_count: 1, + orders: [{ id: 1 }], + }, { + warehouseId: 100000, + appKey: 'APP-KEY-9', + }); + + assert.equal(result.status, 'success'); + assert.equal(result.success_count, 1); + assert.equal(callbackCalls.length, 1); + assert.equal(callbackCalls[0].event, 'stockout.confirm'); + assert.equal(callbackCalls[0].appKey, 'APP-KEY-9'); + assert.equal(callbackCalls[0].data, undefined); + assert.equal(callbackCalls[0].metadata, undefined); + + const request = callbackCalls[0].request; + assert.ok(request.deliveryOrder); + assert.ok(request.packages); + assert.ok(Array.isArray(request.orderLines)); + assert.equal(request.deliveryOrder.deliveryOrderCode, 'SO-1001'); + assert.equal(request.orderLines.length, 1); + // 不再包含 stockoutOrderCode / status 外层薄包装,也不含 event / data / metadata 顶层键 + assert.equal(request.stockoutOrderCode, undefined); + assert.equal(request.status, undefined); + assert.equal(request.event, undefined); + assert.equal(request.data, undefined); + assert.equal(request.metadata, undefined); + }); + + it('手工同步 notice 通道事件名 order_sync_completed 未被误改', async () => { + const { service, noticeCalls } = createHarness(); + + const result = await service.syncManualOrders({ + create_channel: 'MANUAL', + order_ids: [ 1 ], + order_count: 1, + orders: [{ id: 1 }], + }, { + warehouseId: 100000, + }); + + assert.equal(result.status, 'success'); + assert.equal(noticeCalls.length, 1); + assert.equal(noticeCalls[0].event, 'order_sync_completed'); + assert.equal(noticeCalls[0].businessName, 'order'); + }); +}); diff --git a/test/app/service/systems/receiving_entry_match.callback.test.js b/test/app/service/systems/receiving_entry_match.callback.test.js new file mode 100644 index 0000000..c455aee --- /dev/null +++ b/test/app/service/systems/receiving_entry_match.callback.test.js @@ -0,0 +1,494 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const ReceivingEntryMatchService = require('../../../../app/service/systems/receiving_entry_match'); + +/** + * 构建入库单实例桩。 + * @param {Object} [overrides] 覆盖字段。 + * @return {Object} 入库单桩实例。 + */ +function buildEntryOrder(overrides = {}) { + return { + id: 1001, + entry_order_code: 'RK-1001', + warehouse_id: 100000, + store_id: 1000000, + order_type: 'CGRK', + order_status: 'PENDING', + source_type: 'API', + remark: '收货单 SH-9001 到货', + qimen_owner_code: 'OWNER-001', + qimen_warehouse_code: 'WH-001', + items: [ + { id: 1, item_code: 'SKU-1', stock_id: 101, count: 10, received_quantity: 10, inventory_type: 'ZP' }, + ], + ...overrides, + }; +} + +/** + * 构建收货单桩。 + * @param {Object} [overrides] 覆盖字段。 + * @return {Object} 收货单桩(含明细)。 + */ +function buildReceiving(overrides = {}) { + return { + id: 9001, + receiving_number: 'SH-9001', + status: 'completed', + storage_status: 'normal', + warehouse_id: 100000, + details: [ + { id: 8001, system_product_id: 101, product_name: '商品1', actual_quantity: 10, storage_status: 'none', stored_quantity: 0 }, + ], + ...overrides, + }; +} + +/** + * 创建纯桩测试环境:不访问数据库、不依赖 Egg 上下文。 + * @param {Object} [options] 可选配置。 + * @param {Object} [options.entryOrder] 入库单桩实例。 + * @param {Object} [options.receiving] 收货单桩实例。 + * @param {Array} [options.entryItems] 奇门回传时重新加载的入库单明细。 + * @param {Array} [options.bindings] 已存在的绑定行(含软删除)。 + * @param {Function} [options.onQimenSend] 奇门发送桩实现。 + * @param {Function} [options.onSendWithRetry] OpenAPI 回调桩实现。 + * @return {Object} 服务实例、上下文与各调用记录。 + */ +function createHarness(options = {}) { + const logs = { info: [], warn: [], error: [] }; + const bindings = (options.bindings || []).map(item => ({ ...item })); + const createdBindings = []; + const entryOrderUpdates = []; + const receivingUpdates = []; + const receivingDetailUpdates = []; + const qimenSends = []; + const openApiSends = []; + + const ctx = { + app: { + Sequelize: { + Op: { + gte: Symbol('gte'), + ne: Symbol('ne'), + and: Symbol('and'), + }, + }, + formatDate() { + return '2026-09-12 10:00:00'; + }, + qimenClient: { + async send(method, ownerCode, queryData) { + qimenSends.push({ method, ownerCode, queryData }); + if (typeof options.onQimenSend === 'function') { + return await options.onQimenSend(method, ownerCode, queryData); + } + return { xmlArray: { response: { flag: 'success', message: 'ok' } } }; + }, + }, + }, + model: { + EntryOrder: { + async findOne() { + return options.entryOrder || null; + }, + async update(values, updateOptions) { + entryOrderUpdates.push({ values, options: updateOptions }); + return [ 1 ]; + }, + }, + EntryOrderReceiving: { + async findOne(query = {}) { + const where = (query && query.where) || {}; + return bindings.find(item => + Number(item.entry_order_id) === Number(where.entry_order_id) && + Number(item.receiving_id) === Number(where.receiving_id) + ) || null; + }, + async create(values) { + const row = { id: bindings.length + 1, ...values }; + createdBindings.push(values); + bindings.push(row); + return row; + }, + }, + EntryItems: { + async findAll() { + return options.entryItems || []; + }, + }, + Receiving: { + async findOne() { + const receiving = options.receiving || null; + if (!receiving) return null; + return { + ...receiving, + async update(values) { + receivingUpdates.push(values); + }, + }; + }, + }, + ReceivingDetail: { + async update(values, updateOptions) { + receivingDetailUpdates.push({ values, options: updateOptions }); + return [ 1 ]; + }, + }, + StoreWarehouse: { + async findOne() { + return options.storeWarehouse || null; + }, + }, + ApiApp: { + async findOne() { + return options.apiApp || null; + }, + }, + }, + service: { + openapi: { + callback: { + async sendWithRetry(payload) { + openApiSends.push(payload); + if (typeof options.onSendWithRetry === 'function') { + return await options.onSendWithRetry(payload); + } + return { success: true, retryCount: 0 }; + }, + }, + }, + }, + logger: { + info(...args) { + logs.info.push(args.join(' ')); + }, + warn(...args) { + logs.warn.push(args.join(' ')); + }, + error(...args) { + logs.error.push(args.join(' ')); + }, + }, + }; + + const service = new ReceivingEntryMatchService(ctx); + + return { + service, + ctx, + logs, + bindings, + createdBindings, + entryOrderUpdates, + receivingUpdates, + receivingDetailUpdates, + qimenSends, + openApiSends, + }; +} + +describe('test/app/service/systems/receiving_entry_match.callback.test.js', () => { + it('full_match 且新建绑定时回传 _sendCallback,matchType 为 auto_match', async () => { + const harness = createHarness({ + entryOrder: buildEntryOrder({ order_status: 'CREATED' }), + receiving: buildReceiving(), + }); + const callbackCalls = []; + harness.service._getRecentReceivingOrders = async () => [ buildReceiving() ]; + harness.service._findReceivingByRemark = async () => buildReceiving(); + harness.service._compareDetails = () => ({ type: 'full_match', matchedDetails: [] }); + harness.service._sendCallback = async (entryOrder, receivingOrder, matchType) => { + callbackCalls.push({ entryOrder, receivingOrder, matchType }); + return { success: true, sourceType: 'API', detail: { success: true } }; + }; + + await harness.service.matchAfterEntryCompleted(1001); + + assert.equal(callbackCalls.length, 1); + assert.equal(callbackCalls[0].entryOrder.id, 1001); + assert.equal(callbackCalls[0].receivingOrder.id, 9001); + assert.equal(callbackCalls[0].matchType, 'auto_match'); + assert.equal(harness.createdBindings.length, 1); + // 既有行为不破坏:CREATED → PENDING + assert.equal(harness.entryOrderUpdates.length, 1); + assert.equal(harness.entryOrderUpdates[0].values.order_status, 'PENDING'); + }); + + it('receiving_covers_entry 且新建绑定时回传,并标记收货单部分入库', async () => { + const harness = createHarness({ + entryOrder: buildEntryOrder(), + receiving: buildReceiving(), + }); + const callbackCalls = []; + harness.service._getRecentReceivingOrders = async () => [ buildReceiving() ]; + harness.service._findReceivingByRemark = async () => buildReceiving(); + harness.service._compareDetails = () => ({ + type: 'receiving_covers_entry', + matchedDetails: [ + { detailId: 8001, system_product_id: 101, actual_quantity: 15, stored_quantity: 0, entryCount: 10, overage: 5 }, + ], + overageDetails: [], + receivingOnlyItems: [], + }); + harness.service._sendCallback = async (entryOrder, receivingOrder, matchType) => { + callbackCalls.push({ entryOrder, receivingOrder, matchType }); + return { success: true, sourceType: 'QM', detail: { success: true } }; + }; + + await harness.service.matchAfterEntryCompleted(1001); + + assert.equal(callbackCalls.length, 1); + assert.equal(callbackCalls[0].matchType, 'auto_match'); + assert.equal(harness.createdBindings.length, 1); + // 部分入库标记生效 + assert.equal(harness.receivingUpdates.some(item => item.storage_status === 'partial'), true); + assert.equal(harness.receivingDetailUpdates.length, 1); + }); + + it('对比结果不匹配(entry_exceeds_receiving)时不回传且不写绑定', async () => { + const harness = createHarness({ + entryOrder: buildEntryOrder(), + receiving: buildReceiving(), + }); + const callbackCalls = []; + harness.service._getRecentReceivingOrders = async () => [ buildReceiving() ]; + harness.service._findReceivingByRemark = async () => buildReceiving(); + harness.service._compareDetails = () => ({ type: 'entry_exceeds_receiving', uncoveredDetails: [] }); + harness.service._sendCallback = async () => { + callbackCalls.push('called'); + return { success: true }; + }; + + await harness.service.matchAfterEntryCompleted(1001); + + assert.equal(callbackCalls.length, 0); + assert.equal(harness.createdBindings.length, 0); + }); + + it('remark 未匹配到收货单时不回传', async () => { + const harness = createHarness({ + entryOrder: buildEntryOrder(), + receiving: buildReceiving(), + }); + const callbackCalls = []; + harness.service._getRecentReceivingOrders = async () => [ buildReceiving() ]; + harness.service._findReceivingByRemark = async () => null; + harness.service._sendCallback = async () => { + callbackCalls.push('called'); + return { success: true }; + }; + + await harness.service.matchAfterEntryCompleted(1001); + + assert.equal(callbackCalls.length, 0); + assert.equal(harness.createdBindings.length, 0); + }); + + it('入库单无备注时跳过匹配且不回传', async () => { + const harness = createHarness({ + entryOrder: buildEntryOrder({ remark: '' }), + receiving: buildReceiving(), + }); + const callbackCalls = []; + harness.service._sendCallback = async () => { + callbackCalls.push('called'); + return { success: true }; + }; + + await harness.service.matchAfterEntryCompleted(1001); + + assert.equal(callbackCalls.length, 0); + assert.equal(harness.createdBindings.length, 0); + }); + + it('重复触发时仅首次新建绑定回传,第二次不重复回传', async () => { + const harness = createHarness({ + entryOrder: buildEntryOrder({ order_status: 'PENDING' }), + receiving: buildReceiving(), + }); + const callbackCalls = []; + harness.service._getRecentReceivingOrders = async () => [ buildReceiving() ]; + harness.service._findReceivingByRemark = async () => buildReceiving(); + harness.service._compareDetails = () => ({ type: 'full_match', matchedDetails: [] }); + harness.service._sendCallback = async (entryOrder, receivingOrder, matchType) => { + callbackCalls.push({ entryOrder, receivingOrder, matchType }); + return { success: true }; + }; + + await harness.service.matchAfterEntryCompleted(1001); + await harness.service.matchAfterEntryCompleted(1001); + + assert.equal(callbackCalls.length, 1); + assert.equal(harness.createdBindings.length, 1); + assert.equal(harness.bindings.length, 1); + assert.equal(harness.logs.info.some(line => line.includes('绑定关系已存在,跳过')), true); + }); + + it('_sendCallback 抛错时不影响绑定与状态更新,仅记录 warn 日志', async () => { + const harness = createHarness({ + entryOrder: buildEntryOrder({ order_status: 'CREATED' }), + receiving: buildReceiving(), + }); + harness.service._getRecentReceivingOrders = async () => [ buildReceiving() ]; + harness.service._findReceivingByRemark = async () => buildReceiving(); + harness.service._compareDetails = () => ({ type: 'full_match', matchedDetails: [] }); + harness.service._sendCallback = async () => { + throw new Error('回调爆炸'); + }; + + await harness.service.matchAfterEntryCompleted(1001); + + assert.equal(harness.createdBindings.length, 1); + assert.equal(harness.entryOrderUpdates.length, 1); + assert.equal(harness.entryOrderUpdates[0].values.order_status, 'PENDING'); + assert.equal(harness.logs.warn.some(line => line.includes('回传异常(不影响绑定结果)')), true); + }); + + it('_sendCallback 返回失败时不抛错且不影响绑定,仅记录 warn 日志', async () => { + const harness = createHarness({ + entryOrder: buildEntryOrder(), + receiving: buildReceiving(), + }); + harness.service._getRecentReceivingOrders = async () => [ buildReceiving() ]; + harness.service._findReceivingByRemark = async () => buildReceiving(); + harness.service._compareDetails = () => ({ type: 'full_match', matchedDetails: [] }); + harness.service._sendCallback = async () => ({ success: false, sourceType: 'API', detail: { success: false } }); + + await harness.service.matchAfterEntryCompleted(1001); + + assert.equal(harness.createdBindings.length, 1); + assert.equal(harness.logs.warn.some(line => line.includes('回传失败(不影响绑定结果)')), true); + }); + + it('QM 来源走奇门回传分支:method 为 taobao.qimen.entryorder.confirm', async () => { + const harness = createHarness({ + entryOrder: buildEntryOrder({ source_type: 'QM' }), + receiving: buildReceiving(), + entryItems: [ + { item_code: 'SKU-1', item_id: 'ITEM-1', count: 10, inventory_type: 'ZP', owner_code: 'OWNER-001', received_quantity: 10 }, + ], + }); + harness.service._getRecentReceivingOrders = async () => [ buildReceiving() ]; + harness.service._findReceivingByRemark = async () => buildReceiving(); + harness.service._compareDetails = () => ({ type: 'full_match', matchedDetails: [] }); + + await harness.service.matchAfterEntryCompleted(1001); + + assert.equal(harness.qimenSends.length, 1); + assert.equal(harness.qimenSends[0].method, 'taobao.qimen.entryorder.confirm'); + assert.equal(harness.openApiSends.length, 0); + }); + + it('QM 来源奇门报文逐字段不变(entryOrder 与 orderLines 快照一致)', async () => { + const harness = createHarness({ + entryOrder: buildEntryOrder({ source_type: 'QM' }), + receiving: buildReceiving(), + entryItems: [ + { item_code: 'SKU-1', item_id: 'ITEM-1', count: 10, inventory_type: 'ZP', owner_code: 'OWNER-001', received_quantity: 10 }, + { item_code: 'SKU-2', item_id: '', count: 5, inventory_type: '', owner_code: '', received_quantity: 3 }, + ], + }); + harness.service._getRecentReceivingOrders = async () => [ buildReceiving() ]; + harness.service._findReceivingByRemark = async () => buildReceiving(); + harness.service._compareDetails = () => ({ type: 'full_match', matchedDetails: [] }); + + await harness.service.matchAfterEntryCompleted(1001); + + assert.equal(harness.qimenSends.length, 1); + const sent = harness.qimenSends[0]; + assert.equal(sent.ownerCode, 'OWNER-001'); + assert.deepEqual(Object.keys(sent.queryData).sort(), [ 'request' ]); + + const { entryOrder, orderLines } = sent.queryData.request; + assert.deepEqual(entryOrder, { + entryOrderCode: 'RK-1001', + ownerCode: 'OWNER-001', + warehouseCode: 'WH-001', + entryOrderId: 1001, + entryOrderType: 'CGRK', + outBizCode: entryOrder.outBizCode, + confirmType: 0, + status: 'FULFILLED', + freight: 0, + operateTime: '2026-09-12 10:00:00', + remark: '匹配收货单SH-9001自动回传', + }); + assert.match(entryOrder.outBizCode, /^RECEIVING_MATCH_\d+$/); + assert.deepEqual(orderLines, [ + { orderLineNo: 1, ownerCode: 'OWNER-001', itemCode: 'SKU-1', itemId: 'ITEM-1', inventoryType: 'ZP', planQty: 10, actualQty: 10 }, + { orderLineNo: 2, ownerCode: '', itemCode: 'SKU-2', itemId: '', inventoryType: 'ZP', planQty: 5, actualQty: 3 }, + ]); + }); + + it('API 来源走 OpenAPI 回传分支:event 为 entryorder.match,request 结构与奇门一致且无 data/metadata', async () => { + const harness = createHarness({ + entryOrder: buildEntryOrder({ source_type: 'API' }), + receiving: buildReceiving(), + storeWarehouse: { id: 66 }, + apiApp: { self_app_key: 'APP-KEY', self_app_secret: 'SECRET', callback_url: 'https://cb.example.com/hook' }, + entryItems: [ + { item_code: 'SKU-1', item_id: 'ITEM-1', count: 10, inventory_type: 'ZP', owner_code: 'OWNER-001', received_quantity: 10 }, + ], + }); + harness.service._getRecentReceivingOrders = async () => [ buildReceiving() ]; + harness.service._findReceivingByRemark = async () => buildReceiving(); + harness.service._compareDetails = () => ({ type: 'full_match', matchedDetails: [] }); + + await harness.service.matchAfterEntryCompleted(1001); + + assert.equal(harness.openApiSends.length, 1); + assert.equal(harness.qimenSends.length, 0); + + const sent = harness.openApiSends[0]; + assert.equal(sent.event, 'entryorder.match'); + assert.equal(sent.callbackUrl, 'https://cb.example.com/hook'); + assert.equal(sent.data, undefined); + assert.equal(sent.metadata, undefined); + assert.deepEqual(Object.keys(sent.request).sort(), [ 'entryOrder', 'orderLines' ]); + + const { entryOrder, orderLines } = sent.request; + assert.deepEqual(entryOrder, { + entryOrderCode: 'RK-1001', + ownerCode: 'OWNER-001', + warehouseCode: 'WH-001', + entryOrderId: 1001, + entryOrderType: 'CGRK', + outBizCode: entryOrder.outBizCode, + confirmType: 0, + status: 'FULFILLED', + freight: 0, + operateTime: '2026-09-12 10:00:00', + remark: '匹配收货单SH-9001自动回传', + }); + assert.match(entryOrder.outBizCode, /^RECEIVING_MATCH_\d+$/); + assert.deepEqual(orderLines, [ + { orderLineNo: 1, ownerCode: 'OWNER-001', itemCode: 'SKU-1', itemId: 'ITEM-1', inventoryType: 'ZP', planQty: 10, actualQty: 10 }, + ]); + }); + + it('API 来源回传失败不影响绑定与状态更新,仅记录 warn 日志', async () => { + const harness = createHarness({ + entryOrder: buildEntryOrder({ source_type: 'API', order_status: 'CREATED' }), + receiving: buildReceiving(), + storeWarehouse: { id: 66 }, + apiApp: { self_app_key: 'APP-KEY', self_app_secret: 'SECRET', callback_url: 'https://cb.example.com/hook' }, + entryItems: [ + { item_code: 'SKU-1', item_id: 'ITEM-1', count: 10, inventory_type: 'ZP', owner_code: 'OWNER-001', received_quantity: 10 }, + ], + onSendWithRetry: async () => ({ success: false, error: '回调爆炸', retryCount: 3 }), + }); + harness.service._getRecentReceivingOrders = async () => [ buildReceiving() ]; + harness.service._findReceivingByRemark = async () => buildReceiving(); + harness.service._compareDetails = () => ({ type: 'full_match', matchedDetails: [] }); + + await harness.service.matchAfterEntryCompleted(1001); + + assert.equal(harness.createdBindings.length, 1); + assert.equal(harness.entryOrderUpdates.length, 1); + assert.equal(harness.entryOrderUpdates[0].values.order_status, 'PENDING'); + assert.equal(harness.logs.warn.some(line => line.includes('回传失败(不影响绑定结果)')), true); + }); +}); diff --git a/test/scripts/update_api_doc.test.cjs b/test/scripts/update_api_doc.test.cjs new file mode 100644 index 0000000..ed0f51f --- /dev/null +++ b/test/scripts/update_api_doc.test.cjs @@ -0,0 +1,453 @@ +'use strict'; + +/** + * 回归测试:script/update-api-doc.cjs 新建文档(spec.newDoc)与变更文件自动创建能力。 + * + * 覆盖: + * 1. 目标文档不存在 + 未提供 spec.newDoc → 报错文案含 spec.newDoc; + * 2. 目标文档不存在 + spec.newDoc → 生成骨架(module/description/version/updatedAt/http/headers/methods.groups) + * 并正确写入 group/methods,changes 自动创建为仅含本次 change 的数组; + * 3. 目标文档已存在 + spec.newDoc → newDoc 被忽略,结果与不传 newDoc 逐字节一致; + * 4. changes 文件缺失(文档已存在)→ 自动创建;--doc-only 不创建 changes; + * 5. --dry-run 不写任何文件(含新建场景),结尾输出 dry-run 提示; + * 6. --help 输出含 newDoc 说明与示例命令; + * 7. 新建文件为 2 空格缩进 + LF;未知字段透传;docMeta.version 覆盖骨架 version(缺省 0.0.0)。 + * 8. doc 已存在时 docMeta.description 覆盖根 description(仅字符串生效)。 + * + * 目录隔离:通过环境变量 WMS_API_DOC_METHODS_DIR / WMS_API_DOC_CHANGES_DIR 注入临时目录, + * 脚本在模块加载时读取这两个变量(默认值不变,仍为 methods/ 与 methods/changes/)。 + * + * 运行:node test/scripts/update_api_doc.test.cjs + */ +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { spawnSync } = require('node:child_process'); + +const { assert, suite, run } = require('../support/mini_test_framework.cjs'); + +const PROJECT_ROOT = path.resolve(__dirname, '..', '..'); +const SCRIPT_PATH = path.join(PROJECT_ROOT, 'script', 'update-api-doc.cjs'); + +// 临时目录 + 环境注入:必须在 require 脚本前设置(脚本在模块加载时读取目录常量) +const TMP_ROOT = fs.mkdtempSync(path.join(os.tmpdir(), 'wms-update-api-doc-')); +const TMP_METHODS_DIR = path.join(TMP_ROOT, 'methods'); +const TMP_CHANGES_DIR = path.join(TMP_METHODS_DIR, 'changes'); +fs.mkdirSync(TMP_CHANGES_DIR, { recursive: true }); + +process.env.WMS_API_DOC_METHODS_DIR = TMP_METHODS_DIR; +process.env.WMS_API_DOC_CHANGES_DIR = TMP_CHANGES_DIR; + +const { buildNewDoc, validateNewDoc, validateSpec } = require('../../script/update-api-doc.cjs'); + +/** + * 生成一份最小合法 spec(doc 不存在场景可再传 newDoc) + * @param {object} options 配置项 + * @param {string} [options.docName] 文档名,默认 sample + * @param {object} [options.newDoc] 新建骨架配置(默认不传) + * @param {object} [options.docMeta] 文档元信息(默认 {}) + * @param {object} [options.change] 变更记录(默认内置示例) + * @return {object} 更新 spec 对象 + */ +function buildSpec({ docName = 'sample', newDoc = null, docMeta = {}, change = null } = {}) { + const spec = { + docName, + docMeta, + group: { groupName: '示例分组', module: 'sample' }, + methods: [ + { + method: 'sample.echo', + description: '示例方法', + isNeedAuth: true, + isNeedLogin: true, + headers: [], + params: [ + { name: 'name', type: 'string', required: true, source: 'body', description: '名称' }, + ], + response: [ + { name: 'ok', type: 'boolean', required: true, description: '是否成功' }, + ], + errors: [ + { code: 400, message: '参数错误' }, + ], + }, + ], + change: change || { + version: '2026.09.12-sample', + date: '2026-09-12', + summary: '示例变更', + methods: [ 'sample.echo' ], + notes: [ '示例说明' ], + }, + }; + if (newDoc) spec.newDoc = newDoc; + return spec; +} + +/** + * 生成一份最小合法既有文档内容(methods/.json 形状) + * @return {object} 既有文档对象 + */ +function buildExistingDoc() { + return { + module: 'existing', + description: '已存在文档', + version: '3.0.0', + updatedAt: '2026-01-01', + http: { path: '/exist', method: 'POST' }, + headers: [], + methods: { groups: [] }, + }; +} + +/** + * 生成一份最小合法既有变更文件内容(methods/changes/.json 形状) + * @return {object[]} 既有变更记录数组 + */ +function buildExistingChanges() { + return [ + { + version: '2026.01.01-old', + date: '2026-01-01', + summary: '旧记录', + methods: [], + notes: [ '旧说明' ], + }, + ]; +} + +/** + * 将 spec 写入临时 spec 文件并返回绝对路径 + * @param {string} fileName spec 文件名(写入临时根目录) + * @param {object} spec spec 对象 + * @return {string} spec 文件绝对路径 + */ +function writeSpecFile(fileName, spec) { + const specPath = path.join(TMP_ROOT, fileName); + fs.writeFileSync(specPath, JSON.stringify(spec, null, 2), 'utf8'); + return specPath; +} + +/** + * 以子进程方式运行脚本(环境变量指向临时目录,工作目录为项目根目录) + * @param {string[]} args 脚本参数(如 --dry-run) + * @param {object} options 配置项 + * @param {string} [options.specPath] spec 文件绝对路径(默认不传) + * @return {object} spawnSync 结果 + */ +function runCli(args, { specPath } = {}) { + const argv = [ SCRIPT_PATH, ...args ]; + if (specPath) argv.push(`--spec=${specPath}`); + return spawnSync(process.execPath, argv, { + cwd: PROJECT_ROOT, + env: { + ...process.env, + WMS_API_DOC_METHODS_DIR: TMP_METHODS_DIR, + WMS_API_DOC_CHANGES_DIR: TMP_CHANGES_DIR, + }, + encoding: 'utf8', + }); +} + +/** + * 计算临时目录中目标 doc 文件的绝对路径 + * @param {string} docName 文档名 + * @return {string} doc 文件绝对路径 + */ +function docPathOf(docName) { + return path.join(TMP_METHODS_DIR, `${docName}.json`); +} + +/** + * 计算临时目录中目标 change 文件的绝对路径 + * @param {string} docName 文档名 + * @return {string} change 文件绝对路径 + */ +function changePathOf(docName) { + return path.join(TMP_CHANGES_DIR, `${docName}.json`); +} + +/** + * 以 2 空格缩进 + LF 写入既有文档文件 + * @param {string} docName 文档名 + * @param {object} doc 文档对象 + */ +function seedExistingDoc(docName, doc) { + fs.writeFileSync(docPathOf(docName), JSON.stringify(doc, null, ' '), 'utf8'); +} + +/** + * 以 2 空格缩进 + LF 写入既有变更文件 + * @param {string} docName 文档名 + * @param {object[]} changes 变更记录数组 + */ +function seedExistingChanges(docName, changes) { + fs.writeFileSync(changePathOf(docName), JSON.stringify(changes, null, ' '), 'utf8'); +} + +const suites = []; + +// ==================== 1. validateSpec 与骨架构建(纯函数) ==================== +suites.push(suite('validateSpec / validateNewDoc / buildNewDoc 纯函数', t => { + t('doc 不存在且未提供 spec.newDoc → 报错文案含 spec.newDoc', () => { + assert.throws( + () => validateSpec(buildSpec({ docName: 'missing_newdoc' }), { dryRun: false, docOnly: false }), + error => error.message.includes('spec.newDoc') && error.message.includes('create it') + ); + }); + + t('doc 不存在 + spec.newDoc → 校验通过并返回 docExists=false / changeExists=false / newDoc', () => { + const normalized = validateSpec( + buildSpec({ docName: 'newdoc_ok', newDoc: { module: 'demo' } }), + { dryRun: false, docOnly: false } + ); + assert.equal(normalized.docExists, false); + assert.equal(normalized.changeExists, false); + assert.equal(normalized.newDoc.module, 'demo'); + }); + + t('newDoc 字段校验:module 缺失/空白、http 非对象、headers 非数组、未知字段非 plain JSON 均报错', () => { + assert.throws( + () => validateNewDoc({}, 'spec.newDoc'), + error => error.message.includes('spec.newDoc.module') + ); + assert.throws( + () => validateNewDoc({ module: ' ' }, 'spec.newDoc'), + error => error.message.includes('spec.newDoc.module') + ); + assert.throws( + () => validateNewDoc({ module: 'm', http: 'x' }, 'spec.newDoc'), + error => error.message.includes('spec.newDoc.http') + ); + assert.throws( + () => validateNewDoc({ module: 'm', headers: {} }, 'spec.newDoc'), + error => error.message.includes('spec.newDoc.headers') + ); + assert.throws( + () => validateNewDoc({ module: 'm', custom: () => {} }, 'spec.newDoc'), + error => error.message.includes('spec.newDoc.custom') + ); + }); + + t('buildNewDoc:仅提供 module 时骨架默认值正确(version 0.0.0 / updatedAt 今天 / http 与 headers 默认)', () => { + const doc = buildNewDoc({ module: 'demo' }, {}); + assert.equal(doc.module, 'demo'); + assert.equal(doc.description, ''); + assert.equal(doc.version, '0.0.0'); + assert.match(doc.updatedAt, /^\d{4}-\d{2}-\d{2}$/); + assert.deepEqual(doc.http, { path: '', method: 'POST' }); + assert.deepEqual(doc.headers, []); + assert.deepEqual(doc.methods, { groups: [] }); + }); + + t('buildNewDoc:docMeta.version/updatedAt 覆盖、未知字段透传、保留键(version/methods)不透传', () => { + const doc = buildNewDoc( + { + module: 'demo', + description: '描述', + http: { path: '/x' }, + headers: [{ name: 'Content-Type', type: 'string', required: true, description: 'application/json' }], + custom: { a: [ 1, null, true ] }, + version: '9.9.9', + methods: {}, + }, + { version: '2.0.0', updatedAt: '2026-09-01' } + ); + assert.equal(doc.version, '2.0.0'); + assert.equal(doc.updatedAt, '2026-09-01'); + assert.equal(doc.description, '描述'); + assert.deepEqual(doc.http, { path: '/x' }); + assert.deepEqual(doc.custom, { a: [ 1, null, true ] }); + assert.deepEqual(doc.methods, { groups: [] }); + }); +})); + +// ==================== 2. 新建文档与变更文件(子进程正式写入) ==================== +suites.push(suite('新建文档与变更文件(正式写入)', t => { + t('doc 不存在 + newDoc → 骨架字段与 group/methods 全部正确写入,changes 自动创建', () => { + const docName = 'created_doc1'; + const specPath = writeSpecFile(`spec-${docName}.json`, buildSpec({ + docName, + newDoc: { + module: 'demo_mod', + description: 'demo desc', + http: { path: '/demo' }, + headers: [], + customField: { note: '透传' }, + }, + docMeta: { version: '1.2.3', updatedAt: '2026-09-11' }, + })); + const result = runCli([], { specPath }); + assert.equal(result.status, 0, result.stderr); + + assert.ok(fs.existsSync(docPathOf(docName)), result.stdout); + assert.ok(fs.existsSync(changePathOf(docName)), result.stdout); + assert.ok(result.stdout.includes('created:'), result.stdout); + + const rawDoc = fs.readFileSync(docPathOf(docName), 'utf8'); + const doc = JSON.parse(rawDoc); + assert.equal(doc.module, 'demo_mod'); + assert.equal(doc.description, 'demo desc'); + assert.equal(doc.version, '1.2.3'); + assert.equal(doc.updatedAt, '2026-09-11'); + assert.deepEqual(doc.http, { path: '/demo' }); + assert.deepEqual(doc.customField, { note: '透传' }); + assert.equal(doc.methods.groups.length, 1); + assert.equal(doc.methods.groups[0].groupName, '示例分组'); + assert.equal(doc.methods.groups[0].module, 'sample'); + assert.equal(doc.methods.groups[0].list.length, 1); + assert.equal(doc.methods.groups[0].list[0].method, 'sample.echo'); + + const changes = JSON.parse(fs.readFileSync(changePathOf(docName), 'utf8')); + assert.ok(Array.isArray(changes)); + assert.equal(changes.length, 1); + assert.equal(changes[0].version, '2026.09.12-sample'); + + // 格式约定:2 空格缩进 + LF(无 CRLF、无 tab) + assert.ok(!rawDoc.includes('\r\n'), 'doc 应为 LF'); + assert.ok(!rawDoc.includes('\t'), 'doc 缩进不应含 tab'); + assert.match(rawDoc, /\n {2}"module": "demo_mod",/); + }); + + t('doc 不存在 + newDoc 且无 docMeta → 骨架 version 保持 0.0.0,updatedAt 为今天', () => { + const docName = 'created_doc2'; + const specPath = writeSpecFile(`spec-${docName}.json`, buildSpec({ + docName, + newDoc: { module: 'demo_default' }, + })); + const result = runCli([], { specPath }); + assert.equal(result.status, 0, result.stderr); + + const doc = JSON.parse(fs.readFileSync(docPathOf(docName), 'utf8')); + assert.equal(doc.version, '0.0.0'); + assert.match(doc.updatedAt, /^\d{4}-\d{2}-\d{2}$/); + }); + + t('doc 已存在 + spec.newDoc → newDoc 被忽略,结果与不传 newDoc 逐字节一致', () => { + const docName = 'existing_doc1'; + seedExistingDoc(docName, buildExistingDoc()); + seedExistingChanges(docName, buildExistingChanges()); + + const specA = buildSpec({ docName }); + const specB = buildSpec({ + docName, + newDoc: { module: 'IGNORED', description: '不应生效', http: { path: '/x' } }, + }); + const specPathA = writeSpecFile(`spec-${docName}-a.json`, specA); + const specPathB = writeSpecFile(`spec-${docName}-b.json`, specB); + + const resultA = runCli([], { specPath: specPathA }); + assert.equal(resultA.status, 0, resultA.stderr); + const docBytesA = fs.readFileSync(docPathOf(docName)); + const changeBytesA = fs.readFileSync(changePathOf(docName)); + + // 恢复原文件后以带 newDoc 的 spec 再跑一遍 + seedExistingDoc(docName, buildExistingDoc()); + seedExistingChanges(docName, buildExistingChanges()); + const resultB = runCli([], { specPath: specPathB }); + assert.equal(resultB.status, 0, resultB.stderr); + assert.ok(!resultB.stdout.includes('created:'), resultB.stdout); + + assert.ok(docBytesA.equals(fs.readFileSync(docPathOf(docName))), 'doc 落盘内容应逐字节一致'); + assert.ok(changeBytesA.equals(fs.readFileSync(changePathOf(docName))), 'changes 落盘内容应逐字节一致'); + assert.equal(JSON.parse(docBytesA.toString()).module, 'existing'); + }); + + t('doc 已存在 + changes 缺失 → changes 自动创建为数组且仅含本次 change', () => { + const docName = 'existing_doc2'; + seedExistingDoc(docName, buildExistingDoc()); + assert.ok(!fs.existsSync(changePathOf(docName))); + + const specPath = writeSpecFile(`spec-${docName}.json`, buildSpec({ docName })); + const result = runCli([], { specPath }); + assert.equal(result.status, 0, result.stderr); + + assert.ok(fs.existsSync(changePathOf(docName))); + const changes = JSON.parse(fs.readFileSync(changePathOf(docName), 'utf8')); + assert.ok(Array.isArray(changes)); + assert.equal(changes.length, 1); + assert.equal(changes[0].version, '2026.09.12-sample'); + }); + + t('--doc-only + doc 不存在 + newDoc → 只创建 doc,不创建 changes', () => { + const docName = 'doc_only1'; + const specPath = writeSpecFile(`spec-${docName}.json`, buildSpec({ + docName, + newDoc: { module: 'demo_only' }, + })); + const result = runCli([ '--doc-only' ], { specPath }); + assert.equal(result.status, 0, result.stderr); + + assert.ok(fs.existsSync(docPathOf(docName))); + assert.ok(!fs.existsSync(changePathOf(docName))); + }); + + t('doc 已存在 + docMeta.description → 根 description 被覆盖,其余字段不受影响', () => { + const docName = 'existing_doc3'; + seedExistingDoc(docName, buildExistingDoc()); + seedExistingChanges(docName, buildExistingChanges()); + + const specPath = writeSpecFile(`spec-${docName}.json`, buildSpec({ + docName, + docMeta: { version: '3.1.0', updatedAt: '2026-09-13', description: '新根描述' }, + })); + const result = runCli([], { specPath }); + assert.equal(result.status, 0, result.stderr); + + const doc = JSON.parse(fs.readFileSync(docPathOf(docName), 'utf8')); + assert.equal(doc.description, '新根描述'); + assert.equal(doc.version, '3.1.0'); + assert.equal(doc.updatedAt, '2026-09-13'); + assert.equal(doc.module, 'existing'); + assert.equal(doc.methods.groups.length, 1); + }); +})); + +// ==================== 3. dry-run 与 help ==================== +suites.push(suite('dry-run 与 --help', t => { + t('--dry-run + 新建场景 → 不写任何文件,输出 created 行与 dry-run 结尾提示', () => { + const docName = 'dry_new1'; + const specPath = writeSpecFile(`spec-${docName}.json`, buildSpec({ + docName, + newDoc: { module: 'demo_dry' }, + })); + const result = runCli([ '--dry-run' ], { specPath }); + assert.equal(result.status, 0, result.stderr); + assert.ok(result.stdout.includes('created:'), result.stdout); + assert.ok( + result.stdout.includes('dry-run: validated successfully, no files were written.'), + result.stdout + ); + assert.ok(!fs.existsSync(docPathOf(docName))); + assert.ok(!fs.existsSync(changePathOf(docName))); + }); + + t('--dry-run + doc 已存在 → 不修改任何文件', () => { + const docName = 'dry_exist1'; + seedExistingDoc(docName, buildExistingDoc()); + seedExistingChanges(docName, buildExistingChanges()); + const docBytesBefore = fs.readFileSync(docPathOf(docName)); + const changeBytesBefore = fs.readFileSync(changePathOf(docName)); + + const specPath = writeSpecFile(`spec-${docName}.json`, buildSpec({ docName })); + const result = runCli([ '--dry-run' ], { specPath }); + assert.equal(result.status, 0, result.stderr); + assert.ok(!result.stdout.includes('created:'), result.stdout); + assert.ok(docBytesBefore.equals(fs.readFileSync(docPathOf(docName)))); + assert.ok(changeBytesBefore.equals(fs.readFileSync(changePathOf(docName)))); + }); + + t('--help 输出含 newDoc 字段说明与新建文档示例命令', () => { + const result = runCli([ '--help' ]); + assert.equal(result.status, 0, result.stderr); + assert.ok(result.stdout.includes('spec.newDoc'), result.stdout); + assert.ok(result.stdout.includes('module'), result.stdout); + assert.ok(result.stdout.includes('Examples:'), result.stdout); + assert.ok(result.stdout.includes('api-doc-create.json'), result.stdout); + }); +})); + +// 跑完后清理临时目录(测试数据非业务数据,允许删除) +run(suites).then(() => { + fs.rmSync(TMP_ROOT, { recursive: true, force: true }); +});