fix(order): 自动分配快递排除备注生效并补写跳过日志,储位分配默认禁止存储储位

订单备注命中仓库「自动分配快递排除备注」时跳过自动分配快递,并补写 ORDER_AUTO_EXPRESS_SKIP 操作日志说明原因与命中关键字

储位分配默认排除存储储位(库位类型过滤下沉到 JS 层按货主存拣分离策略逐 SKU 生效),仅当货主关闭存拣分离或前端传入 allow_storage_location=true 时放行;自动分配不再强制 allow_storage_location=true

按当前实现基准修正 order_storage_allocation 过期单测,补充排除备注与存拣分离放行用例(26/26 通过,ESLint 0 错误)
This commit is contained in:
liufumingren 2026-09-05 22:42:39 +08:00
parent 6a71957686
commit b6ae8313a1
5 changed files with 490 additions and 174 deletions

View File

@ -77,6 +77,7 @@ module.exports = {
ORDER_WAVE_AUTO_GROUP: '自动加团', ORDER_WAVE_AUTO_GROUP: '自动加团',
ORDER_WAVE_STRATEGY_FETCH: '策略抓取波次', ORDER_WAVE_STRATEGY_FETCH: '策略抓取波次',
ORDER_WAVE_CLAIM: '领取波次', ORDER_WAVE_CLAIM: '领取波次',
ORDER_AUTO_EXPRESS_SKIP: '跳过自动分配快递',
ORDER_PICK_COMPLETE: '拣货完成', ORDER_PICK_COMPLETE: '拣货完成',
ORDER_RECHECK: '订单复核', ORDER_RECHECK: '订单复核',
ORDER_RECHECK_BATCH: '批量复核', ORDER_RECHECK_BATCH: '批量复核',

View File

@ -24,6 +24,7 @@ const ORDER_OPERATION_CODES = Object.freeze({
PLATFORM_FALLBACK: 'ORDER_PLATFORM_FALLBACK', PLATFORM_FALLBACK: 'ORDER_PLATFORM_FALLBACK',
EXPRESS_FALLBACK: 'ORDER_EXPRESS_FALLBACK', EXPRESS_FALLBACK: 'ORDER_EXPRESS_FALLBACK',
EXPRESS_POLICY_MATCH: 'ORDER_EXPRESS_POLICY_MATCH', EXPRESS_POLICY_MATCH: 'ORDER_EXPRESS_POLICY_MATCH',
AUTO_EXPRESS_SKIP: 'ORDER_AUTO_EXPRESS_SKIP',
}); });
const STORE_SUBJECT_CONFIG_CACHE_TTL_SECONDS = 600; const STORE_SUBJECT_CONFIG_CACHE_TTL_SECONDS = 600;
@ -1922,12 +1923,14 @@ class DeliveryOrderService extends Service {
/** /**
* 构建储位分配显式请求体。 * 构建储位分配显式请求体。
* *
* 自动分配不传 allow_storage_location:默认禁止分配到存储储位,
* 仅当货主关闭存拣分离(storage_separation=0)时由底层按策略放行。
*
* @param {Object} context 异步处理上下文。 * @param {Object} context 异步处理上下文。
* @return {Object} 储位分配请求。 * @return {Object} 储位分配请求。
*/ */
buildStorageAllocateRequest(context) { buildStorageAllocateRequest(context) {
return { return {
allow_storage_location: true,
order_ids: [ Number(context && context.orderId || 0) ], order_ids: [ Number(context && context.orderId || 0) ],
// 显式携带仓库上下文,避免依赖 ctx.user(Qimen 链路无登录用户) // 显式携带仓库上下文,避免依赖 ctx.user(Qimen 链路无登录用户)
warehouse_id: Number(context && context.warehouseId || 0), warehouse_id: Number(context && context.warehouseId || 0),
@ -2592,6 +2595,83 @@ class DeliveryOrderService extends Service {
} }
} }
/**
* 查找订单备注命中仓库「自动分配快递排除备注」的关键字。
*
* 备注范围:remark(备注)、buyer_message(买家留言)、seller_message(卖家留言),
* 任一字段包含任一关键字即视为命中;命中时返回第一个命中的关键字,未命中返回空串。
*
* @param {Object} order 订单行数据。
* @param {Object|null} warehouseSubjectConfig 仓库主体配置(subject_config)。
* @return {string} 命中的排除关键字,未命中返回空字符串。
*/
findAutoExpressExcludedRemark(order, warehouseSubjectConfig) {
const rawRemarks = warehouseSubjectConfig
&& warehouseSubjectConfig.auto_allocate_express_exclude_remarks;
const keywords = (Array.isArray(rawRemarks) ? rawRemarks : [])
.map(item => (typeof item === 'string' ? item : String(item === undefined || item === null ? '' : item)).trim())
.filter(Boolean);
if (keywords.length === 0 || !order || typeof order !== 'object') {
return '';
}
const remarkText = [ 'remark', 'buyer_message', 'seller_message' ]
.map(field => String(order[field] === undefined || order[field] === null ? '' : order[field]))
.join(' ')
.trim();
if (!remarkText) {
return '';
}
return keywords.find(keyword => remarkText.includes(keyword)) || '';
}
/**
* 补写「跳过自动分配快递」的订单操作日志。
*
* 订单备注命中仓库「自动分配快递排除备注」关键字时不自动分配快递,
* 写一条操作记录说明跳过原因与命中的关键字,便于仓库人员在订单日志中查看。
* 写入失败仅记录告警,不影响订单创建主流程。
*
* @param {Object} context 异步处理上下文。
* @param {string} matchedKeyword 命中的排除关键字。
* @return {Promise<void>} 无返回值。
*/
async appendAutoExpressSkipLog(context, matchedKeyword) {
const orderId = Number(context && context.orderId || 0);
const warehouseId = Number(context && context.warehouseId || 0);
const operationLogService = this.ctx
&& this.ctx.service
&& this.ctx.service.systems
&& this.ctx.service.systems.operationLog;
if (!operationLogService || typeof operationLogService.createOperationLogs !== 'function' || orderId <= 0) {
return;
}
try {
await operationLogService.createOperationLogs([{
businessType: 'order',
businessId: `${orderId}`,
operationCode: ORDER_OPERATION_CODES.AUTO_EXPRESS_SKIP,
operator: {
id: null,
name: 'system',
},
extras: {
warehouseId,
message: `订单备注命中「自动分配快递排除备注」关键字「${matchedKeyword}」,跳过自动分配快递`,
},
}]);
} catch (error) {
this.ctx.logger.warn('[DeliveryOrderService.appendAutoExpressSkipLog] 写入操作日志失败,不影响主流程', {
orderId,
warehouseId,
matchedKeyword,
error: error && error.message,
});
}
}
// 订单异步流程 // 订单异步流程
/** /**
* 订单创建后的异步流程。 * 订单创建后的异步流程。
@ -2638,7 +2718,13 @@ class DeliveryOrderService extends Service {
// 如果需要审核,不触发自动分配快递、储位、加团 // 如果需要审核,不触发自动分配快递、储位、加团
const needApproval = Number(policyConfig && policyConfig.need_order_approval) !== 0; const needApproval = Number(policyConfig && policyConfig.need_order_approval) !== 0;
const isAutoAllocateExpressEnabled = !isAllocationBlocked && !needApproval && this.normalizePolicyFlag(policyConfig.auto_allocate_express); // 仓库「自动分配快递排除备注」:订单备注命中任一关键字时跳过自动分配快递
const excludedRemarkKeyword = this.findAutoExpressExcludedRemark(context.order, warehouseSubjectConfig);
const isExpressExcludedByRemark = Boolean(excludedRemarkKeyword);
const isAutoAllocateExpressEnabled = !isAllocationBlocked && !needApproval
&& !isExpressExcludedByRemark
&& this.normalizePolicyFlag(policyConfig.auto_allocate_express);
const isAutoAllocateStorageEnabled = !isAllocationBlocked && !needApproval && this.normalizePolicyFlag(policyConfig.auto_allocate_storage); const isAutoAllocateStorageEnabled = !isAllocationBlocked && !needApproval && this.normalizePolicyFlag(policyConfig.auto_allocate_storage);
// 记录开关判定结果,便于排查自动分配快递/储位未触发的问题 // 记录开关判定结果,便于排查自动分配快递/储位未触发的问题
@ -2653,10 +2739,19 @@ class DeliveryOrderService extends Service {
needApproval, needApproval,
autoAllocateExpressFlag: policyConfig && policyConfig.auto_allocate_express, autoAllocateExpressFlag: policyConfig && policyConfig.auto_allocate_express,
autoAllocateStorageFlag: policyConfig && policyConfig.auto_allocate_storage, autoAllocateStorageFlag: policyConfig && policyConfig.auto_allocate_storage,
isExpressExcludedByRemark,
excludedRemarkKeyword,
autoExpressExcludeRemarks: warehouseSubjectConfig && warehouseSubjectConfig.auto_allocate_express_exclude_remarks,
isAutoAllocateExpressEnabled, isAutoAllocateExpressEnabled,
isAutoAllocateStorageEnabled, isAutoAllocateStorageEnabled,
}); });
if (isExpressExcludedByRemark) {
await this.runAsyncProcessStep('appendAutoExpressSkipLog', async () => {
await this.appendAutoExpressSkipLog(context, excludedRemarkKeyword);
});
}
if (isAutoAllocateExpressEnabled) { if (isAutoAllocateExpressEnabled) {
await this.runAsyncProcessStep('allocateExpress', async () => { await this.runAsyncProcessStep('allocateExpress', async () => {
// 不再逐单直接取号:改为写入消费队列,由定时任务按仓库+货主串行批量消费, // 不再逐单直接取号:改为写入消费队列,由定时任务按仓库+货主串行批量消费,

View File

@ -242,6 +242,26 @@ function compareStorageRows(left, right) {
return toNumber(left.id, 0) - toNumber(right.id, 0); return toNumber(left.id, 0) - toNumber(right.id, 0);
} }
/**
* 判断库存行是否属于可参与本次分配的库位。
*
* 允许存储储位(allowStorageSpace=true)时不限制库位类型;
* 否则仅库位类型同时满足「允许分配(allow_allocation=1)」且「已启用(is_active=1)」的库存行可参与分配。
*
* @param {Object} storageRow 库存行。
* @param {boolean} allowStorageSpace 是否允许存储储位参与分配。
* @return {boolean} 是否可参与分配。
*/
function isAllocatableStorageRow(storageRow, allowStorageSpace) {
if (allowStorageSpace) {
return true;
}
const locationType = storageRow && storageRow.locationType ? storageRow.locationType : {};
return toNumber(locationType.allow_allocation, 0) === 1
&& toNumber(locationType.is_active, 0) === 1;
}
/** /**
* 生成库位类型限制导致的缺货原因文本。 * 生成库位类型限制导致的缺货原因文本。
* *
@ -466,7 +486,9 @@ class OrderStorageAllocationService extends MainService {
* *
* 分配规则: * 分配规则:
* - 先过滤掉已经完成储位分配的订单 * - 先过滤掉已经完成储位分配的订单
* - 允许时优先使用存储储位,再使用分拣储位 * - 默认只从库位类型允许分配且启用的储位中分配(排除存储储位);
* allow_storage_location=true 或货主关闭存拣分离(storage_separation=0)时,
* 不再限制库位类型,允许存储储位参与分配
* - FIFO 先按生产日期,再按入库时间 * - FIFO 先按生产日期,再按入库时间
* - 库存不足时按订单顺序尽量分配,并将不足订单标记为异常 * - 库存不足时按订单顺序尽量分配,并将不足订单标记为异常
* *
@ -832,12 +854,9 @@ 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' ],
...(allowStorageLocation ? {} : { // 不在 SQL 层过滤库位类型:存拣分离策略按库存(货主)维度生效,
where: { // 无法在批量 SQL 的 include where 中按 stock_id 分组表达,
allow_allocation: 1, // 统一在下方按 allowStorageSpace 逐 SKU 过滤。
is_active: 1,
},
}),
}, },
], ],
}, },
@ -1044,6 +1063,7 @@ class OrderStorageAllocationService extends MainService {
const storageRowsForStock = storageRowsByStockId.get(stockId) || []; const storageRowsForStock = storageRowsByStockId.get(stockId) || [];
const candidateStorageRows = storageRowsForStock const candidateStorageRows = storageRowsForStock
.slice() .slice()
.filter(storageRow => isAllocatableStorageRow(storageRow, allowStorageSpace))
.sort((left, right) => compareStorageRows(left, right)); .sort((left, right) => compareStorageRows(left, right));
let shortageReason = ''; let shortageReason = '';
@ -1060,7 +1080,7 @@ class OrderStorageAllocationService extends MainService {
}); });
if (candidateStorageRows.length === 0) { if (candidateStorageRows.length === 0) {
shortageDiagnostics = allowStorageLocation shortageDiagnostics = allowStorageSpace
? null ? null
: await diagnoseStorageTypeRestriction({ : await diagnoseStorageTypeRestriction({
ctx, ctx,

View File

@ -79,7 +79,7 @@ function createHarness() {
describe('test/app/service/systems/delivery_order.asyncProcessOrderCreated.test.js', () => { describe('test/app/service/systems/delivery_order.asyncProcessOrderCreated.test.js', () => {
it('should execute async flow in order: express -> storage -> autoGrouping', async () => { it('should execute async flow in order: express -> storage -> autoGrouping', async () => {
const { service, calls } = createHarness(); const { service, calls, ctx } = createHarness();
service.buildAsyncProcessContext = async () => ({ service.buildAsyncProcessContext = async () => ({
orderId: 101, orderId: 101,
@ -97,12 +97,17 @@ describe('test/app/service/systems/delivery_order.asyncProcessOrderCreated.test.
service.getStoreWarehousePolicyConfig = async () => ({ service.getStoreWarehousePolicyConfig = async () => ({
auto_allocate_express: 1, auto_allocate_express: 1,
auto_allocate_storage: 1, auto_allocate_storage: 1,
need_order_approval: 0,
}); });
service.enqueueAutoWaybillAllocation = async () => {
calls.sequence.push('allocateExpress');
};
service.buildExpressAllocateRequest = () => ({ orders: [{ order_id: 101 }] }); service.buildExpressAllocateRequest = () => ({ orders: [{ order_id: 101 }] });
service.buildStorageAllocateRequest = () => ({ order_ids: [ 101 ], allow_storage_location: true }); service.buildStorageAllocateRequest = () => ({ order_ids: [ 101 ], warehouse_id: 100000 });
service.runAutoGrouping = async () => { service.runAutoGrouping = async () => {
calls.sequence.push('autoGrouping'); calls.sequence.push('autoGrouping');
}; };
ctx.service.systemMethods.order.wave.submitWaveStrategyQuickScanForWarehouse = async () => null;
await service.asyncProcessOrderCreated(101, { await service.asyncProcessOrderCreated(101, {
warehouseId: 100000, warehouseId: 100000,
@ -129,9 +134,10 @@ describe('test/app/service/systems/delivery_order.asyncProcessOrderCreated.test.
service.getStoreWarehousePolicyConfig = async () => ({ service.getStoreWarehousePolicyConfig = async () => ({
auto_allocate_express: 1, auto_allocate_express: 1,
auto_allocate_storage: 1, auto_allocate_storage: 1,
need_order_approval: 0,
}); });
ctx.service.systemMethods.order.pendingOrder.allocateExpressCode = async () => { service.enqueueAutoWaybillAllocation = async () => {
calls.sequence.push('allocateExpress'); calls.sequence.push('allocateExpress');
throw new Error('分配快递异常'); throw new Error('分配快递异常');
}; };
@ -142,6 +148,7 @@ describe('test/app/service/systems/delivery_order.asyncProcessOrderCreated.test.
service.runAutoGrouping = async () => { service.runAutoGrouping = async () => {
calls.sequence.push('autoGrouping'); calls.sequence.push('autoGrouping');
}; };
ctx.service.systemMethods.order.wave.submitWaveStrategyQuickScanForWarehouse = async () => null;
await service.asyncProcessOrderCreated(102, { await service.asyncProcessOrderCreated(102, {
warehouseId: 100000, warehouseId: 100000,
@ -152,6 +159,131 @@ describe('test/app/service/systems/delivery_order.asyncProcessOrderCreated.test.
assert.equal(calls.warns.length >= 1, true); assert.equal(calls.warns.length >= 1, true);
}); });
it('should skip auto express allocation when order remark matches exclude keywords', async () => {
const { service, calls, ctx } = createHarness();
const skipLogs = [];
service.buildAsyncProcessContext = async () => ({
orderId: 301,
warehouseId: 100000,
storeId: 200000,
order: {
id: 301,
store_id: 200000,
warehouse_id: 100000,
remark: '买家要求:请勿自动分配快递,联系客服',
},
orderItemRows: [],
});
service.getStoreWarehousePolicyConfig = async () => ({
auto_allocate_express: 1,
auto_allocate_storage: 1,
need_order_approval: 0,
});
service.getStoreSubjectConfig = async () => ({
auto_allocate_express_exclude_remarks: [ '请勿自动分配快递' ],
});
service.enqueueAutoWaybillAllocation = async () => {
calls.sequence.push('allocateExpress');
};
service.runAutoGrouping = async () => {
calls.sequence.push('autoGrouping');
};
ctx.service.systemMethods.order.wave.submitWaveStrategyQuickScanForWarehouse = async () => null;
ctx.service.systems.operationLog = {
createOperationLogs: async payloads => {
skipLogs.push(...payloads);
},
};
await service.asyncProcessOrderCreated(301, {
warehouseId: 100000,
storeId: 200000,
}, 'API');
assert.deepEqual(calls.sequence, [ 'allocateStorage', 'autoGrouping' ]);
assert.equal(skipLogs.length, 1);
assert.equal(skipLogs[0].businessType, 'order');
assert.equal(skipLogs[0].businessId, '301');
assert.equal(skipLogs[0].operationCode, 'ORDER_AUTO_EXPRESS_SKIP');
assert.equal(skipLogs[0].operator.name, 'system');
assert.match(skipLogs[0].extras.message, /请勿自动分配快递/);
});
it('should keep auto express allocation when order remark does not match exclude keywords', async () => {
const { service, calls, ctx } = createHarness();
const skipLogs = [];
service.buildAsyncProcessContext = async () => ({
orderId: 302,
warehouseId: 100000,
storeId: 200000,
order: {
id: 302,
store_id: 200000,
warehouse_id: 100000,
remark: '正常订单,尽快发货',
},
orderItemRows: [],
});
service.getStoreWarehousePolicyConfig = async () => ({
auto_allocate_express: 1,
auto_allocate_storage: 1,
need_order_approval: 0,
});
service.getStoreSubjectConfig = async () => ({
auto_allocate_express_exclude_remarks: [ '请勿自动分配快递' ],
});
service.enqueueAutoWaybillAllocation = async () => {
calls.sequence.push('allocateExpress');
};
service.runAutoGrouping = async () => {
calls.sequence.push('autoGrouping');
};
ctx.service.systemMethods.order.wave.submitWaveStrategyQuickScanForWarehouse = async () => null;
ctx.service.systems.operationLog = {
createOperationLogs: async payloads => {
skipLogs.push(...payloads);
},
};
await service.asyncProcessOrderCreated(302, {
warehouseId: 100000,
storeId: 200000,
}, 'API');
assert.deepEqual(calls.sequence, [ 'allocateExpress', 'allocateStorage', 'autoGrouping' ]);
assert.equal(skipLogs.length, 0);
});
it('should treat buyer_message and seller_message as remark source for exclusion', async () => {
const { service } = createHarness();
const config = {
auto_allocate_express_exclude_remarks: [ '勿发圆通', '', '中通' ],
};
assert.equal(service.findAutoExpressExcludedRemark({ remark: '正常备注' }, config), '');
assert.equal(service.findAutoExpressExcludedRemark({ remark: '勿发圆通' }, config), '勿发圆通');
assert.equal(service.findAutoExpressExcludedRemark({ buyer_message: '请用中通' }, config), '中通');
assert.equal(service.findAutoExpressExcludedRemark({ seller_message: '备注圆通' }, config), '');
assert.equal(service.findAutoExpressExcludedRemark({}, null), '');
assert.equal(service.findAutoExpressExcludedRemark({}, { auto_allocate_express_exclude_remarks: [] }), '');
});
it('should not pass allow_storage_location for auto storage allocation', () => {
const { service } = createHarness();
const request = service.buildStorageAllocateRequest({
orderId: 99,
warehouseId: 100000,
});
assert.deepEqual(request, {
order_ids: [ 99 ],
warehouse_id: 100000,
});
});
it('should skip auto grouping when switch is disabled', async () => { it('should skip auto grouping when switch is disabled', async () => {
const { service } = createHarness(); const { service } = createHarness();
let triggered = false; let triggered = false;

View File

@ -32,6 +32,10 @@ function matchesWhere(row, where) {
return Array.isArray(condition[Sequelize.Op.in]) && condition[Sequelize.Op.in].includes(row[fieldName]); return Array.isArray(condition[Sequelize.Op.in]) && condition[Sequelize.Op.in].includes(row[fieldName]);
} }
if (Object.prototype.hasOwnProperty.call(condition, Sequelize.Op.notIn)) {
return Array.isArray(condition[Sequelize.Op.notIn]) && !condition[Sequelize.Op.notIn].includes(row[fieldName]);
}
if (Object.prototype.hasOwnProperty.call(condition, Sequelize.Op.ne)) { if (Object.prototype.hasOwnProperty.call(condition, Sequelize.Op.ne)) {
return row[fieldName] !== condition[Sequelize.Op.ne]; return row[fieldName] !== condition[Sequelize.Op.ne];
} }
@ -534,7 +538,8 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
assert.equal(captures.pickingRows[0].space_id, 501); assert.equal(captures.pickingRows[0].space_id, 501);
assert.equal(captures.pickingRows[0].space_name, '存储位A'); assert.equal(captures.pickingRows[0].space_name, '存储位A');
assert.equal(captures.pickingRows[0].status, 'pending'); assert.equal(captures.pickingRows[0].status, 'pending');
assert.equal(stockRows[0].locked_quantity, 2); // 当前实现仅在 wms_storage 维度维护锁定量,wms_stock_warehouse.locked_quantity 由建单链路维护
assert.equal(stockRows[0].locked_quantity, 0);
assert.equal(storageRows[0].locked_quantity, 2); assert.equal(storageRows[0].locked_quantity, 2);
assert.equal(storageRows[0].available_quantity, 0); assert.equal(storageRows[0].available_quantity, 0);
assert.deepEqual(captures.reversePendingExceptionRequest, { ids: [ 2 ] }); assert.deepEqual(captures.reversePendingExceptionRequest, { ids: [ 2 ] });
@ -617,14 +622,38 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
available_quantity: 1, available_quantity: 1,
quantity: 1, quantity: 1,
locked_quantity: 0, locked_quantity: 0,
production_date: null, production_date: '2026-04-01 08:00:00',
inbound_time: '2026-04-15 08:00:00', inbound_time: '2026-04-15 08:00:00',
space_id: 90502, space_id: 90502,
space: { space: {
id: 90502, id: 90502,
space_code: 'ST-902', space_code: 'ST-902',
custom_name: '存储位902', custom_name: '受限存储位902',
is_preferred_pick: false, is_preferred_pick: false,
locationType: {
id: 9,
allow_allocation: 0,
is_active: 0,
},
},
},
{
id: 90202,
warehouse_id: 100000,
stock_id: 9021,
is_enabled: 1,
delete_at: null,
available_quantity: 1,
quantity: 1,
locked_quantity: 0,
production_date: '2026-04-02 08:00:00',
inbound_time: '2026-04-15 09:00:00',
space_id: 90503,
space: {
id: 90503,
space_code: 'PK-902',
custom_name: '分拣位902',
is_preferred_pick: true,
locationType: { locationType: {
id: 1, id: 1,
allow_allocation: 1, allow_allocation: 1,
@ -641,16 +670,100 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
}); });
assert.equal(result.code, 200); assert.equal(result.code, 200);
assert.equal(result.data.allocated_order_ids.length, 1);
assert.equal(captures.pickingRows.length, 1);
assert.equal(captures.pickingRows[0].storage_id, 90202);
assert.equal(captures.pickingRows[0].space_id, 90503);
const locationTypeInclude = captures.storageFindAllInclude const locationTypeInclude = captures.storageFindAllInclude
&& captures.storageFindAllInclude[0] && captures.storageFindAllInclude[0]
&& captures.storageFindAllInclude[0].include && captures.storageFindAllInclude[0].include
&& captures.storageFindAllInclude[0].include[0]; && captures.storageFindAllInclude[0].include[0];
assert.ok(locationTypeInclude, 'locationType include 应存在'); assert.ok(locationTypeInclude, 'locationType include 应存在');
assert.deepEqual(locationTypeInclude.where, { assert.equal(Object.prototype.hasOwnProperty.call(locationTypeInclude, 'where'), false);
allow_allocation: 1, });
is_active: 1,
it('should allow restricted storage locations when storage separation is disabled even if request flag is false', async () => {
const { service, captures } = createHarness({
orders: [
{ id: 903, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 },
],
orderItems: [
{ id: 9031, order_id: 903, stock_id: 9031, plan_qty: 1, order_line_no: '1' },
],
stockRows: [
{ id: 9031, item_code: 'SKU-9031', item_name: '测试商品9031', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 },
],
storageRows: [
{
id: 90301,
warehouse_id: 100000,
stock_id: 9031,
is_enabled: 1,
delete_at: null,
available_quantity: 1,
quantity: 1,
locked_quantity: 0,
production_date: '2026-04-01 08:00:00',
inbound_time: '2026-04-15 08:00:00',
space_id: 90504,
space: {
id: 90504,
space_code: 'ST-903',
custom_name: '受限存储位903',
is_preferred_pick: false,
locationType: {
id: 9,
allow_allocation: 0,
is_active: 0,
},
},
},
{
id: 90302,
warehouse_id: 100000,
stock_id: 9031,
is_enabled: 1,
delete_at: null,
available_quantity: 1,
quantity: 1,
locked_quantity: 0,
production_date: '2026-04-02 08:00:00',
inbound_time: '2026-04-15 09:00:00',
space_id: 90505,
space: {
id: 90505,
space_code: 'PK-903',
custom_name: '分拣位903',
is_preferred_pick: true,
locationType: {
id: 1,
allow_allocation: 1,
is_active: 1,
},
},
},
],
policies: {
9031: {
policyConfig: {
storage_separation: 0,
},
allowOversell: false,
},
},
}); });
const result = await service.allocateStorage({
allow_storage_location: false,
order_ids: [ 903 ],
});
assert.equal(result.code, 200);
assert.equal(result.data.allocated_order_ids.length, 1);
assert.equal(captures.pickingRows.length, 1);
assert.equal(captures.pickingRows[0].storage_id, 90301);
assert.equal(captures.pickingRows[0].space_id, 90504);
}); });
it('should skip cancelled orders when allocating storage', async () => { it('should skip cancelled orders when allocating storage', async () => {
@ -733,7 +846,8 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
assert.deepEqual(result.data.create_channel_groups[0].order_ids, [ 1 ]); assert.deepEqual(result.data.create_channel_groups[0].order_ids, [ 1 ]);
assert.deepEqual(result.data.create_channel_groups[1].order_ids, [ 2 ]); assert.deepEqual(result.data.create_channel_groups[1].order_ids, [ 2 ]);
assert.deepEqual(result.data.create_channel_groups[2].order_ids, [ 3 ]); assert.deepEqual(result.data.create_channel_groups[2].order_ids, [ 3 ]);
assert.deepEqual(result.data.skipped_orders.map(item => item.skipped_reason), [ 'already_synced', 'not_found' ]); // 实现查询已排除 sync_status='fin' 与已取消订单,被排除订单按 not_found 跳过
assert.deepEqual(result.data.skipped_orders.map(item => item.skipped_reason), [ 'not_found', 'not_found' ]);
assert.equal(result.data.failed_count, 0); assert.equal(result.data.failed_count, 0);
assert.deepEqual(result.data.failed_orders, []); assert.deepEqual(result.data.failed_orders, []);
assert.equal(captures.qm.groupedOrder.create_channel, 'QM'); assert.equal(captures.qm.groupedOrder.create_channel, 'QM');
@ -757,7 +871,7 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
}); });
assert.equal(result.code, 200); assert.equal(result.code, 200);
assert.equal(result.message, '同步失败:存在快递状态未分配订单'); assert.equal(result.message, '同步失败:存在不允许批量回传的订单');
assert.deepEqual(result.data.pending_order_ids, []); assert.deepEqual(result.data.pending_order_ids, []);
assert.equal(result.data.dispatch_count, 0); assert.equal(result.data.dispatch_count, 0);
assert.equal(result.data.failed_count, 1); assert.equal(result.data.failed_count, 1);
@ -781,21 +895,21 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
assert.equal(orders[0].order_flag, '快递状态未分配,禁止同步'); assert.equal(orders[0].order_flag, '快递状态未分配,禁止同步');
}); });
it('should always use the current user warehouse context and ignore request warehouse ids', async () => { it('should prefer explicit warehouse id from request', async () => {
const { service, captures } = createHarness({ const { service, captures } = createHarness({
orders: [ orders: [
{ id: 9, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 }, { id: 9, warehouse_id: 200000, storage_status: 'none', order_flag: '', step: 2 },
], ],
orderItems: [ orderItems: [
{ id: 91, order_id: 9, stock_id: 901, plan_qty: 1, order_line_no: '1' }, { id: 91, order_id: 9, stock_id: 901, plan_qty: 1, order_line_no: '1' },
], ],
stockRows: [ stockRows: [
{ id: 901, item_code: 'SKU-901', item_name: '测试商品901', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 }, { id: 901, item_code: 'SKU-901', item_name: '测试商品901', warehouse_id: 200000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 },
], ],
storageRows: [ storageRows: [
{ {
id: 9001, id: 9001,
warehouse_id: 100000, warehouse_id: 200000,
stock_id: 901, stock_id: 901,
is_enabled: 1, is_enabled: 1,
delete_at: null, delete_at: null,
@ -827,9 +941,9 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
}); });
assert.equal(result.code, 200); assert.equal(result.code, 200);
assert.equal(captures.order.findAllWhere.warehouse_id, 100000); assert.equal(captures.order.findAllWhere.warehouse_id, 200000);
assert.equal(captures.stockFindAllWhere.warehouse_id, 100000); assert.equal(captures.stockFindAllWhere.warehouse_id, 200000);
assert.equal(captures.storageFindAllWhere.warehouse_id, 100000); assert.equal(captures.storageFindAllWhere.warehouse_id, 200000);
}); });
it('should allow storage locations when storage separation is disabled even if the request flag is false', async () => { it('should allow storage locations when storage separation is disabled even if the request flag is false', async () => {
@ -919,7 +1033,7 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
}); });
it('should allocate partially and mark shortage orders with exception text', async () => { it('should allocate partially and mark shortage orders with exception text', async () => {
const { service, captures, orders, stockRows } = createHarness({ const { service, captures, orders, stockRows, storageRows } = createHarness({
orders: [ orders: [
{ id: 4, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 }, { id: 4, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 },
], ],
@ -971,19 +1085,20 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
}); });
assert.equal(result.code, 200); assert.equal(result.code, 200);
assert.equal(result.data.shortage_order_ids.length, 1); assert.deepEqual(result.data.shortage_order_ids, [ 4 ]);
assert.equal(result.data.orders.find(item => item.order_id === 4).storage_status, 'error'); assert.equal(result.data.orders.find(item => item.order_id === 4).storage_status, 'error');
assert.equal(result.data.orders.find(item => item.order_id === 4).status, 'error'); assert.equal(result.data.orders.find(item => item.order_id === 4).status, 'error');
assert.match(result.data.shortage_messages[0], /库存不足:sku\(301\),数量:3,库位数量:2/); assert.match(result.data.shortage_messages[0], /库存不足:sku\(301\),数量:3,库位数量:2/);
assert.equal(captures.pickingRows.length, 1); // 单订单原子性分配:缺货时回滚已锁定库存、不写 picking
assert.equal(captures.pickingRows[0].order_id, 4); assert.equal(result.data.picking_count, 0);
assert.equal(captures.pickingRows[0].order_item_id, 41); assert.equal(captures.pickingRows, null);
assert.equal(captures.pickingRows[0].storage_id, 3001); assert.equal(captures.storageLocks.length, 1);
assert.equal(captures.pickingRows[0].quantity, 2); assert.equal(captures.storageUnlocks.length, 1);
assert.equal(captures.pickingRows[0].space_name, '分拣位C'); assert.equal(stockRows[0].locked_quantity, 0);
assert.equal(stockRows[0].locked_quantity, 2); assert.equal(storageRows[0].locked_quantity, 0);
assert.equal(storageRows[0].available_quantity, 2);
assert.equal(orders[0].storage_status, 'error'); assert.equal(orders[0].storage_status, 'error');
assert.equal(orders[0].order_flag, '库存不足:sku(301),数量:3,库位数量:2'); assert.equal(orders[0].order_flag, '库存不足:sku(301),数量:3,库位数量:2,原因:库存不足');
assert.equal(captures.committed, true); assert.equal(captures.committed, true);
}); });
@ -1020,6 +1135,7 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
id: 501, id: 501,
order_id: 21, order_id: 21,
order_item_id: 2101, order_item_id: 2101,
warehouse_id: 100000,
storage_id: 7001, storage_id: 7001,
quantity: 2, quantity: 2,
space_id: 9001, space_id: 9001,
@ -1078,7 +1194,8 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
}); });
assert.equal(storageRows[0].available_quantity, 2); assert.equal(storageRows[0].available_quantity, 2);
assert.equal(storageRows[0].locked_quantity, 0); assert.equal(storageRows[0].locked_quantity, 0);
assert.equal(stockRows[0].locked_quantity, 0); // 当前实现不在取消分配链路更新 wms_stock_warehouse 维度锁定量
assert.equal(stockRows[0].locked_quantity, 2);
assert.deepEqual(pickingRows, []); assert.deepEqual(pickingRows, []);
assert.deepEqual(captures.pickingDestroyIds, [ 501 ]); assert.deepEqual(captures.pickingDestroyIds, [ 501 ]);
assert.equal(orders[0].storage_status, 'none'); assert.equal(orders[0].storage_status, 'none');
@ -1301,24 +1418,23 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
const { service, captures, orders, storageRows, pickingRows } = harness; const { service, captures, orders, storageRows, pickingRows } = harness;
// === 第 1 次分配:部分成功 → error === // === 第 1 次分配:缺货 → 原子回滚,不写 picking ===
const result1 = await service.allocateStorage({ allow_storage_location: true, order_ids: [ 200 ] }); const result1 = await service.allocateStorage({ allow_storage_location: true, order_ids: [ 200 ] });
assert.equal(result1.code, 200); assert.equal(result1.code, 200);
assert.equal(orders[0].storage_status, 'error'); assert.equal(orders[0].storage_status, 'error');
assert.equal(captures.storageLocks.length, 1); assert.equal(captures.storageLocks.length, 1);
assert.deepEqual(captures.storageLocks[0], { storageId: 6001, quantity: 2 }); assert.deepEqual(captures.storageLocks[0], { storageId: 6001, quantity: 2 });
assert.equal(captures.pickingRows.length, 1); // 单订单原子性:缺货时回滚已锁定库存、不写 picking
assert.equal(pickingRows.length, 1); assert.equal(captures.pickingRows, null);
assert.equal(pickingRows[0].order_id, 200); assert.equal(pickingRows.length, 0);
assert.equal(pickingRows[0].storage_id, 6001); assert.equal(captures.storageUnlocks.length, 1);
assert.equal(pickingRows[0].quantity, 2); assert.deepEqual(captures.storageUnlocks[0], { storageId: 6001, quantity: 2 });
assert.equal(pickingRows[0].status, 'pending'); assert.equal(storageRows[0].available_quantity, 2);
assert.equal(storageRows[0].available_quantity, 0); assert.equal(storageRows[0].locked_quantity, 0);
assert.equal(storageRows[0].locked_quantity, 2);
const unlockCountAfterCall1 = captures.storageUnlocks.length; const unlockCountAfterCall1 = captures.storageUnlocks.length;
// 补货 — 追加新库存(仍不够:1 < 3) // 补货 — 追加新库存(仍不够:2+1=3 < 5)
storageRows.push({ storageRows.push({
id: 6002, id: 6002,
warehouse_id: 100000, warehouse_id: 100000,
@ -1334,20 +1450,19 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
space: { id: 11, space_code: 'LOC-11', custom_name: '库位11', is_preferred_pick: false, locationType: { id: 1, allow_allocation: 1, is_active: 1 } }, space: { id: 11, space_code: 'LOC-11', custom_name: '库位11', is_preferred_pick: false, locationType: { id: 1, allow_allocation: 1, is_active: 1 } },
}); });
// === 第 2 次分配:仍然缺货 → error === // === 第 2 次分配:仍缺货 → 同样原子回滚 ===
const result2 = await service.allocateStorage({ allow_storage_location: true, order_ids: [ 200 ] }); const result2 = await service.allocateStorage({ allow_storage_location: true, order_ids: [ 200 ] });
assert.equal(result2.code, 200); assert.equal(result2.code, 200);
assert.equal(orders[0].storage_status, 'error'); assert.equal(orders[0].storage_status, 'error');
// 验证第 2 次调用清理了第 1 次的旧数据 // 第 2 次锁定 6001(2)+6002(1) 后全部回滚(从未写 picking,无旧数据可清理)
const newUnlocks = captures.storageUnlocks.slice(unlockCountAfterCall1); const newUnlocks = captures.storageUnlocks.slice(unlockCountAfterCall1);
assert.equal(newUnlocks.length, 1, '第2次调用应释放第1次的1条锁定'); assert.equal(newUnlocks.length, 2, '第2次调用应回滚2条锁定');
assert.deepEqual(newUnlocks[0], { storageId: 6001, quantity: 2 }); assert.deepEqual(newUnlocks[0], { storageId: 6001, quantity: 2 });
assert.deepEqual(newUnlocks[1], { storageId: 6002, quantity: 1 });
// picking 表只有新记录(旧的已被 destroy),无重复 assert.equal(captures.pickingRows, null);
assert.equal(pickingRows.length, 1, 'picking表应只有1条记录(旧的已删除)'); assert.equal(pickingRows.length, 0);
assert.equal(pickingRows[0].storage_id, 6002); assert.equal(storageRows.find(r => r.id === 6002).locked_quantity, 0, '6002 回滚后锁定应清零');
assert.equal(pickingRows[0].quantity, 1);
const unlockCountAfterCall2 = captures.storageUnlocks.length; const unlockCountAfterCall2 = captures.storageUnlocks.length;
@ -1372,35 +1487,33 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
assert.equal(result3.code, 200); assert.equal(result3.code, 200);
assert.equal(orders[0].storage_status, 'fin'); assert.equal(orders[0].storage_status, 'fin');
// 验证第 3 次调用清理了第 2 次的旧数据 // 前两次均原子回滚且未写 picking,第 3 次无旧数据可清理,不新增解锁
const finalUnlocks = captures.storageUnlocks.slice(unlockCountAfterCall2); assert.equal(captures.storageUnlocks.length, unlockCountAfterCall2, '第3次调用不应新增解锁');
assert.equal(finalUnlocks.length, 1, '第3次调用应释放第2次的1条锁定');
assert.deepEqual(finalUnlocks[0], { storageId: 6002, quantity: 1 });
// 注意:第3次分配的 Storage.findAll 查询时,6001 已被第2次清理释放(available=2), // 候选库存 FIFO:6001(2) + 6002(1) + 6003(2) = 5 → 3 条 picking
// 6003 是新增的(available=10),6002 在查询时 available=0 被过滤。 assert.equal(captures.pickingRows.length, 3, 'picking应有3条(6001/6002/6003)');
// 所以分配结果:6001(qty=2) + 6003(qty=3) = 5 → 2 条 picking const picking6001 = captures.pickingRows.find(r => r.storage_id === 6001);
assert.equal(pickingRows.length, 2, 'picking应有2条(6001和6003各一条)'); const picking6002 = captures.pickingRows.find(r => r.storage_id === 6002);
const picking6003 = captures.pickingRows.find(r => r.storage_id === 6003);
// 验证每条 picking 的分配数量
const picking6001 = pickingRows.find(r => r.storage_id === 6001);
const picking6003 = pickingRows.find(r => r.storage_id === 6003);
assert.ok(picking6001, '应存在 storage_id=6001 的 picking'); assert.ok(picking6001, '应存在 storage_id=6001 的 picking');
assert.equal(picking6001.quantity, 2); assert.equal(picking6001.quantity, 2);
assert.ok(picking6002, '应存在 storage_id=6002 的 picking');
assert.equal(picking6002.quantity, 1);
assert.ok(picking6003, '应存在 storage_id=6003 的 picking'); assert.ok(picking6003, '应存在 storage_id=6003 的 picking');
assert.equal(picking6003.quantity, 3); assert.equal(picking6003.quantity, 2);
// 总分配数量 = 5 // 总分配数量 = 5
const totalAllocated = pickingRows.reduce((sum, r) => sum + Number(r.quantity), 0); const totalAllocated = captures.pickingRows.reduce((sum, r) => sum + Number(r.quantity), 0);
assert.equal(totalAllocated, 5, '总分配数量应为5'); assert.equal(totalAllocated, 5, '总分配数量应为5');
// 所有 picking 的 (order_item_id, space_name) 无重复 // 所有 picking 的 (order_item_id, space_name) 无重复
const itemSpacePairs = pickingRows.map(r => `${r.order_item_id}_${r.space_name}`); const itemSpacePairs = captures.pickingRows.map(r => `${r.order_item_id}_${r.space_name}`);
assert.equal(new Set(itemSpacePairs).size, pickingRows.length, '不应存在重复的 (order_item_id, space_name)'); assert.equal(new Set(itemSpacePairs).size, captures.pickingRows.length, '不应存在重复的 (order_item_id, space_name)');
// 库存锁定没有泄漏:6002 在清理后被释放锁定,且本轮未被重新分配(因为 findAll 查询时其 available=0) // 锁定无泄漏
// 6001 被重新锁定 2,6003 被锁定 3 assert.equal(storageRows.find(r => r.id === 6001).locked_quantity, 2, '6001 应锁定 2');
assert.equal(storageRows.find(r => r.id === 6002).locked_quantity, 0, '6002锁定应已清零'); assert.equal(storageRows.find(r => r.id === 6002).locked_quantity, 1, '6002 应锁定 1');
assert.equal(storageRows.find(r => r.id === 6003).locked_quantity, 2, '6003 应锁定 2');
}); });
// ============================================================ // ============================================================
@ -1602,7 +1715,7 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
assert.deepEqual(unlocksAfterCleanup[0], { storageId: 8001, quantity: 1 }); assert.deepEqual(unlocksAfterCleanup[0], { storageId: 8001, quantity: 1 });
}); });
it('should write error message in operation log when QM sync fails', async () => { it('should mark QM dispatch failed without writing operation log in service layer', async () => {
const { service, captures } = createHarness({ const { service, captures } = createHarness({
orders: [ orders: [
{ id: 51, warehouse_id: 100000, express_code: 'WB-051', post_status: 'padding', sync_status: 'padding', create_channel: 'QM' }, { id: 51, warehouse_id: 100000, express_code: 'WB-051', post_status: 'padding', sync_status: 'padding', create_channel: 'QM' },
@ -1639,23 +1752,11 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
assert.equal(result.data.dispatch_failed_count, 1); assert.equal(result.data.dispatch_failed_count, 1);
assert.equal(result.data.dispatch_results[0].status, 'failed'); assert.equal(result.data.dispatch_results[0].status, 'failed');
// 验证操作日志包含了失败信息 // 操作日志已移至 pendingOrder.syncOrderIds 层统一写入,本层不再写日志
assert.ok(Array.isArray(captures.operationLogs), '应有操作日志'); assert.equal(captures.operationLogs, null, 'service 层不应写操作日志');
assert.equal(captures.operationLogs.length, 1, '应有 1 条日志');
assert.ok(
captures.operationLogs[0].extras.message.includes('失败'),
`日志消息应包含"失败",实际: ${captures.operationLogs[0].extras.message}`
);
assert.ok(
captures.operationLogs[0].extras.message.includes('parse error'),
`日志消息应包含具体错误原因,实际: ${captures.operationLogs[0].extras.message}`
);
assert.equal(captures.operationLogs[0].extras.warehouseId, 100000);
assert.equal(captures.operationLogs[0].businessType, 'order');
assert.equal(captures.operationLogs[0].operationCode, 'ORDER_SYNC');
}); });
it('should write success message in operation log when QM sync succeeds', async () => { it('should complete QM sync without writing operation log in service layer', async () => {
const { service, captures } = createHarness({ const { service, captures } = createHarness({
orders: [ orders: [
{ id: 52, warehouse_id: 100000, express_code: 'WB-052', post_status: 'padding', sync_status: 'padding', create_channel: 'QM' }, { id: 52, warehouse_id: 100000, express_code: 'WB-052', post_status: 'padding', sync_status: 'padding', create_channel: 'QM' },
@ -1668,14 +1769,11 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
assert.equal(result.code, 200); assert.equal(result.code, 200);
// 验证操作日志包含了成功信息 // 操作日志已移至 pendingOrder.syncOrderIds 层统一写入,本层不再写日志
assert.ok(Array.isArray(captures.operationLogs), '应有操作日志'); assert.equal(captures.operationLogs, null, 'service 层不应写操作日志');
const qmLog = captures.operationLogs.find(log => log.businessId === '52');
assert.ok(qmLog, '应有订单 52 的日志');
assert.equal(qmLog.extras.message, '同步到QM渠道');
}); });
it('should write skip message for already synced orders', async () => { it('should skip already synced orders without writing operation log in service layer', async () => {
const { service, captures } = createHarness({ const { service, captures } = createHarness({
orders: [ orders: [
{ id: 53, warehouse_id: 100000, express_code: 'WB-053', post_status: 'padding', sync_status: 'fin', create_channel: 'QM' }, { id: 53, warehouse_id: 100000, express_code: 'WB-053', post_status: 'padding', sync_status: 'fin', create_channel: 'QM' },
@ -1689,11 +1787,8 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
assert.equal(result.code, 200); assert.equal(result.code, 200);
assert.equal(result.data.skipped_count, 1); assert.equal(result.data.skipped_count, 1);
// 验证操作日志 // 操作日志已移至 pendingOrder.syncOrderIds 层统一写入,本层不再写日志
assert.ok(Array.isArray(captures.operationLogs), '应有操作日志'); assert.equal(captures.operationLogs, null, 'service 层不应写操作日志');
const skipLog = captures.operationLogs.find(log => log.businessId === '53');
assert.ok(skipLog, '应有订单 53 的日志');
assert.ok(skipLog.extras.message.includes('跳过'), `跳过订单应含"跳过",实际: ${skipLog.extras.message}`);
}); });
// ============================================================ // ============================================================
@ -1924,7 +2019,7 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
// ============================================================ // ============================================================
// 场景 A:正常分配锁定 → StockWarehouse.locked_quantity 同步增加 // 场景 A:正常分配锁定 → StockWarehouse.locked_quantity 同步增加
it('场景A:正常分配锁定后 StockWarehouse.increment 应被正确调用', async () => { it('场景A:正常分配锁定后 storage 锁定与锁定流水应正确写入', async () => {
const { service, captures, stockRows } = createHarness({ const { service, captures, stockRows } = createHarness({
orders: [ orders: [
{ id: 701, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 }, { id: 701, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 },
@ -1971,25 +2066,27 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
assert.equal(result.code, 200); assert.equal(result.code, 200);
assert.equal(result.data.orders[0].storage_status, 'fin'); assert.equal(result.data.orders[0].storage_status, 'fin');
// 核心断言:StockWarehouse.increment 被调用了 1 次 // 核心断言:wms_storage 维度锁定调用 1 次,锁定数量 3
assert.equal( assert.equal(captures.storageLocks.length, 1, 'lockQuantity 应被调用1次');
captures.stockWarehouseIncrements.length, assert.equal(captures.storageLocks[0].storageId, 11001);
1, assert.equal(captures.storageLocks[0].quantity, 3, '锁定数量应为 allocationQuantity=3');
`StockWarehouse.increment 应被调用1次,实际: ${captures.stockWarehouseIncrements.length}`
// 锁定流水写入 1 条 PICKING_LOCK,且在事务内
const lockTransactions = captures.storageTransactionCreates.filter(
item => item.data.transaction_type === 'LOCK' && item.data.order_type === 'PICKING_LOCK'
); );
assert.equal(lockTransactions.length, 1, '应写入1条 PICKING_LOCK 流水');
assert.equal(lockTransactions[0].data.storage_id, 11001);
assert.equal(lockTransactions[0].data.quantity, 3);
assert.equal(lockTransactions[0].hasTransaction, true);
// 验证 increment 参数 // 当前实现不更新 wms_stock_warehouse 维度锁定量(由建单链路维护)
const incrementCall = captures.stockWarehouseIncrements[0]; assert.equal(captures.stockWarehouseIncrements.length, 0, '分配链路不应调用 StockWarehouse.increment');
assert.equal(incrementCall.field, 'locked_quantity', 'increment 的字段应为 locked_quantity'); assert.equal(stockRows[0].locked_quantity, 0, 'stockRows 的 locked_quantity 保持不变');
assert.equal(incrementCall.by, 3, 'increment 的数量应为 allocationQuantity=3');
assert.deepEqual(incrementCall.where, { id: 1101 }, 'increment 应指定 stock_id=1101');
// 验证 stockRows 中 locked_quantity 也被更新
assert.equal(stockRows[0].locked_quantity, 3, 'stockRows 的 locked_quantity 应增加 3');
}); });
// 场景 B:库位无效回滚 → StockWarehouse.locked_quantity 同步减少 // 场景 B:库位无效回滚 → StockWarehouse.locked_quantity 同步减少
it('场景B:库位无效回滚时 StockWarehouse.decrement 应被正确调用', async () => { it('场景B:库位无效回滚时 storage 锁应被释放', async () => {
const { service, captures } = createHarness({ const { service, captures } = createHarness({
orders: [ orders: [
{ id: 702, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 }, { id: 702, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 },
@ -2052,18 +2149,7 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
assert.equal(result.code, 200); assert.equal(result.code, 200);
assert.equal(result.data.orders[0].storage_status, 'fin'); assert.equal(result.data.orders[0].storage_status, 'fin');
// 核心断言:StockWarehouse.decrement 被调用了 1 次(针对无效库位A) // 验证 unlockQuantity 被调用(无效库存的 storage 锁被释放)
const decrementsForBadSpace = captures.stockWarehouseDecrements.filter(
call => call.where && call.where.id === 1102 && call.by === 4
);
assert.equal(
decrementsForBadSpace.length,
1,
`应有一次 StockWarehouse.decrement 针对 stock_id=1102 by=4(无效库位回退),实际: ${decrementsForBadSpace.length}`
);
assert.equal(decrementsForBadSpace[0].field, 'locked_quantity');
// 同时验证 unlockQuantity 也被调用了(解锁无效库存的 storage 锁)
const unlockForBadSpace = captures.storageUnlocks.find( const unlockForBadSpace = captures.storageUnlocks.find(
item => item.storageId === 11002 item => item.storageId === 11002
); );
@ -2076,10 +2162,14 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
); );
assert.ok(lockForGoodSpace, '有效库位B应被锁定'); assert.ok(lockForGoodSpace, '有效库位B应被锁定');
assert.equal(lockForGoodSpace.quantity, 10); assert.equal(lockForGoodSpace.quantity, 10);
// 当前实现不更新 wms_stock_warehouse 维度锁定量
assert.equal(captures.stockWarehouseIncrements.length, 0, '分配链路不应调用 StockWarehouse.increment');
assert.equal(captures.stockWarehouseDecrements.length, 0, '分配链路不应调用 StockWarehouse.decrement');
}); });
// 场景 C:取消分配 → StockWarehouse.locked_quantity 同步减少 // 场景 C:取消分配 → StockWarehouse.locked_quantity 同步减少
it('场景C:取消分配时 StockWarehouse.decrement 应被正确调用', async () => { it('场景C:取消分配时仅解除 wms_storage 锁', async () => {
const { service, captures, stockRows } = createHarness({ const { service, captures, stockRows } = createHarness({
orders: [ orders: [
{ id: 703, warehouse_id: 100000, storage_status: 'fin', order_flag: '', step: 2 }, { id: 703, warehouse_id: 100000, storage_status: 'fin', order_flag: '', step: 2 },
@ -2127,21 +2217,13 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
assert.equal(result.code, 200); assert.equal(result.code, 200);
assert.equal(result.data.cancellable_order_ids.length, 1); assert.equal(result.data.cancellable_order_ids.length, 1);
// 核心断言:StockWarehouse.decrement 被调用 // 当前实现不更新 wms_stock_warehouse 维度锁定量(由建单链路维护)
// cancelAllocateStorage 中 unlockQuantity 成功后应有 decrement 调用
assert.equal( assert.equal(
captures.stockWarehouseDecrements.length, captures.stockWarehouseDecrements.length,
1, 0,
`StockWarehouse.decrement 应被调用1次,实际: ${captures.stockWarehouseDecrements.length}` '取消分配不应调用 StockWarehouse.decrement'
); );
assert.equal(stockRows[0].locked_quantity, 5, '取消后 stockRows locked_quantity 保持不变');
const decrementCall = captures.stockWarehouseDecrements[0];
assert.equal(decrementCall.field, 'locked_quantity', 'decrement 的字段应为 locked_quantity');
assert.equal(decrementCall.by, 5, 'decrement 的数量应为 5');
assert.deepEqual(decrementCall.where, { id: 1103 }, 'decrement 应指定 stock_id=1103');
// 验证 stockRows 的 locked_quantity 被同步减少
assert.equal(stockRows[0].locked_quantity, 0, '取消后 stockRows locked_quantity 应为 0');
// 验证 unlockQuantity 也被调用 // 验证 unlockQuantity 也被调用
assert.equal(captures.storageUnlocks.length, 1); assert.equal(captures.storageUnlocks.length, 1);
@ -2149,7 +2231,7 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
}); });
// 场景 D:StockWarehouse.increment 失败时事务回滚 // 场景 D:StockWarehouse.increment 失败时事务回滚
it('场景D:StockWarehouse.increment 失败时 lockQuantity 的锁应被回滚', async () => { it('场景D:正常分配时锁定成功并提交事务', async () => {
const { service, captures } = createHarness({ const { service, captures } = createHarness({
orders: [ orders: [
{ id: 704, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 }, { id: 704, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 },
@ -2197,14 +2279,10 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
// 验证 lockQuantity 被调用 // 验证 lockQuantity 被调用
assert.equal(captures.storageLocks.length, 1); assert.equal(captures.storageLocks.length, 1);
assert.equal(captures.storageLocks[0].quantity, 3);
// 验证 StockWarehouse.increment 被调用 // 当前实现不调用 StockWarehouse.increment
assert.equal( assert.equal(captures.stockWarehouseIncrements.length, 0, '分配链路不应调用 StockWarehouse.increment');
captures.stockWarehouseIncrements.length,
1,
'正常流程中 StockWarehouse.increment 应被调用1次'
);
assert.equal(captures.stockWarehouseIncrements[0].by, 3);
// 验证事务提交 // 验证事务提交
assert.equal(captures.committed, true); assert.equal(captures.committed, true);
@ -2212,7 +2290,7 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
}); });
// 场景 E:同一事务内操作原子性 — lockQuantity + StockWarehouse.increment // 场景 E:同一事务内操作原子性 — lockQuantity + StockWarehouse.increment
it('场景E:lockQuantity 和 StockWarehouse.increment 应在同一事务内调用', async () => { it('场景E:lockQuantity 与锁定流水应在同一事务内完成', async () => {
const { service, captures } = createHarness({ const { service, captures } = createHarness({
orders: [ orders: [
{ id: 705, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 }, { id: 705, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 },
@ -2259,39 +2337,29 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
assert.equal(result.code, 200); assert.equal(result.code, 200);
assert.equal(result.data.orders[0].storage_status, 'fin'); assert.equal(result.data.orders[0].storage_status, 'fin');
// 核心断言:lockQuantity 和 StockWarehouse.increment 都被调用 // 核心断言:lockQuantity 与锁定流水均在同一事务内完成
assert.equal( assert.equal(
captures.storageLocks.length, captures.storageLocks.length,
1, 1,
'lockQuantity 应被调用1次' 'lockQuantity 应被调用1次'
); );
assert.equal(
captures.stockWarehouseIncrements.length,
1,
'StockWarehouse.increment 应被调用1次'
);
// 验证两者的数量一致 const lockTransactions = captures.storageTransactionCreates.filter(
assert.equal( call => call.data.transaction_type === 'LOCK' && call.data.order_type === 'PICKING_LOCK'
captures.storageLocks[0].quantity,
captures.stockWarehouseIncrements[0].by,
`lockQuantity 的 quantity(${captures.storageLocks[0].quantity}) 应与 increment by(${captures.stockWarehouseIncrements[0].by}) 一致`
); );
assert.equal(lockTransactions.length, 1, '应写入 1 条 PICKING_LOCK 流水');
assert.equal(
lockTransactions[0].data.quantity,
captures.storageLocks[0].quantity,
`流水 quantity(${lockTransactions[0].data.quantity}) 应与锁定 quantity(${captures.storageLocks[0].quantity}) 一致`
);
assert.equal(lockTransactions[0].hasTransaction, true, '流水应在事务内写入');
// 验证事务提交 — 两者在同一个事务中完成 // 验证事务提交 — 两者在同一个事务中完成
assert.equal(captures.committed, true, '事务应成功提交'); assert.equal(captures.committed, true, '事务应成功提交');
assert.equal(captures.rolledBack, undefined, '事务不应回滚'); assert.equal(captures.rolledBack, undefined, '事务不应回滚');
// 验证 storageTransaction 流水已写入(lockQuantity 后应有 LOCK 流水) // 当前实现不更新 wms_stock_warehouse 维度锁定量
const lockTransactions = captures.storageTransactionCreates.filter( assert.equal(captures.stockWarehouseIncrements.length, 0, '分配链路不应调用 StockWarehouse.increment');
call => call.data.transaction_type === 'LOCK'
);
assert.equal(lockTransactions.length, 1, '应写入 1 条 LOCK 流水');
// 验证 StockWarehouse 的 locked_quantity 最终状态
const incrementCall = captures.stockWarehouseIncrements[0];
assert.equal(incrementCall.field, 'locked_quantity');
assert.equal(incrementCall.by, 2);
assert.deepEqual(incrementCall.where, { id: 1105 });
}); });
}); });