WMS_MAIN/test/app/service/systems/express_platform.polyapi.test.js
liufumingren 8f2e141fe0 fix(express): 菠萝派平台返回空 results 时判定为系统级失败
- polyapi 取号结果 results 为空数组且请求含订单时(如 code=40000 / GSE.REQUEST_FAILURE.SYSTEMERROR),
  旧逻辑会当成 0 条结果继续走成功分支,订单既不回写运单号也不标记异常;
  现直接按失败抛出,失败原因拼接 submessage/message,并附带 polyapirequestid 便于平台侧定位。
- 顺带修正 providercode 判断处的代码风格(if 后空格)。

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-28 07:22:33 +08:00

548 lines
19 KiB
JavaScript
Raw 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: [],
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 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.syncOrderIdsCalls.length, 1);
assert.deepEqual(calls.syncOrderIdsCalls[0], {
orderIds: [ 101, 102 ],
warehouseId: 100000,
});
});
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);
});
});