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

View File

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

View File

@ -265,6 +265,7 @@ function createHarness(options = {}) {
Storage: {
async findAll(options = {}) {
captures.storageFindAllWhere = options.where;
captures.storageFindAllInclude = options.include;
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');
});
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 () => {
const { service, captures, orders } = createHarness({
orders: [