feat(order): 取消订单事务原子化,储位分配支持允许受限库位

This commit is contained in:
liufumingren 2026-08-27 23:41:54 +08:00
parent 33a92bdc8d
commit 4ddcbe60a4
3 changed files with 315 additions and 146 deletions

View File

@ -2388,6 +2388,10 @@ class PendingOrderService extends OrderBaseService {
/** /**
* 将待处理订单取消,并关闭到已取消状态。 * 将待处理订单取消,并关闭到已取消状态。
* 仅允许取消当前仓库内处于待审核、待处理、待处理异常语义的订单。 * 仅允许取消当前仓库内处于待审核、待处理、待处理异常语义的订单。
*
* 取消、波次清理、储位释放与创建锁释放在同一事务内完成:
* 任一环节失败整体回滚,避免"已取消但库存锁定未释放"的中间态。
*
* @param {Object} data 请求体。 * @param {Object} data 请求体。
* @param {number[]} data.ids 订单ID 数组。 * @param {number[]} data.ids 订单ID 数组。
* @return {Promise<Object>} 更新后的订单信息。 * @return {Promise<Object>} 更新后的订单信息。
@ -2403,91 +2407,106 @@ class PendingOrderService extends OrderBaseService {
const model = await this.getOrderModel('order', warehouseId); const model = await this.getOrderModel('order', warehouseId);
const where = this.buildOrderWhere(orderIds, warehouseId); const where = this.buildOrderWhere(orderIds, warehouseId);
const existingOrders = await model.findAll({ const transaction = await this.ctx.model.transaction();
where, let normalizedOrders = [];
raw: true, let firstOrder = null;
}); let affectedRows = 0;
if (!Array.isArray(existingOrders) || existingOrders.length === 0) { try {
return this.success('取消成功', { // 锁定订单行后读取最新状态,与储位分配事务串行化,避免读到过期快照
updated_count: 0, const existingOrders = await model.findAll({
ids: [], where,
transaction,
lock: transaction.LOCK.UPDATE,
raw: true,
}); });
}
if (existingOrders.length !== orderIds.length) { if (!Array.isArray(existingOrders) || existingOrders.length === 0) {
throw new Error('订单不存在或不属于当前仓库'); await transaction.rollback();
} return this.success('取消成功', {
updated_count: 0,
ids: [],
});
}
const nonCancelableOrder = existingOrders.find(order => !this.isCancelablePendingOrder(order)); if (existingOrders.length !== orderIds.length) {
if (nonCancelableOrder) { throw new Error('订单不存在或不属于当前仓库');
throw new Error('订单当前状态不允许取消'); }
}
// 已同步订单不允许取消,转为拦截处理 const nonCancelableOrder = existingOrders.find(order => !this.isCancelablePendingOrder(order));
const syncedOrders = existingOrders.filter( if (nonCancelableOrder) {
order => String(order.sync_status || '').trim() === 'fin' throw new Error('订单当前状态不允许取消');
); }
if (syncedOrders.length > 0) {
const syncedOrderIds = syncedOrders.map(order => Number(order.id)).filter( // 已同步订单不允许取消,转为拦截处理
id => Number.isInteger(id) && id > 0 const syncedOrders = existingOrders.filter(
order => String(order.sync_status || '').trim() === 'fin'
); );
if (syncedOrderIds.length > 0) { if (syncedOrders.length > 0) {
const syncNow = new Date(); const syncedOrderIds = syncedOrders.map(order => Number(order.id)).filter(
await model.update( id => Number.isInteger(id) && id > 0
{
intercept_status: 'requested',
updated_at: syncNow,
},
{
where: {
id: syncedOrderIds,
},
}
); );
// 同步更新运单表拦截标记 if (syncedOrderIds.length > 0) {
try { const syncNow = new Date();
const { Op: cancelOp } = this.app.Sequelize; await model.update(
await this.ctx.model.OrderExpress.update( {
{ is_intercept: 'Y' }, intercept_status: 'requested',
{ where: { order_id: { [cancelOp.in]: syncedOrderIds }, warehouse_id: warehouseId } } updated_at: syncNow,
},
{
where: {
id: syncedOrderIds,
},
transaction,
}
); );
} catch (expressErr) { // 同步更新运单表拦截标记
this.ctx.logger.warn( try {
`[PendingOrderService.cancelOrder] 更新运单拦截标记失败, count=${syncedOrderIds.length}, error=${expressErr.message}` const { Op: cancelOp } = this.app.Sequelize;
await this.ctx.model.OrderExpress.update(
{ is_intercept: 'Y' },
{ where: { order_id: { [cancelOp.in]: syncedOrderIds }, warehouse_id: warehouseId }, transaction }
);
} catch (expressErr) {
this.ctx.logger.warn(
`[PendingOrderService.cancelOrder] 更新运单拦截标记失败, count=${syncedOrderIds.length}, error=${expressErr.message}`
);
}
this.ctx.logger.info(
`[PendingOrderService.cancelOrder] 订单已同步,不可取消,已转为拦截处理,订单ID: ${syncedOrderIds.join(',')}`
); );
} }
this.ctx.logger.info(
`[PendingOrderService.cancelOrder] 订单已同步,不可取消,已转为拦截处理,订单ID: ${syncedOrderIds.join(',')}` // 拦截标记已写入,提交后抛出业务错误(调用方按"已转拦截"处理)
); await transaction.commit();
const syncedCodes = syncedOrders
.map(order => String(order.delivery_order_code || order.pre_delivery_order_code || order.id || '').trim())
.filter(Boolean)
.join(', ');
throw new Error(`订单已同步,不可取消,已转为拦截处理:${syncedCodes}`);
} }
const syncedCodes = syncedOrders
.map(order => String(order.delivery_order_code || order.pre_delivery_order_code || order.id || '').trim())
.filter(Boolean)
.join(', ');
throw new Error(`订单已同步,不可取消,已转为拦截处理:${syncedCodes}`);
}
const now = new Date(); const now = new Date();
const updateValues = { const updateValues = {
status: PENDING_CANCEL_STATUS, status: PENDING_CANCEL_STATUS,
step: PENDING_CANCEL_STEP, step: PENDING_CANCEL_STEP,
outbound_status: PENDING_OUTBOUND_STATUS, outbound_status: PENDING_OUTBOUND_STATUS,
updated_at: now, updated_at: now,
}; };
const updateResult = await model.update(updateValues, { const updateResult = await model.update(updateValues, {
where, where,
}); transaction,
});
const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0); affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0);
if (affectedRows <= 0) { if (affectedRows <= 0) {
throw new Error('订单不存在或不属于当前仓库'); throw new Error('订单不存在或不属于当前仓库');
} }
const ordersWithWave = existingOrders.filter(order => Number(order.wave_id) > 0); const ordersWithWave = existingOrders.filter(order => Number(order.wave_id) > 0);
if (ordersWithWave.length > 0) { if (ordersWithWave.length > 0) {
try {
const { Op } = this.app.Sequelize; const { Op } = this.app.Sequelize;
const WaveBatch = this.ctx.model.WaveBatch; const WaveBatch = this.ctx.model.WaveBatch;
@ -2509,13 +2528,14 @@ class PendingOrderService extends OrderBaseService {
}, },
warehouse_id: warehouseId, warehouse_id: warehouseId,
}, },
transaction,
} }
); );
await this.ctx.service.systemMethods.order.wave.deleteOrderWaveIndexByOrderIds({ await this.ctx.service.systemMethods.order.wave.deleteOrderWaveIndexByOrderIds({
warehouseId, warehouseId,
orderIds: waveOrderIds, orderIds: waveOrderIds,
transaction: undefined, transaction,
}); });
// 重建受影响波次的订单索引(wave_index 重新排序) // 重建受影响波次的订单索引(wave_index 重新排序)
@ -2527,6 +2547,7 @@ class PendingOrderService extends OrderBaseService {
warehouseId, warehouseId,
waveIds: affectedWaveIds, waveIds: affectedWaveIds,
orderModel: model, orderModel: model,
transaction,
}); });
} }
} }
@ -2551,6 +2572,7 @@ class PendingOrderService extends OrderBaseService {
[Op.gt]: 0, [Op.gt]: 0,
}, },
}, },
transaction,
}); });
const wave = await WaveBatch.findOne({ const wave = await WaveBatch.findOne({
@ -2560,6 +2582,7 @@ class PendingOrderService extends OrderBaseService {
}, },
attributes: [ 'wave_id', 'total_orders', 'wave_status' ], attributes: [ 'wave_id', 'total_orders', 'wave_status' ],
raw: true, raw: true,
transaction,
}); });
if (!wave) { if (!wave) {
@ -2580,6 +2603,7 @@ class PendingOrderService extends OrderBaseService {
wave_id: waveId, wave_id: waveId,
warehouse_id: warehouseId, warehouse_id: warehouseId,
}, },
transaction,
} }
); );
} else { } else {
@ -2592,61 +2616,66 @@ class PendingOrderService extends OrderBaseService {
wave_id: waveId, wave_id: waveId,
warehouse_id: warehouseId, warehouse_id: warehouseId,
}, },
transaction,
} }
); );
} }
} }
} }
} catch (waveErr) {
this.ctx.logger.warn('[PendingOrderService.cancelOrder] 清理波次关联失败,不影响订单取消', waveErr);
} }
}
// 释放储位分配和库存锁定 // 释放储位分配和库存锁定(复用同一事务,取消与释放原子生效)
try {
await this.service.systems.orderStorageAllocation.cancelAllocateStorage({ await this.service.systems.orderStorageAllocation.cancelAllocateStorage({
order_ids: orderIds, order_ids: orderIds,
transaction,
}); });
} catch (allocErr) {
this.ctx.logger.warn('[PendingOrderService.cancelOrder] 释放储位分配失败,不影响订单取消', allocErr);
}
// 释放创建锁(lockItemStorages 加的锁,不含 picking 锁) // 释放创建锁(lockItemStorages 加的锁,不含 picking 锁)
try {
await this.releaseCreationLockForCancel({ await this.releaseCreationLockForCancel({
orderIds, orderIds,
warehouseId, warehouseId,
transaction,
}); });
} catch (releaseErr) {
this.ctx.logger.warn('[PendingOrderService.cancelOrder] 释放创建锁失败,不影响订单取消', releaseErr); const updatedOrders = await model.findAll({
where,
transaction,
raw: true,
});
if (!Array.isArray(updatedOrders) || updatedOrders.length === 0) {
throw new Error('订单不存在或不属于当前仓库');
}
const orderMap = new Map(updatedOrders.map(order => [ Number(order.id), order ]));
normalizedOrders = orderIds
.map(orderId => orderMap.get(orderId))
.filter(Boolean)
.map(order => ({
id: order.id,
status: order.status,
step: Number(order.step ?? PENDING_CANCEL_STEP),
updated_at: order.updated_at,
}));
if (normalizedOrders.length === 0) {
throw new Error('订单不存在或不属于当前仓库');
}
firstOrder = normalizedOrders[0];
await transaction.commit();
} catch (error) {
if (!transaction.finished) {
try {
await transaction.rollback();
} catch (rollbackError) {
this.ctx.logger.error('[PendingOrderService.cancelOrder] 事务回滚失败', rollbackError);
}
}
throw error;
} }
const updatedOrders = await model.findAll({
where,
raw: true,
});
if (!Array.isArray(updatedOrders) || updatedOrders.length === 0) {
throw new Error('订单不存在或不属于当前仓库');
}
const orderMap = new Map(updatedOrders.map(order => [ Number(order.id), order ]));
const normalizedOrders = orderIds
.map(orderId => orderMap.get(orderId))
.filter(Boolean)
.map(order => ({
id: order.id,
status: order.status,
step: Number(order.step ?? PENDING_CANCEL_STEP),
updated_at: order.updated_at,
}));
if (normalizedOrders.length === 0) {
throw new Error('订单不存在或不属于当前仓库');
}
const firstOrder = normalizedOrders[0];
// 写入取消操作日志(不影响主流程) // 写入取消操作日志(不影响主流程)
try { try {
const operator = this.getOrderLogOperator(); const operator = this.getOrderLogOperator();
@ -6409,9 +6438,10 @@ ${numbered}`;
* @param {Object} options - 释放参数。 * @param {Object} options - 释放参数。
* @param {number[]} options.orderIds - 订单ID 数组。 * @param {number[]} options.orderIds - 订单ID 数组。
* @param {number} options.warehouseId - 仓库ID。 * @param {number} options.warehouseId - 仓库ID。
* @param {Object} [options.transaction] - 可选外部事务;传入时复用,由调用方负责提交与回滚。
* @return {Promise<void>} * @return {Promise<void>}
*/ */
async releaseCreationLockForCancel({ orderIds, warehouseId } = {}) { async releaseCreationLockForCancel({ orderIds, warehouseId, transaction: externalTransaction } = {}) {
const { ctx, app } = this; const { ctx, app } = this;
const { Op } = app.Sequelize; const { Op } = app.Sequelize;
@ -6431,7 +6461,7 @@ ${numbered}`;
return; return;
} }
const transaction = await ctx.model.transaction(); const transaction = externalTransaction || await ctx.model.transaction();
try { try {
// 直接从 order_items 读取 plan_qty,按 stock_id 汇总 // 直接从 order_items 读取 plan_qty,按 stock_id 汇总
@ -6446,7 +6476,9 @@ ${numbered}`;
}); });
if (!Array.isArray(orderItems) || orderItems.length === 0) { if (!Array.isArray(orderItems) || orderItems.length === 0) {
await transaction.commit(); if (!externalTransaction) {
await transaction.commit();
}
return; return;
} }
@ -6461,7 +6493,9 @@ ${numbered}`;
} }
if (stockReleaseMap.size === 0) { if (stockReleaseMap.size === 0) {
await transaction.commit(); if (!externalTransaction) {
await transaction.commit();
}
return; return;
} }
@ -6482,12 +6516,16 @@ ${numbered}`;
} }
} }
await transaction.commit(); if (!externalTransaction) {
await transaction.commit();
}
} catch (error) { } catch (error) {
try { if (!externalTransaction) {
await transaction.rollback(); try {
} catch (rollbackError) { await transaction.rollback();
ctx.logger.error('[PendingOrderService.releaseCreationLockForCancel] 回滚失败', rollbackError); } catch (rollbackError) {
ctx.logger.error('[PendingOrderService.releaseCreationLockForCancel] 回滚失败', rollbackError);
}
} }
throw error; throw error;
} }

