feat(wave): 策略命中数按同快递拆分统计与退回原因中文标签

- getWaveStrategyMatchedOrderCountFilteredMap 改收策略行并按 require_same_express 拆分计数,
  同快递策略按 items_hash+快递分组, 与抓取候选 SQL 口径一致, max_same_structure<=0 视为不设上限
- waveStrategyFallbackOrderList excluded_reason 改中文标签, 兼容 lock_status 归一化 Y/N 与原始值
This commit is contained in:
liufumingren 2026-08-21 02:20:07 +08:00
parent d4dc25c8e7
commit 232985a272
2 changed files with 80 additions and 60 deletions

View File

@ -47,6 +47,12 @@ const WAVE_STRATEGY_FALLBACK_WHERE_FIELD_MAP = Object.freeze({
province: 'province',
sys_platform_name: 'sys_platform_name',
});
const WAVE_STRATEGY_FALLBACK_EXCLUDED_REASON_LABELS = Object.freeze({
locked: '已锁定',
intercepted: '已拦截',
printed: '已打印',
no_match: '未匹配策略',
});
const BATCH_LIST_ASSIGNMENT_FILTER_SCHEMAS = Object.freeze({
storage: Object.freeze({
fieldName: 'storage_assignment_status',
@ -104,7 +110,7 @@ class WaveService extends OrderBaseService {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'wavePickTaskCancelSelf,groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,waveStrategyFetchPda,waveStrategyFetchAdmin,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,wavePickTaskList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress';
const _noNeedLog = 'groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,waveStrategyFetchPda,waveStrategyFetchAdmin,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,wavePickTaskList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress';
const _noNeedLog = 'groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,waveStrategyFetchAdmin,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,wavePickTaskList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress';
const _noNeedAuth = 'groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,waveStrategyFetchPda,waveStrategyFetchAdmin,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,wavePickTaskList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
@ -2675,12 +2681,9 @@ class WaveService extends OrderBaseService {
});
const list = Array.isArray(queryResult && queryResult.rows) ? queryResult.rows : [];
const strategyIds = [ ...new Set(list
.map(item => Number(item && item.id || 0))
.filter(item => Number.isInteger(item) && item > 0)) ];
const matchedOrderCountMap = await this.getWaveStrategyMatchedOrderCountFilteredMap(
contextWarehouseId,
strategyIds
list
);
const nextFetchOrderCountMap = calculateNextFetchOrderCount
? await this.getWaveStrategyNextFetchOrderCountMap(contextWarehouseId, list)
@ -2996,34 +2999,55 @@ class WaveService extends OrderBaseService {
/**
* 按策略统计过滤后命中订单数。
*
* 过滤口径:
* 过滤口径与抓取候选 SQL(getWaveStrategyFetchCandidateOrders)保持一致:
* 1) 仅统计未在波次订单(wave_id = 0);
* 2) 仅统计 step != 0 的订单;
* 3) 仅统计状态有效订单(status != cancel 且 outbound_status != padding);
* 4) 同结构数量需落在策略 min_same_structure/max_same_structure 区间内。
*
* 同结构定义沿用快速扫描口径:优先 items_hash,空时回退 items。
* 3) 仅统计状态有效订单(status != cancel 且 outbound_status != padding);
* 4) 同结构数量需落在策略 min_same_structure/max_same_structure 区间内;
* 当 require_same_express = 1 时按「结构(items_hash) + 快递」分组计数,
* 否则仅按结构(items_hash)分组计数。
*
* @param {number|string} warehouseId 仓库ID。
* @param {Array<number|string>} strategyIds 当前页策略ID列表。
* @param {Array<Object|number|string>} strategyRows 当前页策略行数组(含 require_same_express)。
* @return {Promise<Map<number, number>>} strategy_id 到过滤后命中订单数的映射。
*/
async getWaveStrategyMatchedOrderCountFilteredMap(warehouseId, strategyIds = []) {
async getWaveStrategyMatchedOrderCountFilteredMap(warehouseId, strategyRows = []) {
const normalizedWarehouseId = Number(warehouseId || 0);
if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
throw new Error('未识别到当前仓库上下文');
}
const normalizedStrategyIds = [ ...new Set((Array.isArray(strategyIds) ? strategyIds : [])
.map(item => Number(item))
.filter(item => Number.isInteger(item) && item > 0)) ];
if (normalizedStrategyIds.length === 0) {
const normalizedStrategies = [ ...new Map((Array.isArray(strategyRows) ? strategyRows : [])
.map(item => {
const strategyId = Number(item && (item.id ?? item.strategy_id) || 0);
if (!Number.isInteger(strategyId) || strategyId <= 0) {
return null;
}
return [ strategyId, {
id: strategyId,
requireSameExpress: Number(item && item.require_same_express || 0) === 1,
}];
})
.filter(Boolean)).values() ];
if (normalizedStrategies.length === 0) {
return new Map();
}
const orderModel = await this.getOrderModel('pendingOrder', normalizedWarehouseId);
const orderTableName = this.getModelTableSqlName(orderModel);
const querySql = `
const expressExpr = alias => `COALESCE(NULLIF(TRIM(COALESCE(${alias}.sys_logistics_code, '')), ''), NULLIF(TRIM(COALESCE(${alias}.logistics_code, '')), ''), TRIM(COALESCE(${alias}.logistics_name, '')))`;
const matchedMap = new Map();
const runCountQuery = async (strategyGroup, requireSameExpress) => {
const strategyIds = strategyGroup.map(item => item.id);
if (strategyIds.length === 0) {
return;
}
const groupKeyExtra = requireSameExpress ? `, ${expressExpr('src')} AS express_key` : '';
const joinKeyExtra = requireSameExpress ? ` AND same_structure.express_key = ${expressExpr('o')}` : '';
const querySql = `
SELECT
m.strategy_id,
COUNT(DISTINCT m.order_id) AS matched_order_count_filtered
@ -3042,7 +3066,7 @@ class WaveService extends OrderBaseService {
AND o.lock_status = 'none'
INNER JOIN (
SELECT
src.items_hash AS structure_key,
src.items_hash AS structure_key${groupKeyExtra},
COUNT(1) AS same_structure_count
FROM ${orderTableName} src
WHERE src.warehouse_id = :warehouseId
@ -3055,37 +3079,42 @@ class WaveService extends OrderBaseService {
AND src.outbound_status != 'padding'
AND src.intercept_status = 'none'
AND src.lock_status = 'none'
GROUP BY src.items_hash
GROUP BY src.items_hash${requireSameExpress ? `, ${expressExpr('src')}` : ''}
) same_structure
ON same_structure.structure_key = o.items_hash
ON same_structure.structure_key = o.items_hash${joinKeyExtra}
INNER JOIN wms_wave_strategy s
ON s.id = m.strategy_id
AND s.warehouse_id = :warehouseId
WHERE m.warehouse_id = :warehouseId
AND m.strategy_id IN (:strategyIds)
AND same_structure.same_structure_count >= COALESCE(s.min_same_structure, 0)
AND (s.max_same_structure IS NULL OR same_structure.same_structure_count <= s.max_same_structure)
AND same_structure.same_structure_count >= COALESCE(NULLIF(s.min_same_structure, 0), 0)
AND (s.max_same_structure IS NULL OR s.max_same_structure <= 0 OR same_structure.same_structure_count <= s.max_same_structure)
GROUP BY m.strategy_id
`;
const queryRows = await this.ctx.model.query(querySql, {
replacements: {
warehouseId: normalizedWarehouseId,
strategyIds: normalizedStrategyIds,
},
type: this.ctx.model.QueryTypes.SELECT,
});
const queryRows = await this.ctx.model.query(querySql, {
replacements: {
warehouseId: normalizedWarehouseId,
strategyIds,
},
type: this.ctx.model.QueryTypes.SELECT,
});
const matchedMap = new Map();
(Array.isArray(queryRows) ? queryRows : []).forEach(row => {
const strategyId = Number(row && row.strategy_id || 0);
const matchedCount = Number(row && row.matched_order_count_filtered || 0);
if (!Number.isInteger(strategyId) || strategyId <= 0) {
return;
}
(Array.isArray(queryRows) ? queryRows : []).forEach(row => {
const strategyId = Number(row && row.strategy_id || 0);
const matchedCount = Number(row && row.matched_order_count_filtered || 0);
if (!Number.isInteger(strategyId) || strategyId <= 0) {
return;
}
matchedMap.set(strategyId, matchedCount);
});
matchedMap.set(strategyId, matchedCount);
});
};
await Promise.all([
runCountQuery(normalizedStrategies.filter(item => item.requireSameExpress), true),
runCountQuery(normalizedStrategies.filter(item => !item.requireSameExpress), false),
]);
return matchedMap;
}
@ -3978,6 +4007,12 @@ class WaveService extends OrderBaseService {
buildWaveStrategyFallbackOrderListItem(orderRow = {}, itemSnapshot = '') {
const normalizedOrderRow = this.isPlainObject(orderRow) ? orderRow : {};
// normalizeOrderListItem 已将 lock_status 归一化为 Y/N(none→N,其余→Y),
// 这里兼容归一化值(Y/N)与原始值(none/warehouse/store),避免把 N 误判为已锁定。
const lockStatus = String(normalizedOrderRow.lock_status || '').trim();
const isLocked = lockStatus === 'Y'
|| (lockStatus !== '' && lockStatus !== 'N' && lockStatus !== 'none');
return {
id: normalizedOrderRow.id ?? null,
delivery_no: normalizedOrderRow.delivery_no ?? normalizedOrderRow.delivery_order_code ?? null,
@ -3992,13 +4027,13 @@ class WaveService extends OrderBaseService {
sys_platform_name: normalizedOrderRow.sys_platform_name ?? null,
item_snapshot: String(itemSnapshot || ''),
wave_index: Number(normalizedOrderRow.wave_index || 0),
excluded_reason: normalizedOrderRow.lock_status !== 'none'
? 'locked'
excluded_reason: isLocked
? WAVE_STRATEGY_FALLBACK_EXCLUDED_REASON_LABELS.locked
: normalizedOrderRow.intercept_status !== 'none'
? 'intercepted'
? WAVE_STRATEGY_FALLBACK_EXCLUDED_REASON_LABELS.intercepted
: normalizedOrderRow.print_status === 'fin'
? 'printed'
: 'no_match',
? WAVE_STRATEGY_FALLBACK_EXCLUDED_REASON_LABELS.printed
: WAVE_STRATEGY_FALLBACK_EXCLUDED_REASON_LABELS.no_match,
};
}
@ -6548,9 +6583,6 @@ class WaveService extends OrderBaseService {
const normalizedOrder = this.isPlainObject(order) ? order : {};
const normalizedStrategy = this.isPlainObject(strategy) ? strategy : {};
const structureStoreSetMap = context && context.structureStoreSetMap instanceof Map ? context.structureStoreSetMap : new Map();
const structurePrimaryExpressMap = context && context.structurePrimaryExpressMap instanceof Map
? context.structurePrimaryExpressMap
: null;
const structurePrimaryOwnerMap = context && context.structurePrimaryOwnerMap instanceof Map
? context.structurePrimaryOwnerMap
: null;
@ -6576,18 +6608,6 @@ class WaveService extends OrderBaseService {
}
}
if (normalizedStrategy.require_same_express === true && structurePrimaryExpressMap instanceof Map) {
const primaryExpressKey = String(structurePrimaryExpressMap.get(structureKey) || '').trim().toLowerCase();
if (!primaryExpressKey) {
return false;
}
const currentExpressKey = String(this.getWaveStrategyQuickScanExpressKey(normalizedOrder) || '').trim().toLowerCase();
if (currentExpressKey !== primaryExpressKey) {
return false;
}
}
const itemsCount = Number(normalizedOrder.items_count || 0);
const itemsTotal = Number(normalizedOrder.items_total || 0);

View File

@ -314,7 +314,7 @@ describe('test/app/service/systemMethods/order/wave.waveStrategyQuickScan.test.j
assert.deepEqual(result.matchedOrderIds, [ 101, 102 ]);
});
it('require_same_express=true 时应按同结构主快递优先命中', async () => {
it('require_same_express=true 时扫描阶段不再按主快递排除订单', async () => {
const { service } = createHarness();
const orders = [
@ -389,6 +389,6 @@ describe('test/app/service/systemMethods/order/wave.waveStrategyQuickScan.test.j
),
});
assert.deepEqual(result.matchedOrderIds, [ 201, 202 ]);
assert.deepEqual(result.matchedOrderIds, [ 201, 202, 203 ]);
});
});