feat(order): 新增运单号批量导入,并增加运单号仓库内唯一校验
- 新增 order.pendingOrder.importWaybill:按 delivery_order_code + store_remark 定位当前仓库待处理订单,逐条写入运单记录并返回逐条结果 - manualWaybill 与 importWaybill 共用 assertWaybillEntryAllowed / assertWaybillCodeUnused / createManualWaybillRecord,保证口径一致 - manualWaybill 增加运单号同仓库唯一校验(delete_at 为空时已存在即拒绝) - 同步更新 API 文档(methods/system.json、methods/changes/system.json)与 AI_METHOD_ROUTING.md - 补充 importWaybill 单元测试,修复 manualWaybill 测试缺失的 OrderExpress.findOne 桩 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
parent
22e95306b7
commit
1e1c13f38c
@ -462,8 +462,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods
|
||||
- list, manualOutboundOrder
|
||||
- app/service/systemMethods/order/packing.js (11)
|
||||
- list, get, setEndTime, forceRecord, export, exportTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress
|
||||
- app/service/systemMethods/order/pendingOrder.js (89)
|
||||
- list, detail, reverseReviewOrder, assertOrdersWithoutWaybill, syncWavesAfterReverseReview, allocateStorage, allocateStorageProgress, normalizeAllocateStorageTaskProgress, normalizeAllocateStorageTaskCount, normalizeAllocateStorageTaskCounts, normalizeAllocateStorageRequestId, getAllocateStorageTaskCacheKey, setAllocateStorageTaskProgress, getAllocateStorageTaskProgress, getAllocateExpressTaskCacheKey, normalizeAllocateExpressTaskId, setAllocateExpressTaskProgress, getAllocateExpressTaskProgress, getSyncOrderIdsTaskCacheKey, normalizeSyncOrderIdsRequestId, setSyncOrderIdsTaskProgress, getSyncOrderIdsTaskProgress, cancelAllocateStorage, syncOrderIds, syncOrderIdsProgress, allocateExpressCode, allocateExpressCodeTaskProgress, markPendingOutboundOrder, cancelOrder, normalizePendingOutboundOrderIds, normalizePendingCancelOrderIds, isCancelablePendingOrder, updateOrderPlatform, updateOrderExpress, updateAddress, updateRemark, cloneOrder, parseAddress, parseAddressLocal, createOrder, downloadCreateTemplate, normalizeIdsInput, batchIntercept, batchInterceptTaskProgress, generateBatchInterceptTaskId, normalizeBatchInterceptTaskId, normalizeBatchInterceptOrderIds, getBatchInterceptTaskCacheKey, setBatchInterceptTaskProgress, getBatchInterceptTaskProgress, runBatchInterceptTask, batchLock, batchLockTaskProgress, generateBatchLockTaskId, normalizeBatchLockTaskId, normalizeBatchLockOrderIds, getBatchLockTaskCacheKey, setBatchLockTaskProgress, getBatchLockTaskProgress, runBatchLockTask, batchUnlock, batchUnlockTaskProgress, generateBatchUnlockTaskId, normalizeBatchUnlockTaskId, normalizeBatchUnlockOrderIds, getBatchUnlockTaskCacheKey, setBatchUnlockTaskProgress, getBatchUnlockTaskProgress, runBatchUnlockTask, batchUnintercept, batchUninterceptTaskProgress, generateBatchUninterceptTaskId, normalizeBatchUninterceptTaskId, normalizeBatchUninterceptOrderIds, getBatchUninterceptTaskCacheKey, setBatchUninterceptTaskProgress, getBatchUninterceptTaskProgress, runBatchUninterceptTask, manualWaybill, releaseCreationLockForCancel, allocateSubOrderNumber, writeAllocateSubOrderErrorFlag, writeAllocateSubOrderLog, allocateSubOrderNumberProgress, getAllocateSubOrderTaskCacheKey, setAllocateSubOrderTaskProgress, getAllocateSubOrderTaskProgress, buildSubOrderDetails, batchMarkPrinted
|
||||
- app/service/systemMethods/order/pendingOrder.js (96)
|
||||
- list, detail, reverseReviewOrder, assertOrdersWithoutWaybill, syncWavesAfterReverseReview, allocateStorage, allocateStorageProgress, normalizeAllocateStorageTaskProgress, normalizeAllocateStorageTaskCount, normalizeAllocateStorageTaskCounts, normalizeAllocateStorageRequestId, getAllocateStorageTaskCacheKey, setAllocateStorageTaskProgress, getAllocateStorageTaskProgress, getAllocateExpressTaskCacheKey, normalizeAllocateExpressTaskId, setAllocateExpressTaskProgress, getAllocateExpressTaskProgress, getSyncOrderIdsTaskCacheKey, normalizeSyncOrderIdsRequestId, setSyncOrderIdsTaskProgress, getSyncOrderIdsTaskProgress, cancelAllocateStorage, syncOrderIds, syncOrderIdsProgress, allocateExpressCode, allocateExpressCodeTaskProgress, markPendingOutboundOrder, cancelOrder, normalizePendingOutboundOrderIds, normalizePendingCancelOrderIds, isCancelablePendingOrder, updateOrderPlatform, updateOrderExpress, updateAddress, updateRemark, cloneOrder, parseAddress, parseAddressLocal, createOrder, downloadCreateTemplate, normalizeIdsInput, batchIntercept, batchInterceptTaskProgress, generateBatchInterceptTaskId, normalizeBatchInterceptTaskId, normalizeBatchInterceptOrderIds, getBatchInterceptTaskCacheKey, setBatchInterceptTaskProgress, getBatchInterceptTaskProgress, runBatchInterceptTask, batchLock, batchLockTaskProgress, generateBatchLockTaskId, normalizeBatchLockTaskId, normalizeBatchLockOrderIds, getBatchLockTaskCacheKey, setBatchLockTaskProgress, getBatchLockTaskProgress, runBatchLockTask, batchUnlock, batchUnlockTaskProgress, generateBatchUnlockTaskId, normalizeBatchUnlockTaskId, normalizeBatchUnlockOrderIds, getBatchUnlockTaskCacheKey, setBatchUnlockTaskProgress, getBatchUnlockTaskProgress, runBatchUnlockTask, batchUnintercept, batchUninterceptTaskProgress, generateBatchUninterceptTaskId, normalizeBatchUninterceptTaskId, normalizeBatchUninterceptOrderIds, getBatchUninterceptTaskCacheKey, setBatchUninterceptTaskProgress, getBatchUninterceptTaskProgress, runBatchUninterceptTask, manualWaybill, importWaybill, normalizeWaybillImportRows, pickImportRowValue, resolveOrderForWaybillImport, assertWaybillEntryAllowed, assertWaybillCodeUnused, createManualWaybillRecord, releaseCreationLockForCancel, allocateSubOrderNumber, writeAllocateSubOrderErrorFlag, writeAllocateSubOrderLog, allocateSubOrderNumberProgress, getAllocateSubOrderTaskCacheKey, setAllocateSubOrderTaskProgress, getAllocateSubOrderTaskProgress, buildSubOrderDetails, batchMarkPrinted
|
||||
- app/service/systemMethods/order/print.js (4)
|
||||
- getWavePlatformPrintData, getOrderPrintData, getPrintDataByWaybillCodes, unlockWavePlatformPrintDataByGroup
|
||||
- app/service/systemMethods/order/recheckOrder.js (59)
|
||||
|
||||
@ -860,9 +860,9 @@ class PendingOrderService extends OrderBaseService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,parseAddressLocal,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill,allocateSubOrderNumber,allocateSubOrderNumberProgress,batchMarkPrinted';
|
||||
const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,parseAddress,parseAddressLocal,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill,allocateSubOrderNumber,allocateSubOrderNumberProgress,batchMarkPrinted';
|
||||
const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,parseAddressLocal,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill,allocateSubOrderNumber,allocateSubOrderNumberProgress,batchMarkPrinted';
|
||||
const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,parseAddressLocal,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill,importWaybill,allocateSubOrderNumber,allocateSubOrderNumberProgress,batchMarkPrinted';
|
||||
const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,parseAddress,parseAddressLocal,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill,importWaybill,allocateSubOrderNumber,allocateSubOrderNumberProgress,batchMarkPrinted';
|
||||
const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,parseAddressLocal,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill,importWaybill,allocateSubOrderNumber,allocateSubOrderNumberProgress,batchMarkPrinted';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
@ -6794,6 +6794,7 @@ class PendingOrderService extends OrderBaseService {
|
||||
*
|
||||
* 为指定待处理订单创建一条运单记录(wms_order_express 表),
|
||||
* 仅允许 step 在 [1,2,3] 且 outbound_status 不为 'padding' 的订单操作。
|
||||
* 运单号在同一仓库内唯一,已被其它订单占用时拒绝录入。
|
||||
* 完成后同步更新订单表的 print_status 与 post_status 为 'fin',表示外部已打印。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
@ -6877,26 +6878,289 @@ class PendingOrderService extends OrderBaseService {
|
||||
throw new Error(`订单 ${orderId} 不存在或不属于当前仓库`);
|
||||
}
|
||||
|
||||
const orderWarehouseId = Number(order.warehouse_id) || warehouseId;
|
||||
|
||||
// 3. 校验订单状态与运单号占用(同一仓库内唯一)
|
||||
await this.assertWaybillEntryAllowed({ order, orderId, warehouseId: orderWarehouseId });
|
||||
await this.assertWaybillCodeUnused({ waybillCode, warehouseId: orderWarehouseId });
|
||||
|
||||
// 4. 创建运单记录并同步订单状态
|
||||
const result = await this.createManualWaybillRecord({
|
||||
order,
|
||||
orderModel: model,
|
||||
waybillCode,
|
||||
logisticsInterfaceName,
|
||||
expressResolved,
|
||||
warehouseId: orderWarehouseId,
|
||||
operator,
|
||||
logWarehouseId,
|
||||
expressCode: expressCodeRaw || null,
|
||||
operationCode: 'ORDER_MANUAL_WAYBILL',
|
||||
actionText: '手工录入运单号',
|
||||
autoSyncSource: 'manualWaybill',
|
||||
});
|
||||
|
||||
return this.success('ok', result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 导入运单号(批量)。
|
||||
*
|
||||
* 入参为记录数组,每条记录按 delivery_order_code + store_remark(货主备注
|
||||
* wms_store_warehouse.store_remask)唯一定位待处理订单,定位到订单后按 manualWaybill
|
||||
* 的口径写入运单记录并同步订单打印/过账状态。
|
||||
* 运单号在同一仓库内唯一,已被占用时该条失败。
|
||||
* 单条失败不影响其它记录,返回逐条处理结果。
|
||||
*
|
||||
* @param {Array<Object>|Object} data 请求体,记录数组(或 { list: [] } / { rows: [] } 等包装)。
|
||||
* @param {string} data.delivery_order_code 发货单号。
|
||||
* @param {string} data.store_remark 货主备注。
|
||||
* @param {string} data.waybill_code 运单号。
|
||||
* @return {Promise<Object>} 统一 success 包装,data 为逐条结果数组。
|
||||
*/
|
||||
async importWaybill(data = {}) {
|
||||
const rows = this.normalizeWaybillImportRows(data);
|
||||
if (rows.length === 0) {
|
||||
throw new Error('导入数据不能为空或格式错误');
|
||||
}
|
||||
|
||||
const warehouseId = Number(this.getWarehouseId());
|
||||
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
|
||||
throw new Error('未识别到当前仓库上下文');
|
||||
}
|
||||
|
||||
const operator = this.getOrderLogOperator();
|
||||
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
|
||||
const orderModel = await this.getOrderModel('order', warehouseId);
|
||||
const requestId = `${Date.now()}${Math.floor(Math.random() * 1000)}`;
|
||||
const operatorId = Number(this.ctx.user && this.ctx.user.id) || 0;
|
||||
|
||||
const results = [];
|
||||
// 本次导入内的运单号占用登记:运单号 → 首次出现的发货单号,避免同批次重复导入
|
||||
const batchWaybillOwner = new Map();
|
||||
|
||||
for (let index = 0; index < rows.length; index++) {
|
||||
const row = rows[index];
|
||||
const isRowObject = this.isPlainObject(row);
|
||||
const rowData = isRowObject ? row : {};
|
||||
const deliveryOrderCode = this.pickImportRowValue(rowData, [ 'delivery_order_code', 'deliveryOrderCode' ]);
|
||||
const storeRemark = this.pickImportRowValue(rowData, [ 'store_remark', 'storeRemark' ]);
|
||||
const waybillCode = this.pickImportRowValue(rowData, [ 'waybill_code', 'waybillCode' ]);
|
||||
|
||||
const result = {
|
||||
delivery_order_code: deliveryOrderCode,
|
||||
store_remark: storeRemark,
|
||||
waybill_code: waybillCode,
|
||||
success: false,
|
||||
info: '',
|
||||
};
|
||||
results.push(result);
|
||||
|
||||
if (!isRowObject) {
|
||||
result.info = '数据格式错误:每条记录必须为对象';
|
||||
continue;
|
||||
}
|
||||
if (!deliveryOrderCode) {
|
||||
result.info = 'delivery_order_code(发货单号)不能为空';
|
||||
continue;
|
||||
}
|
||||
if (!waybillCode) {
|
||||
result.info = 'waybill_code(运单号)不能为空';
|
||||
continue;
|
||||
}
|
||||
if (batchWaybillOwner.has(waybillCode)) {
|
||||
const firstOwner = batchWaybillOwner.get(waybillCode);
|
||||
result.info = firstOwner === deliveryOrderCode
|
||||
? `运单号 ${waybillCode} 在本次导入数据中重复`
|
||||
: `运单号 ${waybillCode} 在本次导入数据中重复(首次出现在发货单号 ${firstOwner})`;
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const { order, message } = await this.resolveOrderForWaybillImport({
|
||||
orderModel,
|
||||
warehouseId,
|
||||
deliveryOrderCode,
|
||||
storeRemark,
|
||||
});
|
||||
if (!order) {
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
const orderId = Number(order.id);
|
||||
const orderWarehouseId = Number(order.warehouse_id) || warehouseId;
|
||||
|
||||
await this.assertWaybillEntryAllowed({ order, orderId, warehouseId: orderWarehouseId });
|
||||
await this.assertWaybillCodeUnused({ waybillCode, warehouseId: orderWarehouseId });
|
||||
|
||||
const record = await this.createManualWaybillRecord({
|
||||
order,
|
||||
orderModel,
|
||||
waybillCode,
|
||||
logisticsInterfaceName: null,
|
||||
expressResolved: null,
|
||||
warehouseId: orderWarehouseId,
|
||||
operator,
|
||||
logWarehouseId,
|
||||
operationCode: 'ORDER_IMPORT_WAYBILL',
|
||||
actionText: '导入运单号',
|
||||
autoSyncSource: 'importWaybill',
|
||||
requestId,
|
||||
operatorId,
|
||||
rowIndex: index + 1,
|
||||
});
|
||||
|
||||
batchWaybillOwner.set(waybillCode, deliveryOrderCode);
|
||||
result.success = true;
|
||||
result.info = 'ok';
|
||||
result.order_id = orderId;
|
||||
result.express_record_id = record.id;
|
||||
} catch (error) {
|
||||
result.info = error && error.message ? error.message : `${error}`;
|
||||
}
|
||||
}
|
||||
|
||||
return this.success('ok', results);
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化运单号导入数据为记录数组(保留原始行,非对象行在逐条处理时返回失败)。
|
||||
* @param {Object|Array} data 请求体。
|
||||
* @return {Array<Object>} 记录数组。
|
||||
*/
|
||||
normalizeWaybillImportRows(data = {}) {
|
||||
if (Array.isArray(data)) {
|
||||
return data;
|
||||
}
|
||||
|
||||
if (!this.isPlainObject(data)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
for (const candidate of [ data.list, data.rows, data.items, data.data ]) {
|
||||
if (Array.isArray(candidate)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取导入行字段,支持 snake_case 与 camelCase,返回 trim 后的字符串。
|
||||
* @param {Object} row 导入行。
|
||||
* @param {string[]} keys 候选字段名。
|
||||
* @return {string} 字段值。
|
||||
*/
|
||||
pickImportRowValue(row, keys = []) {
|
||||
for (const key of keys) {
|
||||
if (!Object.prototype.hasOwnProperty.call(row, key)) {
|
||||
continue;
|
||||
}
|
||||
const value = row[key];
|
||||
if (value === undefined || value === null) {
|
||||
continue;
|
||||
}
|
||||
return String(value).trim();
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 按发货单号 + 货主备注定位唯一待处理订单。
|
||||
* @param {Object} params 参数。
|
||||
* @param {Object} params.orderModel 待处理订单模型。
|
||||
* @param {number} params.warehouseId 仓库ID。
|
||||
* @param {string} params.deliveryOrderCode 发货单号。
|
||||
* @param {string} params.storeRemark 货主备注。
|
||||
* @return {Promise<{order: Object|null, message: string}>} 订单与失败原因。
|
||||
*/
|
||||
async resolveOrderForWaybillImport({ orderModel, warehouseId, deliveryOrderCode, storeRemark } = {}) {
|
||||
const orders = await orderModel.findAll({
|
||||
where: {
|
||||
delivery_order_code: deliveryOrderCode,
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
attributes: [ 'id', 'step', 'outbound_status', 'warehouse_id', 'store_id', 'sys_logistics_code', 'sys_logistics_name', 'delivery_order_code', 'source_order_codes' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (!Array.isArray(orders) || orders.length === 0) {
|
||||
return { order: null, message: `发货单号 ${deliveryOrderCode} 对应的订单不存在` };
|
||||
}
|
||||
|
||||
const { Op } = this.app.Sequelize;
|
||||
const storeIds = [
|
||||
...new Set(orders.map(item => Number(item.store_id || 0)).filter(id => id > 0)),
|
||||
];
|
||||
const storeRemarkMap = new Map();
|
||||
if (storeIds.length > 0 && this.ctx.model && this.ctx.model.StoreWarehouse) {
|
||||
const swRows = await this.ctx.model.StoreWarehouse.findAll({
|
||||
where: {
|
||||
store_id: { [Op.in]: storeIds },
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
attributes: [ 'store_id', 'store_remask' ],
|
||||
raw: true,
|
||||
});
|
||||
for (const sw of (Array.isArray(swRows) ? swRows : [])) {
|
||||
const storeId = Number(sw.store_id || 0);
|
||||
if (storeId > 0 && !storeRemarkMap.has(storeId)) {
|
||||
storeRemarkMap.set(storeId, String(sw.store_remask || '').trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const matched = orders.filter(
|
||||
item => (storeRemarkMap.get(Number(item.store_id || 0)) || '') === storeRemark
|
||||
);
|
||||
|
||||
if (matched.length === 0) {
|
||||
return {
|
||||
order: null,
|
||||
message: `发货单号 ${deliveryOrderCode} 对应订单的货主备注与导入的 store_remark(${storeRemark})不一致`,
|
||||
};
|
||||
}
|
||||
|
||||
if (matched.length > 1) {
|
||||
return {
|
||||
order: null,
|
||||
message: `发货单号 ${deliveryOrderCode} + 货主备注匹配到 ${matched.length} 条订单,无法唯一确定`,
|
||||
};
|
||||
}
|
||||
|
||||
return { order: matched[0], message: '' };
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验订单是否允许录入运单号:仅待处理(step 1/2/3、非待出库)且未分配过运单号。
|
||||
* @param {Object} params 参数。
|
||||
* @param {Object} params.order 订单行。
|
||||
* @param {number} params.orderId 订单ID。
|
||||
* @param {number} params.warehouseId 仓库ID。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async assertWaybillEntryAllowed({ order, orderId, warehouseId } = {}) {
|
||||
const allowedSteps = new Set([ 1, 2, 3 ]);
|
||||
if (!allowedSteps.has(order.step)) {
|
||||
throw new Error(`订单 ${orderId} 当前步骤为 ${order.step},仅允许待处理状态(step 1/2/3)的订单手工录入运单号`);
|
||||
const step = Number(order && order.step);
|
||||
if (!allowedSteps.has(step)) {
|
||||
throw new Error(`订单 ${orderId} 当前步骤为 ${step},仅允许待处理状态(step 1/2/3)的订单手工录入运单号`);
|
||||
}
|
||||
|
||||
if (order.outbound_status === PENDING_OUTBOUND_STATUS) {
|
||||
throw new Error(`订单 ${orderId} 已标记待出库,不允许手工录入运单号`);
|
||||
}
|
||||
|
||||
// 3. 创建运单记录
|
||||
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
|
||||
if (!orderExpressModel) {
|
||||
throw new Error('OrderExpress 模型未加载');
|
||||
}
|
||||
|
||||
// 3.0 检查是否已分配运单号:若已有 status=1 的记录,拒绝重复录入
|
||||
// 已分配运单号(status=1)的订单拒绝重复录入
|
||||
const existingCompleted = await orderExpressModel.findOne({
|
||||
where: {
|
||||
order_id: orderId,
|
||||
warehouse_id: Number(order.warehouse_id) || warehouseId,
|
||||
warehouse_id: Number(warehouseId) || 0,
|
||||
status: 1,
|
||||
},
|
||||
attributes: [ 'id', 'waybill_code' ],
|
||||
@ -6908,12 +7172,98 @@ class PendingOrderService extends OrderBaseService {
|
||||
`订单 ${orderId} 已分配运单号${existingWaybill ? `(${existingWaybill})` : ''},不允许重复手工录入`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 3.1 计算 business_key 递增:查找当前订单已有最大 business_key,+1 递增
|
||||
/**
|
||||
* 校验运单号在同一仓库内是否已被使用。
|
||||
* @param {Object} params 参数。
|
||||
* @param {string} params.waybillCode 运单号。
|
||||
* @param {number} params.warehouseId 仓库ID。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async assertWaybillCodeUnused({ waybillCode, warehouseId } = {}) {
|
||||
const normalizedWarehouseId = Number(warehouseId);
|
||||
if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
|
||||
throw new Error('未识别到当前仓库上下文');
|
||||
}
|
||||
|
||||
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
|
||||
if (!orderExpressModel) {
|
||||
throw new Error('OrderExpress 模型未加载');
|
||||
}
|
||||
|
||||
const used = await orderExpressModel.findOne({
|
||||
where: {
|
||||
waybill_code: waybillCode,
|
||||
warehouse_id: normalizedWarehouseId,
|
||||
delete_at: null,
|
||||
},
|
||||
attributes: [ 'id', 'order_id', 'waybill_code' ],
|
||||
raw: true,
|
||||
});
|
||||
if (!used) {
|
||||
return;
|
||||
}
|
||||
|
||||
const usedOrderId = Number(used.order_id) || 0;
|
||||
throw new Error(
|
||||
`运单号 ${waybillCode} 已被${usedOrderId > 0 ? `订单 ${usedOrderId} ` : '其它订单'}使用,同一仓库内不允许重复使用`
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 为订单创建手工录入的运单记录,并同步订单打印/过账状态、写入操作日志、触发自动回传。
|
||||
*
|
||||
* manualWaybill 与 importWaybill 共用该逻辑,调用方需先完成参数、订单状态与运单号唯一性校验。
|
||||
*
|
||||
* @param {Object} params 参数。
|
||||
* @param {Object} params.order 订单行。
|
||||
* @param {Object} params.orderModel 订单模型。
|
||||
* @param {string} params.waybillCode 运单号。
|
||||
* @param {string|null} params.logisticsInterfaceName 物流接口名称。
|
||||
* @param {Object|null} params.expressResolved 快递解析结果,null 表示沿用订单当前系统快递信息。
|
||||
* @param {number} params.warehouseId 仓库ID。
|
||||
* @param {string} params.operator 操作人。
|
||||
* @param {number|string} params.logWarehouseId 操作日志仓库ID。
|
||||
* @param {string|null} [params.expressCode] 传入的快递编码(仅用于日志与返回)。
|
||||
* @param {string} [params.operationCode] 操作日志编码。
|
||||
* @param {string} [params.actionText] 操作日志动作描述。
|
||||
* @param {string} [params.autoSyncSource] 自动回传日志来源标识。
|
||||
* @param {string} [params.requestId] 批量导入请求号(写入操作日志)。
|
||||
* @param {number} [params.operatorId] 操作人ID(写入操作日志)。
|
||||
* @param {number} [params.rowIndex] 导入行号(写入操作日志)。
|
||||
* @return {Promise<Object>} 运单记录结果。
|
||||
*/
|
||||
async createManualWaybillRecord({
|
||||
order,
|
||||
orderModel,
|
||||
waybillCode,
|
||||
logisticsInterfaceName = null,
|
||||
expressResolved = null,
|
||||
warehouseId,
|
||||
operator,
|
||||
logWarehouseId,
|
||||
expressCode = null,
|
||||
operationCode = 'ORDER_MANUAL_WAYBILL',
|
||||
actionText = '手工录入运单号',
|
||||
autoSyncSource = 'manualWaybill',
|
||||
requestId = null,
|
||||
operatorId = 0,
|
||||
rowIndex = 0,
|
||||
} = {}) {
|
||||
const orderId = Number(order.id);
|
||||
const orderWarehouseId = Number(warehouseId) || Number(order.warehouse_id) || 0;
|
||||
|
||||
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
|
||||
if (!orderExpressModel) {
|
||||
throw new Error('OrderExpress 模型未加载');
|
||||
}
|
||||
|
||||
// 计算 business_key 递增:查找当前订单已有最大 business_key,+1 递增
|
||||
const maxBusinessKey = await orderExpressModel.max('business_key', {
|
||||
where: {
|
||||
order_id: orderId,
|
||||
warehouse_id: Number(order.warehouse_id) || warehouseId,
|
||||
warehouse_id: orderWarehouseId,
|
||||
},
|
||||
});
|
||||
const nextBusinessKey = Number.isFinite(Number(maxBusinessKey)) && Number(maxBusinessKey) > 0
|
||||
@ -6932,14 +7282,14 @@ class PendingOrderService extends OrderBaseService {
|
||||
: String(order.sys_logistics_name || '').trim() || null,
|
||||
delivery_order_code: String(order.delivery_order_code || '').trim() || null,
|
||||
source_order_codes: String(order.source_order_codes || '').trim() || null,
|
||||
warehouse_id: Number(order.warehouse_id) || warehouseId,
|
||||
warehouse_id: orderWarehouseId,
|
||||
store_id: order.store_id != null ? Number(order.store_id) : null,
|
||||
business_key: nextBusinessKey,
|
||||
status: 1,
|
||||
create_at: new Date(),
|
||||
});
|
||||
|
||||
// 3.2 更新订单表的 print_status 与 post_status 为 'fin',表示外部已打印;
|
||||
// 更新订单表的 print_status 与 post_status 为 'fin',表示外部已打印;
|
||||
// 若传入了 express_code,同步修改订单的快递信息(与 updateOrderExpress 口径一致)
|
||||
const orderUpdateFields = {
|
||||
print_status: 'fin',
|
||||
@ -6953,7 +7303,7 @@ class PendingOrderService extends OrderBaseService {
|
||||
orderUpdateFields.logistics_name = expressResolved.logisticsName;
|
||||
}
|
||||
|
||||
await model.update(
|
||||
await orderModel.update(
|
||||
orderUpdateFields,
|
||||
{
|
||||
where: {
|
||||
@ -6962,12 +7312,12 @@ class PendingOrderService extends OrderBaseService {
|
||||
}
|
||||
);
|
||||
|
||||
// 4. 记录操作日志
|
||||
// 记录操作日志
|
||||
try {
|
||||
await this.ctx.service.systems.operationLog.createOperationLog({
|
||||
businessType: 'order',
|
||||
businessId: String(orderId),
|
||||
operationCode: 'ORDER_MANUAL_WAYBILL',
|
||||
operationCode,
|
||||
operator,
|
||||
extras: {
|
||||
warehouseId: logWarehouseId,
|
||||
@ -6976,27 +7326,30 @@ class PendingOrderService extends OrderBaseService {
|
||||
logisticsInterfaceName,
|
||||
businessKey: nextBusinessKey,
|
||||
expressRecordId: expressRecord.id,
|
||||
expressCode: expressCodeRaw || null,
|
||||
expressCode: expressCode || null,
|
||||
sysLogisticsCode: expressResolved ? expressResolved.sysLogisticsCode : String(order.sys_logistics_code || '').trim() || null,
|
||||
sysLogisticsName: expressResolved ? expressResolved.sysLogisticsName : String(order.sys_logistics_name || '').trim() || null,
|
||||
logisticsCode: expressResolved ? expressResolved.logisticsCode : String(order.sys_logistics_code || '').trim() || null,
|
||||
logisticsName: expressResolved ? expressResolved.logisticsName : String(order.sys_logistics_name || '').trim() || null,
|
||||
requestId,
|
||||
operatorId,
|
||||
rowIndex,
|
||||
message: expressResolved
|
||||
? `手工录入运单号:订单 ${orderId},运单号 ${waybillCode},快递 ${expressResolved.logisticsCode}(${expressResolved.logisticsName})`
|
||||
: `手工录入运单号:订单 ${orderId},运单号 ${waybillCode}`,
|
||||
? `${actionText}:订单 ${orderId},运单号 ${waybillCode},快递 ${expressResolved.logisticsCode}(${expressResolved.logisticsName})`
|
||||
: `${actionText}:订单 ${orderId},运单号 ${waybillCode}`,
|
||||
},
|
||||
beforeChanges: null,
|
||||
});
|
||||
} catch (logErr) {
|
||||
this.ctx.logger.warn('[PendingOrderService.manualWaybill] 写入操作日志失败,不影响业务', logErr);
|
||||
this.ctx.logger.warn(`[PendingOrderService.${autoSyncSource}] 写入操作日志失败,不影响业务`, logErr);
|
||||
}
|
||||
|
||||
// 5. 自动同步回传(受合约策略 auto_sync_back 控制)
|
||||
// 自动同步回传(受合约策略 auto_sync_back 控制)
|
||||
try {
|
||||
const storeId = Number(order.store_id) || 0;
|
||||
if (storeId > 0) {
|
||||
const contractConfig = await this.service.systems.storeWarehouse.getContractConfig(
|
||||
Number(order.warehouse_id) || warehouseId,
|
||||
orderWarehouseId,
|
||||
storeId
|
||||
);
|
||||
if (
|
||||
@ -7007,13 +7360,13 @@ class PendingOrderService extends OrderBaseService {
|
||||
// SN 订单自动回传会被拦截并置异常,自动触发场景静默跳过
|
||||
const autoSyncFilter = await this.filterAutoSyncSnOrderIds({
|
||||
orderIds: [ orderId ],
|
||||
warehouseId: Number(order.warehouse_id) || warehouseId,
|
||||
source: 'manualWaybill',
|
||||
warehouseId: orderWarehouseId,
|
||||
source: autoSyncSource,
|
||||
});
|
||||
if (autoSyncFilter.orderIds.length > 0) {
|
||||
this.syncOrderIds({ orderIds: autoSyncFilter.orderIds }).catch(err => {
|
||||
this.ctx.logger.error(
|
||||
`[auto_sync_back] manualWaybill 自动同步失败: ${err.message}`
|
||||
`[auto_sync_back] ${autoSyncSource} 自动同步失败: ${err.message}`
|
||||
);
|
||||
});
|
||||
}
|
||||
@ -7021,7 +7374,7 @@ class PendingOrderService extends OrderBaseService {
|
||||
}
|
||||
} catch (err) {
|
||||
this.ctx.logger.error(
|
||||
`[auto_sync_back] manualWaybill 自动同步异常: ${err.message}`
|
||||
`[auto_sync_back] ${autoSyncSource} 自动同步异常: ${err.message}`
|
||||
);
|
||||
}
|
||||
|
||||
@ -7034,14 +7387,14 @@ class PendingOrderService extends OrderBaseService {
|
||||
create_at: expressRecord.create_at,
|
||||
};
|
||||
if (expressResolved) {
|
||||
result.express_code = expressCodeRaw;
|
||||
result.express_code = expressCode;
|
||||
result.sys_logistics_code = expressResolved.sysLogisticsCode;
|
||||
result.sys_logistics_name = expressResolved.sysLogisticsName;
|
||||
result.logistics_code = expressResolved.logisticsCode;
|
||||
result.logistics_name = expressResolved.logisticsName;
|
||||
}
|
||||
|
||||
return this.success('ok', result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@ -1,4 +1,22 @@
|
||||
[
|
||||
{
|
||||
"version": "2026.11.23-order-pendingOrder-import-waybill",
|
||||
"date": "2026-11-23",
|
||||
"type": "enhanced",
|
||||
"summary": "feat: order.pendingOrder 新增 importWaybill(运单号批量导入);manualWaybill 增加运单号仓库内唯一校验。",
|
||||
"methods": [
|
||||
"order.pendingOrder.manualWaybill",
|
||||
"order.pendingOrder.importWaybill"
|
||||
],
|
||||
"notes": [
|
||||
"importWaybill 入参为记录数组,字段 delivery_order_code / store_remark / waybill_code,以 delivery_order_code + store_remark(wms_store_warehouse.store_remask)定位当前仓库待处理订单",
|
||||
"逐条处理并返回 [{ delivery_order_code, store_remark, waybill_code, success, info, order_id?, express_record_id? }],单条失败不影响其它记录",
|
||||
"运行单条逻辑与 manualWaybill 共用 createManualWaybillRecord:写 wms_order_express(status=1、business_key 递增)、订单 print_status/post_status=fin、操作日志(ORDER_IMPORT_WAYBILL)与 auto_sync_back 自动回传",
|
||||
"manualWaybill 与 importWaybill 均新增运单号仓库内唯一校验:同一 warehouse_id 下 wms_order_express 已存在该 waybill_code(delete_at 为空)即拒绝",
|
||||
"校验逻辑抽为 assertWaybillEntryAllowed(订单状态/已分配运单号)与 assertWaybillCodeUnused(仓库内唯一),两个方法共用"
|
||||
],
|
||||
"module": "order"
|
||||
},
|
||||
{
|
||||
"version": "2026.11.21-b2b-snapshot-stock-attrs",
|
||||
"date": "2026-11-21",
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
"module": "system",
|
||||
"description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内",
|
||||
"version": "0.3.375",
|
||||
"updatedAt": "2026-11-21",
|
||||
"updatedAt": "2026-11-23",
|
||||
"headers": [
|
||||
{
|
||||
"name": "platform",
|
||||
@ -34235,7 +34235,7 @@
|
||||
},
|
||||
{
|
||||
"method": "order.pendingOrder.manualWaybill",
|
||||
"description": "手工录入运单号。为指定待处理订单创建一条运单记录(wms_order_express 表),仅允许 step 在 [1,2,3] 且 outbound_status 不为 'padding' 的订单操作。完成后自动更新订单表的 print_status 与 post_status 为 'fin',表示外部已打印。可选传入 express_code,行为参考 updateOrderExpress:从当前仓库快递列表(带缓存)中查找对应项,若为自定义映射(is_system_setting=true),订单 sys_logistics_code/name 写系统快递编码和名称、logistics_code/name 写自定义编码和名称;若为系统快递(is_system_setting=false),四个字段均写系统快递的 code/name;未找到则报错;不传则运单记录沿用订单当前系统快递信息。",
|
||||
"description": "手工录入运单号。为指定待处理订单创建一条运单记录(wms_order_express 表),仅允许 step 在 [1,2,3] 且 outbound_status 不为 'padding' 的订单操作。运单号在同一仓库内唯一:wms_order_express 中同一 warehouse_id 下已存在该 waybill_code(未删除记录)时拒绝录入。完成后自动更新订单表的 print_status 与 post_status 为 'fin',表示外部已打印。可选传入 express_code,行为参考 updateOrderExpress:从当前仓库快递列表(带缓存)中查找对应项,若为自定义映射(is_system_setting=true),订单 sys_logistics_code/name 写系统快递编码和名称、logistics_code/name 写自定义编码和名称;若为系统快递(is_system_setting=false),四个字段均写系统快递的 code/name;未找到则报错;不传则运单记录沿用订单当前系统快递信息。",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
"headers": [
|
||||
@ -34259,7 +34259,7 @@
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"source": "body",
|
||||
"description": "运单号,非空字符串"
|
||||
"description": "运单号,非空字符串;同一仓库内不允许重复使用"
|
||||
},
|
||||
{
|
||||
"name": "logistics_interface_name",
|
||||
@ -34365,6 +34365,14 @@
|
||||
"code": 400,
|
||||
"message": "订单已标记待出库,不允许手工录入运单号"
|
||||
},
|
||||
{
|
||||
"code": 400,
|
||||
"message": "订单已分配运单号,不允许重复手工录入"
|
||||
},
|
||||
{
|
||||
"code": 400,
|
||||
"message": "运单号 <waybill_code> 已被订单 <order_id> 使用,同一仓库内不允许重复使用"
|
||||
},
|
||||
{
|
||||
"code": 404,
|
||||
"message": "快递编码 <express_code> 不存在"
|
||||
@ -34823,6 +34831,103 @@
|
||||
"message": "查询失败"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"method": "order.pendingOrder.importWaybill",
|
||||
"description": "导入运单号(批量)。入参为记录数组(也可用 { list: [] } / { rows: [] } / { items: [] } / { data: [] } 包装),每条记录以 delivery_order_code(发货单号)+ store_remark(货主备注,取 wms_store_warehouse.store_remask)唯一定位当前仓库的待处理订单,定位成功后按 order.pendingOrder.manualWaybill 的口径写入运单记录(wms_order_express),并同步订单 print_status / post_status 为 'fin'、写入操作日志(ORDER_IMPORT_WAYBILL)、按合约 auto_sync_back 策略触发自动回传。运单号在同一仓库内唯一(同一 warehouse_id 下已存在未删除记录即视为已使用),同一批次内重复的运单号也视为失败。单条失败不影响其它记录,按入参顺序返回逐条结果,info 为 'ok' 或失败原因。",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
"headers": [
|
||||
{
|
||||
"name": "Authorization",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "Bearer token"
|
||||
}
|
||||
],
|
||||
"params": [
|
||||
{
|
||||
"name": "list",
|
||||
"type": "array",
|
||||
"required": true,
|
||||
"source": "body",
|
||||
"description": "导入记录数组;兼容 deliveryOrderCode / storeRemark / waybillCode 驼峰字段",
|
||||
"children": [
|
||||
{
|
||||
"name": "delivery_order_code",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "发货单号,非空"
|
||||
},
|
||||
{
|
||||
"name": "store_remark",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "货主备注(wms_store_warehouse.store_remask),与发货单号一起唯一定位订单"
|
||||
},
|
||||
{
|
||||
"name": "waybill_code",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "运单号,非空;同一仓库内不允许重复使用"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"response": [
|
||||
{
|
||||
"name": "delivery_order_code",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "发货单号(回传入参值)"
|
||||
},
|
||||
{
|
||||
"name": "store_remark",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "货主备注(回传入参值)"
|
||||
},
|
||||
{
|
||||
"name": "waybill_code",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "运单号(回传入参值)"
|
||||
},
|
||||
{
|
||||
"name": "success",
|
||||
"type": "boolean",
|
||||
"required": true,
|
||||
"description": "该条是否导入成功"
|
||||
},
|
||||
{
|
||||
"name": "info",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "成功时为 'ok',失败时为失败原因"
|
||||
},
|
||||
{
|
||||
"name": "order_id",
|
||||
"type": "number",
|
||||
"required": false,
|
||||
"description": "命中的订单 ID,仅成功时返回"
|
||||
},
|
||||
{
|
||||
"name": "express_record_id",
|
||||
"type": "number",
|
||||
"required": false,
|
||||
"description": "创建的运单记录 ID(wms_order_express.id),仅成功时返回"
|
||||
}
|
||||
],
|
||||
"errors": [
|
||||
{
|
||||
"code": 400,
|
||||
"message": "导入数据不能为空或格式错误"
|
||||
},
|
||||
{
|
||||
"code": 400,
|
||||
"message": "未识别到当前仓库上下文"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
@ -0,0 +1,342 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const Sequelize = require('sequelize');
|
||||
const PendingOrderService = require('../../../../../app/service/systemMethods/order/pendingOrder');
|
||||
|
||||
/**
|
||||
* 判断模拟行数据是否匹配 where 条件(支持 eq/ne/in/is 与普通等值)。
|
||||
* @param {Object} row 待匹配数据。
|
||||
* @param {Object} where Sequelize where 条件。
|
||||
* @return {boolean} 是否匹配。
|
||||
*/
|
||||
function matchesWhere(row, where) {
|
||||
if (!where || typeof where !== 'object') {
|
||||
return true;
|
||||
}
|
||||
|
||||
return Object.entries(where).every(([ fieldName, condition ]) => {
|
||||
const actual = row[fieldName];
|
||||
if (condition && typeof condition === 'object' && !Array.isArray(condition)) {
|
||||
if (Object.prototype.hasOwnProperty.call(condition, Sequelize.Op.in)) {
|
||||
return condition[Sequelize.Op.in].includes(actual);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(condition, Sequelize.Op.ne)) {
|
||||
return actual !== condition[Sequelize.Op.ne];
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(condition, Sequelize.Op.is)) {
|
||||
const expected = condition[Sequelize.Op.is];
|
||||
return expected === null
|
||||
? actual === null || actual === undefined
|
||||
: actual === expected;
|
||||
}
|
||||
}
|
||||
return actual === condition;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造导入运单号测试上下文。
|
||||
*
|
||||
* @param {Object} [options] 打桩配置。
|
||||
* @param {Array<Object>} [options.orders] 待处理订单行。
|
||||
* @param {Array<Object>} [options.expressRows] 已有运单记录行。
|
||||
* @param {Array<Object>} [options.contracts] 货主签约行(store_id/store_remask)。
|
||||
* @return {{ service: Object, calls: Object, ctx: Object }} 服务实例与调用记录。
|
||||
*/
|
||||
function createImportWaybillHarness(options = {}) {
|
||||
const warehouseId = options.warehouseId || 100000;
|
||||
const calls = {
|
||||
operationLogs: [],
|
||||
expressCreatePayloads: [],
|
||||
orderUpdatePayloads: [],
|
||||
};
|
||||
|
||||
const orderRows = (options.orders || []).map(row => ({ ...row }));
|
||||
const expressRows = (options.expressRows || []).map(row => ({ ...row, delete_at: row.delete_at ?? null }));
|
||||
const contracts = (options.contracts || []).map(row => ({ ...row }));
|
||||
|
||||
const ctx = {
|
||||
app: { Sequelize },
|
||||
user: {
|
||||
store_id: warehouseId,
|
||||
id: 9001,
|
||||
employees_id: '9001',
|
||||
employees_name: '测试员',
|
||||
},
|
||||
model: {
|
||||
OrderExpress: {
|
||||
async findOne(query) {
|
||||
const matched = expressRows.find(row => matchesWhere(row, query && query.where));
|
||||
return matched ? { ...matched } : null;
|
||||
},
|
||||
async max(field, query) {
|
||||
const values = expressRows
|
||||
.filter(row => matchesWhere(row, query && query.where))
|
||||
.map(row => Number(row[field]) || 0);
|
||||
return values.length > 0 ? Math.max(...values) : null;
|
||||
},
|
||||
async create(values) {
|
||||
calls.expressCreatePayloads.push({ ...values });
|
||||
const row = { id: expressRows.length + 10001, ...values };
|
||||
expressRows.push(row);
|
||||
return row;
|
||||
},
|
||||
},
|
||||
StoreWarehouse: {
|
||||
async findAll(query) {
|
||||
return contracts
|
||||
.filter(row => matchesWhere(row, query && query.where))
|
||||
.map(row => ({ ...row }));
|
||||
},
|
||||
},
|
||||
},
|
||||
service: {
|
||||
systems: {
|
||||
operationLog: {
|
||||
async createOperationLog(payload) {
|
||||
calls.operationLogs.push(payload);
|
||||
return { id: 1 };
|
||||
},
|
||||
},
|
||||
storeWarehouse: {
|
||||
async getContractConfig() {
|
||||
return null;
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
logger: {
|
||||
info() {},
|
||||
warn() {},
|
||||
error() {},
|
||||
},
|
||||
};
|
||||
|
||||
const service = new PendingOrderService(ctx);
|
||||
|
||||
service.getWarehouseId = () => warehouseId;
|
||||
service.getOrderLogOperator = () => ({ id: '9001', name: '测试员' });
|
||||
service.getOrderLogWarehouseId = () => warehouseId;
|
||||
service.success = (msg, data) => ({ code: 0, msg, data });
|
||||
service.syncOrderIds = () => Promise.resolve();
|
||||
|
||||
service.getOrderModel = async () => ({
|
||||
async findOne(query) {
|
||||
const matched = orderRows.find(row => matchesWhere(row, query && query.where));
|
||||
return matched ? { ...matched } : null;
|
||||
},
|
||||
async findAll(query) {
|
||||
return orderRows
|
||||
.filter(row => matchesWhere(row, query && query.where))
|
||||
.map(row => ({ ...row }));
|
||||
},
|
||||
async update(values, query) {
|
||||
calls.orderUpdatePayloads.push({ values, where: query && query.where });
|
||||
const matched = orderRows.filter(row => matchesWhere(row, query && query.where));
|
||||
for (const row of matched) {
|
||||
Object.assign(row, values);
|
||||
}
|
||||
return [ matched.length ];
|
||||
},
|
||||
});
|
||||
|
||||
return { service, calls, ctx };
|
||||
}
|
||||
|
||||
describe('pendingOrder.importWaybill — 运单号导入', () => {
|
||||
const warehouseId = 100000;
|
||||
const baseOrder = {
|
||||
id: 501,
|
||||
step: 1,
|
||||
outbound_status: 'none',
|
||||
warehouse_id: warehouseId,
|
||||
store_id: 1000000,
|
||||
delivery_order_code: 'DO20261123001',
|
||||
source_order_codes: 'SO20261123001',
|
||||
sys_logistics_code: 'SF',
|
||||
sys_logistics_name: '顺丰',
|
||||
};
|
||||
const baseContract = { store_id: 1000000, warehouse_id: warehouseId, store_remask: '一号货主' };
|
||||
|
||||
it('按 delivery_order_code + store_remark 命中订单时导入成功', async () => {
|
||||
const { service, calls } = createImportWaybillHarness({
|
||||
orders: [ baseOrder ],
|
||||
contracts: [ baseContract ],
|
||||
});
|
||||
|
||||
const response = await service.importWaybill([{
|
||||
delivery_order_code: 'DO20261123001',
|
||||
store_remark: '一号货主',
|
||||
waybill_code: 'SF1000000001',
|
||||
}]);
|
||||
|
||||
assert.equal(calls.expressCreatePayloads.length, 1);
|
||||
assert.equal(calls.expressCreatePayloads[0].waybill_code, 'SF1000000001');
|
||||
assert.equal(calls.expressCreatePayloads[0].order_id, 501);
|
||||
assert.equal(calls.expressCreatePayloads[0].warehouse_id, warehouseId);
|
||||
assert.equal(calls.expressCreatePayloads[0].status, 1);
|
||||
assert.equal(calls.orderUpdatePayloads[0].values.print_status, 'fin');
|
||||
assert.equal(calls.orderUpdatePayloads[0].values.post_status, 'fin');
|
||||
|
||||
assert.equal(response.data.length, 1);
|
||||
assert.equal(response.data[0].delivery_order_code, 'DO20261123001');
|
||||
assert.equal(response.data[0].success, true);
|
||||
assert.equal(response.data[0].info, 'ok');
|
||||
assert.equal(response.data[0].order_id, 501);
|
||||
});
|
||||
|
||||
it('发货单号不存在时该条返回失败,不影响其它记录', async () => {
|
||||
const { service } = createImportWaybillHarness({
|
||||
orders: [ baseOrder ],
|
||||
contracts: [ baseContract ],
|
||||
});
|
||||
|
||||
const response = await service.importWaybill([
|
||||
{ delivery_order_code: 'DO_NOT_EXIST', store_remark: '一号货主', waybill_code: 'SF1000000002' },
|
||||
{ delivery_order_code: 'DO20261123001', store_remark: '一号货主', waybill_code: 'SF1000000003' },
|
||||
]);
|
||||
|
||||
assert.equal(response.data[0].success, false);
|
||||
assert.match(response.data[0].info, /不存在/);
|
||||
assert.equal(response.data[1].success, true);
|
||||
});
|
||||
|
||||
it('货主备注与订单不一致时返回失败', async () => {
|
||||
const { service } = createImportWaybillHarness({
|
||||
orders: [ baseOrder ],
|
||||
contracts: [ baseContract ],
|
||||
});
|
||||
|
||||
const response = await service.importWaybill([{
|
||||
delivery_order_code: 'DO20261123001',
|
||||
store_remark: '二号货主',
|
||||
waybill_code: 'SF1000000004',
|
||||
}]);
|
||||
|
||||
assert.equal(response.data[0].success, false);
|
||||
assert.match(response.data[0].info, /货主备注/);
|
||||
});
|
||||
|
||||
it('运单号已被同仓库其它订单使用时返回失败', async () => {
|
||||
const { service } = createImportWaybillHarness({
|
||||
orders: [ baseOrder ],
|
||||
contracts: [ baseContract ],
|
||||
expressRows: [{
|
||||
id: 1,
|
||||
order_id: 999,
|
||||
waybill_code: 'SF1000000005',
|
||||
warehouse_id: warehouseId,
|
||||
status: 1,
|
||||
business_key: 1,
|
||||
}],
|
||||
});
|
||||
|
||||
const response = await service.importWaybill([{
|
||||
delivery_order_code: 'DO20261123001',
|
||||
store_remark: '一号货主',
|
||||
waybill_code: 'SF1000000005',
|
||||
}]);
|
||||
|
||||
assert.equal(response.data[0].success, false);
|
||||
assert.match(response.data[0].info, /已被订单 999 使用/);
|
||||
});
|
||||
|
||||
it('同一批次内运单号重复时后一条返回失败', async () => {
|
||||
const { service } = createImportWaybillHarness({
|
||||
orders: [
|
||||
baseOrder,
|
||||
{ ...baseOrder, id: 502, delivery_order_code: 'DO20261123002' },
|
||||
],
|
||||
contracts: [ baseContract ],
|
||||
});
|
||||
|
||||
const response = await service.importWaybill([
|
||||
{ delivery_order_code: 'DO20261123001', store_remark: '一号货主', waybill_code: 'SF1000000006' },
|
||||
{ delivery_order_code: 'DO20261123002', store_remark: '一号货主', waybill_code: 'SF1000000006' },
|
||||
]);
|
||||
|
||||
assert.equal(response.data[0].success, true);
|
||||
assert.equal(response.data[1].success, false);
|
||||
assert.match(response.data[1].info, /本次导入数据中重复/);
|
||||
});
|
||||
|
||||
it('缺少必填入参时逐条返回失败原因', async () => {
|
||||
const { service } = createImportWaybillHarness();
|
||||
|
||||
const response = await service.importWaybill([
|
||||
{ delivery_order_code: '', store_remark: '一号货主', waybill_code: 'SF1000000007' },
|
||||
{ delivery_order_code: 'DO20261123001', store_remark: '一号货主', waybill_code: ' ' },
|
||||
]);
|
||||
|
||||
assert.match(response.data[0].info, /delivery_order_code/);
|
||||
assert.match(response.data[1].info, /waybill_code/);
|
||||
});
|
||||
|
||||
it('支持 { list: [] } 包装的入参', async () => {
|
||||
const { service } = createImportWaybillHarness({
|
||||
orders: [ baseOrder ],
|
||||
contracts: [ baseContract ],
|
||||
});
|
||||
|
||||
const response = await service.importWaybill({
|
||||
list: [{ delivery_order_code: 'DO20261123001', store_remark: '一号货主', waybill_code: 'SF1000000008' }],
|
||||
});
|
||||
|
||||
assert.equal(response.data[0].success, true);
|
||||
});
|
||||
|
||||
it('非对象行返回失败且保持逐条顺序', async () => {
|
||||
const { service } = createImportWaybillHarness({
|
||||
orders: [ baseOrder ],
|
||||
contracts: [ baseContract ],
|
||||
});
|
||||
|
||||
const response = await service.importWaybill([
|
||||
'not-an-object',
|
||||
{ delivery_order_code: 'DO20261123001', store_remark: '一号货主', waybill_code: 'SF1000000011' },
|
||||
]);
|
||||
|
||||
assert.equal(response.data.length, 2);
|
||||
assert.equal(response.data[0].success, false);
|
||||
assert.match(response.data[0].info, /必须为对象/);
|
||||
assert.equal(response.data[1].success, true);
|
||||
});
|
||||
|
||||
it('manualWaybill 对已占用运单号(同仓库)拒绝录入', async () => {
|
||||
const { service } = createImportWaybillHarness({
|
||||
orders: [ baseOrder ],
|
||||
contracts: [ baseContract ],
|
||||
expressRows: [{
|
||||
id: 2,
|
||||
order_id: 888,
|
||||
waybill_code: 'SF1000000009',
|
||||
warehouse_id: warehouseId,
|
||||
status: 0,
|
||||
business_key: 1,
|
||||
}],
|
||||
});
|
||||
|
||||
await assert.rejects(
|
||||
() => service.manualWaybill({ order_id: 501, waybill_code: 'SF1000000009' }),
|
||||
/已被订单 888 使用/
|
||||
);
|
||||
});
|
||||
|
||||
it('运单号唯一性按仓库维度校验,其它仓库占用不影响', async () => {
|
||||
const { service } = createImportWaybillHarness({
|
||||
expressRows: [{
|
||||
id: 3,
|
||||
order_id: 777,
|
||||
waybill_code: 'SF1000000010',
|
||||
warehouse_id: 200000,
|
||||
status: 1,
|
||||
business_key: 1,
|
||||
}],
|
||||
});
|
||||
|
||||
await assert.doesNotReject(
|
||||
() => service.assertWaybillCodeUnused({ waybillCode: 'SF1000000010', warehouseId })
|
||||
);
|
||||
});
|
||||
});
|
||||
@ -45,6 +45,9 @@ function createManualWaybillLogHarness(options = {}) {
|
||||
},
|
||||
model: {
|
||||
OrderExpress: {
|
||||
async findOne() {
|
||||
return options.existingCompleted || null;
|
||||
},
|
||||
async max(field, whereOptions) {
|
||||
return orderExpressMax;
|
||||
},
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user