fix(order): 拦截请求按取消处理(未同步/手工单)与拦截确认无拣货行补建拦截锁
- batchIntercept/cancelOrderForInterceptRequest: 未同步订单与手工单拦截请求分流为取消处理,释放两层锁;已同步手工单按明细 inbound 回补 stock quantity(stockId 快速路径),取消后两层可用数守恒 - order_storage_allocation 拦截模式: 无拣货行订单补建拦截锁定(quantity/intercept 同增、available=0),写 INTERCEPT_LOCK 流水 - OperationLog 模型字段修正为下划线命名
This commit is contained in:
parent
e17461fe51
commit
67f57f820d
@ -30,6 +30,119 @@ function shouldSkipWorkOrder(ctx) {
|
||||
return !!(ctx && ctx.inboxContext && ctx.inboxContext.skip_work_order === true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 拦截请求按取消订单处理(未同步订单/手工单规则):
|
||||
* 订单状态置 cancel,释放 stock 建单锁与 storage 储位锁,不写拦截状态。
|
||||
* 已同步订单(sync=fin)取消时按订单明细回补 stock quantity(同步出库冲回),
|
||||
* 保证取消后两层可用数守恒。
|
||||
* 整体在一个事务内执行,失败回滚并告警,不阻断主流程。
|
||||
*
|
||||
* @param {Object} ctx Egg 上下文。
|
||||
* @param {Object} orderModel 当前仓库订单模型。
|
||||
* @param {number|string} warehouseId 仓库ID。
|
||||
* @param {Array<number>} orderIds 订单ID数组。
|
||||
* @param {Array<number>} syncedOrderIds 其中已同步的订单ID(取消时需回补 stock quantity)。
|
||||
* @param {Object} operator 操作人信息({ id, name })。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async function cancelOrderForInterceptRequest(ctx, orderModel, warehouseId, orderIds, syncedOrderIds, operator) {
|
||||
if (!Array.isArray(orderIds) || orderIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const syncedIds = Array.isArray(syncedOrderIds) ? syncedOrderIds.map(id => Number(id)).filter(id => Number.isInteger(id) && id > 0) : [];
|
||||
const now = new Date();
|
||||
const transaction = await ctx.model.transaction();
|
||||
|
||||
try {
|
||||
await orderModel.update(
|
||||
{ status: 'cancel', step: 9, outbound_status: 'padding', updated_at: now },
|
||||
{ where: { id: { [ctx.app.Sequelize.Op.in]: orderIds }, warehouse_id: warehouseId }, transaction }
|
||||
);
|
||||
|
||||
// 释放储位分配(普通模式:解除锁定/返还实物)
|
||||
await ctx.service.systems.orderStorageAllocation.cancelAllocateStorage({
|
||||
order_ids: orderIds,
|
||||
transaction,
|
||||
});
|
||||
|
||||
// 释放 stock 建单锁(仅未同步订单:已同步订单的建单锁已在同步出库时释放)
|
||||
const unsyncedIds = orderIds
|
||||
.map(id => Number(id))
|
||||
.filter(id => Number.isInteger(id) && id > 0 && !syncedIds.includes(id));
|
||||
if (unsyncedIds.length > 0) {
|
||||
await ctx.service.systemMethods.order.pendingOrder.releaseCreationLockForCancel({
|
||||
orderIds: unsyncedIds,
|
||||
warehouseId,
|
||||
transaction,
|
||||
});
|
||||
}
|
||||
|
||||
// 已同步订单:回补 stock quantity(同步出库冲回,货物回可用)
|
||||
if (syncedIds.length > 0) {
|
||||
const orderItemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId);
|
||||
const cancelOrderItems = await orderItemsModel.findAll({
|
||||
where: { order_id: { [ctx.app.Sequelize.Op.in]: syncedIds } },
|
||||
attributes: [ 'order_id', 'stock_id', 'plan_qty' ],
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
|
||||
for (const item of Array.isArray(cancelOrderItems) ? cancelOrderItems : []) {
|
||||
const stockId = Number(item && item.stock_id) || 0;
|
||||
const qty = Number(item && item.plan_qty) || 0;
|
||||
if (stockId <= 0 || qty <= 0) {
|
||||
continue;
|
||||
}
|
||||
const inboundResult = await ctx.service.systems.stockStore.inbound(
|
||||
stockId,
|
||||
qty,
|
||||
transaction,
|
||||
{ stockId }
|
||||
);
|
||||
if (!inboundResult || inboundResult.success !== true) {
|
||||
throw new Error(
|
||||
`未同步/手工单取消回补库存失败: stockId=${stockId}, qty=${qty}, ${(inboundResult && inboundResult.error) || '未知错误'}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await transaction.commit();
|
||||
} catch (error) {
|
||||
await transaction.rollback().catch(() => {});
|
||||
ctx.logger.warn(`[inbox functions] 未同步/手工单按取消处理失败: ${error.message}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// 写入操作日志(失败不影响主流程)
|
||||
try {
|
||||
const logSvc = ctx.service?.systems?.operationLog;
|
||||
if (logSvc && typeof logSvc.createOperationLogs === 'function') {
|
||||
await logSvc.createOperationLogs(
|
||||
orderIds.map(orderId => ({
|
||||
businessType: 'order',
|
||||
businessId: String(orderId),
|
||||
operationCode: 'ORDER_INTERCEPT_REQUEST_CANCELED',
|
||||
operator: operator || { id: '0', name: 'AI系统' },
|
||||
extras: {
|
||||
warehouseId,
|
||||
orderId,
|
||||
message: syncedIds.includes(Number(orderId))
|
||||
? '已同步手工单拦截请求按取消订单处理(库存已回补)'
|
||||
: '未同步订单拦截请求按取消订单处理',
|
||||
externalLogType: 'NONE',
|
||||
},
|
||||
}))
|
||||
);
|
||||
}
|
||||
} catch (logErr) {
|
||||
ctx.logger.warn(`[inbox functions] 未同步/手工单按取消处理-操作日志失败: ${logErr.message}`);
|
||||
}
|
||||
|
||||
ctx.logger.info(`[inbox functions] 未同步/手工单按取消处理: ${orderIds.length} 个订单`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 站内信函数注册表。
|
||||
* 负责注册 AI 可调用的函数(含 handler),支持按分组声明可见性。
|
||||
@ -1102,7 +1215,7 @@ class InboxFunctionsService extends Service {
|
||||
const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
|
||||
if (orderModel) {
|
||||
const orders = await orderModel.findAll({
|
||||
attributes: [ 'id', 'step', 'wave_id', 'inspection_status', 'intercept_time' ],
|
||||
attributes: [ 'id', 'step', 'wave_id', 'inspection_status', 'intercept_time', 'sync_status', 'create_channel' ],
|
||||
where: {
|
||||
id: { [ctx.app.Sequelize.Op.in]: orderIds },
|
||||
step: { [ctx.app.Sequelize.Op.in]: [ 1, 2, 3 ] },
|
||||
@ -1124,6 +1237,9 @@ class InboxFunctionsService extends Service {
|
||||
}
|
||||
|
||||
const interceptOrderIds = [];
|
||||
// 未同步订单/手工单:拦截请求按取消订单处理(释放两层锁,不走拦截)
|
||||
const cancelHandledOrderIds = [];
|
||||
const syncedCancelOrderIds = [];
|
||||
const kickOutOrderIds = [];
|
||||
|
||||
// 批量查询散单的称重状态(wms_order_express.weighing_weight)
|
||||
@ -1164,7 +1280,16 @@ class InboxFunctionsService extends Service {
|
||||
}
|
||||
|
||||
if (needIntercept) {
|
||||
interceptOrderIds.push(orderId);
|
||||
const isManualOrder = String(order.create_channel || '').trim().toUpperCase() === 'MANUAL';
|
||||
const isUnsyncedOrder = String(order.sync_status || '').trim() !== 'fin';
|
||||
if (isManualOrder || isUnsyncedOrder) {
|
||||
cancelHandledOrderIds.push(orderId);
|
||||
if (!isUnsyncedOrder) {
|
||||
syncedCancelOrderIds.push(orderId);
|
||||
}
|
||||
} else {
|
||||
interceptOrderIds.push(orderId);
|
||||
}
|
||||
}
|
||||
|
||||
// 规则2:有波次且未打印
|
||||
@ -1222,6 +1347,18 @@ class InboxFunctionsService extends Service {
|
||||
);
|
||||
}
|
||||
|
||||
// 未同步/手工单:拦截请求按取消订单处理(释放两层锁)
|
||||
if (cancelHandledOrderIds.length > 0) {
|
||||
await cancelOrderForInterceptRequest(
|
||||
ctx,
|
||||
orderModel,
|
||||
warehouseId,
|
||||
cancelHandledOrderIds,
|
||||
syncedCancelOrderIds,
|
||||
{ id: '0', name: groupName || 'AI系统' }
|
||||
);
|
||||
}
|
||||
|
||||
// 执行踢出波次
|
||||
if (kickOutOrderIds.length > 0) {
|
||||
await ctx.service.systemMethods.order.wave.batchRemoveOrders({
|
||||
@ -1986,7 +2123,7 @@ class InboxFunctionsService extends Service {
|
||||
const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
|
||||
if (orderModel) {
|
||||
const orders = await orderModel.findAll({
|
||||
attributes: [ 'id', 'step', 'wave_id', 'inspection_status', 'intercept_time' ],
|
||||
attributes: [ 'id', 'step', 'wave_id', 'inspection_status', 'intercept_time', 'sync_status', 'create_channel' ],
|
||||
where: { id: { [ctx.app.Sequelize.Op.in]: orderIds }, step: { [ctx.app.Sequelize.Op.in]: [ 1, 2, 3 ] } },
|
||||
raw: true,
|
||||
});
|
||||
@ -2001,6 +2138,9 @@ class InboxFunctionsService extends Service {
|
||||
waveMap = Object.fromEntries(waves.map(w => [ w.wave_id, w ]));
|
||||
}
|
||||
const interceptOrderIds = [];
|
||||
// 未同步订单/手工单:拦截请求按取消订单处理(释放两层锁,不走拦截)
|
||||
const cancelHandledOrderIds = [];
|
||||
const syncedCancelOrderIds = [];
|
||||
// 批量查询散单的称重状态
|
||||
const scatterIds = orders
|
||||
.filter(o => o.wave_id > 0 && waveMap[o.wave_id] && waveMap[o.wave_id].wave_type === 2)
|
||||
@ -2028,7 +2168,18 @@ class InboxFunctionsService extends Service {
|
||||
} else {
|
||||
needIntercept = true;
|
||||
}
|
||||
if (needIntercept) interceptOrderIds.push(order.id);
|
||||
if (needIntercept) {
|
||||
const isManualOrder = String(order.create_channel || '').trim().toUpperCase() === 'MANUAL';
|
||||
const isUnsyncedOrder = String(order.sync_status || '').trim() !== 'fin';
|
||||
if (isManualOrder || isUnsyncedOrder) {
|
||||
cancelHandledOrderIds.push(order.id);
|
||||
if (!isUnsyncedOrder) {
|
||||
syncedCancelOrderIds.push(order.id);
|
||||
}
|
||||
} else {
|
||||
interceptOrderIds.push(order.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (interceptOrderIds.length > 0) {
|
||||
const noticeNow = new Date();
|
||||
@ -2069,6 +2220,18 @@ class InboxFunctionsService extends Service {
|
||||
}
|
||||
ctx.logger.info(`[inbox functions] 取消拦截-设置拦截状态: ${interceptOrderIds.length} 个订单`);
|
||||
}
|
||||
|
||||
// 未同步/手工单:拦截请求按取消订单处理(释放两层锁)
|
||||
if (cancelHandledOrderIds.length > 0) {
|
||||
await cancelOrderForInterceptRequest(
|
||||
ctx,
|
||||
orderModel,
|
||||
warehouseId,
|
||||
cancelHandledOrderIds,
|
||||
syncedCancelOrderIds,
|
||||
{ id: '0', name: groupName || 'AI系统' }
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
|
||||
@ -4670,7 +4670,7 @@ class PendingOrderService extends OrderBaseService {
|
||||
}
|
||||
|
||||
const orderRows = await orderModel.findAll({
|
||||
attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code', 'wave_id', 'inspection_status', 'intercept_time' ],
|
||||
attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code', 'wave_id', 'inspection_status', 'intercept_time', 'sync_status', 'create_channel' ],
|
||||
where: {
|
||||
warehouse_id: warehouseId,
|
||||
id: {
|
||||
@ -4714,8 +4714,22 @@ class PendingOrderService extends OrderBaseService {
|
||||
}
|
||||
}
|
||||
|
||||
// 未同步订单与手工单不发起拦截,默认按取消订单处理:
|
||||
// 释放 stock 建单锁与 storage 储位锁,不走常规拦截(不迁移拦截锁)
|
||||
const cancelHandledOrderRows = [];
|
||||
const interceptTargetRows = [];
|
||||
for (const row of eligibleOrderRows) {
|
||||
const isManualOrder = String(row.create_channel || '').trim().toUpperCase() === 'MANUAL';
|
||||
const isUnsyncedOrder = String(row.sync_status || '').trim() !== 'fin';
|
||||
if (isManualOrder || isUnsyncedOrder) {
|
||||
cancelHandledOrderRows.push(row);
|
||||
} else {
|
||||
interceptTargetRows.push(row);
|
||||
}
|
||||
}
|
||||
|
||||
const normalizedOrderRows = Array.isArray(validOrderRows) ? validOrderRows : [];
|
||||
const eligibleOrderCount = eligibleOrderRows.length;
|
||||
const eligibleOrderCount = interceptTargetRows.length;
|
||||
const totalOrderCount = orderIds.length;
|
||||
const validOrderCount = normalizedOrderRows.length;
|
||||
|
||||
@ -4746,10 +4760,141 @@ class PendingOrderService extends OrderBaseService {
|
||||
return;
|
||||
}
|
||||
|
||||
// 分批更新拦截状态,每批最多500条(仅处理未命中「已复核/已称重」前置校验的订单)
|
||||
const cancelledOrderIds = [];
|
||||
const UPDATE_CHUNK_SIZE = 500;
|
||||
for (let i = 0; i < eligibleOrderRows.length; i += UPDATE_CHUNK_SIZE) {
|
||||
const chunkRows = eligibleOrderRows.slice(i, i + UPDATE_CHUNK_SIZE);
|
||||
|
||||
// ── 未同步/手工单:按取消订单处理(状态置 cancel + 释放两层锁,不走拦截) ──
|
||||
// 已同步订单(stock 层已同步出库)取消时按订单明细回补 stock quantity,
|
||||
// 保证取消后两层可用数守恒(storage 锁释放、stock 数量冲回)
|
||||
if (cancelHandledOrderRows.length > 0) {
|
||||
const cancelIds = cancelHandledOrderRows.map(row => Number(row.id)).filter(id => Number.isInteger(id) && id > 0);
|
||||
const now = new Date();
|
||||
|
||||
for (let i = 0; i < cancelIds.length; i += UPDATE_CHUNK_SIZE) {
|
||||
const chunkCancelIds = cancelIds.slice(i, i + UPDATE_CHUNK_SIZE);
|
||||
if (chunkCancelIds.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const chunkRows = cancelHandledOrderRows.filter(row => chunkCancelIds.includes(Number(row.id)));
|
||||
const syncedCancelIds = chunkRows
|
||||
.filter(row => String(row.sync_status || '').trim() === 'fin')
|
||||
.map(row => Number(row.id));
|
||||
const unsyncedCancelIds = chunkCancelIds.filter(id => !syncedCancelIds.includes(id));
|
||||
|
||||
const cancelTransaction = await this.ctx.model.transaction();
|
||||
try {
|
||||
await orderModel.update(
|
||||
{ status: 'cancel', step: 9, outbound_status: 'padding', updated_at: now },
|
||||
{ where: { id: { [Op.in]: chunkCancelIds }, warehouse_id: warehouseId }, transaction: cancelTransaction }
|
||||
);
|
||||
|
||||
// 释放储位分配(普通模式:解除锁定/返还实物)
|
||||
const originalUser = ctx.user;
|
||||
ctx.user = originalUser
|
||||
? { ...originalUser, store_id: warehouseId }
|
||||
: { store_id: warehouseId };
|
||||
try {
|
||||
await this.service.systems.orderStorageAllocation.cancelAllocateStorage({
|
||||
order_ids: chunkCancelIds,
|
||||
transaction: cancelTransaction,
|
||||
});
|
||||
} finally {
|
||||
ctx.user = originalUser;
|
||||
}
|
||||
|
||||
// 释放 stock 建单锁(仅未同步订单:已同步订单的建单锁已在同步出库时释放)
|
||||
if (unsyncedCancelIds.length > 0) {
|
||||
await this.releaseCreationLockForCancel({
|
||||
orderIds: unsyncedCancelIds,
|
||||
warehouseId,
|
||||
transaction: cancelTransaction,
|
||||
});
|
||||
}
|
||||
|
||||
// 已同步订单:回补 stock quantity(同步出库冲回,货物回可用)
|
||||
if (syncedCancelIds.length > 0) {
|
||||
const orderItemsModel = await this.ctx.model.OrderItemsFactory.getCurrentModel(warehouseId);
|
||||
const cancelOrderItems = await orderItemsModel.findAll({
|
||||
where: { order_id: { [Op.in]: syncedCancelIds } },
|
||||
attributes: [ 'stock_id', 'plan_qty' ],
|
||||
raw: true,
|
||||
transaction: cancelTransaction,
|
||||
});
|
||||
|
||||
// 回补依赖 ctx.user.store_id 写流水,任务执行时上下文可能已失效,临时注入
|
||||
const inboundOriginalUser = ctx.user;
|
||||
ctx.user = inboundOriginalUser
|
||||
? { ...inboundOriginalUser, store_id: warehouseId }
|
||||
: { store_id: warehouseId };
|
||||
|
||||
for (const item of Array.isArray(cancelOrderItems) ? cancelOrderItems : []) {
|
||||
const stockId = Number(item && item.stock_id) || 0;
|
||||
const qty = Number(item && item.plan_qty) || 0;
|
||||
if (stockId <= 0 || qty <= 0) {
|
||||
continue;
|
||||
}
|
||||
const inboundResult = await this.ctx.service.systems.stockStore.inbound(
|
||||
stockId,
|
||||
qty,
|
||||
cancelTransaction,
|
||||
{ stockId }
|
||||
);
|
||||
if (!inboundResult || inboundResult.success !== true) {
|
||||
throw new Error(
|
||||
`未同步/手工单取消回补库存失败: stockId=${stockId}, qty=${qty}, ${(inboundResult && inboundResult.error) || '未知错误'}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
ctx.user = inboundOriginalUser;
|
||||
}
|
||||
|
||||
await cancelTransaction.commit();
|
||||
} catch (cancelErr) {
|
||||
await cancelTransaction.rollback().catch(() => {});
|
||||
ctx.logger.warn(
|
||||
`[order.pendingOrder.batchIntercept] 未同步/手工单取消失败, ids=${chunkCancelIds.join(',')}, error=${cancelErr.message}`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
cancelledOrderIds.push(...chunkCancelIds);
|
||||
|
||||
// 写入操作日志(失败不影响主流程)
|
||||
try {
|
||||
const cancelLogRows = chunkRows
|
||||
.map(row => {
|
||||
const orderId = Number(row.id || 0);
|
||||
const isSynced = String(row.sync_status || '').trim() === 'fin';
|
||||
return {
|
||||
business_type: 'order',
|
||||
business_id: String(orderId),
|
||||
operation_code: 'ORDER_INTERCEPT_REQUEST_CANCELED',
|
||||
operator_id: operator && operator.id != null ? String(operator.id) : null,
|
||||
operator_name: operator && operator.name ? String(operator.name) : 'system',
|
||||
external_log_type: 'NONE',
|
||||
warehouse_id: logWarehouseId || null,
|
||||
platform_code: 'SYSTEM',
|
||||
message: isSynced
|
||||
? '已同步手工单拦截请求按取消订单处理(库存已回补)'
|
||||
: '未同步订单拦截请求按取消订单处理',
|
||||
created_at: new Date(),
|
||||
};
|
||||
})
|
||||
.filter(row => Number(row.businessId) > 0);
|
||||
if (cancelLogRows.length > 0 && this.ctx.model && this.ctx.model.OperationLog) {
|
||||
await this.ctx.model.OperationLog.bulkCreate(cancelLogRows);
|
||||
}
|
||||
} catch (logErr) {
|
||||
ctx.logger.warn(`[order.pendingOrder.batchIntercept] 未同步/手工单取消日志写入失败, count=${chunkCancelIds.length}, error=${logErr.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 分批更新拦截状态,每批最多500条(仅处理未命中「已复核/已称重」前置校验的订单)
|
||||
for (let i = 0; i < interceptTargetRows.length; i += UPDATE_CHUNK_SIZE) {
|
||||
const chunkRows = interceptTargetRows.slice(i, i + UPDATE_CHUNK_SIZE);
|
||||
if (chunkRows.length === 0) {
|
||||
continue;
|
||||
}
|
||||
@ -4876,13 +5021,14 @@ class PendingOrderService extends OrderBaseService {
|
||||
order_ids: orderIds,
|
||||
intercepted_order_ids: interceptedOrderIds,
|
||||
intercepted_order_count: interceptedOrderIds.length,
|
||||
cancelled_order_ids: cancelledOrderIds,
|
||||
cancelled_order_count: cancelledOrderIds.length,
|
||||
skipped_order_ids: skippedInterceptOrderIds,
|
||||
skipped_order_count: skippedInterceptOrderIds.length,
|
||||
total_order_count: totalOrderCount,
|
||||
duration_ms: durationMs,
|
||||
message: skippedInterceptOrderIds.length > 0
|
||||
? `已拦截 ${interceptedOrderIds.length} 条订单,跳过 ${skippedInterceptOrderIds.length} 条(已复核/已称重)`
|
||||
: `已拦截 ${interceptedOrderIds.length} 条订单`,
|
||||
message: `已拦截 ${interceptedOrderIds.length} 条订单,未同步/手工单按取消处理 ${cancelledOrderIds.length} 条`
|
||||
+ (skippedInterceptOrderIds.length > 0 ? `,跳过 ${skippedInterceptOrderIds.length} 条(已复核/已称重)` : ''),
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
|
||||
@ -2229,6 +2229,9 @@ class OrderStorageAllocationService extends MainService {
|
||||
|
||||
const skippedOrders = [];
|
||||
const eligibleOrderIds = [];
|
||||
// 拦截模式:无拣货行(含已软删)或储位已释放但已同步出库的订单,
|
||||
// 按订单明细补建拦截锁承接总量差,避免可用数漂移
|
||||
const interceptNoPickingOrderIds = [];
|
||||
|
||||
for (const orderId of orderIds) {
|
||||
const orderRow = orderMap.get(orderId);
|
||||
@ -2249,6 +2252,11 @@ class OrderStorageAllocationService extends MainService {
|
||||
}
|
||||
|
||||
if (String(orderRow.storage_status || 'none') !== STORAGE_STATUS_FIN) {
|
||||
// 拦截确认模式:储位已释放但已同步出库的订单(stock 层已扣、storage 层无锁可迁)
|
||||
// 不直接跳过,登记为拦截锁补建候选,保证可用数守恒
|
||||
if (interceptMode && String(orderRow.sync_status || '').trim() === 'fin') {
|
||||
interceptNoPickingOrderIds.push(orderId);
|
||||
}
|
||||
skippedOrders.push({
|
||||
order_id: orderId,
|
||||
status: 'skipped',
|
||||
@ -2268,24 +2276,29 @@ class OrderStorageAllocationService extends MainService {
|
||||
});
|
||||
|
||||
if (eligibleOrderIds.length === 0) {
|
||||
if (!externalTransaction) {
|
||||
await transaction.commit();
|
||||
// 拦截模式下存在无拣货行补建候选(储位已释放但已同步出库)时,
|
||||
// 继续执行拦截分支完成拦截锁补建,保证可用数守恒
|
||||
const hasNoPickingCompensate = interceptMode && interceptNoPickingOrderIds.length > 0;
|
||||
if (!hasNoPickingCompensate) {
|
||||
if (!externalTransaction) {
|
||||
await transaction.commit();
|
||||
}
|
||||
return {
|
||||
code: 200,
|
||||
message: '没有需要取消分配的订单',
|
||||
data: {
|
||||
warehouse_id: warehouseId,
|
||||
requested_order_ids: orderIds,
|
||||
cancellable_order_ids: [],
|
||||
skipped_orders: skippedOrders,
|
||||
orders: skippedOrders,
|
||||
picking_count: 0,
|
||||
storage_unlock_summary: [],
|
||||
storage_return_summary: [],
|
||||
stock_unlock_summary: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
code: 200,
|
||||
message: '没有需要取消分配的订单',
|
||||
data: {
|
||||
warehouse_id: warehouseId,
|
||||
requested_order_ids: orderIds,
|
||||
cancellable_order_ids: [],
|
||||
skipped_orders: skippedOrders,
|
||||
orders: skippedOrders,
|
||||
picking_count: 0,
|
||||
storage_unlock_summary: [],
|
||||
storage_return_summary: [],
|
||||
stock_unlock_summary: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const pickingRows = await pickingModel.findAll({
|
||||
@ -2354,6 +2367,14 @@ class OrderStorageAllocationService extends MainService {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (interceptMode) {
|
||||
// 拦截确认:储位状态为 fin 但无拣货行(已软删/已删除)的订单不跳过,
|
||||
// 按订单明细补建拦截锁,承接同步出库造成的总量差
|
||||
cancellableOrderIds.push(orderId);
|
||||
interceptNoPickingOrderIds.push(orderId);
|
||||
continue;
|
||||
}
|
||||
|
||||
skippedOrders.push({
|
||||
order_id: orderId,
|
||||
status: 'skipped',
|
||||
@ -2363,24 +2384,29 @@ class OrderStorageAllocationService extends MainService {
|
||||
}
|
||||
|
||||
if (cancellableOrderIds.length === 0) {
|
||||
if (!externalTransaction) {
|
||||
await transaction.commit();
|
||||
// 拦截模式下存在无拣货行补建候选(储位已释放但已同步出库)时,
|
||||
// 继续执行拦截分支完成拦截锁补建,保证可用数守恒
|
||||
const hasNoPickingCompensate = interceptMode && interceptNoPickingOrderIds.length > 0;
|
||||
if (!hasNoPickingCompensate) {
|
||||
if (!externalTransaction) {
|
||||
await transaction.commit();
|
||||
}
|
||||
return {
|
||||
code: 200,
|
||||
message: '没有需要取消分配的订单',
|
||||
data: {
|
||||
warehouse_id: warehouseId,
|
||||
requested_order_ids: orderIds,
|
||||
cancellable_order_ids: [],
|
||||
skipped_orders: skippedOrders,
|
||||
orders: skippedOrders,
|
||||
picking_count: 0,
|
||||
storage_unlock_summary: [],
|
||||
storage_return_summary: [],
|
||||
stock_unlock_summary: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
code: 200,
|
||||
message: '没有需要取消分配的订单',
|
||||
data: {
|
||||
warehouse_id: warehouseId,
|
||||
requested_order_ids: orderIds,
|
||||
cancellable_order_ids: [],
|
||||
skipped_orders: skippedOrders,
|
||||
orders: skippedOrders,
|
||||
picking_count: 0,
|
||||
storage_unlock_summary: [],
|
||||
storage_return_summary: [],
|
||||
stock_unlock_summary: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const storageRows = await storageModel.findAll({
|
||||
@ -2407,6 +2433,8 @@ class OrderStorageAllocationService extends MainService {
|
||||
|
||||
const storageUnlockSummary = [];
|
||||
const storageReturnSummary = [];
|
||||
// 拦截模式无拣货行补建汇总(storage_id -> 补建拦截锁数量),随响应返回供对账追溯
|
||||
const interceptCompensateSummaryMap = new Map();
|
||||
|
||||
if (interceptMode) {
|
||||
// ── 拦截模式:库存不归还可用,移入拦截锁定字段(intercept_locked_quantity) ──
|
||||
@ -2678,6 +2706,178 @@ class OrderStorageAllocationService extends MainService {
|
||||
for (const [ storageId, quantity ] of interceptReturnSummaryMap.entries()) {
|
||||
storageReturnSummary.push({ storage_id: storageId, returned_quantity: quantity });
|
||||
}
|
||||
|
||||
// ── 拦截模式无拣货行补建:拣货行已被删除/软删(取消储位分配等路径)的订单, ──
|
||||
// ── 同步出库已在 stock 层扣减而 storage 层从未扣,拦截锁无行可迁。 ──
|
||||
// ── 按订单明细数量补建拦截锁(intercept +q、available -q、quantity 不变), ──
|
||||
// ── 确保可用数守恒:storage 可用 === stock 可用。 ──
|
||||
if (interceptNoPickingOrderIds.length > 0) {
|
||||
const orderItemsModel = ctx.model && ctx.model.OrderItemsFactory
|
||||
&& typeof ctx.model.OrderItemsFactory.getCurrentModel === 'function'
|
||||
? await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId)
|
||||
: null;
|
||||
|
||||
if (!orderItemsModel) {
|
||||
writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 拦截模式无拣货行补建跳过:订单明细模型不可用', {
|
||||
interceptNoPickingOrderIds,
|
||||
});
|
||||
} else {
|
||||
const noPickingOrderItems = await orderItemsModel.findAll({
|
||||
where: {
|
||||
order_id: { [Op.in]: interceptNoPickingOrderIds },
|
||||
},
|
||||
attributes: [ 'order_id', 'stock_id', 'plan_qty' ],
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
|
||||
// 按 (order_id, stock_id) 汇总补建量
|
||||
const compensatePlanMap = new Map(); // orderId -> [{ stockId, qty }]
|
||||
for (const item of Array.isArray(noPickingOrderItems) ? noPickingOrderItems : []) {
|
||||
const itemOrderId = toNumber(item && item.order_id, 0);
|
||||
const stockId = toNumber(item && item.stock_id, 0);
|
||||
const qty = toNumber(item && item.plan_qty, 0);
|
||||
if (itemOrderId <= 0 || stockId <= 0 || qty <= 0) {
|
||||
continue;
|
||||
}
|
||||
const plans = compensatePlanMap.get(itemOrderId) || [];
|
||||
const existing = plans.find(p => p.stockId === stockId);
|
||||
if (existing) {
|
||||
existing.qty += qty;
|
||||
} else {
|
||||
plans.push({ stockId, qty });
|
||||
}
|
||||
compensatePlanMap.set(itemOrderId, plans);
|
||||
}
|
||||
|
||||
// 逐商品查询可用库存行(有行挂锁,无行补建行),并写拦截锁定流水
|
||||
for (const orderId of interceptNoPickingOrderIds) {
|
||||
const plans = compensatePlanMap.get(orderId) || [];
|
||||
if (plans.length === 0) {
|
||||
continue;
|
||||
}
|
||||
const orderRow = orderMap.get(orderId) || {};
|
||||
const orderNo = String(orderRow.delivery_order_code || orderRow.pre_delivery_order_code || '').trim()
|
||||
|| 'INTERCEPT_CONFIRM';
|
||||
const orderStoreId = toNumber(orderRow.store_id, 0) || null;
|
||||
|
||||
for (const plan of plans) {
|
||||
const { stockId, qty } = plan;
|
||||
|
||||
// 优先找该商品数量最多的未删除行挂锁,保证拦截锁落在真实库存行上
|
||||
const candidateRows = await storageModel.findAll({
|
||||
where: {
|
||||
stock_id: stockId,
|
||||
warehouse_id: warehouseId,
|
||||
is_enabled: 1,
|
||||
delete_at: null,
|
||||
},
|
||||
order: [[ 'quantity', 'DESC' ]],
|
||||
lock: transaction ? transaction.LOCK.UPDATE : undefined,
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
|
||||
if (candidateRows.length > 0) {
|
||||
const targetRow = candidateRows[0];
|
||||
const beforeInterceptLockedQuantity = toNumber(targetRow.intercept_locked_quantity, 0);
|
||||
|
||||
await ctx.service.systems.storage.index.updateQuantity(
|
||||
Number(targetRow.id),
|
||||
0,
|
||||
0,
|
||||
{ transaction, interceptLockedChange: qty }
|
||||
);
|
||||
|
||||
await ctx.model.StorageTransaction.create({
|
||||
transaction_type: 'LOCK',
|
||||
warehouse_id: warehouseId,
|
||||
store_id: Number(targetRow.store_id) || orderStoreId,
|
||||
stock_id: stockId,
|
||||
storage_id: Number(targetRow.id),
|
||||
space_id: Number(targetRow.space_id) || null,
|
||||
quantity: qty,
|
||||
before_quantity: Number(targetRow.quantity) || 0,
|
||||
after_quantity: Number(targetRow.quantity) || 0,
|
||||
before_locked_quantity: Number(targetRow.locked_quantity) || 0,
|
||||
after_locked_quantity: Number(targetRow.locked_quantity) || 0,
|
||||
before_intercept_locked_quantity: beforeInterceptLockedQuantity,
|
||||
after_intercept_locked_quantity: beforeInterceptLockedQuantity + qty,
|
||||
batch_no: targetRow.batch_no || null,
|
||||
inventory_type: targetRow.inventory_type || 'ZP',
|
||||
order_type: 'INTERCEPT_LOCK',
|
||||
order_no: orderNo,
|
||||
order_id: orderId,
|
||||
operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''),
|
||||
operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '',
|
||||
remark: '拦截确认(无拣货行补建拦截锁定)',
|
||||
}, { transaction });
|
||||
|
||||
interceptCompensateSummaryMap.set(
|
||||
Number(targetRow.id),
|
||||
(interceptCompensateSummaryMap.get(Number(targetRow.id)) || 0) + qty
|
||||
);
|
||||
} else {
|
||||
// 该商品没有任何库存行:按缺行补建(quantity=q、intercept=q、available=0)
|
||||
const created = await storageModel.create({
|
||||
warehouse_id: warehouseId,
|
||||
store_id: orderStoreId,
|
||||
space_id: fallbackDefaultSpaceId,
|
||||
stock_id: stockId,
|
||||
batch_no: String(orderNo).slice(0, 100),
|
||||
inventory_type: 'ZP',
|
||||
quantity: qty,
|
||||
locked_quantity: 0,
|
||||
intercept_locked_quantity: qty,
|
||||
available_quantity: 0,
|
||||
inbound_time: now,
|
||||
inbound_order_no: String(orderNo).slice(0, 100),
|
||||
is_enabled: 1,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
}, { transaction });
|
||||
const plainCreated = created && typeof created.get === 'function'
|
||||
? created.get({ plain: true })
|
||||
: created;
|
||||
|
||||
await ctx.model.StorageTransaction.create({
|
||||
transaction_type: 'LOCK',
|
||||
warehouse_id: warehouseId,
|
||||
store_id: plainCreated.store_id,
|
||||
stock_id: stockId,
|
||||
storage_id: plainCreated.id,
|
||||
space_id: plainCreated.space_id,
|
||||
quantity: qty,
|
||||
before_quantity: qty,
|
||||
after_quantity: qty,
|
||||
before_locked_quantity: 0,
|
||||
after_locked_quantity: 0,
|
||||
before_intercept_locked_quantity: 0,
|
||||
after_intercept_locked_quantity: qty,
|
||||
batch_no: plainCreated.batch_no,
|
||||
inventory_type: 'ZP',
|
||||
order_type: 'INTERCEPT_LOCK',
|
||||
order_no: orderNo,
|
||||
order_id: orderId,
|
||||
operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''),
|
||||
operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '',
|
||||
remark: '拦截确认(无拣货行补建库存行并拦截锁定)',
|
||||
}, { transaction });
|
||||
|
||||
interceptCompensateSummaryMap.set(
|
||||
Number(plainCreated.id),
|
||||
(interceptCompensateSummaryMap.get(Number(plainCreated.id)) || 0) + qty
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 拦截模式无拣货行补建完成', {
|
||||
interceptNoPickingOrderIds,
|
||||
interceptCompensateSummary: Array.from(interceptCompensateSummaryMap.entries()),
|
||||
});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// ── 普通取消模式:解除锁定/返还实物,回到可用数量(既有行为不变) ──
|
||||
// pending 记录:解除锁定,实物库存不动
|
||||
@ -2848,6 +3048,8 @@ class OrderStorageAllocationService extends MainService {
|
||||
picking_count: cancelPickingIds.length,
|
||||
storage_unlock_summary: storageUnlockSummary,
|
||||
storage_return_summary: storageReturnSummary,
|
||||
intercept_compensate_summary: Array.from(interceptCompensateSummaryMap.entries())
|
||||
.map(([ storageId, quantity ]) => ({ storage_id: storageId, intercept_locked_quantity: quantity })),
|
||||
stock_unlock_summary: [],
|
||||
};
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user