feat: 推单二级校验 + 快递分配异步化 + 打印 stock_id 直读
- delivery_order: 新增 auth_status=2 + warehouse_use_status=1 二级签约校验 - express: createWaybillCodePipeline 支持 awaitTasks/onBatchComplete 选项 - pendingOrder: allocateExpressCode 异步进度缓存 + cancelAllocateStorage 拣货完成前置校验 - order_print: 新增 wms_picking.stock_id→wms_stock_warehouse 直读路径,消除 order_items 强依赖
This commit is contained in:
parent
b9ead1fba2
commit
ca5c8a269e
@ -28,6 +28,17 @@ const BATCH_LOCK_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24;
|
||||
const BATCH_UNLOCK_TASK_CACHE_KEY_PREFIX = 'order:batch-unlock:';
|
||||
const BATCH_UNLOCK_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24;
|
||||
|
||||
const ALLOCATE_EXPRESS_TASK_CACHE_KEY_PREFIX = 'order:pending:allocate_express:request:';
|
||||
const ALLOCATE_EXPRESS_TASK_CACHE_TTL_SECONDS = 60 * 60 * 2;
|
||||
const ALLOCATE_EXPRESS_PROGRESS_MAP = Object.freeze({
|
||||
submitted: 5,
|
||||
running: 50,
|
||||
success: 100,
|
||||
failed: 100,
|
||||
not_found: 0,
|
||||
unknown: 0,
|
||||
});
|
||||
|
||||
const BATCH_UNINTERCEPT_TASK_CACHE_KEY_PREFIX = 'order:batch-unintercept:';
|
||||
const BATCH_UNINTERCEPT_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24;
|
||||
|
||||
@ -517,9 +528,9 @@ class PendingOrderService extends OrderBaseService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill';
|
||||
const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill';
|
||||
const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill';
|
||||
const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill';
|
||||
const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill';
|
||||
const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
@ -1385,6 +1396,88 @@ class PendingOrderService extends OrderBaseService {
|
||||
}
|
||||
}
|
||||
|
||||
// ========== allocateExpressCode 异步任务进度缓存工具方法 ==========
|
||||
|
||||
/**
|
||||
* 获取快递分配任务缓存键。
|
||||
*
|
||||
* @param {string} taskId 任务ID。
|
||||
* @return {string} 缓存键。
|
||||
*/
|
||||
getAllocateExpressTaskCacheKey(taskId = '') {
|
||||
const normalizedTaskId = String(taskId || '').trim();
|
||||
if (!normalizedTaskId) {
|
||||
return '';
|
||||
}
|
||||
return `${ALLOCATE_EXPRESS_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范快递分配任务ID。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @return {string} 归一化后的任务ID。
|
||||
*/
|
||||
normalizeAllocateExpressTaskId(data = {}) {
|
||||
const normalizedData = this.isPlainObject(data) ? data : {};
|
||||
return String(normalizedData.task_id || normalizedData.taskId || '').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入快递分配任务进度。
|
||||
*
|
||||
* @param {string} taskId 任务ID。
|
||||
* @param {Object} payload 任务状态与结果。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async setAllocateExpressTaskProgress(taskId = '', payload = {}) {
|
||||
const cacheKey = this.getAllocateExpressTaskCacheKey(taskId);
|
||||
if (!cacheKey || typeof this.app.setCacheAsync !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
const safePayload = this.isPlainObject(payload) ? payload : {};
|
||||
const progressPayload = {
|
||||
task_id: String(taskId || '').trim(),
|
||||
status: String(safePayload.status || 'unknown').trim(),
|
||||
progress: Number(safePayload.progress || 0),
|
||||
message: String(safePayload.message || ''),
|
||||
result: safePayload.result || null,
|
||||
error: String(safePayload.error || ''),
|
||||
update_time: Date.now(),
|
||||
};
|
||||
|
||||
try {
|
||||
await this.app.setCacheAsync(cacheKey, progressPayload, ALLOCATE_EXPRESS_TASK_CACHE_TTL_SECONDS);
|
||||
} catch (error) {
|
||||
this.ctx.logger.warn('[pendingOrder.allocateExpressCode] 写入任务进度缓存失败: %s', error && error.message ? error.message : error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取快递分配任务进度。
|
||||
*
|
||||
* @param {string} taskId 任务ID。
|
||||
* @return {Promise<Object|null>} 任务缓存结果。
|
||||
*/
|
||||
async getAllocateExpressTaskProgress(taskId = '') {
|
||||
const cacheKey = this.getAllocateExpressTaskCacheKey(taskId);
|
||||
if (!cacheKey || typeof this.app.getCacheAsync !== 'function') {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const cached = await this.app.getCacheAsync(cacheKey);
|
||||
if (!this.isPlainObject(cached)) {
|
||||
return null;
|
||||
}
|
||||
return cached;
|
||||
} catch (error) {
|
||||
this.ctx.logger.warn('[pendingOrder.allocateExpressCode] 读取任务进度缓存失败: %s', error && error.message ? error.message : error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ========== syncOrderIds 异步任务进度缓存工具方法 ==========
|
||||
|
||||
/**
|
||||
@ -1498,6 +1591,32 @@ class PendingOrderService extends OrderBaseService {
|
||||
|
||||
console.log('[PendingOrderService.cancelAllocateStorage] 归一化入参', normalizedData);
|
||||
|
||||
// 前置校验:拣货完成的订单不允许取消分配储位
|
||||
const rawCancelOrderIds = Array.isArray(normalizedData.order_ids)
|
||||
? normalizedData.order_ids
|
||||
: (normalizedData.order_ids != null ? [ normalizedData.order_ids ] : []);
|
||||
const cancelOrderIds = [ ...new Set(rawCancelOrderIds.map(id => Number(id)).filter(id => Number.isFinite(id) && id > 0)) ];
|
||||
|
||||
if (cancelOrderIds.length > 0) {
|
||||
const model = await this.getOrderModel('order', this.getWarehouseId());
|
||||
const where = this.buildOrderWhere(cancelOrderIds, this.getWarehouseId());
|
||||
const orders = await model.findAll({
|
||||
where,
|
||||
attributes: [ 'id', 'pick_status' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const pickedOrderIds = (Array.isArray(orders) ? orders : [])
|
||||
.filter(o => o.pick_status === 'fin')
|
||||
.map(o => Number(o.id));
|
||||
|
||||
if (pickedOrderIds.length > 0) {
|
||||
throw new Error(
|
||||
`以下订单已拣货完成,不允许取消分配储位:${pickedOrderIds.join(', ')}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
console.log('[PendingOrderService.cancelAllocateStorage] 调用 orderStorageAllocation.cancelAllocateStorage 前', normalizedData);
|
||||
const result = await this.service.systems.orderStorageAllocation.cancelAllocateStorage(normalizedData);
|
||||
@ -1859,15 +1978,10 @@ class PendingOrderService extends OrderBaseService {
|
||||
|
||||
/**
|
||||
* 批量分配待处理订单的快递号,并复用现有运单创建核心链路。
|
||||
*
|
||||
* 请求体必须直接传入订单对象数组,订单对象应为来自待处理订单列表或详情的原始订单对象。
|
||||
* 每个订单对象必须包含 order_id 与 business_key;sys_platform_code 与 logistics_code 为订单对象自带字段,
|
||||
* 前端无需额外拼装或单独构造,直接原样回传订单对象即可。business_key 可为单个序号,也可为序号数组。
|
||||
* 其余字段会原样透传给运单创建链路。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {Array<Object>} data.orders 订单对象数组。
|
||||
* @return {Promise<Object>} 统一 success 包装的运单创建结果。
|
||||
* @return {Promise<Object>} 统一 success 包装,立即返回 task_id。
|
||||
*/
|
||||
async allocateExpressCode(data) {
|
||||
const { orders } = data || {};
|
||||
@ -1875,79 +1989,138 @@ class PendingOrderService extends OrderBaseService {
|
||||
throw new Error('分配快递号接口仅支持订单对象数组入参');
|
||||
}
|
||||
|
||||
const orderIds = [ ...new Set(
|
||||
orders
|
||||
.map(order => Number(order && (order.order_id || order.id)))
|
||||
.filter(orderId => Number.isFinite(orderId) && orderId > 0)
|
||||
) ];
|
||||
|
||||
const { service } = this;
|
||||
try {
|
||||
const result = await service.systems.express.createWaybillCodePipeline(orders);
|
||||
return this.success('ok', result);
|
||||
} catch (error) {
|
||||
|
||||
// 生成任务ID,立即返回给前端
|
||||
const taskId = `exp_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
|
||||
const taskPayload = {
|
||||
task_id: taskId,
|
||||
status: 'submitted',
|
||||
progress: ALLOCATE_EXPRESS_PROGRESS_MAP.submitted,
|
||||
message: '分配快递任务已提交',
|
||||
result: null,
|
||||
error: '',
|
||||
};
|
||||
await this.setAllocateExpressTaskProgress(taskId, taskPayload);
|
||||
|
||||
// 后台异步执行
|
||||
setImmediate(async () => {
|
||||
try {
|
||||
const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
|
||||
const orderDeliveryModel = orderDeliveryFactory && typeof orderDeliveryFactory.getCurrentModel === 'function'
|
||||
? await orderDeliveryFactory.getCurrentModel()
|
||||
: null;
|
||||
await this.setAllocateExpressTaskProgress(taskId, {
|
||||
status: 'running',
|
||||
progress: ALLOCATE_EXPRESS_PROGRESS_MAP.running,
|
||||
message: '快递分配处理中',
|
||||
});
|
||||
|
||||
if (orderDeliveryModel && orderIds.length > 0) {
|
||||
// 查询当前订单的 express_code,只回滚没有运单号的
|
||||
const currentOrders = await orderDeliveryModel.findAll({
|
||||
// eslint-disable-next-line array-bracket-spacing
|
||||
where: { id: { [this.app.Sequelize.Op.in]: orderIds } },
|
||||
attributes: [ 'id', 'express_code', 'post_status' ],
|
||||
raw: true,
|
||||
});
|
||||
const result = await service.systems.express.createWaybillCodePipeline(orders, {
|
||||
awaitTasks: true,
|
||||
});
|
||||
|
||||
const noWaybillOrderIds = (Array.isArray(currentOrders) ? currentOrders : [])
|
||||
.filter(o => !String(o.express_code || '').trim())
|
||||
.map(o => Number(o.id))
|
||||
.filter(id => id > 0);
|
||||
await this.setAllocateExpressTaskProgress(taskId, {
|
||||
status: 'success',
|
||||
progress: ALLOCATE_EXPRESS_PROGRESS_MAP.success,
|
||||
message: '快递分配完成',
|
||||
result,
|
||||
});
|
||||
} catch (error) {
|
||||
const errorMessage = error && error.message ? error.message : String(error);
|
||||
|
||||
if (noWaybillOrderIds.length > 0) {
|
||||
await orderDeliveryModel.update(
|
||||
{ post_status: 'none', updated_at: new Date() },
|
||||
// 异常标记和失败日志仍在 asyncTask 内部处理,这里仅记录任务状态
|
||||
await this.setAllocateExpressTaskProgress(taskId, {
|
||||
status: 'failed',
|
||||
progress: ALLOCATE_EXPRESS_PROGRESS_MAP.failed,
|
||||
message: '快递分配失败',
|
||||
error: errorMessage,
|
||||
});
|
||||
|
||||
// 回滚无运单号订单的 post_status
|
||||
try {
|
||||
const orderIds = [ ...new Set(
|
||||
orders
|
||||
.map(order => Number(order && (order.order_id || order.id)))
|
||||
.filter(orderId => Number.isFinite(orderId) && orderId > 0)
|
||||
) ];
|
||||
|
||||
const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
|
||||
const orderDeliveryModel = orderDeliveryFactory && typeof orderDeliveryFactory.getCurrentModel === 'function'
|
||||
? await orderDeliveryFactory.getCurrentModel()
|
||||
: null;
|
||||
|
||||
if (orderDeliveryModel && orderIds.length > 0) {
|
||||
const currentOrders = await orderDeliveryModel.findAll({
|
||||
// eslint-disable-next-line array-bracket-spacing
|
||||
{ where: { id: { [this.app.Sequelize.Op.in]: noWaybillOrderIds } } }
|
||||
);
|
||||
this.ctx.logger.info('[PendingOrderService.allocateExpressCode] 回滚 post_status 为 none', {
|
||||
orderIds: noWaybillOrderIds,
|
||||
where: { id: { [this.app.Sequelize.Op.in]: orderIds } },
|
||||
attributes: [ 'id', 'express_code', 'post_status' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const noWaybillOrderIds = (Array.isArray(currentOrders) ? currentOrders : [])
|
||||
.filter(o => !String(o.express_code || '').trim())
|
||||
.map(o => Number(o.id))
|
||||
.filter(id => id > 0);
|
||||
|
||||
if (noWaybillOrderIds.length > 0) {
|
||||
await orderDeliveryModel.update(
|
||||
{ post_status: 'none', updated_at: new Date() },
|
||||
// eslint-disable-next-line array-bracket-spacing
|
||||
{ where: { id: { [this.app.Sequelize.Op.in]: noWaybillOrderIds } } }
|
||||
);
|
||||
this.ctx.logger.info('[PendingOrderService.allocateExpressCode] 回滚 post_status 为 none', {
|
||||
orderIds: noWaybillOrderIds,
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (markError) {
|
||||
this.ctx.logger.warn('[PendingOrderService.allocateExpressCode] 回写订单状态失败,不影响主流程', markError);
|
||||
}
|
||||
} catch (markError) {
|
||||
this.ctx.logger.warn('[PendingOrderService.allocateExpressCode] 通过统一 helper 回写订单失败状态失败,不影响主流程', markError);
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
const operationLogService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.operationLog;
|
||||
if (orderIds.length > 0 && operationLogService && typeof operationLogService.createOperationLogs === 'function') {
|
||||
const operator = this.getOrderLogOperator() || {};
|
||||
const logWarehouseId = this.getOrderLogWarehouseId(this.getWarehouseId()) || null;
|
||||
const errorMessage = error && error.message ? String(error.message) : String(error);
|
||||
return this.success('ok', {
|
||||
...taskPayload,
|
||||
update_time: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
const payloads = orderIds.map(orderId => ({
|
||||
businessType: 'order',
|
||||
businessId: String(orderId),
|
||||
operationCode: 'ORDER_EXPRESS_ALLOCATE_FAILED',
|
||||
operator,
|
||||
extras: {
|
||||
message: `分配快递失败:${errorMessage}`,
|
||||
warehouseId: logWarehouseId,
|
||||
externalLogType: 'NONE',
|
||||
},
|
||||
}));
|
||||
|
||||
await operationLogService.createOperationLogs(payloads);
|
||||
}
|
||||
} catch (logError) {
|
||||
this.ctx.logger.warn('[PendingOrderService.allocateExpressCode] 写入分配快递失败日志失败,不影响主流程', logError);
|
||||
}
|
||||
|
||||
throw error;
|
||||
/**
|
||||
* 查询快递分配任务进度。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {string} data.task_id 任务ID(下划线写法)。
|
||||
* @param {string} data.taskId 任务ID(驼峰写法)。
|
||||
* @return {Promise<Object>} 统一 success 包装。
|
||||
*/
|
||||
async allocateExpressCodeTaskProgress(data = {}) {
|
||||
const taskId = this.normalizeAllocateExpressTaskId(data);
|
||||
if (!taskId) {
|
||||
return this.success('ok', {
|
||||
task_id: '',
|
||||
status: 'not_found',
|
||||
progress: ALLOCATE_EXPRESS_PROGRESS_MAP.not_found,
|
||||
message: '任务不存在',
|
||||
result: null,
|
||||
error: '',
|
||||
update_time: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
const cachedTask = await this.getAllocateExpressTaskProgress(taskId);
|
||||
if (!cachedTask) {
|
||||
return this.success('ok', {
|
||||
task_id: taskId,
|
||||
status: 'not_found',
|
||||
progress: ALLOCATE_EXPRESS_PROGRESS_MAP.not_found,
|
||||
message: '任务不存在',
|
||||
result: null,
|
||||
error: '',
|
||||
update_time: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
return this.success('ok', {
|
||||
...cachedTask,
|
||||
update_time: cachedTask.update_time || Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@ -5540,6 +5713,23 @@ class PendingOrderService extends OrderBaseService {
|
||||
throw new Error('OrderExpress 模型未加载');
|
||||
}
|
||||
|
||||
// 3.0 检查是否已分配运单号:若已有 status=1 的记录,拒绝重复录入
|
||||
const existingCompleted = await orderExpressModel.findOne({
|
||||
where: {
|
||||
order_id: orderId,
|
||||
warehouse_id: Number(order.warehouse_id) || warehouseId,
|
||||
status: 1,
|
||||
},
|
||||
attributes: [ 'id', 'waybill_code' ],
|
||||
raw: true,
|
||||
});
|
||||
if (existingCompleted) {
|
||||
const existingWaybill = String(existingCompleted.waybill_code || '').trim();
|
||||
throw new Error(
|
||||
`订单 ${orderId} 已分配运单号${existingWaybill ? `(${existingWaybill})` : ''},不允许重复手工录入`
|
||||
);
|
||||
}
|
||||
|
||||
// 3.1 计算 business_key 递增:查找当前订单已有最大 business_key,+1 递增
|
||||
const maxBusinessKey = await orderExpressModel.max('business_key', {
|
||||
where: {
|
||||
|
||||
@ -1845,10 +1845,10 @@ class PrintService extends MainService {
|
||||
|
||||
const updateResult = await orderDeliveryModel.update({
|
||||
print_lock_status: 'warehouse',
|
||||
print_status: 'fin',
|
||||
}, {
|
||||
where: {
|
||||
id: orderIds,
|
||||
print_lock_status: 'none',
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@ -814,7 +814,23 @@ class DeliveryOrderService extends Service {
|
||||
});
|
||||
|
||||
if (!relation) {
|
||||
throw new Error('货主未与当前仓库签约,无法创建订单');
|
||||
throw new Error('仓库方已暂停接收推单,无法创建订单,请联系仓库方');
|
||||
}
|
||||
|
||||
const relation2 = await ctx.model.StoreWarehouse.findOne({
|
||||
where: {
|
||||
store_id: storeId,
|
||||
warehouse_id: warehouseId,
|
||||
auth_status: 2,
|
||||
warehouse_use_status: 1,
|
||||
},
|
||||
attributes: [ 'id' ],
|
||||
transaction,
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (!relation2) {
|
||||
throw new Error('仓库已禁用,无法创建订单,如需继续推单请进入货主后台修改配置');
|
||||
}
|
||||
|
||||
const storeWarehouseService = ctx.service && ctx.service.systems && ctx.service.systems.storeWarehouse;
|
||||
|
||||
@ -2326,13 +2326,17 @@ class ExpressService extends Service {
|
||||
* business_key 支持单值或数组输入,内部会展开成多条记录后再分组批处理。
|
||||
*【已使用】
|
||||
* @param {Array<Object>} orders 订单与业务键列表。
|
||||
* @param {Object} [options] 可选配置。
|
||||
* @param {boolean} [options.awaitTasks=false] 是否等待所有异步任务完成后再返回。
|
||||
* @param {Function} [options.onBatchComplete] 单批完成回调 ({ processed, total })。
|
||||
* @return {Promise<Object>} 处理结果,包含 orders、waybill_codes 和 skippedOrders。
|
||||
*/
|
||||
async createWaybillCodePipeline(orders = []) {
|
||||
async createWaybillCodePipeline(orders = [], options = {}) {
|
||||
const { app } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
const orderList = Array.isArray(orders) ? orders : [];
|
||||
const traceId = this.buildWaybillTraceId({}, `pipeline_${Date.now()}`);
|
||||
const pipelineOptions = options && typeof options === 'object' ? options : {};
|
||||
|
||||
this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 入口请求', {
|
||||
traceId,
|
||||
@ -2484,11 +2488,19 @@ class ExpressService extends Service {
|
||||
|
||||
for (const batch of batches) {
|
||||
// 异步不阻塞调用 createWaybillCode,快速返回结果给前端,后续的订单处理和异常回写都在 createWaybillCode 内部完成。
|
||||
this.asyncTask(batch, {
|
||||
...groupedOrder.options,
|
||||
trace_id: traceId,
|
||||
warehouse_id: warehouseId,
|
||||
}, matchedPlatformWithRequestCode, expressInterfaceConfig);
|
||||
if (pipelineOptions.awaitTasks) {
|
||||
await this.asyncTask(batch, {
|
||||
...groupedOrder.options,
|
||||
trace_id: traceId,
|
||||
warehouse_id: warehouseId,
|
||||
}, matchedPlatformWithRequestCode, expressInterfaceConfig);
|
||||
} else {
|
||||
this.asyncTask(batch, {
|
||||
...groupedOrder.options,
|
||||
trace_id: traceId,
|
||||
warehouse_id: warehouseId,
|
||||
}, matchedPlatformWithRequestCode, expressInterfaceConfig);
|
||||
}
|
||||
}
|
||||
}
|
||||
this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 流水线任务提交完成', {
|
||||
@ -2557,17 +2569,55 @@ class ExpressService extends Service {
|
||||
order_id: order && (order.id || order.order_id),
|
||||
business_key: order.business_key,
|
||||
}));
|
||||
const failedOrderIds = err_orders
|
||||
const allOrderIds = err_orders
|
||||
.map(order => Number(order && order.order_id))
|
||||
.filter(orderId => Number.isFinite(orderId) && orderId > 0);
|
||||
|
||||
// 查询已成功分配(status=1)的订单,从失败列表中排除,避免误标异常
|
||||
const successOrderIdSet = new Set();
|
||||
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
|
||||
if (orderExpressModel && allOrderIds.length > 0) {
|
||||
try {
|
||||
const successRows = await orderExpressModel.findAll({
|
||||
where: {
|
||||
order_id: { [this.app.Sequelize.Op.in]: allOrderIds },
|
||||
status: 1,
|
||||
},
|
||||
attributes: [ 'order_id' ],
|
||||
raw: true,
|
||||
});
|
||||
for (const row of Array.isArray(successRows) ? successRows : []) {
|
||||
const successOrderId = Number(row && row.order_id);
|
||||
if (Number.isFinite(successOrderId) && successOrderId > 0) {
|
||||
successOrderIdSet.add(successOrderId);
|
||||
}
|
||||
}
|
||||
if (successOrderIdSet.size > 0) {
|
||||
this.ctx.logger.info('[ExpressService.asyncTask] 排除已成功分配的订单,不标记异常', {
|
||||
traceId,
|
||||
successOrderIds: Array.from(successOrderIdSet),
|
||||
});
|
||||
}
|
||||
} catch (statusCheckError) {
|
||||
this.ctx.logger.error('[ExpressService.asyncTask] 查询已成功订单状态失败,降级为全量标记', {
|
||||
traceId,
|
||||
error: statusCheckError && statusCheckError.message ? statusCheckError.message : `${statusCheckError}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const failedOrderIds = allOrderIds.filter(orderId => !successOrderIdSet.has(orderId));
|
||||
const logWarehouseId = this.getOrderLogWarehouseId(options && options.warehouse_id);
|
||||
const errorMessage = error && error.message ? String(error.message) : String(error);
|
||||
this.service.systems.orderPendingException.markPendingException(
|
||||
{
|
||||
ids: err_orders.map(order => order.order_id),
|
||||
exception_text: `订单快递分配失败: ${errorMessage}`,
|
||||
}
|
||||
);
|
||||
|
||||
if (failedOrderIds.length > 0) {
|
||||
this.service.systems.orderPendingException.markPendingException(
|
||||
{
|
||||
ids: failedOrderIds,
|
||||
exception_text: `订单快递分配失败: ${errorMessage}`,
|
||||
}
|
||||
);
|
||||
}
|
||||
await this.createAllocateExpressFailureLogs(failedOrderIds, errorMessage, logWarehouseId);
|
||||
await this.hardDeleteWaybillAsyncOrderExpressRows(err_orders, {
|
||||
platform_code: options.sys_platform_code,
|
||||
|
||||
@ -179,8 +179,9 @@ class OrderPrintSystemService extends OrderBaseService {
|
||||
* 同时从 wms_stock_barcodes 表批量查询每个 stock_id 对应的全部条码,
|
||||
* 注入到打印项的 barcodes 数组中,供 resolveItemBarcodeText 优先读取。
|
||||
*
|
||||
* stock_id 优先读取 wms_order_items.stock_id 列,兜底读取 item_snapshot 内的 stock_id,
|
||||
* 确保不同来源的订单明细都能正确关联到条码数据。
|
||||
* stock_id 优先读取 wms_picking.stock_id(20260708 新增列),
|
||||
* 兜底读取 wms_order_items.stock_id / item_snapshot.stock_id,
|
||||
* 消除对 order_items 明细表的强依赖,使配送表订单打印链路也能正常获取商品信息。
|
||||
*
|
||||
* @param {Array<Object>} orderRows 订单列表。
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
@ -212,7 +213,7 @@ class OrderPrintSystemService extends OrderBaseService {
|
||||
[Op.ne]: 'cancel',
|
||||
},
|
||||
},
|
||||
attributes: [ 'id', 'order_id', 'order_item_id', 'quantity', 'space_id', 'space_name', 'status' ],
|
||||
attributes: [ 'id', 'order_id', 'order_item_id', 'quantity', 'space_id', 'space_name', 'status', 'stock_id' ],
|
||||
order: [[ 'order_id', 'ASC' ], [ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
});
|
||||
@ -285,10 +286,50 @@ class OrderPrintSystemService extends OrderBaseService {
|
||||
pickingRowsByOrderId.set(orderId, list);
|
||||
}
|
||||
|
||||
// 阶段一:构建所有打印项并收集 stock_id
|
||||
const printItemsByOrderId = new Map();
|
||||
// 阶段一:收集 stock_id(优先 picking.stock_id,兜底 order_items.stock_id)
|
||||
const allStockIds = new Set();
|
||||
|
||||
// 1a) 从 wms_picking 直接收集 stock_id(新增路径,绕过 order_items 明细表)
|
||||
for (const row of normalizedPickingRows) {
|
||||
const stockId = Number(row && row.stock_id || 0);
|
||||
if (stockId > 0) {
|
||||
allStockIds.add(stockId);
|
||||
}
|
||||
}
|
||||
|
||||
// 1b) 从 order_items 兜底收集 stock_id(兼容 picking.stock_id 为 NULL 的旧数据)
|
||||
for (const row of Array.isArray(orderItemRows) ? orderItemRows : []) {
|
||||
const itemSnapshot = this.normalizeItemSnapshot(row.item_snapshot);
|
||||
const stockId = Number(row.stock_id || itemSnapshot.stock_id || 0);
|
||||
if (stockId > 0) {
|
||||
allStockIds.add(stockId);
|
||||
}
|
||||
}
|
||||
|
||||
const uniqueStockIds = Array.from(allStockIds);
|
||||
|
||||
// 阶段二:批量查询 wms_stock_warehouse 获取商品编码与名称(新增直读路径)
|
||||
const stockWarehouseMap = new Map();
|
||||
if (uniqueStockIds.length > 0) {
|
||||
const stockWarehouseModel = this.ctx.model && this.ctx.model.StockWarehouse;
|
||||
if (stockWarehouseModel && typeof stockWarehouseModel.findAll === 'function') {
|
||||
const stockRows = await stockWarehouseModel.findAll({
|
||||
where: {
|
||||
id: { [Op.in]: uniqueStockIds },
|
||||
is_valid: 'Y',
|
||||
},
|
||||
attributes: [ 'id', 'item_code', 'item_name' ],
|
||||
raw: true,
|
||||
});
|
||||
for (const row of Array.isArray(stockRows) ? stockRows : []) {
|
||||
stockWarehouseMap.set(Number(row.id), row);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 阶段三:构建所有打印项(使用 stock_warehouse 直读数据)
|
||||
const printItemsByOrderId = new Map();
|
||||
|
||||
for (const orderRow of rows) {
|
||||
const orderId = Number(orderRow && orderRow.id || 0);
|
||||
const pickingList = pickingRowsByOrderId.get(orderId) || [];
|
||||
@ -307,27 +348,36 @@ class OrderPrintSystemService extends OrderBaseService {
|
||||
custom_name: locationRow.custom_name,
|
||||
custom_barcode: locationRow.custom_barcode,
|
||||
}, [ 'space_name', 'space_code', 'custom_name', 'custom_barcode' ]);
|
||||
|
||||
// stock_id 优先级:picking.stock_id > order_items.stock_id > item_snapshot.stock_id
|
||||
const pickingStockId = Number(pickingRow && pickingRow.stock_id || 0);
|
||||
const orderItemStockId = Number(orderItemRow.stock_id || itemSnapshot.stock_id || 0);
|
||||
const stockId = pickingStockId > 0 ? pickingStockId : orderItemStockId;
|
||||
|
||||
// 从 stock_warehouse 直读商品编码与名称(新增路径,绕过 order_items)
|
||||
const stockInfo = stockId > 0 ? stockWarehouseMap.get(stockId) : null;
|
||||
|
||||
// item_name 优先级:stock_warehouse > order_items > item_snapshot
|
||||
const itemName = this.getFirstNonEmptyFieldText({
|
||||
stock_item_name: stockInfo && stockInfo.item_name,
|
||||
snapshot_item_name: itemSnapshot.item_name,
|
||||
snapshot_name: itemSnapshot.name,
|
||||
snapshot_title: itemSnapshot.title,
|
||||
item_name: orderItemRow.item_name,
|
||||
}, [ 'snapshot_item_name', 'snapshot_name', 'snapshot_title', 'item_name' ]);
|
||||
}, [ 'stock_item_name', 'snapshot_item_name', 'snapshot_name', 'snapshot_title', 'item_name' ]);
|
||||
|
||||
// barcode 优先级:stock_warehouse.item_code > item_snapshot > order_items.item_code
|
||||
const barcode = this.getFirstNonEmptyFieldText({
|
||||
stock_item_code: stockInfo && stockInfo.item_code,
|
||||
barcode: itemSnapshot.barcode,
|
||||
item_barcode: itemSnapshot.item_barcode,
|
||||
bar_code: itemSnapshot.bar_code,
|
||||
item_code: orderItemRow.item_code,
|
||||
sku_code: itemSnapshot.sku_code,
|
||||
sku: itemSnapshot.sku,
|
||||
}, [ 'barcode', 'item_barcode', 'bar_code', 'item_code', 'sku_code', 'sku' ]);
|
||||
const quantity = Number(pickingRow && pickingRow.quantity || orderItemRow.plan_qty || 0);
|
||||
// 优先使用列 stock_id,兜底使用 item_snapshot 内的 stock_id
|
||||
const stockId = Number(orderItemRow.stock_id || itemSnapshot.stock_id || 0);
|
||||
}, [ 'stock_item_code', 'barcode', 'item_barcode', 'bar_code', 'item_code', 'sku_code', 'sku' ]);
|
||||
|
||||
if (stockId > 0) {
|
||||
allStockIds.add(stockId);
|
||||
}
|
||||
const quantity = Number(pickingRow && pickingRow.quantity || orderItemRow.plan_qty || 0);
|
||||
|
||||
return {
|
||||
order_item_id: orderItemId,
|
||||
@ -350,9 +400,8 @@ class OrderPrintSystemService extends OrderBaseService {
|
||||
printItemsByOrderId.set(orderId, printItems);
|
||||
}
|
||||
|
||||
// 阶段二:批量查询 wms_stock_barcodes 获取所有条码
|
||||
// 阶段四:批量查询 wms_stock_barcodes 获取所有条码
|
||||
const barcodeMap = new Map();
|
||||
const uniqueStockIds = Array.from(allStockIds);
|
||||
|
||||
if (uniqueStockIds.length > 0) {
|
||||
const stockBarcodeModel = this.ctx.model && this.ctx.model.StockBarcode;
|
||||
@ -385,7 +434,7 @@ class OrderPrintSystemService extends OrderBaseService {
|
||||
}
|
||||
}
|
||||
|
||||
// 阶段三:注入条码并构建结果映射
|
||||
// 阶段五:注入条码并构建结果映射
|
||||
for (const orderRow of rows) {
|
||||
const orderId = Number(orderRow && orderRow.id || 0);
|
||||
const printItems = printItemsByOrderId.get(orderId);
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user