feat(openapi): 出站回调命名与报文改奇门同层级

- 回调 method 由 snake_case 事件名改为 模块.动作:entryorder.confirm / entryorder.match / deliveryorder.confirm / stockout.confirm / deliveryorder.cancel(原 order.cancel 与入站方法同名,改名避免 callback_url 误指向 /openapi 时被路由到取消单据接口)。

- 时间戳统一为秒级(String(Math.floor(Date.now()/1000))),与 /openapi 入站 ±600 秒时效校验及回调调试页一致。

- 报文体由 { event, data, metadata } 改为奇门同层级 { request: {...} }(移除 metadata,事件标识只靠 query 的 method);入库类回调与奇门侧共用同一份报文组装。

- deliveryorder.confirm 改为逐单发送(仅同步成功的订单);stockout.confirm 直接复用 buildStockoutConfirmDataInternal 结果。

- 修复 entryorder.match 死代码:绑定成功且本次新建绑定时回传,重复触发不重复通知,回传失败不影响绑定。

- 调试页 /docs/api/openapi/callback-test 按真实报文预填;新增出站回调文档页 /docs/api/openapi_callback 及入口链接。

- script/update-api-doc.cjs 支持 spec.newDoc 新建文档与 docMeta.description(附单测)。

- 文档:methods/openapi_callback.json、AI_METHOD_ROUTING.md 5.6 节、docs/openapi-callback-events.md、docs/api-doc-update-workflow.md 等。
This commit is contained in:
liufumingren 2026-09-13 02:24:37 +08:00
parent e19b5fc18c
commit d725e7e457
24 changed files with 6096 additions and 198 deletions

File diff suppressed because one or more lines are too long

View File

@ -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({
</div>
<pre id="docResourcePreview" class="req-result muted">点击上方按钮后,可直接预览当前文档的变更记录或原文 JSON。</pre>
</div>`}
${isExternalApi ? (docData.module === 'warehouse_notify' ? `<div class="openapi-guide">
${isOpenapi || isWarehouse ? (docData.module === 'warehouse_notify' ? `<div class="openapi-guide">
<h3>请求方式</h3>
<pre class="guide-code">POST {notify_url}?app_key={app_key}&amp;method={方法名}&amp;timestamp={时间戳}&amp;sign={签名}
Content-Type: application/json
@ -1212,6 +1215,10 @@ Content-Type: application/json
${isOpenapi ? `<p style="margin-top:12px;font-size:13px;">
<a href="/docs/api/openapi/callback-test" style="color:#1565c0;">→ 回调测试工具</a>
<span class="muted">(模拟接收回调通知,验证回调链路)</span>
</p>
<p style="margin-top:12px;font-size:13px;">
<a href="/docs/api/openapi_callback" style="color:#1565c0;">→ 出站回调文档</a>
<span class="muted">(WMS → 外部的回调事件定义,共 5 个)</span>
</p>` : ''}
</div>`) : ''}
</section>
@ -2157,6 +2164,14 @@ class DocsController extends Controller {
await this.renderDoc('openapi');
}
/**
* 渲染 OpenAPI 出站回调文档独立页面。
* @return {Promise<void>} 无返回值。
*/
async openapiCallbackEvents() {
await this.renderDoc('openapi_callback');
}
/**
* 渲染仓库开放 API 文档独立页面。
* @return {Promise<void>} 无返回值。

View File

@ -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 {
<div class="container">
<div class="card">
<h1>OpenAPI 回调测试</h1>
<p class="desc">选择已注册的回调事件,填入测试 URL,模拟真实回调推送。</p>
<p class="desc">选择已注册的回调事件,自动填充与真实回调完全一致的完整报文体(奇门同层级 { request },可编辑),填入测试 URL 模拟推送。</p>
<p style="margin-top:6px;font-size:13px;">
<a href="/docs/api/openapi" style="color:#1565c0;">← 返回 API 文档</a>
&nbsp;|&nbsp;
<a href="/docs/api/openapi_callback" style="color:#1565c0;">→ 出站回调文档</a>
</p>
</div>
@ -72,8 +75,8 @@ class OpenapiCallbackController extends Controller {
<label>测试回调 URL</label>
<input id="callbackUrlInput" type="text" placeholder="https://your-system.com/api/callback" />
<label>回调数据 Body(自动填充模板,可编辑)</label>
<textarea id="dataInput" rows="8" placeholder='{}'></textarea>
<label>完整报文体(奇门同层级 { request },与真实回调一致,可编辑)</label>
<textarea id="dataInput" rows="8" placeholder='{"request":{}}'></textarea>
<button id="sendBtn" class="send-btn" onclick="sendTest()">发送测试回调</button>
@ -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 = '{}';

View File

@ -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);

View File

@ -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<Object>} 回调结果 { 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<Object>} 回调结果 { 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);

View File

@ -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',
},
},
},
];

View File

@ -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<Object>} 回调测试结果。
*/
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) {

View File

@ -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<Object>} 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<Object> }} 组装后的业务报文
*/
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<Object|null>} 返回回传结果 { 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 };
}

