fix(openapi): deliveryorder.confirm 回调 appKey 按货主合约反查
- 背景:order_storage_allocation 构造的 routeContext 不含 appKey, finalizeLocalChannelOrdersInternal 的 if(appKey) 门禁导致 API 同步链路的 deliveryorder.confirm 从未真正发出;订单表 from_key 也兜不住 (normalizeOrderFromKey 仅接受整数,字符串 app_key 被归一化为 null) - order_async.js 新增 resolveOpenApiAppByStoreInternal:口径与入库单 _sendOpenApiCallback 对齐(wms_store_warehouse auth_status=2 → wms_api_app is_enabled=1 且 callback_url 非空) - notifyApiDeliveryOrderConfirmsInternal 逐单解析 appKey:context.appKey 非空优先 (不触发反查),缺失时按 orderRow.store_id 反查并按货主缓存(同批次无 N+1); 解析不到 appKey 的订单 warn 后跳过、不发请求 - 补充回调成功 info 日志(含 appKey) - 文档:methods/openapi_callback.json 1.2.0 → 1.3.0、变更记录 methods/changes/openapi_callback.json、docs/openapi-callback-events.md、 AI_METHOD_ROUTING.md 同步 - test: order_async.openapi.callback.test.js 覆盖 context.appKey 为空时反查发送
This commit is contained in:
parent
cf3b9092c6
commit
2555f3bb4d
@ -229,7 +229,7 @@ rg "class .*Service|module.exports" app/service/qimenMethods
|
||||
|---|---|---|---|
|
||||
| `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`) |
|
||||
| `order_completed` | `deliveryorder.confirm` | API 渠道订单同步(出库)完成后逐单触发(仅对 `syncResults` 中 `status==='success'` 的订单,成功 N 单 = N 次回调;fire-and-forget,失败仅 warn)。发送用 appKey 优先取调用上下文 `context.appKey`,缺失时按订单货主(`store_id`+`warehouse_id`)合约反查 `wms_store_warehouse(auth_status=2)` → `wms_api_app(is_enabled=1 且 callback_url 非空)` 的 `self_app_key`(同批次按货主缓存),解析不到则跳过该订单不发(此前 routeContext 缺 appKey 导致该回调从未发出,2026-09-13 已修复) | `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 行) |
|
||||
|
||||
|
||||
@ -857,6 +857,80 @@ async function processManualOrderInternal(service, orderModel, orderItemsModel,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 按订单货主合约反查可用的 OpenAPI 应用配置(ApiApp)。
|
||||
*
|
||||
* 口径与入库单回调 _sendOpenApiCallback 对齐:
|
||||
* 先按 store_id + warehouse_id + auth_status=2 查 StoreWarehouse 授权关系,
|
||||
* 再按 contract_id 查启用(is_enabled=1)且配置了 callback_url 的 ApiApp。
|
||||
* 未找到授权关系 / 无可用 ApiApp 配置时返回 null 并记录 warn 日志。
|
||||
*
|
||||
* @param {Object} service 订单异步服务实例。
|
||||
* @param {number|string} storeId 货主 ID。
|
||||
* @param {number|string} warehouseId 仓库 ID。
|
||||
* @return {Promise<Object|null>} { appKey, selfAppSecret, callbackUrl },未找到可用配置时返回 null。
|
||||
*/
|
||||
async function resolveOpenApiAppByStoreInternal(service, storeId, warehouseId) {
|
||||
const normalizedStoreId = Number(storeId || 0);
|
||||
const normalizedWarehouseId = Number(warehouseId || 0);
|
||||
const storeWarehouseModel = service.ctx.model && service.ctx.model.StoreWarehouse;
|
||||
const apiAppModel = service.ctx.model && service.ctx.model.ApiApp;
|
||||
|
||||
if (!Number.isFinite(normalizedStoreId) || normalizedStoreId <= 0
|
||||
|| !Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0
|
||||
|| !storeWarehouseModel || typeof storeWarehouseModel.findOne !== 'function'
|
||||
|| !apiAppModel || typeof apiAppModel.findOne !== 'function') {
|
||||
service.ctx.logger.warn('[OrderAsyncService.resolveOpenApiAppByStore] 缺少货主/仓库上下文或数据模型不可用,无法反查 ApiApp', {
|
||||
storeId: normalizedStoreId,
|
||||
warehouseId: normalizedWarehouseId,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
const { Op } = service.app.Sequelize;
|
||||
|
||||
const storeWarehouse = await storeWarehouseModel.findOne({
|
||||
where: {
|
||||
store_id: normalizedStoreId,
|
||||
warehouse_id: normalizedWarehouseId,
|
||||
auth_status: 2,
|
||||
},
|
||||
attributes: [ 'id' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (!storeWarehouse) {
|
||||
service.ctx.logger.warn(`[OrderAsyncService] OpenAPI回调:未找到授权关系 storeId=${normalizedStoreId} warehouseId=${normalizedWarehouseId}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
const apiApp = await apiAppModel.findOne({
|
||||
where: {
|
||||
contract_id: storeWarehouse.id,
|
||||
is_enabled: 1,
|
||||
callback_url: {
|
||||
[Op.and]: [
|
||||
{ [Op.ne]: null },
|
||||
{ [Op.ne]: '' },
|
||||
],
|
||||
},
|
||||
},
|
||||
attributes: [ 'self_app_key', 'self_app_secret', 'callback_url' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (!apiApp || !apiApp.callback_url) {
|
||||
service.ctx.logger.warn(`[OrderAsyncService] OpenAPI回调:未找到有效ApiApp配置 storeId=${normalizedStoreId} warehouseId=${normalizedWarehouseId} contractId=${storeWarehouse.id}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
appKey: String(apiApp.self_app_key || '').trim(),
|
||||
selfAppSecret: String(apiApp.self_app_secret || '').trim(),
|
||||
callbackUrl: String(apiApp.callback_url || '').trim(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 逐单发送 API 渠道订单确认回调(deliveryorder.confirm)。
|
||||
*
|
||||
@ -865,11 +939,14 @@ async function processManualOrderInternal(service, orderModel, orderItemsModel,
|
||||
* 每个同步成功的订单发送一次 OpenAPI 回调;单订单组装/发送失败
|
||||
* 仅记录 warn 日志,不影响其他订单与主流程。
|
||||
*
|
||||
* appKey 解析优先级:context.appKey 非空时优先使用(不触发合约反查);
|
||||
* 缺失时按订单货主(orderRow.store_id)合约反查 ApiApp 的 self_app_key。
|
||||
* 解析不到 appKey 的订单仅 warn 后跳过,不发请求(保持既有门禁语义)。
|
||||
*
|
||||
* @param {Object} service 订单异步服务实例。
|
||||
* @param {Object} options 通知参数。
|
||||
* @param {string} options.appKey 应用 app_key。
|
||||
* @param {number} options.warehouseId 仓库 ID。
|
||||
* @param {Object} options.context 同步上下文(透传给报文组装)。
|
||||
* @param {Object} options.context 同步上下文(appKey 可选,缺失时按订单货主合约反查)。
|
||||
* @param {Array<Object>} options.successResults 同步成功结果列表。
|
||||
* @param {Map<number, Object>} options.orderMap 订单 ID 到主表记录的映射。
|
||||
* @param {Map<number, Array<Object>>} options.itemsByOrderId 订单 ID 到明细列表的映射。
|
||||
@ -877,7 +954,6 @@ async function processManualOrderInternal(service, orderModel, orderItemsModel,
|
||||
*/
|
||||
async function notifyApiDeliveryOrderConfirmsInternal(service, options = {}) {
|
||||
const {
|
||||
appKey,
|
||||
warehouseId,
|
||||
context = {},
|
||||
successResults = [],
|
||||
@ -896,6 +972,11 @@ async function notifyApiDeliveryOrderConfirmsInternal(service, options = {}) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 上下文 appKey 非空时优先使用,保持既有语义,不触发合约反查
|
||||
const contextAppKey = String(context.appKey || '').trim();
|
||||
// 逐货主缓存合约反查结果:同一批次同货主只查一次库
|
||||
const appByStoreCache = new Map();
|
||||
|
||||
// 一次性批量读取运单号(单次查询,避免逐单 N+1),
|
||||
// 与 syncQmOrdersInternal 的加载方式保持一致
|
||||
const waybillCodeMap = await buildOrderWaybillCodeMapInternal(service, successOrderIds, warehouseId);
|
||||
@ -927,17 +1008,50 @@ async function notifyApiDeliveryOrderConfirmsInternal(service, options = {}) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 逐单解析发送用 appKey:context.appKey 优先,缺失时按订单货主合约反查;
|
||||
// 解析不到 appKey 的订单跳过,不发请求(保留门禁语义)
|
||||
let resolvedAppKey = contextAppKey;
|
||||
if (!resolvedAppKey) {
|
||||
const storeId = Number(orderRow.store_id) || 0;
|
||||
if (storeId <= 0) {
|
||||
service.ctx.logger.warn(`[OrderAsyncService] deliveryorder.confirm 回调跳过:订单缺少货主 store_id orderId=${orderId}`, {
|
||||
deliveryOrderCode: String(orderRow.delivery_order_code || '').trim(),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!appByStoreCache.has(storeId)) {
|
||||
appByStoreCache.set(storeId, await resolveOpenApiAppByStoreInternal(service, storeId, warehouseId));
|
||||
}
|
||||
|
||||
const resolvedApp = appByStoreCache.get(storeId);
|
||||
if (!resolvedApp || !String(resolvedApp.appKey || '').trim()) {
|
||||
service.ctx.logger.warn(`[OrderAsyncService] deliveryorder.confirm 回调跳过:货主无可用 ApiApp 配置 orderId=${orderId} storeId=${storeId}`, {
|
||||
deliveryOrderCode: String(orderRow.delivery_order_code || '').trim(),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
resolvedAppKey = String(resolvedApp.appKey).trim();
|
||||
}
|
||||
|
||||
const callbackResult = await callbackService.sendByAppKey({
|
||||
appKey,
|
||||
appKey: resolvedAppKey,
|
||||
event: 'deliveryorder.confirm',
|
||||
request: requestData.request,
|
||||
});
|
||||
|
||||
if (!callbackResult || callbackResult.success !== true) {
|
||||
service.ctx.logger.warn(`[OrderAsyncService] deliveryorder.confirm 回调失败 orderId=${orderId}`, {
|
||||
appKey: resolvedAppKey,
|
||||
deliveryOrderCode: String(orderRow.delivery_order_code || '').trim(),
|
||||
error: callbackResult && callbackResult.error,
|
||||
});
|
||||
} else {
|
||||
service.ctx.logger.info(`[OrderAsyncService] deliveryorder.confirm 回调成功 orderId=${orderId}`, {
|
||||
appKey: resolvedAppKey,
|
||||
deliveryOrderCode: String(orderRow.delivery_order_code || '').trim(),
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
service.ctx.logger.warn(`[OrderAsyncService] deliveryorder.confirm 回调异常 orderId=${orderId}`, {
|
||||
@ -955,7 +1069,7 @@ async function notifyApiDeliveryOrderConfirmsInternal(service, options = {}) {
|
||||
* @param {Object} service 订单异步服务实例。
|
||||
* @param {string} createChannel 创建渠道(MANUAL / API)。
|
||||
* @param {Object} [groupedOrder] 分组后的订单(含 order_ids / order_count / orders)。
|
||||
* @param {Object} [context] 同步上下文(含 warehouseId / appKey / request_id)。
|
||||
* @param {Object} [context] 同步上下文(含 warehouseId / request_id;appKey 可选,缺失时按订单货主合约反查)。
|
||||
* @param {string} [syncTarget] 同步目标(internal / api)。
|
||||
* @return {Promise<Object>} 同步结果(含 success_count / failed_count / sync_results 等)。
|
||||
*/
|
||||
@ -1080,30 +1194,26 @@ async function finalizeLocalChannelOrdersInternal(service, createChannel, groupe
|
||||
const failedCount = syncResults.filter(item => item.status === 'failed').length;
|
||||
const overallSuccess = failedCount === 0 && successCount === syncResults.length;
|
||||
|
||||
// 同步成功后触发 OpenAPI 回调通知(fire-and-forget,不阻塞主流程)
|
||||
// 同步成功后触发 OpenAPI 回调通知(fire-and-forget,不阻塞主流程)。
|
||||
// appKey 不在此处统一解析:context.appKey 非空时优先使用,缺失时由
|
||||
// notifyApiDeliveryOrderConfirmsInternal 按订单货主合约逐单反查(多货主批次各自解析),
|
||||
// 解析不到 appKey 的订单仅 warn 后跳过,不发请求(保留门禁语义)。
|
||||
if (createChannel === CREATE_CHANNEL_API && successCount > 0) {
|
||||
try {
|
||||
const callbackService = service.ctx.service.openapi && service.ctx.service.openapi.callback;
|
||||
|
||||
if (callbackService && typeof callbackService.sendByAppKey === 'function') {
|
||||
const appKey = String(context.appKey || '').trim();
|
||||
const successResults = syncResults.filter(item => item.status === 'success');
|
||||
|
||||
if (appKey) {
|
||||
// 逐单发送 deliveryorder.confirm:只对同步成功的订单发送,
|
||||
// 报文与奇门 taobao.qimen.deliveryorder.confirm 的 request 节点完全一致
|
||||
const successResults = syncResults.filter(item => item.status === 'success');
|
||||
|
||||
notifyApiDeliveryOrderConfirmsInternal(service, {
|
||||
appKey,
|
||||
warehouseId,
|
||||
context,
|
||||
successResults,
|
||||
orderMap,
|
||||
itemsByOrderId,
|
||||
}).catch(err => {
|
||||
service.ctx.logger.warn(`[OrderAsyncService] OpenAPI 回调忽略失败: ${err.message}`);
|
||||
});
|
||||
}
|
||||
notifyApiDeliveryOrderConfirmsInternal(service, {
|
||||
warehouseId,
|
||||
context,
|
||||
successResults,
|
||||
orderMap,
|
||||
itemsByOrderId,
|
||||
}).catch(err => {
|
||||
service.ctx.logger.warn(`[OrderAsyncService] OpenAPI 回调忽略失败: ${err.message}`);
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
service.ctx.logger.warn(`[OrderAsyncService] 触发回调异常,不影响主流程: ${err.message}`);
|
||||
|
||||
@ -193,7 +193,7 @@ app_key=APP2024011514301234&method=entryorder.confirm×tamp=1758047400&v=1.0
|
||||
- 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` 解析)
|
||||
- 发送途径:`sendByAppKey`;发送用 appKey 解析优先级:调用上下文 `context.appKey` 非空时优先(**不触发合约反查**),缺失时按订单货主(`store_id` + `warehouse_id`)合约反查 —— `wms_store_warehouse(auth_status=2)` → `wms_api_app(is_enabled=1 且 callback_url 非空)` 的 `self_app_key`(`resolveOpenApiAppByStoreInternal`,口径与入库单回调 `inbound_direct_log.js#_sendOpenApiCallback` 对齐);同一批次按货主 `Map` 缓存(N 个成功单 / M 个货主 → 2M 次查询,无 N+1)
|
||||
- **逐单发送语义(2026-09-13 变化)**:
|
||||
|
||||
| 维度 | 改动前 | 改动后 |
|
||||
@ -204,6 +204,7 @@ app_key=APP2024011514301234&method=entryorder.confirm×tamp=1758047400&v=1.0
|
||||
| 失败处理 | 不阻塞主流程 | 单订单组装/发送失败仅 warn,不影响其他订单与主流程 |
|
||||
|
||||
- 查询开销:复用原有主表+明细查询,新增 1 次运单号批量查询(`buildOrderWaybillCodeMapInternal`,强制同仓校验,无 N+1)
|
||||
- **appKey 门禁修复(2026-09-13)**:此前 `order_storage_allocation.js` 构造的 `routeContext` 不含 `appKey`,而 `finalizeLocalChannelOrdersInternal` 内有 `if (appKey)` 门禁,导致 `syncOrderIds(API)` 链路的 `deliveryorder.confirm` **从未真正发出过请求**;订单 `wms_order_delivery.from_key` 也兜不住(`normalizeOrderFromKey` 只接受整数,字符串 app_key 被归一化为 null)。本次改为按货主合约反查 appKey 修复。解析不到 appKey(订单缺 `store_id` / 无授权关系 / 无「启用且 callback_url 非空」的 ApiApp)的订单 warn 后跳过、不发请求;同步失败的订单不发送
|
||||
- `request` 结构(注册表 `request` 模板口径):
|
||||
|
||||
```json
|
||||
|
||||
@ -1,4 +1,18 @@
|
||||
[
|
||||
{
|
||||
"version": "2026.09.13-openapi-callback-deliveryorder-confirm-appkey-resolve",
|
||||
"date": "2026-09-13",
|
||||
"type": "updated",
|
||||
"summary": "同步 deliveryorder.confirm 触发条件(appKey 解析规则):发送用 appKey 由仅依赖调用上下文 context.appKey 改为「context.appKey 非空优先,缺失时按订单货主(store_id + warehouse_id)合约反查 wms_store_warehouse(auth_status=2) → wms_api_app(is_enabled=1 且 callback_url 非空) 的 self_app_key,同批次按货主缓存无 N+1」;解析不到 appKey 的订单 warn 后跳过、不发送。修复此前 routeContext 不含 appKey 导致该回调从未真正发出的问题。文档版本 1.2.0 → 1.3.0。",
|
||||
"methods": [
|
||||
"deliveryorder.confirm"
|
||||
],
|
||||
"notes": [
|
||||
"背景:order_storage_allocation.js 构造的 routeContext 不含 appKey,finalizeLocalChannelOrdersInternal 内 if(appKey) 门禁使 syncOrderIds(API) 链路的 deliveryorder.confirm 从未真正发出请求;订单 wms_order_delivery.from_key 兜不住(normalizeOrderFromKey 仅接受整数,字符串 app_key 被归一化为 null)",
|
||||
"实现:order_async.js 新增 resolveOpenApiAppByStoreInternal(口径与 inbound_direct_log.js#_sendOpenApiCallback 对齐);notifyApiDeliveryOrderConfirmsInternal 逐单解析 appKey:context.appKey 优先(不触发反查)→ 按 orderRow.store_id 合约反查 → 逐货主 Map 缓存(N 成功单 / M 货主 → 2M 次查询);解析不到 appKey(订单缺 store_id / 无授权关系 / 无可用 ApiApp 配置)warn 后跳过该订单",
|
||||
"同步 docs/openapi-callback-events.md 3.3 与 AI_METHOD_ROUTING.md 5.6"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.09.13-openapi-callback-request-protocol",
|
||||
"date": "2026-09-13",
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
{
|
||||
"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",
|
||||
"version": "1.3.0",
|
||||
"updatedAt": "2026-09-13",
|
||||
"http": {
|
||||
"path": "{ApiApp.callback_url}",
|
||||
@ -495,7 +495,7 @@
|
||||
},
|
||||
{
|
||||
"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)。",
|
||||
"description": "订单发货完成出站回调(逐单发送)。触发前提:createChannel=API 且本批存在同步成功订单(仅对 syncResults 中 status==='success' 的订单发送,成功 N 单 = N 次回调;fire-and-forget,失败仅 warn,不阻塞主流程)。发送用 appKey 优先取调用上下文 context.appKey,缺失时按订单货主(store_id + warehouse_id)合约反查 —— wms_store_warehouse(auth_status=2) → wms_api_app(is_enabled=1 且 callback_url 非空) 的 self_app_key;同一批次按货主缓存,无 N+1。解析不到 appKey(订单缺 store_id / 无授权关系 / 无可用 ApiApp 配置)时跳过该订单并告警,不发送请求;同步失败的订单不发送。触发实现:app/service/systems/order_async.js#finalizeLocalChannelOrdersInternal → notifyApiDeliveryOrderConfirmsInternal(复用 buildQimenDeliveryOrderConfirmDataInternal 组装与奇门 taobao.qimen.deliveryorder.confirm 完全一致的 request 报文;复用原有主表+明细查询,新增 1 次运单号批量查询,无 N+1)。",
|
||||
"isNeedAuth": true,
|
||||
"isNeedLogin": false,
|
||||
"headers": [],
|
||||
@ -879,7 +879,8 @@
|
||||
"重试策略:非 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)",
|
||||
"发送途径:sendByAppKey;appKey 解析优先级:context.appKey 非空时优先(不触发合约反查),缺失时按订单货主(store_id + warehouse_id)合约反查 resolveOpenApiAppByStoreInternal —— wms_store_warehouse(auth_status=2) → wms_api_app(contract_id 且 is_enabled=1 且 callback_url 非空) 的 self_app_key;同一批次按货主 Map 缓存(N 个成功单 / M 个货主 → 2M 次查询,无 N+1)",
|
||||
"appKey 门禁修复(2026-09-13):此前 order_storage_allocation.js 构造的 routeContext 不含 appKey,finalizeLocalChannelOrdersInternal 内 if(appKey) 门禁使 syncOrderIds(API) 链路的 deliveryorder.confirm 从未真正发出请求;订单 wms_order_delivery.from_key 也兜不住(normalizeOrderFromKey 仅接受整数,字符串 app_key 被归一化为 null)。本次改为按货主合约反查修复;解析不到 appKey(订单缺 store_id / 无授权关系 / 无可用 ApiApp 配置)的订单 warn 后跳过,不发请求",
|
||||
"逐单发送语义(破坏性变更):改动前一次回调携带整批 orderIds(含失败/跳过);改后仅对 syncResults 中 status==='success' 的订单逐单发送,成功 N 单 = N 次回调;组装/发送失败仅 warn,不影响其他订单与主流程",
|
||||
"fire-and-forget 触发:回调结果不影响订单同步主流程"
|
||||
]
|
||||
|
||||
@ -21,12 +21,62 @@ async function waitFor(predicate, timeoutMs = 500) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造订单主表记录(raw),字段与 harness 默认单一致,便于多货主场景复用。
|
||||
* @param {number} id 订单 ID。
|
||||
* @param {number} storeId 货主 ID。
|
||||
* @param {string} [deliveryOrderCode] 出库单号,缺省自动生成。
|
||||
* @return {Object} 订单主表记录。
|
||||
*/
|
||||
function makeOrderRow(id, storeId, deliveryOrderCode) {
|
||||
return {
|
||||
id,
|
||||
warehouse_id: 100000,
|
||||
store_id: storeId,
|
||||
delivery_order_code: deliveryOrderCode || `DO-${id}`,
|
||||
warehouse_code: 'WH-100',
|
||||
order_type: 'JYCK',
|
||||
logistics_code: 'YTO',
|
||||
logistics_name: '圆通速递',
|
||||
express_code: '',
|
||||
name: '测试客户',
|
||||
mobile: '13800000000',
|
||||
source_order_codes: `SO-${id}`,
|
||||
sync_status: 'pending',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造订单明细记录(raw)。
|
||||
* @param {number} id 明细 ID。
|
||||
* @param {number} orderId 所属订单 ID。
|
||||
* @param {string} [itemCode] 商品编码,缺省自动生成。
|
||||
* @return {Object} 订单明细记录。
|
||||
*/
|
||||
function makeOrderItem(id, orderId, itemCode) {
|
||||
return {
|
||||
id,
|
||||
order_id: orderId,
|
||||
order_line_no: '1',
|
||||
source_order_code: `SRC-${orderId}`,
|
||||
owner_code: `OWNER-${orderId}`,
|
||||
item_code: itemCode || `SKU-${orderId}`,
|
||||
item_id: String(id),
|
||||
item_name: `测试商品${orderId}`,
|
||||
plan_qty: 1,
|
||||
actual_qty: 1,
|
||||
inventory_type: 'ZP',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建订单异步服务测试桩(覆盖 OpenAPI 回调与 notice 通道断言)。
|
||||
* @param {Object} [options] 可选配置。
|
||||
* @param {Array} [options.orderRows] 订单主表记录(raw)。
|
||||
* @param {Array} [options.orderItems] 订单明细记录(raw)。
|
||||
* @param {Array} [options.orderExpressRows] 运单号记录(raw)。
|
||||
* @param {Array} [options.storeWarehouseRows] 货主-仓库授权关系记录(raw)。
|
||||
* @param {Array} [options.apiAppRows] ApiApp 配置记录(raw)。
|
||||
* @param {Object} [options.stockoutOrder] 出库单主表记录(raw)。
|
||||
* @param {Function} [options.onSendByAppKey] OpenAPI 回调桩实现。
|
||||
* @param {Function} [options.onOutbound] 库存扣减桩实现(可模拟失败订单)。
|
||||
@ -40,6 +90,10 @@ function createHarness(options = {}) {
|
||||
const transactionCalls = [];
|
||||
const stockoutUpdates = [];
|
||||
const orderUpdates = [];
|
||||
const storeWarehouseCalls = [];
|
||||
const apiAppCalls = [];
|
||||
const warnLogs = [];
|
||||
const infoLogs = [];
|
||||
|
||||
const orderRows = Array.isArray(options.orderRows)
|
||||
? options.orderRows.map(item => ({ ...item }))
|
||||
@ -86,6 +140,27 @@ function createHarness(options = {}) {
|
||||
waybill_code: 'WB-1001',
|
||||
},
|
||||
];
|
||||
const storeWarehouseRows = Array.isArray(options.storeWarehouseRows)
|
||||
? options.storeWarehouseRows
|
||||
: [
|
||||
{
|
||||
id: 20001,
|
||||
store_id: 1000000,
|
||||
warehouse_id: 100000,
|
||||
auth_status: 2,
|
||||
},
|
||||
];
|
||||
const apiAppRows = Array.isArray(options.apiAppRows)
|
||||
? options.apiAppRows
|
||||
: [
|
||||
{
|
||||
contract_id: 20001,
|
||||
is_enabled: 1,
|
||||
callback_url: 'https://example.com/callback',
|
||||
self_app_key: 'WMSD08A0001',
|
||||
self_app_secret: 'SECRET-1',
|
||||
},
|
||||
];
|
||||
|
||||
const ctx = {
|
||||
app: {
|
||||
@ -165,6 +240,26 @@ function createHarness(options = {}) {
|
||||
return orderExpressRows.filter(item => normalizedIds.includes(Number(item.order_id)));
|
||||
},
|
||||
},
|
||||
StoreWarehouse: {
|
||||
async findOne(query = {}) {
|
||||
storeWarehouseCalls.push(query);
|
||||
const where = query.where || {};
|
||||
return storeWarehouseRows.find(row => Number(row.store_id) === Number(where.store_id)
|
||||
&& Number(row.warehouse_id) === Number(where.warehouse_id)
|
||||
&& Number(row.auth_status) === Number(where.auth_status)) || null;
|
||||
},
|
||||
},
|
||||
ApiApp: {
|
||||
async findOne(query = {}) {
|
||||
apiAppCalls.push(query);
|
||||
const where = query.where || {};
|
||||
return apiAppRows.find(row => Number(row.contract_id) === Number(where.contract_id)
|
||||
&& Number(row.is_enabled) === Number(where.is_enabled)
|
||||
&& row.callback_url !== null
|
||||
&& row.callback_url !== undefined
|
||||
&& String(row.callback_url).trim() !== '') || null;
|
||||
},
|
||||
},
|
||||
OrderStockout: {
|
||||
async findOne() {
|
||||
return options.stockoutOrder || {
|
||||
@ -253,8 +348,12 @@ function createHarness(options = {}) {
|
||||
},
|
||||
},
|
||||
logger: {
|
||||
info() {},
|
||||
warn() {},
|
||||
info(message) {
|
||||
infoLogs.push(String(message));
|
||||
},
|
||||
warn(message) {
|
||||
warnLogs.push(String(message));
|
||||
},
|
||||
error() {},
|
||||
},
|
||||
};
|
||||
@ -270,6 +369,10 @@ function createHarness(options = {}) {
|
||||
transactionCalls,
|
||||
stockoutUpdates,
|
||||
orderUpdates,
|
||||
storeWarehouseCalls,
|
||||
apiAppCalls,
|
||||
warnLogs,
|
||||
infoLogs,
|
||||
};
|
||||
}
|
||||
|
||||
@ -497,4 +600,217 @@ describe('test/app/service/systems/order_async.openapi.callback.test.js', () =>
|
||||
assert.equal(noticeCalls[0].event, 'order_sync_completed');
|
||||
assert.equal(noticeCalls[0].businessName, 'order');
|
||||
});
|
||||
|
||||
it('context.appKey 为空时按订单货主合约反查 ApiApp 并发送回调(appKey=self_app_key)', async () => {
|
||||
const { service, callbackCalls, storeWarehouseCalls, apiAppCalls } = createHarness();
|
||||
|
||||
const result = await service.syncApiOrders({
|
||||
create_channel: 'API',
|
||||
order_ids: [ 1 ],
|
||||
order_count: 1,
|
||||
orders: [{ id: 1 }],
|
||||
}, {
|
||||
warehouseId: 100000,
|
||||
});
|
||||
|
||||
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, 'WMSD08A0001');
|
||||
assert.equal(storeWarehouseCalls.length, 1);
|
||||
assert.equal(apiAppCalls.length, 1);
|
||||
});
|
||||
|
||||
it('context.appKey 非空时优先使用,且不触发合约反查', async () => {
|
||||
const { service, callbackCalls, storeWarehouseCalls, apiAppCalls } = 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');
|
||||
|
||||
await waitFor(() => callbackCalls.length === 1);
|
||||
|
||||
assert.equal(callbackCalls.length, 1);
|
||||
assert.equal(callbackCalls[0].appKey, 'APP-KEY-8');
|
||||
// 未触发货主合约反查
|
||||
assert.equal(storeWarehouseCalls.length, 0);
|
||||
assert.equal(apiAppCalls.length, 0);
|
||||
});
|
||||
|
||||
it('合约下无授权关系时跳过回调并记录 warn', async () => {
|
||||
const { service, callbackCalls, storeWarehouseCalls, apiAppCalls, warnLogs } = createHarness({
|
||||
storeWarehouseRows: [],
|
||||
});
|
||||
|
||||
const result = await service.syncApiOrders({
|
||||
create_channel: 'API',
|
||||
order_ids: [ 1 ],
|
||||
order_count: 1,
|
||||
orders: [{ id: 1 }],
|
||||
}, {
|
||||
warehouseId: 100000,
|
||||
});
|
||||
|
||||
assert.equal(result.status, 'success');
|
||||
|
||||
await waitFor(() => warnLogs.some(log => log.includes('未找到授权关系')));
|
||||
|
||||
assert.equal(callbackCalls.length, 0);
|
||||
assert.equal(storeWarehouseCalls.length, 1);
|
||||
assert.equal(apiAppCalls.length, 0);
|
||||
});
|
||||
|
||||
it('合约下 ApiApp 停用或 callback_url 为空时跳过回调并记录 warn', async () => {
|
||||
const cases = [
|
||||
{
|
||||
name: 'is_enabled=0',
|
||||
apiAppRows: [
|
||||
{
|
||||
contract_id: 20001,
|
||||
is_enabled: 0,
|
||||
callback_url: 'https://example.com/callback',
|
||||
self_app_key: 'WMSD08A0001',
|
||||
self_app_secret: 'SECRET-1',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'callback_url 为空',
|
||||
apiAppRows: [
|
||||
{
|
||||
contract_id: 20001,
|
||||
is_enabled: 1,
|
||||
callback_url: '',
|
||||
self_app_key: 'WMSD08A0001',
|
||||
self_app_secret: 'SECRET-1',
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
for (const caseItem of cases) {
|
||||
const { service, callbackCalls, storeWarehouseCalls, apiAppCalls, warnLogs } = createHarness({
|
||||
apiAppRows: caseItem.apiAppRows,
|
||||
});
|
||||
|
||||
const result = await service.syncApiOrders({
|
||||
create_channel: 'API',
|
||||
order_ids: [ 1 ],
|
||||
order_count: 1,
|
||||
orders: [{ id: 1 }],
|
||||
}, {
|
||||
warehouseId: 100000,
|
||||
});
|
||||
|
||||
assert.equal(result.status, 'success');
|
||||
|
||||
await waitFor(() => warnLogs.some(log => log.includes('未找到有效ApiApp配置')));
|
||||
|
||||
assert.equal(callbackCalls.length, 0, `${caseItem.name} 不应发送回调`);
|
||||
assert.equal(storeWarehouseCalls.length, 1);
|
||||
assert.equal(apiAppCalls.length, 1);
|
||||
}
|
||||
});
|
||||
|
||||
it('多货主批次各自按货主反查 appKey,同货主只查一次库', async () => {
|
||||
const { service, callbackCalls, storeWarehouseCalls, apiAppCalls } = createHarness({
|
||||
orderRows: [
|
||||
makeOrderRow(1, 1000000, 'DO-1001'),
|
||||
makeOrderRow(2, 1000000, 'DO-1002'),
|
||||
makeOrderRow(3, 2000000, 'DO-1003'),
|
||||
],
|
||||
orderItems: [
|
||||
makeOrderItem(101, 1, 'SKU-1'),
|
||||
makeOrderItem(102, 2, 'SKU-2'),
|
||||
makeOrderItem(103, 3, 'SKU-3'),
|
||||
],
|
||||
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' },
|
||||
],
|
||||
storeWarehouseRows: [
|
||||
{ id: 20001, store_id: 1000000, warehouse_id: 100000, auth_status: 2 },
|
||||
{ id: 20002, store_id: 2000000, warehouse_id: 100000, auth_status: 2 },
|
||||
],
|
||||
apiAppRows: [
|
||||
{
|
||||
contract_id: 20001,
|
||||
is_enabled: 1,
|
||||
callback_url: 'https://example.com/cb1',
|
||||
self_app_key: 'WMSD08A0001',
|
||||
self_app_secret: 'SECRET-1',
|
||||
},
|
||||
{
|
||||
contract_id: 20002,
|
||||
is_enabled: 1,
|
||||
callback_url: 'https://example.com/cb2',
|
||||
self_app_key: 'WMSD08A0002',
|
||||
self_app_secret: 'SECRET-2',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
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,
|
||||
});
|
||||
|
||||
assert.equal(result.success_count, 3);
|
||||
|
||||
await waitFor(() => callbackCalls.length === 3);
|
||||
|
||||
assert.equal(callbackCalls.length, 3);
|
||||
const appKeyByCode = new Map(callbackCalls.map(call => [ call.request.deliveryOrder.deliveryOrderCode, call.appKey ]));
|
||||
assert.equal(appKeyByCode.get('DO-1001'), 'WMSD08A0001');
|
||||
assert.equal(appKeyByCode.get('DO-1002'), 'WMSD08A0001');
|
||||
assert.equal(appKeyByCode.get('DO-1003'), 'WMSD08A0002');
|
||||
// 缓存命中:3 单共 2 个货主,StoreWarehouse / ApiApp 各只查询 2 次
|
||||
assert.equal(storeWarehouseCalls.length, 2);
|
||||
assert.equal(apiAppCalls.length, 2);
|
||||
});
|
||||
|
||||
it('订单缺少货主 store_id 时跳过回调并记录 warn', async () => {
|
||||
const { service, callbackCalls, storeWarehouseCalls, apiAppCalls, warnLogs } = createHarness({
|
||||
orderRows: [
|
||||
makeOrderRow(1, 0, 'DO-1001'),
|
||||
],
|
||||
orderItems: [
|
||||
makeOrderItem(101, 1, 'SKU-1'),
|
||||
],
|
||||
});
|
||||
|
||||
const result = await service.syncApiOrders({
|
||||
create_channel: 'API',
|
||||
order_ids: [ 1 ],
|
||||
order_count: 1,
|
||||
orders: [{ id: 1 }],
|
||||
}, {
|
||||
warehouseId: 100000,
|
||||
});
|
||||
|
||||
assert.equal(result.status, 'success');
|
||||
|
||||
await waitFor(() => warnLogs.some(log => log.includes('订单缺少货主')));
|
||||
|
||||
assert.equal(callbackCalls.length, 0);
|
||||
assert.equal(storeWarehouseCalls.length, 0);
|
||||
assert.equal(apiAppCalls.length, 0);
|
||||
});
|
||||
});
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user