WMS_MAIN/test/app/service/systems/receiving_entry_match.callback.test.js
liufumingren d725e7e457 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 等。
2026-09-13 02:24:37 +08:00

495 lines
19 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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