WMS_MAIN/test/app/service/systems/express_platform.polyapi.test.js
liufumingren 9af7dcf8fb feat(storeWarehouse): 签约关系接口配置按货主开放接口落库且回调地址统一取配置
- storeWarehouse.store.saveApiConfig:新增 resolveContractApiInterfaceType,
  interface_type_id=3(OPEN_API_WAREHOUSE 仓库开放接口)自动映射为 2(OPEN_API 货主开放接口)落库,
  不再要求当前主体为仓库(货主可维护自身签约关系下的接口配置)
- callback_url 不再取入参(含 callbackUrl 别名),统一写入 config.openapi.defaultCallbackUrl(新增配置项,默认空)
- storeWarehouse.store.listApiConfig:interface_type_id 过滤同步映射(传 3 按 2 查询)
- 文档:methods/system.json 升级 0.3.350、methods/changes/system.json 变更记录、docs/openapi-callback-events.md 回调地址来源说明
- 测试:saveApiConfig 新增 4 条用例(3→2 落库、忽略入参回调地址、默认值未配置、货主主体可保存、缺失类型 404),listApiConfig 新增 1 条过滤映射用例

同时提交工作区其余在制品改动:
- waybill:移除 wms_order_express_trace 模型并新增 drop 迁移,轨迹查询/取号/打印链路调整
- order:订单 SN 编码(order_item_sn / order_item_sn_log / sn_code_rule、has_sn_item 回填迁移),pendingOrder/recheckOrder/wave/base 调整
- express_platform、order_async、order_export、order_storage_allocation、storage.report、stock_store 配套修复
- lib:新增 jd_client,调整 qimen_client、callback_functions 及配套测试

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-14 17:14:04 +08:00