View File

@ -832,10 +832,12 @@ class OrderStorageAllocationService extends MainService {
as: 'locationType', as: 'locationType',
required: true, required: true,
attributes: [ 'id', 'type_code', 'type_name', 'allow_allocation', 'is_active' ], attributes: [ 'id', 'type_code', 'type_name', 'allow_allocation', 'is_active' ],
where: { ...(allowStorageLocation ? {} : {
allow_allocation: 1, where: {
is_active: 1, allow_allocation: 1,
}, is_active: 1,
},
}),
}, },
], ],
}, },
@ -851,6 +853,7 @@ class OrderStorageAllocationService extends MainService {
stockIdCount: stockIds.length, stockIdCount: stockIds.length,
stockIdSample: stockIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), stockIdSample: stockIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT),
storageRowCount: Array.isArray(storageRows) ? storageRows.length : 0, storageRowCount: Array.isArray(storageRows) ? storageRows.length : 0,
allowStorageLocation,
}); });
const storageRowsByStockId = new Map(); const storageRowsByStockId = new Map();
@ -1057,15 +1060,19 @@ class OrderStorageAllocationService extends MainService {
}); });
if (candidateStorageRows.length === 0) { if (candidateStorageRows.length === 0) {
shortageDiagnostics = await diagnoseStorageTypeRestriction({ shortageDiagnostics = allowStorageLocation
ctx, ? null
Op, : await diagnoseStorageTypeRestriction({
warehouseId, ctx,
stockId, Op,
transaction, warehouseId,
cache: shortageReasonCache, stockId,
}); transaction,
shortageReason = String(shortageDiagnostics.reason || '').trim(); cache: shortageReasonCache,
});
shortageReason = shortageDiagnostics
? String(shortageDiagnostics.reason || '').trim()
: '';
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 无候选库位,标记缺货原因', { writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 无候选库位,标记缺货原因', {
orderId, orderId,
@ -2143,13 +2150,16 @@ class OrderStorageAllocationService extends MainService {
}; };
} }
const transaction = await ctx.model.transaction(); // 支持外部事务:由调用方(如取消订单流程)传入时复用,保证"取消+释放"原子生效
const externalTransaction = data && data.transaction ? data.transaction : null;
const transaction = externalTransaction || await ctx.model.transaction();
const { Op } = app.Sequelize; const { Op } = app.Sequelize;
const now = new Date(); const now = new Date();
writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 事务已创建', { writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 事务已创建', {
warehouseId, warehouseId,
orderIds, orderIds,
hasExternalTransaction: Boolean(externalTransaction),
}); });
try { try {
@ -2228,7 +2238,9 @@ class OrderStorageAllocationService extends MainService {
}); });
if (eligibleOrderIds.length === 0) { if (eligibleOrderIds.length === 0) {
await transaction.commit(); if (!externalTransaction) {
await transaction.commit();
}
return { return {
code: 200, code: 200,
message: '没有需要取消分配的订单', message: '没有需要取消分配的订单',
@ -2307,7 +2319,9 @@ class OrderStorageAllocationService extends MainService {
} }
if (cancellableOrderIds.length === 0) { if (cancellableOrderIds.length === 0) {
await transaction.commit(); if (!externalTransaction) {
await transaction.commit();
}
return { return {
code: 200, code: 200,
message: '没有需要取消分配的订单', message: '没有需要取消分配的订单',
@ -2514,7 +2528,9 @@ class OrderStorageAllocationService extends MainService {
stock_unlock_summary: [], stock_unlock_summary: [],
}; };
await transaction.commit(); if (!externalTransaction) {
await transaction.commit();
}
writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 事务提交完成', { writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 事务提交完成', {
warehouseId, warehouseId,
@ -2529,17 +2545,19 @@ class OrderStorageAllocationService extends MainService {
data: responseData, data: responseData,
}; };
} catch (error) { } catch (error) {
writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 发生异常,准备回滚事务', { if (!externalTransaction) {
warehouseId, writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 发生异常,准备回滚事务', {
orderIds, warehouseId,
error, orderIds,
}); error,
await transaction.rollback(); });
writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 事务回滚完成', { await transaction.rollback();
warehouseId, writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 事务回滚完成', {
orderIds, warehouseId,
error, orderIds,
}); error,
});
}
throw error; throw error;
} }
} }