View File

@ -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<Object>} options.successResults 同步成功结果列表。
* @param {Map<number, Object>} options.orderMap 订单 ID 到主表记录的映射。
* @param {Map<number, Array<Object>>} options.itemsByOrderId 订单 ID 到明细列表的映射。
* @return {Promise<void>} 无返回值,失败仅记录 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<Object>} 同步结果(含 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) {

View File

@ -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<void>}
* @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<Array<Object>|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<Object>} orderLines 入库明细行数组
* @param {Object} [options] 可选配置
* @param {string} [options.outBizCode] 外部业务编码,缺省时自动生成 RECEIVING_MATCH_时间戳
* @param {string} [options.remark] 备注
* @return {{ entryOrder: Object, orderLines: Array<Object> }} 组装后的业务报文
*/
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) {

View File

@ -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 不重复" ]
}
}

View File

@ -0,0 +1,190 @@
# API 文档更新工作流(`script/update-api-doc.cjs`)
> 本文档说明 `methods/*.json`(接口文档 SSOT)与 `methods/changes/*.json`(变更记录)的**唯一合规写入方式**:
> 通过 `npm run doc:api:update -- --spec=<path>` 执行,禁止直接手写这两个目录下的 JSON。
> 内容以 `script/update-api-doc.cjs` 实际实现为准;回归测试见 `test/scripts/update_api_doc.test.cjs`(13 用例)。
## 1. 命令用法
```powershell
npm run doc:api:update -- --spec=<path> # 正式写入(主文档 + 变更记录)
npm run doc:api:update -- --spec=<path> --dry-run # 只校验并打印计划,不写任何文件
npm run doc:api:update -- --spec=<path> --doc-only # 只写 methods/<docName>.json,跳过变更记录
npm run doc:api:update -- --help # 打印用法、选项与 spec.newDoc 说明(-h 等价)
```
- `--spec=<path>`:必填;相对路径按项目根目录(`process.cwd()`)解析。缺省报 `Missing required --spec=<path> argument.`;文件不存在报 `Spec file not found: <path>`。
- 脚本底层等价于 `node ./script/update-api-doc.cjs --spec=<path>`,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/<docName>.json` 与 `methods/changes/<docName>.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/<docName>.json` **不存在**时,spec 必须提供 `newDoc`,脚本自动生成文档骨架后再应用 `group` / `methods`;否则报:
```
Target doc file not found: <path> (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/<docName>.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/<docName>.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/<docName>.json` 与 `methods/changes/<docName>.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/<docName>.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=<path> argument.` | 未传 `--spec=`(npm 调用需加 `--` 分隔符) |
| `Spec file not found: <path>` | 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: <path> (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 等。

View File

@ -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&timestamp={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&timestamp=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` 等)为追加式历史,保持原样,不回改。

View File

@ -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&timestamp=&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 校验)"
]
}
]

File diff suppressed because it is too large Load Diff

View File

@ -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> Path to the fixed update spec JSON file.',
' --dry-run Validate and print the planned changes without writing files.',
' --doc-only Update methods/<docName>.json only and skip methods/changes/<docName>.json.',
'',
'spec.newDoc (optional spec field, only used when methods/<docName>.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/<docName>.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,
};

View File

@ -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 应为秒级');
});
});

View File

@ -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<string>} 字段名集合。
*/
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} 源码中出现`
);
}
}
});
});

View File

@ -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/);
});
});
});

View File

@ -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');
});
});

View File

@ -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<Object>} [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<Object>} 明细行数组。
*/
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);
});
});
});

View File

@ -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<void>} 条件成立或超时后返回。
*/
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');
});
});

View File

@ -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<Object>} [options.entryItems] 奇门回传时重新加载的入库单明细。
* @param {Array<Object>} [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);
});
});

View File

@ -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/<docName>.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/<docName>.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 });
});