573 lines
20 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 ExpressPlatformService = require('../../../../app/service/systems/express_platform');
/**
* 创建菠萝派平台服务测试桩。
*
* @param {Object} [options={}] 测试配置。
* @return {Object} 测试上下文、调用记录与服务实例。
*/
function createPolyapiHarness(options = {}) {
const relationRows = Array.isArray(options.relationRows)
? options.relationRows
: [
{
id: 77,
store_id: 2001,
warehouse_id: 100000,
print_quantity: 8,
print_quantity_locked: 5,
},
];
const calls = {
transaction: 0,
transactionRef: null,
loadExpressList: 0,
request: 0,
operationLogCreate: 0,
operationLogBatchCreate: 0,
operationLogArgsList: [],
orderExpressUpdate: 0,
orderExpressUpdateArgsList: [],
orderExpressFindAll: 0,
orderExpressFindAllQuery: null,
orderDeliveryFindAll: 0,
orderDeliveryFindAllQuery: null,
orderDeliveryUpdate: 0,
orderDeliveryUpdateArgsList: [],
storeWarehouseFindAll: 0,
storeWarehouseFindAllQuery: null,
storeWarehouseIncrement: 0,
storeWarehouseIncrementArgsList: [],
storeWarehouseUpdate: 0,
storeWarehouseUpdateArgsList: [],
printQuantityLogCreate: 0,
printQuantityLogCreateArgsList: [],
getWaybillAsyncOrderDeliveryModel: 0,
getWaybillAsyncOrderDeliveryModelArgs: [],
getContractConfigCalls: [],
filterAutoSyncSnOrderIdsCalls: [],
syncOrderIdsCalls: [],
callSequence: [],
};
const orderDeliveryModel = {
async findAll(query) {
calls.orderDeliveryFindAll += 1;
calls.orderDeliveryFindAllQuery = query;
return [];
},
async update(values, query) {
calls.callSequence.push('orderDelivery.update');
calls.orderDeliveryUpdate += 1;
calls.orderDeliveryUpdateArgsList.push({ values, query });
return [ 1 ];
},
};
const storeWarehouseModel = {
async findAll(query) {
calls.callSequence.push('storeWarehouse.findAll');
calls.storeWarehouseFindAll += 1;
calls.storeWarehouseFindAllQuery = query;
return relationRows;
},
async increment(field, query = {}) {
calls.callSequence.push(`storeWarehouse.increment.${field}`);
calls.storeWarehouseIncrement += 1;
calls.storeWarehouseIncrementArgsList.push({ field, query });
const targetId = Number(query.where && query.where.id);
const targetRow = relationRows.find(item => Number(item.id) === targetId);
if (targetRow && field) {
targetRow[field] = Number(targetRow[field] || 0) + Number(query.by || 0);
}
return [ 1 ];
},
async update(values, query) {
calls.callSequence.push('storeWarehouse.update');
calls.storeWarehouseUpdate += 1;
calls.storeWarehouseUpdateArgsList.push({ values, query });
const targetId = Number(query.where && query.where.id);
const targetRow = relationRows.find(item => Number(item.id) === targetId);
if (targetRow && values && typeof values === 'object') {
Object.assign(targetRow, values);
}
return [ 1 ];
},
};
const ctx = {
app: {
Sequelize: {
Op: {
or: 'or',
in: 'in',
},
},
formatDate(date, formatStr = 'YYYY-MM-DD HH:mm:ss') {
const targetDate = date instanceof Date ? date : new Date(date);
const values = {
YYYY: String(targetDate.getFullYear()),
MM: String(targetDate.getMonth() + 1).padStart(2, '0'),
DD: String(targetDate.getDate()).padStart(2, '0'),
HH: String(targetDate.getHours()).padStart(2, '0'),
mm: String(targetDate.getMinutes()).padStart(2, '0'),
ss: String(targetDate.getSeconds()).padStart(2, '0'),
};
return formatStr.replace(/YYYY|MM|DD|HH|mm|ss/g, token => values[token]);
},
},
model: {
async transaction(callback) {
calls.transaction += 1;
const transaction = {
LOCK: {
UPDATE: 'UPDATE',
},
};
calls.transactionRef = transaction;
calls.callSequence.push('transaction.begin');
const result = await callback(transaction);
calls.callSequence.push('transaction.commit');
return result;
},
OrderExpress: {
async findAll(query) {
calls.callSequence.push('orderExpress.findAll');
calls.orderExpressFindAll += 1;
calls.orderExpressFindAllQuery = query;
return Array.isArray(options.orderExpressRows)
? options.orderExpressRows
: [
{
order_id: 101,
business_key: 9101,
waybill_code: 'REAL-WB-101',
},
{
order_id: 102,
business_key: 9102,
waybill_code: 'REAL-WB-102',
},
{
order_id: 103,
business_key: 9103,
waybill_code: 'REAL-WB-103',
},
];
},
async update(values, query) {
calls.callSequence.push('orderExpress.update');
calls.orderExpressUpdate += 1;
calls.orderExpressUpdateArgsList.push({ values, query });
return [ 1 ];
},
},
StoreWarehouse: storeWarehouseModel,
StoreWarehousePrintQuantityLog: {
async create(values, opts) {
calls.callSequence.push('storeWarehousePrintQuantityLog.create');
calls.printQuantityLogCreate += 1;
calls.printQuantityLogCreateArgsList.push({ values, opts });
return values;
},
},
},
logger: {
info() {},
warn() {},
error() {},
},
service: {
systems: {
express: {
async loadExpressList() {
calls.loadExpressList += 1;
return [
{
code: 'SF',
polyapi_code: 'SF_API',
polyapi_extra_info: { channel: 'polyapi' },
},
];
},
async getWaybillAsyncOrderDeliveryModel(warehouseId) {
calls.getWaybillAsyncOrderDeliveryModel += 1;
calls.getWaybillAsyncOrderDeliveryModelArgs.push(warehouseId);
return orderDeliveryModel;
},
},
poloApi: {
async request(apiName, bizcontent, matchedPlatform, token) {
calls.request += 1;
calls.requestArgs = {
apiName,
bizcontent,
matchedPlatform,
token,
};
if (apiName === 'Differ.JH.Logistics.PostOrder' && options.postOrderResult !== undefined) {
return options.postOrderResult;
}
return options.result || {
code: '10000',
results: [
{
orderno: '186a0_65_9101',
waybill_code: 'REAL-WB-101',
logisticno: 'PRE-WB-101',
printinfo: 'print-101',
signature: 'sign-101',
encryptprintinfo: 'enc-101',
issuccess: '1',
},
{
orderno: '186a0_66_9102',
logisticno: 'WB-102',
printinfo: 'print-102',
signature: 'sign-102',
encryptprintinfo: 'enc-102',
issuccess: '1',
},
{
orderno: '186a0_67_9103',
logisticno: 'WB-103',
printinfo: 'print-103',
signature: 'sign-103',
encryptprintinfo: 'enc-103',
issuccess: '1',
},
],
};
},
},
operationLog: {
async createOperationLogs(payloads = []) {
calls.callSequence.push('operationLog.createOperationLogs');
calls.operationLogBatchCreate += 1;
calls.operationLogCreate += payloads.length;
calls.operationLogArgsList.push(...payloads);
return payloads;
},
async createOperationLog(payload) {
calls.callSequence.push('operationLog.createOperationLog');
calls.operationLogCreate += 1;
calls.operationLogArgsList.push(payload);
return payload;
},
},
storeWarehouse: {
async getContractConfig(warehouseId, storeId) {
calls.getContractConfigCalls.push({ warehouseId, storeId });
if (options.contractConfig !== undefined) {
return options.contractConfig;
}
return { policy_config: { auto_sync_back: 1 } };
},
},
},
systemMethods: {
order: {
pendingOrder: {
async filterAutoSyncSnOrderIds(request) {
calls.filterAutoSyncSnOrderIdsCalls.push(request);
const skipped = Array.isArray(options.snOrderIds) ? options.snOrderIds : [];
const requestOrderIds = Array.isArray(request.orderIds) ? request.orderIds : [];
return {
orderIds: requestOrderIds.filter(orderId => !skipped.includes(orderId)),
skippedSnOrderIds: requestOrderIds.filter(orderId => skipped.includes(orderId)),
};
},
async syncOrderIds(request) {
calls.syncOrderIdsCalls.push(request);
return { flag: 'success' };
},
},
},
},
},
};
return {
ctx,
calls,
relationRows,
service: new ExpressPlatformService(ctx),
};
}
/**
* 构造平台回调入参。
*
* @return {Object} 菠萝派平台回调入参。
*/
function buildPolyapiPayload() {
return {
matchedPlatform: {
ordersource: 'WMS',
shoptype: 'SHOP',
},
listByWarehousePlatformCode: {
id: 11,
warehouse_id: 100000,
platform_code: 'KS',
sys_express_code: 'SF',
logistics_code: 'SF-LOGI',
logistics_name: '顺丰',
name: '顺丰平台',
token: 'token-1',
client_id: 'client-1',
site_code: 'site-1',
},
orders: [
{
order_id: 101,
business_key: 9101,
order_delivery: {
id: 101,
store_id: 2001,
warehouse_id: 100000,
},
},
{
order_id: 102,
business_key: 9102,
order_delivery: {
id: 102,
store_id: 2001,
warehouse_id: 100000,
},
},
{
order_id: 103,
business_key: 9103,
order_delivery: {
id: 103,
warehouse_id: 100000,
},
},
],
};
}
describe('test/app/service/systems/express_platform.polyapi.test.js', () => {
it('should update success orders and deduct both print balance and locked balance after polyapi callback success', async () => {
const { calls, relationRows, service } = createPolyapiHarness();
const result = await service.polyapi(buildPolyapiPayload());
assert.equal(calls.request, 2);
assert.equal(calls.transaction, 1);
assert.equal(calls.orderExpressUpdate, 3);
assert.equal(calls.orderDeliveryUpdate, 3);
assert.equal(calls.storeWarehouseFindAll, 1);
assert.equal(calls.storeWarehouseIncrement, 0);
assert.equal(calls.storeWarehouseUpdate, 1);
assert.equal(calls.printQuantityLogCreate, 1);
assert.equal(calls.operationLogBatchCreate, 1);
assert.equal(calls.operationLogCreate, 3);
assert.equal(calls.orderExpressUpdateArgsList[0].query.transaction, calls.transactionRef);
assert.equal(calls.orderDeliveryUpdateArgsList[0].query.transaction, calls.transactionRef);
assert.equal(calls.storeWarehouseUpdateArgsList[0].query.transaction, calls.transactionRef);
assert.deepEqual(calls.storeWarehouseFindAllQuery.where.or, [
{ store_id: 2001, warehouse_id: 100000 },
]);
assert.equal(calls.storeWarehouseUpdateArgsList[0].values.print_quantity, 6);
assert.equal(calls.storeWarehouseUpdateArgsList[0].values.print_quantity_locked, 3);
assert.equal(calls.storeWarehouseUpdateArgsList[0].query.where.id, 77);
assert.equal(calls.orderExpressFindAll, 1);
assert.deepEqual(calls.orderExpressFindAllQuery.where.order_id.in, [ 101, 102, 103 ]);
assert.equal(calls.orderDeliveryFindAll, 1);
assert.deepEqual(calls.orderDeliveryFindAllQuery.where.id, [ 101, 102, 103 ]);
assert.equal(calls.printQuantityLogCreateArgsList[0].opts.transaction, calls.transactionRef);
assert.equal(calls.printQuantityLogCreateArgsList[0].values.change_type, 'order_deduct');
assert.ok(calls.printQuantityLogCreateArgsList[0].values.change_quantity < 0);
assert.ok(calls.printQuantityLogCreateArgsList[0].values.balance_before >= 0);
assert.ok(calls.printQuantityLogCreateArgsList[0].values.balance_after >= 0);
assert.equal(relationRows[0].print_quantity, 6);
assert.equal(relationRows[0].print_quantity_locked, 3);
assert.equal(calls.getWaybillAsyncOrderDeliveryModel, 4);
assert.deepEqual(calls.getWaybillAsyncOrderDeliveryModelArgs, [ 100000, 100000, 100000, 100000 ]);
assert.equal(calls.operationLogArgsList[0].businessId, '101');
assert.equal(calls.requestArgs.bizcontent.orders[0].logisticno, 'REAL-WB-101');
assert.equal(calls.requestArgs.bizcontent.orders[1].logisticno, 'REAL-WB-102');
assert.equal(calls.requestArgs.bizcontent.orders[2].logisticno, 'REAL-WB-103');
const transactionCommitIndex = calls.callSequence.indexOf('transaction.commit');
const operationLogIndex = calls.callSequence.indexOf('operationLog.createOperationLogs');
assert.ok(transactionCommitIndex > -1);
assert.ok(operationLogIndex > transactionCommitIndex);
assert.equal(result.flag, true);
assert.equal(result.code, 0);
assert.equal(result.message, '菠萝派平台数据处理成功');
assert.equal(calls.orderExpressUpdateArgsList[0].values.status, 1);
assert.equal(calls.orderDeliveryUpdateArgsList[0].values.post_status, 'fin');
});
it('should throw when polyapi returns system error with empty results', async () => {
const { calls, service } = createPolyapiHarness({
postOrderResult: {
code: '40000',
env: '3',
messagefrom: 'POLY',
msg: 'System Error',
polyapirequestid: '1276199519688854528P3672M010E11',
polyapitotalms: 5,
results: [],
subcode: 'GSE.REQUEST_FAILURE.SYSTEMERROR',
submessage: '服务异常请稍后再试',
},
});
await assert.rejects(
() => service.polyapi(buildPolyapiPayload()),
/菠萝派分配快递号失败: 服务异常请稍后再试/
);
// 取号失败不应进入回写事务,也不应写成功日志
assert.equal(calls.transaction, 0);
assert.equal(calls.orderExpressUpdate, 0);
assert.equal(calls.orderDeliveryUpdate, 0);
assert.equal(calls.operationLogBatchCreate, 0);
// 失败订单的锁定打印量需要回退
assert.equal(calls.storeWarehouseIncrement, 1);
assert.equal(
calls.storeWarehouseIncrementArgsList[0].field,
'print_quantity_locked'
);
// 只有 101/102 带 store_id,回退 2 笔
assert.equal(calls.storeWarehouseIncrementArgsList[0].query.by, -2);
});
it('should still deduct print balance when locked balance is zero after polyapi callback success', async () => {
const { calls, relationRows, service } = createPolyapiHarness({
relationRows: [
{
id: 88,
store_id: 2001,
warehouse_id: 100000,
print_quantity: 3,
print_quantity_locked: 0,
},
],
});
const result = await service.polyapi(buildPolyapiPayload());
assert.equal(calls.transaction, 1);
assert.equal(calls.orderExpressUpdate, 3);
assert.equal(calls.orderDeliveryUpdate, 3);
assert.equal(calls.storeWarehouseFindAll, 1);
assert.equal(calls.storeWarehouseIncrement, 0);
assert.equal(calls.storeWarehouseUpdate, 1);
assert.equal(calls.printQuantityLogCreate, 1);
assert.equal(calls.storeWarehouseUpdateArgsList[0].values.print_quantity, 1);
assert.equal(calls.storeWarehouseUpdateArgsList[0].values.print_quantity_locked, 0);
assert.equal(calls.storeWarehouseUpdateArgsList[0].query.where.id, 88);
assert.equal(calls.storeWarehouseUpdateArgsList[0].query.transaction, calls.transactionRef);
assert.equal(calls.printQuantityLogCreateArgsList[0].opts.transaction, calls.transactionRef);
assert.equal(calls.printQuantityLogCreateArgsList[0].values.change_type, 'order_deduct');
assert.ok(calls.printQuantityLogCreateArgsList[0].values.change_quantity < 0);
assert.ok(calls.printQuantityLogCreateArgsList[0].values.balance_before >= 0);
assert.ok(calls.printQuantityLogCreateArgsList[0].values.balance_after >= 0);
assert.equal(relationRows[0].print_quantity, 1);
assert.equal(relationRows[0].print_quantity_locked, 0);
assert.equal(calls.orderExpressUpdateArgsList[0].query.transaction, calls.transactionRef);
assert.equal(calls.orderDeliveryUpdateArgsList[0].query.transaction, calls.transactionRef);
assert.equal(result.flag, true);
assert.equal(result.code, 0);
assert.equal(result.message, '菠萝派平台数据处理成功');
});
it('should deduct print balance even when print quantity is negative after polyapi callback success', async () => {
const { calls, relationRows, service } = createPolyapiHarness({
relationRows: [
{
id: 99,
store_id: 2001,
warehouse_id: 100000,
print_quantity: -1,
print_quantity_locked: 2,
},
],
});
const result = await service.polyapi(buildPolyapiPayload());
assert.equal(calls.transaction, 1);
assert.equal(calls.storeWarehouseFindAll, 1);
assert.equal(calls.storeWarehouseIncrement, 0);
assert.equal(calls.storeWarehouseUpdate, 1);
assert.equal(calls.printQuantityLogCreate, 1);
assert.equal(calls.storeWarehouseUpdateArgsList[0].values.print_quantity, -3);
assert.equal(calls.storeWarehouseUpdateArgsList[0].values.print_quantity_locked, 0);
assert.equal(calls.storeWarehouseUpdateArgsList[0].query.where.id, 99);
assert.equal(calls.storeWarehouseUpdateArgsList[0].query.transaction, calls.transactionRef);
assert.equal(calls.printQuantityLogCreateArgsList[0].opts.transaction, calls.transactionRef);
assert.equal(calls.printQuantityLogCreateArgsList[0].values.change_type, 'order_deduct');
assert.ok(calls.printQuantityLogCreateArgsList[0].values.change_quantity < 0);
assert.ok(calls.printQuantityLogCreateArgsList[0].values.balance_before >= 0);
assert.ok(calls.printQuantityLogCreateArgsList[0].values.balance_after >= 0);
assert.equal(relationRows[0].print_quantity, -3);
assert.equal(relationRows[0].print_quantity_locked, 0);
assert.equal(result.flag, true);
assert.equal(result.code, 0);
assert.equal(result.message, '菠萝派平台数据处理成功');
});
it('auto_sync_back 开启且无登录用户上下文时,应以显式 warehouseId 触发订单同步回传', async () => {
const { calls, service } = createPolyapiHarness();
await service.polyapi(buildPolyapiPayload());
assert.equal(calls.getContractConfigCalls.length, 1);
assert.deepEqual(calls.getContractConfigCalls[0], { warehouseId: 100000, storeId: 2001 });
assert.equal(calls.filterAutoSyncSnOrderIdsCalls.length, 1);
assert.deepEqual(calls.filterAutoSyncSnOrderIdsCalls[0], {
orderIds: [ 101, 102 ],
warehouseId: 100000,
source: 'polyapi',
});
assert.equal(calls.syncOrderIdsCalls.length, 1);
assert.deepEqual(calls.syncOrderIdsCalls[0], {
orderIds: [ 101, 102 ],
warehouseId: 100000,
});
});
it('auto_sync_back 开启时 SN 订单静默跳过,不触发同步回传', async () => {
const { calls, service } = createPolyapiHarness({ snOrderIds: [ 101, 102 ] });
await service.polyapi(buildPolyapiPayload());
assert.equal(calls.filterAutoSyncSnOrderIdsCalls.length, 1);
assert.equal(calls.syncOrderIdsCalls.length, 0);
});
it('auto_sync_back 关闭时不应触发订单同步回传', async () => {
const { calls, service } = createPolyapiHarness({
contractConfig: { policy_config: { auto_sync_back: 0 } },
});
await service.polyapi(buildPolyapiPayload());
assert.equal(calls.syncOrderIdsCalls.length, 0);
});
});