View File

@ -265,6 +265,7 @@ function createHarness(options = {}) {
Storage: { Storage: {
async findAll(options = {}) { async findAll(options = {}) {
captures.storageFindAllWhere = options.where; captures.storageFindAllWhere = options.where;
captures.storageFindAllInclude = options.include;
return storageRows.filter(row => matchesWhere(row, options.where)).map(row => ({ ...row })); return storageRows.filter(row => matchesWhere(row, options.where)).map(row => ({ ...row }));
}, },
}, },
@ -540,6 +541,118 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
assert.equal(orders[1].storage_status, 'fin'); assert.equal(orders[1].storage_status, 'fin');
}); });
it('should ignore location type restriction when allow_storage_location is true', async () => {
const { service, captures } = createHarness({
orders: [
{ id: 901, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 },
],
orderItems: [
{ id: 9011, order_id: 901, stock_id: 9011, plan_qty: 1, order_line_no: '1' },
],
stockRows: [
{ id: 9011, item_code: 'SKU-9011', item_name: '测试商品9011', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 },
],
storageRows: [
{
id: 90101,
warehouse_id: 100000,
stock_id: 9011,
is_enabled: 1,
delete_at: null,
available_quantity: 1,
quantity: 1,
locked_quantity: 0,
production_date: null,
inbound_time: '2026-04-15 08:00:00',
space_id: 90501,
space: {
id: 90501,
space_code: 'ST-901',
custom_name: '受限存储位',
is_preferred_pick: false,
locationType: {
id: 9,
allow_allocation: 0,
is_active: 0,
},
},
},
],
});
const result = await service.allocateStorage({
allow_storage_location: true,
order_ids: [ 901 ],
});
assert.equal(result.code, 200);
assert.equal(result.data.allocated_order_ids.length, 1);
const locationTypeInclude = captures.storageFindAllInclude
&& captures.storageFindAllInclude[0]
&& captures.storageFindAllInclude[0].include
&& captures.storageFindAllInclude[0].include[0];
assert.ok(locationTypeInclude, 'locationType include 应存在');
assert.equal(Object.prototype.hasOwnProperty.call(locationTypeInclude, 'where'), false);
});
it('should keep location type restriction when allow_storage_location is false', async () => {
const { service, captures } = createHarness({
orders: [
{ id: 902, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 },
],
orderItems: [
{ id: 9021, order_id: 902, stock_id: 9021, plan_qty: 1, order_line_no: '1' },
],
stockRows: [
{ id: 9021, item_code: 'SKU-9021', item_name: '测试商品9021', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 },
],
storageRows: [
{
id: 90201,
warehouse_id: 100000,
stock_id: 9021,
is_enabled: 1,
delete_at: null,
available_quantity: 1,
quantity: 1,
locked_quantity: 0,
production_date: null,
inbound_time: '2026-04-15 08:00:00',
space_id: 90502,
space: {
id: 90502,
space_code: 'ST-902',
custom_name: '存储位902',
is_preferred_pick: false,
locationType: {
id: 1,
allow_allocation: 1,
is_active: 1,
},
},
},
],
});
const result = await service.allocateStorage({
allow_storage_location: false,
order_ids: [ 902 ],
});
assert.equal(result.code, 200);
const locationTypeInclude = captures.storageFindAllInclude
&& captures.storageFindAllInclude[0]
&& captures.storageFindAllInclude[0].include
&& captures.storageFindAllInclude[0].include[0];
assert.ok(locationTypeInclude, 'locationType include 应存在');
assert.deepEqual(locationTypeInclude.where, {
allow_allocation: 1,
is_active: 1,
});
});
it('should skip cancelled orders when allocating storage', async () => { it('should skip cancelled orders when allocating storage', async () => {
const { service, captures, orders } = createHarness({ const { service, captures, orders } = createHarness({
orders: [ orders: [