Co-authored-by: Copilot <copilot@github.com>
This commit is contained in:
liufumingren 2026-05-11 08:44:27 +08:00
parent f0b5758ada
commit 9c2b254206
37 changed files with 12559 additions and 110 deletions

View File

@ -0,0 +1,195 @@
'use strict';
/**
* 执行波次策略快速扫描通用流程。
*
* @param {Object} [options={}] 扫描参数。
* @param {Array<Object>} [options.orders] 订单数组。
* @param {Array<Object>} [options.strategyList] 策略数组。
* @param {Function} [options.getStructureKey] 获取订单结构 key。
* @param {Function} [options.getExpressKey] 获取订单快递 key。
* @param {Function} [options.isOrderMatched] 判断订单是否命中策略。
* @param {Function} [options.getMatchedStrategyIds] 获取订单命中策略ID数组。
* @param {Function} [options.onProgress] 异步进度回调。
* @return {Promise<{totalOrderCount:number, processedOrderCount:number, matchedOrderIds:Array<number>, unmatchedOrderIds:Array<number>, matchedStrategyIdsByOrder:Object}>} 扫描结果。
*/
async function runWaveStrategyQuickScanRunner(options = {}) {
const normalizedOptions = options && typeof options === 'object' ? options : {};
const normalizedOrders = Array.isArray(normalizedOptions.orders) ? normalizedOptions.orders : [];
const strategyList = Array.isArray(normalizedOptions.strategyList) ? normalizedOptions.strategyList : [];
const getStructureKey = typeof normalizedOptions.getStructureKey === 'function'
? normalizedOptions.getStructureKey
: () => '';
const getExpressKey = typeof normalizedOptions.getExpressKey === 'function'
? normalizedOptions.getExpressKey
: () => '';
const isOrderMatched = typeof normalizedOptions.isOrderMatched === 'function'
? normalizedOptions.isOrderMatched
: () => false;
const getMatchedStrategyIds = typeof normalizedOptions.getMatchedStrategyIds === 'function'
? normalizedOptions.getMatchedStrategyIds
: null;
const onProgress = typeof normalizedOptions.onProgress === 'function'
? normalizedOptions.onProgress
: null;
const structureStoreSetMap = new Map();
const structureOwnerCountMap = new Map();
const structureExpressCountMap = new Map();
for (const order of normalizedOrders) {
const structureKey = String(getStructureKey(order) || '').trim();
if (!structureKey) {
continue;
}
const storeId = String(order && order.store_id || '').trim().toLowerCase();
if (!structureStoreSetMap.has(structureKey)) {
structureStoreSetMap.set(structureKey, new Set());
}
if (!structureOwnerCountMap.has(structureKey)) {
structureOwnerCountMap.set(structureKey, new Map());
}
if (!structureExpressCountMap.has(structureKey)) {
structureExpressCountMap.set(structureKey, new Map());
}
if (storeId) {
structureStoreSetMap.get(structureKey).add(storeId);
const ownerCountMap = structureOwnerCountMap.get(structureKey);
ownerCountMap.set(storeId, Number(ownerCountMap.get(storeId) || 0) + 1);
}
const expressKey = String(getExpressKey(order) || '').trim().toLowerCase();
if (expressKey) {
const expressCountMap = structureExpressCountMap.get(structureKey);
expressCountMap.set(expressKey, Number(expressCountMap.get(expressKey) || 0) + 1);
}
}
const structurePrimaryOwnerMap = new Map();
for (const [ structureKey, ownerCountMap ] of structureOwnerCountMap.entries()) {
if (!(ownerCountMap instanceof Map) || ownerCountMap.size === 0) {
continue;
}
let primaryOwner = '';
let maxCount = 0;
for (const [ storeId, count ] of ownerCountMap.entries()) {
const normalizedStoreId = String(storeId || '').trim().toLowerCase();
const normalizedCount = Number(count || 0);
if (!normalizedStoreId || normalizedCount <= 0) {
continue;
}
if (
normalizedCount > maxCount
|| (normalizedCount === maxCount && (!primaryOwner || normalizedStoreId < primaryOwner))
) {
maxCount = normalizedCount;
primaryOwner = normalizedStoreId;
}
}
if (primaryOwner) {
structurePrimaryOwnerMap.set(structureKey, primaryOwner);
}
}
const structurePrimaryExpressMap = new Map();
for (const [ structureKey, expressCountMap ] of structureExpressCountMap.entries()) {
if (!(expressCountMap instanceof Map) || expressCountMap.size === 0) {
continue;
}
let primaryExpressKey = '';
let maxCount = 0;
for (const [ expressKey, count ] of expressCountMap.entries()) {
const normalizedExpressKey = String(expressKey || '').trim().toLowerCase();
const normalizedCount = Number(count || 0);
if (!normalizedExpressKey || normalizedCount <= 0) {
continue;
}
if (
normalizedCount > maxCount
|| (normalizedCount === maxCount && (!primaryExpressKey || normalizedExpressKey < primaryExpressKey))
) {
maxCount = normalizedCount;
primaryExpressKey = normalizedExpressKey;
}
}
if (primaryExpressKey) {
structurePrimaryExpressMap.set(structureKey, primaryExpressKey);
}
}
const matchedOrderIds = [];
const unmatchedOrderIds = [];
const matchedStrategyIdsByOrder = {};
const totalOrderCount = normalizedOrders.length;
let processedOrderCount = 0;
for (const order of normalizedOrders) {
const context = {
structureStoreSetMap,
structureOwnerCountMap,
structurePrimaryOwnerMap,
structureExpressCountMap,
structurePrimaryExpressMap,
};
const orderId = Number(order && order.id || 0);
let matched = false;
if (getMatchedStrategyIds) {
const rawMatchedStrategyIds = getMatchedStrategyIds(order, strategyList, context);
const matchedStrategyIds = [ ...new Set((Array.isArray(rawMatchedStrategyIds) ? rawMatchedStrategyIds : [])
.map(id => Number(id))
.filter(id => Number.isInteger(id) && id > 0)) ];
matched = matchedStrategyIds.length > 0;
if (Number.isInteger(orderId) && orderId > 0) {
matchedStrategyIdsByOrder[orderId] = matchedStrategyIds;
}
} else {
matched = Boolean(isOrderMatched(order, strategyList, context));
}
if (Number.isInteger(orderId) && orderId > 0) {
if (matched) {
matchedOrderIds.push(orderId);
} else {
unmatchedOrderIds.push(orderId);
}
}
processedOrderCount += 1;
if (onProgress && (processedOrderCount % 200 === 0 || processedOrderCount === totalOrderCount)) {
await onProgress({
totalOrderCount,
processedOrderCount,
matchedOrderCount: matchedOrderIds.length,
unmatchedOrderCount: unmatchedOrderIds.length,
});
}
}
if (onProgress && totalOrderCount === 0) {
await onProgress({
totalOrderCount,
processedOrderCount,
matchedOrderCount: 0,
unmatchedOrderCount: 0,
});
}
return {
totalOrderCount,
processedOrderCount,
matchedOrderIds,
unmatchedOrderIds,
matchedStrategyIdsByOrder,
};
}
module.exports = runWaveStrategyQuickScanRunner;

View File

@ -43,6 +43,7 @@ module.exports = app => {
Object.freeze({ code: 'receiving_reviewed', name: '收货审核完成', business: 'receiving', description: '收货单批量审核通过后的通知' }),
Object.freeze({ code: 'order_sync_completed', name: '订单同步完成', business: 'order', description: '本地创建入口同步完成后的通知' }),
Object.freeze({ code: 'order_cancel_intercepted', name: '订单取消拦截', business: 'order', description: '订单取消失败并触发拦截执行后的通知' }),
Object.freeze({ code: 'wave_strategy_quick_scan_failed', name: '波次策略兜底扫描失败', business: 'order', description: '定时兜底扫描任务在仓库维度触发失败时通知' }),
Object.freeze({
code: 'store_warehouse_print_quantity_adjusted',
name: '货主面单余额调整',

View File

@ -399,6 +399,18 @@ module.exports = app => {
defaultValue: '',
comment: '波次号,空字符串表示未分配',
},
wave_strategy_version: {
type: INTEGER(10),
allowNull: false,
defaultValue: 0,
comment: '波次策略版本号',
},
wave_scan_result: {
type: INTEGER(10),
allowNull: false,
defaultValue: 0,
comment: '波次扫描结果,0未扫描,1扫描符合,2扫描没有符合',
},
// 状态机字段
post_status: {
type: ENUM(...StatusEnum.POST_STATUS),

View File

@ -0,0 +1,53 @@
// app/model/order_wave_strategy_match.js
'use strict';
module.exports = app => {
const { BIGINT, INTEGER, DATE } = app.Sequelize;
const OrderWaveStrategyMatch = app.model.define('wms_order_wave_strategy_match', {
id: {
type: BIGINT,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键',
},
warehouse_id: {
type: INTEGER(10),
allowNull: false,
comment: '仓库ID',
},
order_id: {
type: BIGINT,
allowNull: false,
comment: '订单ID,逻辑关联分仓主表,不做物理外键',
},
strategy_id: {
type: INTEGER(10),
allowNull: false,
comment: '命中的波次策略ID',
},
create_time: {
type: DATE,
allowNull: false,
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '写入时间',
},
}, {
tableName: 'wms_order_wave_strategy_match',
timestamps: false,
comment: '订单波次策略命中明细表,记录每个订单命中的全部策略',
indexes: [
{
name: 'idx_warehouse_order',
fields: [ 'warehouse_id', 'order_id' ],
},
{
name: 'idx_warehouse_strategy',
fields: [ 'warehouse_id', 'strategy_id' ],
},
],
});
return OrderWaveStrategyMatch;
};

View File

@ -1,10 +1,15 @@
// app/model/picking_strategy.js
'use strict';
/**
* 波次策略模型定义。
* @param {import('egg').Application} app Egg 应用实例
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} 波次策略模型
*/
module.exports = app => {
const { BIGINT, INTEGER, STRING, TINYINT, BOOLEAN, JSON, TEXT, DATE } = app.Sequelize;
const PickingStrategy = app.model.define('wms_picking_strategy', {
const WaveStrategy = app.model.define('wms_wave_strategy', {
id: {
type: INTEGER,
primaryKey: true,
@ -147,10 +152,10 @@ module.exports = app => {
comment: '更新时间',
},
}, {
tableName: 'wms_picking_strategy',
tableName: 'wms_wave_strategy',
timestamps: false,
underscored: false,
comment: '拣货策略配置表',
comment: '波次策略配置表',
indexes: [
{
name: 'idx_warehouse_type',
@ -163,5 +168,5 @@ module.exports = app => {
],
});
return PickingStrategy;
return WaveStrategy;
};

View File

@ -0,0 +1,150 @@
'use strict';
const FALLBACK_TASK_NAME = 'wave_strategy_quick_scan_fallback';
module.exports = {
schedule: {
interval: '10m',
type: 'worker',
immediate: false,
disable: false,
},
/**
* 执行波次策略快速扫描兜底任务。
*
* @param {Object} ctx Egg 上下文。
* @return {Promise<void>} 无返回值。
*/
async task(ctx) {
if (ctx.app._waveStrategyQuickScanFallbackRunning) {
ctx.logger.info(`[${FALLBACK_TASK_NAME}] 任务仍在运行中,跳过本轮调度`);
return;
}
ctx.app._waveStrategyQuickScanFallbackRunning = true;
let totalWarehouseCount = 0;
let submitSuccessCount = 0;
let reusedRunningTaskCount = 0;
let submitFailedCount = 0;
let cleanupDeletedCount = 0;
try {
const storeRows = await ctx.model.Store.findAll({
attributes: [ 'id' ],
where: {
status: 1,
project: 'warehouse',
},
raw: true,
});
const warehouseIds = Array.isArray(storeRows)
? storeRows.map(item => Number(item && item.id || 0)).filter(item => Number.isInteger(item) && item > 0)
: [];
totalWarehouseCount = warehouseIds.length;
for (const warehouseId of warehouseIds) {
try {
const submitPayload = await ctx.service.systemMethods.order.wave.submitWaveStrategyQuickScanForWarehouse(warehouseId);
const submitMessage = String(submitPayload && submitPayload.message || '').trim();
const submitState = String(submitPayload && submitPayload.state || '').trim();
const isReusedRunningTask = submitMessage.includes('已有快速扫描任务在运行中')
|| [ 'running', 'submitted' ].includes(submitState) && submitMessage.includes('运行中');
if (isReusedRunningTask) {
reusedRunningTaskCount += 1;
} else {
submitSuccessCount += 1;
}
} catch (error) {
submitFailedCount += 1;
const errorMessage = error && error.message ? error.message : `${error}`;
ctx.logger.warn(`[${FALLBACK_TASK_NAME}] 仓库触发失败`, {
warehouseId,
error: errorMessage,
});
const noticeService = ctx.service
&& ctx.service.systems
&& ctx.service.systems.notice
&& typeof ctx.service.systems.notice.send === 'function'
? ctx.service.systems.notice
: (ctx.service
&& ctx.service.systems
&& ctx.service.systems.notice
&& ctx.service.systems.notice.index
&& typeof ctx.service.systems.notice.index.send === 'function'
? ctx.service.systems.notice.index
: null);
if (!noticeService) {
ctx.logger.warn(`[${FALLBACK_TASK_NAME}] 通知服务不可用,跳过失败通知`, {
warehouseId,
error: errorMessage,
});
continue;
}
try {
await noticeService.send({
event: 'wave_strategy_quick_scan_failed',
businessName: 'order',
warehouseId,
subjectId: warehouseId,
subject: {
id: warehouseId,
type: 'warehouse',
},
title: `波次策略兜底扫描触发失败(仓库 ${warehouseId})`,
content: `兜底扫描任务触发失败,仓库 ${warehouseId},错误:${errorMessage}`,
data: {
warehouse_id: warehouseId,
error: errorMessage,
task: FALLBACK_TASK_NAME,
},
metadata: {
warehouse_id: warehouseId,
error: errorMessage,
task: FALLBACK_TASK_NAME,
},
sender: {
id: 0,
name: 'system',
},
});
} catch (noticeError) {
ctx.logger.warn(`[${FALLBACK_TASK_NAME}] 发送失败通知异常`, {
warehouseId,
error: noticeError && noticeError.message ? noticeError.message : `${noticeError}`,
});
}
}
}
try {
cleanupDeletedCount = Number(
await ctx.service.systemMethods.order.wave.cleanupWaveStrategyQuickScanMatchedStrategies({ expireHours: 24 })
) || 0;
} catch (cleanupError) {
ctx.logger.warn(`[${FALLBACK_TASK_NAME}] 命中副表清理失败`, {
error: cleanupError && cleanupError.message ? cleanupError.message : `${cleanupError}`,
});
}
ctx.logger.info(`[${FALLBACK_TASK_NAME}] 任务完成`, {
totalWarehouseCount,
submitSuccessCount,
reusedRunningTaskCount,
submitFailedCount,
cleanupDeletedCount,
});
} catch (error) {
ctx.logger.error(`[${FALLBACK_TASK_NAME}] 任务执行失败: ${error && error.message ? error.message : error}`);
} finally {
ctx.app._waveStrategyQuickScanFallbackRunning = false;
}
},
};

View File

@ -39,6 +39,8 @@ const ORDER_LIST_BASE_ATTRIBUTES = Object.freeze([
'items', 'items_count', 'items_total', 'items_weight',
'wave_id',
'wave_no',
'wave_strategy_version',
'wave_scan_result',
'post_status', 'storage_status', 'pick_status', 'pack_status',
'inspection_status', 'print_status', 'claim_status',
'outbound_status', 'lock_status', 'intercept_status', 'basket_number',
@ -93,6 +95,23 @@ const MODULE_CONFIGS = Object.freeze({
},
},
},
waveStrategyFallbackOrder: {
modelType: 'current',
defaultWhere: {
step: {
operator: 'ne',
value: 0,
},
wave_id: {
operator: 'eq',
value: 0,
},
wave_scan_result: {
operator: 'eq',
value: 2,
},
},
},
outboundOrder: {
modelType: 'current',
defaultWhere: {
@ -467,6 +486,34 @@ class OrderBaseService extends MainService {
return ORDER_WEIGHT_TYPE_LABELS[0];
}
/**
* 规范波次扫描结果,空值时默认返回 0(未扫描)。
* @param {*} scanResult 扫描结果原始值。
* @return {number|string} 规范化后的扫描结果。
*/
normalizeWaveScanResult(scanResult) {
if (scanResult === null || scanResult === undefined || scanResult === '') {
return 0;
}
const numericResult = Number(scanResult);
return Number.isNaN(numericResult) ? scanResult : numericResult;
}
/**
* 规范波次策略版本,空值时默认返回 0。
* @param {*} strategyVersion 波次策略版本原始值。
* @return {number|string} 规范化后的波次策略版本。
*/
normalizeWaveStrategyVersion(strategyVersion) {
if (strategyVersion === null || strategyVersion === undefined || strategyVersion === '') {
return 0;
}
const numericVersion = Number(strategyVersion);
return Number.isNaN(numericVersion) ? strategyVersion : numericVersion;
}
/**
* 规范订单列表单行输出,保证重量类型直接返回中文。
* @param {Object} order 订单列表行数据。
@ -482,6 +529,8 @@ class OrderBaseService extends MainService {
name: this.maskListSensitiveValue(order.name),
tel: this.maskListSensitiveValue(order.tel),
weight_type: this.formatWeightTypeLabel(order.weight_type),
wave_strategy_version: this.normalizeWaveStrategyVersion(order.wave_strategy_version),
wave_scan_result: this.normalizeWaveScanResult(order.wave_scan_result),
};
}
@ -689,6 +738,8 @@ class OrderBaseService extends MainService {
name: this.maskListSensitiveValue(orderRow.name),
tel: this.maskListSensitiveValue(orderRow.tel),
mobile: this.maskListSensitiveValue(orderRow.mobile),
wave_strategy_version: this.normalizeWaveStrategyVersion(orderRow.wave_strategy_version),
wave_scan_result: this.normalizeWaveScanResult(orderRow.wave_scan_result),
sys_platform_name: Object.prototype.hasOwnProperty.call(orderRow, 'sys_platform_name')
? (orderRow.sys_platform_name ?? null)
: null,

File diff suppressed because it is too large Load Diff

View File

@ -11,9 +11,9 @@ class PickService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'query';
const _noNeedRight = 'query,wavePickTaskDetail';
const _noNeedLog = 'query';
const _noNeedAuth = 'query';
const _noNeedAuth = 'query,wavePickTaskDetail';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
@ -167,6 +167,55 @@ class PickService extends MainService {
return this.fail('查询失败', {}, 500);
}
}
/**
* 查询拣货任务详情。
*
* 仅允许任务创建人查看任务详情,包含主任务、波次、订单与框信息。
*
* @param {Object} data 请求参数。
* @param {number|string} data.task_id 拣货任务ID。
* @return {Promise<Object>} 统一 success/fail 包装结果。
*/
async wavePickTaskDetail(data = {}) {
const { service, ctx } = this;
const requestData = this.isPlainObject(data) ? data : {};
const { task_id } = requestData;
const taskId = Number(task_id);
if (!Number.isInteger(taskId) || taskId <= 0) {
return this.fail('task_id 必填且必须为正整数', {}, 400);
}
const stateUser = this.isPlainObject(ctx && ctx.state && ctx.state.user) ? ctx.state.user : null;
const ctxUser = this.isPlainObject(ctx && ctx.user) ? ctx.user : null;
const operatorSource = stateUser || ctxUser || {};
const rawOperatorId = operatorSource.employees_id ?? operatorSource.operator_id ?? operatorSource.id;
const operatorId = Number(rawOperatorId || 0);
if (!Number.isInteger(operatorId) || operatorId <= 0) {
return this.fail('未获取到操作人上下文', {}, 401);
}
try {
const result = await service.systems.pick.wavePickTaskDetail({
taskId,
operatorId,
});
return this.success('ok', {
data: result,
code: 200,
});
} catch (error) {
const code = Number(error && error.code);
if (Number.isInteger(code) && code >= 400 && code < 600) {
return this.fail(error.message || '查询失败', {}, code);
}
ctx.logger.error('[PickService.wavePickTaskDetail] 查询拣货任务详情失败: %s', error && error.message ? error.message : error);
return this.fail('查询失败', {}, 500);
}
}
}
module.exports = PickService;

View File

@ -47,7 +47,7 @@ class SettingWarehouseMethodsService extends MainService {
}
try {
const list = targetService.getFieldMeta();
const list = await targetService.getFieldMeta();
return this.success('ok', { list });
} catch (error) {
return this.fail(error.message || '获取仓库设置字段信息失败', {

View File

@ -1834,6 +1834,26 @@ class DeliveryOrderService extends Service {
await this.runAsyncProcessStep('autoGrouping', async () => {
await this.runAutoGrouping(context);
});
await this.runAsyncProcessStep('waveStrategyQuickScan', async () => {
await this.withPatchedCtxUser({
store_id: context.warehouseId,
warehouse_id: context.warehouseId,
}, async () => {
const result = await this.ctx.service.systemMethods.order.wave.submitWaveStrategyQuickScanForWarehouse(
context.warehouseId
);
const taskId = result && typeof result === 'object'
? (result.taskId || result.task_id || result.id || null)
: result;
this.ctx.logger.info('[DeliveryOrderService.asyncProcessOrderCreated] wave strategy quick scan triggered', {
warehouseId: context.warehouseId,
orderId: context.orderId,
taskId,
});
});
});
}
}

View File

@ -25,6 +25,7 @@ const DEFAULT_REGISTERED_EVENT_CODES = Object.freeze([
'*',
'receiving_completed',
'order_cancel_intercepted',
'wave_strategy_quick_scan_failed',
'store_warehouse_print_quantity_adjusted',
]);
const DRIVER_TYPE_ALIASES = Object.freeze({

View File

@ -3,6 +3,33 @@
const Service = require('egg').Service;
const REVIEWED_INSPECTION_STATUS = 'fin';
const PICK_MODE_VIEW_META_MAP = {
1: {
mode_code: '1',
mode_name: '团购小波次',
require_box_allocations: true,
},
2: {
mode_code: '2',
mode_name: '散单单品单件',
require_box_allocations: false,
},
3: {
mode_code: '3',
mode_name: '散单先拣后分',
require_box_allocations: true,
},
4: {
mode_code: '4',
mode_name: '边拣边分',
require_box_allocations: true,
},
5: {
mode_code: '5',
mode_name: '团购大波次',
require_box_allocations: false,
},
};
class PickSystemService extends Service {
/**
@ -38,6 +65,436 @@ class PickSystemService extends Service {
return error;
}
/**
* 获取数据表列名集合。
*
* 用于在不确定列是否存在时进行安全查询拼装,避免因列缺失导致 SQL 执行失败。
*
* @param {string} tableName 数据表名。
* @return {Promise<Set<string>>} 列名集合。
*/
async getTableColumnSet(tableName) {
const { ctx } = this;
const normalizedTableName = String(tableName || '').trim();
if (!normalizedTableName) {
return new Set();
}
const escapedTableName = normalizedTableName.replace(/`/g, '``');
try {
const rows = await ctx.model.query(`SHOW COLUMNS FROM \`${escapedTableName}\``, {
type: ctx.model.QueryTypes.SELECT,
});
return new Set((Array.isArray(rows) ? rows : [])
.map(row => String(row && row.Field || '').trim())
.filter(Boolean));
} catch (error) {
ctx.logger.warn(`[pick.wavePickTaskDetail] 获取表字段失败,table=${normalizedTableName},将按兜底处理: ${error.message}`);
return new Set();
}
}
/**
* 读取订单商品分表数据并构建索引。
*
* 优先使用 OrderItemsFactory 当前分表模型;若模型不可用或查询失败,返回空映射而不抛异常。
*
* @param {Object} params 查询参数。
* @param {number} params.warehouseId 仓库ID。
* @param {Array<number>} params.orderItemIds 订单明细ID列表。
* @return {Promise<Map<number, Object>>} 订单明细映射。
*/
async loadOrderItemMap(params = {}) {
const { ctx } = this;
const warehouseId = Number(params && params.warehouseId || 0);
const orderItemIds = Array.isArray(params && params.orderItemIds)
? params.orderItemIds.filter(id => Number.isInteger(id) && id > 0)
: [];
if (!Number.isInteger(warehouseId) || warehouseId <= 0 || orderItemIds.length === 0) {
return new Map();
}
const factory = ctx.model && ctx.model.OrderItemsFactory;
if (!factory || typeof factory.getCurrentModel !== 'function') {
return new Map();
}
try {
const orderItemModel = await factory.getCurrentModel(warehouseId);
if (!orderItemModel || typeof orderItemModel.findAll !== 'function') {
return new Map();
}
const orderItemRows = await orderItemModel.findAll({
where: {
id: {
[this.app.Sequelize.Op.in]: orderItemIds,
},
},
attributes: [ 'id', 'item_code', 'item_name', 'stock_id', 'plan_qty', 'item_snapshot' ],
raw: true,
});
return new Map((Array.isArray(orderItemRows) ? orderItemRows : [])
.map(row => [ Number(row && row.id || 0), row ]));
} catch (error) {
ctx.logger.warn(`[pick.wavePickTaskDetail] 订单商品分表查询失败,将按空字段降级: ${error.message}`);
return new Map();
}
}
/**
* 生成拣货明细汇总信息。
*
* @param {Array<Object>} pickingDetails 拣货明细列表。
* @return {{total_lines: number, total_qty: number, distinct_spaces: number, distinct_items: number}} 汇总结果。
*/
buildPickingSummary(pickingDetails = []) {
const normalizedDetails = Array.isArray(pickingDetails) ? pickingDetails : [];
const distinctSpaceIds = new Set();
const distinctItemKeys = new Set();
for (const detail of normalizedDetails) {
const spaceId = Number(detail && detail.space_id || 0);
if (spaceId > 0) {
distinctSpaceIds.add(spaceId);
}
const itemCode = String(detail && detail.item_code || '').trim();
const orderItemId = Number(detail && detail.order_item_id || 0);
if (itemCode) {
distinctItemKeys.add(`code:${itemCode}`);
} else if (orderItemId > 0) {
distinctItemKeys.add(`order_item_id:${orderItemId}`);
}
}
return {
total_lines: normalizedDetails.length,
total_qty: normalizedDetails.reduce((sum, detail) => sum + Number(detail && detail.quantity || 0), 0),
distinct_spaces: distinctSpaceIds.size,
distinct_items: distinctItemKeys.size,
};
}
/**
* 获取拣货模式视图元信息。
*
* @param {number} pickMode 拣货模式编码。
* @return {{mode_code: number, mode_name: string, require_box_allocations: boolean}} 视图元信息。
*/
getPickModeViewMeta(pickMode) {
const normalizedPickMode = Number(pickMode || 0);
const baseMeta = PICK_MODE_VIEW_META_MAP[normalizedPickMode] || {
mode_code: normalizedPickMode || 0,
mode_name: '未知模式',
require_box_allocations: false,
};
return {
mode_code: Number(baseMeta.mode_code || 0),
mode_name: String(baseMeta.mode_name || '').trim(),
require_box_allocations: Boolean(baseMeta.require_box_allocations),
};
}
/**
* 加载订单与波次映射关系。
*
* @param {Object} params 查询参数。
* @param {number} params.warehouseId 仓库ID。
* @param {Array<number>} params.orderIds 订单ID列表。
* @return {Promise<Map<number, number>>} 订单ID到wave_id映射。
*/
async loadOrderWaveMap(params = {}) {
const { ctx } = this;
const warehouseId = Number(params && params.warehouseId || 0);
const orderIds = Array.isArray(params && params.orderIds)
? params.orderIds.filter(id => Number.isInteger(id) && id > 0)
: [];
if (!Number.isInteger(warehouseId) || warehouseId <= 0 || orderIds.length === 0) {
return new Map();
}
try {
const orderModel = await this.getOrderModel(warehouseId);
const orderRows = await orderModel.findAll({
where: {
id: {
[this.app.Sequelize.Op.in]: orderIds,
},
warehouse_id: warehouseId,
},
attributes: [ 'id', 'wave_id' ],
raw: true,
});
return new Map((Array.isArray(orderRows) ? orderRows : [])
.map(row => [ Number(row && row.id || 0), Number(row && row.wave_id || 0) ])
.filter(([ orderId, waveId ]) => orderId > 0 && waveId > 0));
} catch (error) {
ctx.logger.warn(`[pick.wavePickTaskDetail] 订单wave_id查询失败,将按空映射降级: ${error.message}`);
return new Map();
}
}
/**
* 构建按拣货模式区分的拣货形态视图。
*
* @param {Object} params 构建参数。
* @param {number} params.pickMode 拣货模式。
* @param {number} params.taskId 任务ID。
* @param {number} params.warehouseId 仓库ID。
* @param {Array<Object>} params.pickingDetails 拣货明细。
* @param {Array<Object>} params.boxRows 框明细。
* @param {Array<Object>} params.taskOrderRows 任务订单关联明细。
* @param {Map<number, Object>} params.boxMapByNo 框号到框信息映射。
* @return {Promise<Object>} picking_view 结构。
*/
async buildPickingView(params = {}) {
const { ctx } = this;
const pickMode = Number(params && params.pickMode || 0);
const taskId = Number(params && params.taskId || 0);
const warehouseId = Number(params && params.warehouseId || 0);
const pickingDetails = Array.isArray(params && params.pickingDetails) ? params.pickingDetails : [];
const boxRows = Array.isArray(params && params.boxRows) ? params.boxRows : [];
const taskOrderRows = Array.isArray(params && params.taskOrderRows) ? params.taskOrderRows : [];
const boxMapByNo = params && params.boxMapByNo instanceof Map ? params.boxMapByNo : new Map();
const pickMeta = this.getPickModeViewMeta(pickMode);
const groupMap = new Map();
const buildGroupKey = detail => {
const spaceId = Number(detail && detail.space_id || 0);
const itemCode = String(detail && detail.item_code || '').trim();
const stockId = Number(detail && detail.stock_id || 0);
if (itemCode) {
return `${spaceId}::${itemCode}`;
}
return `${spaceId}::stock_${stockId}`;
};
for (const detail of pickingDetails) {
const groupKey = buildGroupKey(detail);
if (!groupMap.has(groupKey)) {
groupMap.set(groupKey, {
space_id: Number(detail && detail.space_id || 0),
space_name: String(detail && detail.space_name || '').trim(),
location_space: detail && detail.location_space ? detail.location_space : null,
item_code: String(detail && detail.item_code || '').trim(),
item_name: String(detail && detail.item_name || '').trim(),
stock_id: Number(detail && detail.stock_id || 0),
total_qty: 0,
box_allocations: [],
details: [],
});
}
const groupItem = groupMap.get(groupKey);
groupItem.total_qty += Number(detail && detail.quantity || 0);
groupItem.details.push(detail);
}
const allocationMapByGroup = new Map();
const appendAllocation = (groupKey, boxId, allocatedQty) => {
const normalizedBoxId = Number(boxId || 0);
const normalizedQty = Number(allocatedQty || 0);
if (normalizedBoxId <= 0 || normalizedQty <= 0) {
return;
}
if (!allocationMapByGroup.has(groupKey)) {
allocationMapByGroup.set(groupKey, new Map());
}
const groupAllocationMap = allocationMapByGroup.get(groupKey);
groupAllocationMap.set(
normalizedBoxId,
Number(groupAllocationMap.get(normalizedBoxId) || 0) + normalizedQty
);
};
if (pickMeta.require_box_allocations) {
if (pickMode === 4) {
const boxNosByOrderId = new Map();
for (const row of taskOrderRows) {
const orderId = Number(row && row.order_id || 0);
const boxNo = Number(row && row.box_no || 0);
if (orderId <= 0 || boxNo <= 0) {
continue;
}
if (!boxNosByOrderId.has(orderId)) {
boxNosByOrderId.set(orderId, new Set());
}
boxNosByOrderId.get(orderId).add(boxNo);
}
for (const [ groupKey, groupItem ] of groupMap) {
for (const detail of groupItem.details) {
const orderId = Number(detail && detail.order_id || 0);
const quantity = Number(detail && detail.quantity || 0);
const boxNos = boxNosByOrderId.get(orderId);
if (!boxNos || quantity <= 0) {
continue;
}
for (const boxNo of boxNos) {
const boxInfo = boxMapByNo.get(Number(boxNo || 0));
const boxId = Number(boxInfo && boxInfo.box_id || 0);
appendAllocation(groupKey, boxId, quantity);
}
}
}
} else if (pickMode === 1) {
const taskWaveRows = await ctx.model.query(`
SELECT
ptw.wave_id,
ptw.box_no
FROM wms_wave_pick_task_wave ptw
WHERE ptw.task_id = :taskId
ORDER BY ptw.id ASC
`, {
replacements: { taskId },
type: ctx.model.QueryTypes.SELECT,
});
const waveToBoxNosMap = new Map();
for (const row of Array.isArray(taskWaveRows) ? taskWaveRows : []) {
const waveId = Number(row && row.wave_id || 0);
const boxNo = Number(row && row.box_no || 0);
if (waveId <= 0 || boxNo <= 0) {
continue;
}
if (!waveToBoxNosMap.has(waveId)) {
waveToBoxNosMap.set(waveId, new Set());
}
waveToBoxNosMap.get(waveId).add(boxNo);
}
const orderIds = [ ...new Set(pickingDetails
.map(detail => Number(detail && detail.order_id || 0))
.filter(orderId => Number.isInteger(orderId) && orderId > 0)) ];
const orderWaveMap = await this.loadOrderWaveMap({
warehouseId,
orderIds,
});
for (const [ groupKey, groupItem ] of groupMap) {
for (const detail of groupItem.details) {
const orderId = Number(detail && detail.order_id || 0);
const quantity = Number(detail && detail.quantity || 0);
const waveId = Number(orderWaveMap.get(orderId) || 0);
const boxNos = waveToBoxNosMap.get(waveId);
if (!boxNos || quantity <= 0) {
continue;
}
for (const boxNo of boxNos) {
const boxInfo = boxMapByNo.get(Number(boxNo || 0));
const boxId = Number(boxInfo && boxInfo.box_id || 0);
appendAllocation(groupKey, boxId, quantity);
}
}
}
} else if (pickMode === 3) {
const boxMapByRefId = new Map();
for (const row of boxRows) {
const refId = Number(row && row.ref_id || 0);
const boxId = Number(row && row.box_id || 0);
if (refId <= 0 || boxId <= 0) {
continue;
}
if (!boxMapByRefId.has(refId)) {
boxMapByRefId.set(refId, []);
}
boxMapByRefId.get(refId).push(row);
}
for (const [ groupKey, groupItem ] of groupMap) {
const stockId = Number(groupItem && groupItem.stock_id || 0);
const targetBoxes = boxMapByRefId.get(stockId);
if (!Array.isArray(targetBoxes) || targetBoxes.length === 0) {
continue;
}
const groupQty = Number(groupItem && groupItem.total_qty || 0);
if (groupQty <= 0) {
continue;
}
for (const boxInfo of targetBoxes) {
appendAllocation(groupKey, Number(boxInfo && boxInfo.box_id || 0), groupQty);
}
}
}
}
const itemList = Array.from(groupMap.entries()).map(([ groupKey, groupItem ]) => {
const groupAllocationMap = allocationMapByGroup.get(groupKey) || new Map();
const boxAllocations = pickMeta.require_box_allocations
? Array.from(groupAllocationMap.entries())
.map(([ boxId, allocatedQty ]) => {
const boxInfo = boxRows.find(row => Number(row && row.box_id || 0) === Number(boxId || 0)) || {};
return {
box_id: Number(boxInfo && boxInfo.box_id || 0),
box_no: Number(boxInfo && boxInfo.box_no || 0),
box_type: Number(boxInfo && boxInfo.box_type || 0),
required_qty: Number(boxInfo && boxInfo.required_qty || 0),
picked_qty: Number(boxInfo && boxInfo.picked_qty || 0),
allocated_qty: Number(allocatedQty || 0),
};
})
.sort((a, b) => {
const boxNoA = Number(a && a.box_no || 0);
const boxNoB = Number(b && b.box_no || 0);
if (boxNoA !== boxNoB) {
return boxNoA - boxNoB;
}
return Number(a && a.box_id || 0) - Number(b && b.box_id || 0);
})
: [];
return {
space_id: Number(groupItem && groupItem.space_id || 0),
space_name: String(groupItem && groupItem.space_name || '').trim(),
location_space: groupItem && groupItem.location_space ? groupItem.location_space : null,
item_code: String(groupItem && groupItem.item_code || '').trim(),
item_name: String(groupItem && groupItem.item_name || '').trim(),
stock_id: Number(groupItem && groupItem.stock_id || 0),
total_qty: Number(groupItem && groupItem.total_qty || 0),
box_allocations: boxAllocations,
};
});
itemList.sort((a, b) => {
const sequenceA = Number(a && a.location_space && a.location_space.pick_sequence || 0);
const sequenceB = Number(b && b.location_space && b.location_space.pick_sequence || 0);
if (sequenceA !== sequenceB) {
return sequenceA - sequenceB;
}
const priorityA = Number(a && a.location_space && a.location_space.pick_priority || 0);
const priorityB = Number(b && b.location_space && b.location_space.pick_priority || 0);
if (priorityA !== priorityB) {
return priorityA - priorityB;
}
const spaceIdA = Number(a && a.space_id || 0);
const spaceIdB = Number(b && b.space_id || 0);
if (spaceIdA !== spaceIdB) {
return spaceIdA - spaceIdB;
}
const itemCodeA = String(a && a.item_code || '').trim();
const itemCodeB = String(b && b.item_code || '').trim();
return itemCodeA.localeCompare(itemCodeB);
});
return {
mode_code: pickMeta.mode_code,
mode_name: pickMeta.mode_name,
require_box_allocations: pickMeta.require_box_allocations,
group_by: 'space+item',
sort_by: [ 'pick_sequence', 'pick_priority', 'space_id', 'item_code' ],
items: itemList,
};
}
/**
* 解析订单所属波次信息。
*
@ -324,6 +781,216 @@ class PickSystemService extends Service {
fullDisplay,
});
}
/**
* 查询拣货任务详情。
*
* 按 task_id 查询任务主信息,并返回与拣货直接相关的框明细与拣货明细;
* 仅允许任务创建人(pick_user_id)查看。
*
* @param {Object} params 查询参数。
* @param {number} params.taskId 任务ID。
* @param {number} params.operatorId 当前操作人ID。
* @return {Promise<{task: Object, boxes: Array<Object>, picking_details: Array<Object>, picking_summary: Object, picking_view: Object}>} 任务详情。
*/
async wavePickTaskDetail(params = {}) {
const { ctx } = this;
const taskId = Number(params && params.taskId || 0);
const operatorId = Number(params && params.operatorId || 0);
if (!Number.isInteger(taskId) || taskId <= 0) {
throw this.createBusinessError('task_id 必填且必须为正整数', 400);
}
if (!Number.isInteger(operatorId) || operatorId <= 0) {
throw this.createBusinessError('未获取到操作人上下文', 401);
}
const taskRows = await ctx.model.query(`
SELECT
t.id AS task_id,
t.task_no,
t.status,
t.pick_mode,
t.pick_user_id,
t.start_time AS start_at,
t.finish_time AS finish_at,
t.batch_no,
t.warehouse_id
FROM wms_wave_pick_task t
WHERE t.id = :taskId
LIMIT 1
`, {
replacements: { taskId },
type: ctx.model.QueryTypes.SELECT,
});
const taskRow = Array.isArray(taskRows) && taskRows.length > 0 ? taskRows[0] : null;
if (!taskRow) {
throw this.createBusinessError('拣货任务不存在', 404);
}
const taskPickUserId = Number(taskRow.pick_user_id || 0);
if (!Number.isInteger(taskPickUserId) || taskPickUserId !== operatorId) {
throw this.createBusinessError('当前操作人与任务创建人不一致,无权查看', 403);
}
const warehouseId = Number(taskRow.warehouse_id || 0);
const boxColumnSet = await this.getTableColumnSet('wms_wave_pick_task_box');
const boxExtraSelect = [];
if (boxColumnSet.has('ref_label')) {
boxExtraSelect.push('b.ref_label');
}
if (boxColumnSet.has('required_qty')) {
boxExtraSelect.push('b.required_qty');
}
if (boxColumnSet.has('picked_qty')) {
boxExtraSelect.push('b.picked_qty');
}
if (boxColumnSet.has('ref_id')) {
boxExtraSelect.push('b.ref_id');
}
const [ taskOrderRows, boxRows ] = await Promise.all([
ctx.model.query(`
SELECT
pto.order_id,
pto.box_no
FROM wms_wave_pick_task_order pto
WHERE pto.task_id = :taskId
ORDER BY pto.id ASC
`, {
replacements: { taskId },
type: ctx.model.QueryTypes.SELECT,
}),
ctx.model.query(`
SELECT
b.id AS box_id,
b.box_no,
b.box_type,
b.box_status AS status${boxExtraSelect.length > 0 ? `,\n ${boxExtraSelect.join(',\n ')}` : ''}
FROM wms_wave_pick_task_box b
WHERE b.task_id = :taskId
ORDER BY b.id ASC
`, {
replacements: { taskId },
type: ctx.model.QueryTypes.SELECT,
}),
]);
const normalizedTaskOrderRows = Array.isArray(taskOrderRows) ? taskOrderRows : [];
const orderIds = [ ...new Set(normalizedTaskOrderRows
.map(row => Number(row && row.order_id || 0))
.filter(orderIdItem => Number.isInteger(orderIdItem) && orderIdItem > 0)) ];
const pickingRows = orderIds.length > 0
? await ctx.model.Picking.findAll({
where: {
order_id: {
[this.app.Sequelize.Op.in]: orderIds,
},
},
attributes: [ 'id', 'order_id', 'order_item_id', 'quantity', 'storage_id', 'space_id', 'space_name' ],
order: [[ 'id', 'ASC' ]],
raw: true,
})
: [];
const pickingSpaceIds = [ ...new Set((Array.isArray(pickingRows) ? pickingRows : [])
.map(row => Number(row && row.space_id || 0))
.filter(spaceId => Number.isInteger(spaceId) && spaceId > 0)) ];
const locationRows = pickingSpaceIds.length > 0
? await ctx.model.LocationSpace.findAll({
where: {
id: {
[this.app.Sequelize.Op.in]: pickingSpaceIds,
},
},
attributes: [ 'id', 'space_code', 'custom_name', 'custom_barcode', 'pick_sequence', 'pick_priority' ],
raw: true,
})
: [];
const locationMap = new Map((Array.isArray(locationRows) ? locationRows : [])
.map(row => [ Number(row && row.id || 0), row ]));
const orderItemIds = [ ...new Set((Array.isArray(pickingRows) ? pickingRows : [])
.map(row => Number(row && row.order_item_id || 0))
.filter(orderItemId => Number.isInteger(orderItemId) && orderItemId > 0)) ];
const orderItemMap = await this.loadOrderItemMap({
warehouseId,
orderItemIds,
});
const normalizedBoxRows = Array.isArray(boxRows) ? boxRows : [];
const boxMapByNo = new Map(normalizedBoxRows
.map(row => [ Number(row && row.box_no || 0), row ])
.filter(([ boxNo ]) => boxNo > 0));
const pickingDetails = (Array.isArray(pickingRows) ? pickingRows : []).map(row => {
const orderItemId = Number(row && row.order_item_id || 0);
const currentSpaceId = Number(row && row.space_id || 0);
const locationRow = locationMap.get(currentSpaceId) || {};
const orderItemRow = orderItemMap.get(orderItemId) || {};
return {
order_id: Number(row && row.order_id || 0),
order_item_id: orderItemId,
quantity: Number(row && row.quantity || 0),
storage_id: Number(row && row.storage_id || 0),
space_id: currentSpaceId,
space_name: String(row && row.space_name || '').trim(),
location_space: {
space_code: String(locationRow.space_code || '').trim(),
custom_name: String(locationRow.custom_name || '').trim(),
custom_barcode: String(locationRow.custom_barcode || '').trim(),
pick_sequence: Number(locationRow.pick_sequence || 0),
pick_priority: Number(locationRow.pick_priority || 0),
},
item_code: String(orderItemRow.item_code || '').trim(),
item_name: String(orderItemRow.item_name || '').trim(),
stock_id: Number(orderItemRow.stock_id || 0),
plan_qty: Number(orderItemRow.plan_qty || 0),
item_snapshot: orderItemRow.item_snapshot || null,
};
});
const pickingSummary = this.buildPickingSummary(pickingDetails);
const pickMode = Number(taskRow.pick_mode || 0);
const pickingView = await this.buildPickingView({
pickMode,
taskId,
warehouseId,
pickingDetails,
boxRows: normalizedBoxRows,
taskOrderRows: normalizedTaskOrderRows,
boxMapByNo,
});
return {
task: {
task_id: Number(taskRow.task_id || 0),
task_no: String(taskRow.task_no || '').trim(),
status: Number(taskRow.status || 0),
pick_mode: pickMode,
start_at: taskRow.start_at || null,
finish_at: taskRow.finish_at || null,
batch_no: String(taskRow.batch_no || '').trim(),
},
boxes: normalizedBoxRows.map(row => ({
box_id: Number(row && row.box_id || 0),
box_no: Number(row && row.box_no || 0),
box_type: Number(row && row.box_type || 0),
status: Number(row && row.status || 0),
ref_id: Number(row && row.ref_id || 0),
ref_label: String(row && row.ref_label || '').trim() || null,
required_qty: Number(row && row.required_qty || 0),
picked_qty: Number(row && row.picked_qty || 0),
})),
picking_details: pickingDetails,
picking_summary: pickingSummary,
picking_view: pickingView,
};
}
}
module.exports = PickSystemService;

View File

@ -2,6 +2,9 @@
const { Service } = require('egg');
const INTERNAL_WAVE_STRATEGY_VERSION_KEY = 'wave_strategy_version';
const DEFAULT_WAVE_STRATEGY_VERSION = 1;
// 仓库设置字段元信息(对应 wms_store.subject_config)
const WAREHOUSE_SETTING_FIELDS = Object.freeze([
Object.freeze({
@ -61,11 +64,11 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([
}),
Object.freeze({
key: 'delete_order_wave_prefix',
name: '删单波次前缀',
name: '散单波次前缀',
type: 'string',
default: 'A',
required: false,
description: '删单波次编号前缀,最多 5 个字符,默认 A',
description: '散单波次编号前缀,最多 5 个字符,默认 A',
maxLength: 5,
}),
Object.freeze({
@ -88,9 +91,151 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([
Object.freeze({ value: 'async', label: '异步回调' }),
],
}),
Object.freeze({
key: INTERNAL_WAVE_STRATEGY_VERSION_KEY,
name: '仓库波次策略版本号',
type: 'integer',
default: DEFAULT_WAVE_STRATEGY_VERSION,
required: false,
description: '内部字段:仓库波次策略版本号',
min: 0,
hidden: true,
internal: true,
}),
]);
class SettingWarehouseService extends Service {
/**
* 读取默认快递与平台编码选项,查询失败时自动降级为空列表。
*
* @return {Promise<Object>} 返回字段 key 到 options 的映射。
*/
async getDefaultCodeFieldOptionsMap() {
const modelContainer = this.ctx && this.ctx.model ? this.ctx.model : (this.app && this.app.model ? this.app.model : {});
const expressModel = modelContainer && modelContainer.Express;
const platformModel = modelContainer && modelContainer.Platform;
const fetchOptions = async model => {
if (!model || typeof model.findAll !== 'function') {
return [];
}
try {
const rows = await model.findAll({
attributes: [ 'code', 'name' ],
order: [[ 'code', 'ASC' ]],
});
if (!Array.isArray(rows)) {
return [];
}
return rows
.map(item => {
const code = item && item.code !== undefined && item.code !== null ? String(item.code) : '';
if (!code) {
return null;
}
const name = item && item.name !== undefined && item.name !== null ? String(item.name) : '';
return {
value: code,
label: name || code,
};
})
.filter(Boolean);
} catch (_error) {
return [];
}
};
const [ expressOptions, platformOptions ] = await Promise.all([
fetchOptions(expressModel),
fetchOptions(platformModel),
]);
return {
default_express_code: expressOptions,
default_platform_code: platformOptions,
};
}
/**
* 规范化仓库波次策略版本号,返回数字。
*
* @param {number|string|null|undefined} value 原始版本号。
* @param {Object} [options={}] 额外选项。
* @param {boolean} [options.useDefaultWhenEmpty=false] 空值时是否使用默认值。
* @return {number} 规范化后的版本号数字。
* @throws {Error} 输入不合法时抛出,状态码 400。
*/
normalizeWaveStrategyVersion(value, options = {}) {
const { useDefaultWhenEmpty = false } = options;
if (value === undefined || value === null || value === '') {
if (useDefaultWhenEmpty) {
return DEFAULT_WAVE_STRATEGY_VERSION;
}
throw this.createError('subject_config.wave_strategy_version 必须是数字或数字字符串', 400);
}
if (typeof value === 'number') {
if (!Number.isSafeInteger(value) || value < 0) {
throw this.createError('subject_config.wave_strategy_version 必须是非负整数', 400);
}
return value;
}
if (typeof value === 'string') {
const trimmed = value.trim();
if (!/^\d+$/.test(trimmed)) {
throw this.createError('subject_config.wave_strategy_version 必须是数字或数字字符串', 400);
}
const numericVersion = Number(trimmed);
if (!Number.isSafeInteger(numericVersion)) {
throw this.createError('subject_config.wave_strategy_version 超出安全整数范围', 400);
}
return numericVersion;
}
throw this.createError('subject_config.wave_strategy_version 必须是数字或数字字符串', 400);
}
/**
* 规范化 subject_config 内部字段,确保内部字段落库时为数字。
*
* @param {Object} subjectConfig 原始配置对象。
* @return {Object} 规范化后的配置对象。
*/
normalizeSubjectConfigInternalFields(subjectConfig) {
const nextConfig = {
...(subjectConfig && typeof subjectConfig === 'object' && !Array.isArray(subjectConfig) ? subjectConfig : {}),
};
nextConfig[INTERNAL_WAVE_STRATEGY_VERSION_KEY] = this.normalizeWaveStrategyVersion(
nextConfig[INTERNAL_WAVE_STRATEGY_VERSION_KEY],
{ useDefaultWhenEmpty: true }
);
return nextConfig;
}
/**
* 对外响应时移除内部字段,避免暴露内部配置。
*
* @param {Object} subjectConfig 配置对象。
* @return {Object} 过滤后的配置对象。
*/
sanitizeSubjectConfigForOutput(subjectConfig) {
const nextConfig = {
...(subjectConfig && typeof subjectConfig === 'object' && !Array.isArray(subjectConfig) ? subjectConfig : {}),
};
delete nextConfig[INTERNAL_WAVE_STRATEGY_VERSION_KEY];
return nextConfig;
}
createError(message, code = 500) {
const error = new Error(message);
error.code = code;
@ -155,21 +300,31 @@ class SettingWarehouseService extends Service {
/**
* 获取仓库设置字段元信息列表。
*
* @return {Array} 字段元信息数组(浅拷贝,含 options 拷贝)。
* @return {Promise<Array>} 字段元信息数组(浅拷贝,含 options 拷贝)。
*/
getFieldMeta() {
return WAREHOUSE_SETTING_FIELDS.map(field => ({
key: field.key,
name: field.name,
type: field.type,
default: field.default,
required: field.required,
description: field.description,
...(Array.isArray(field.options) ? { options: field.options.map(o => ({ ...o })) } : {}),
...(field.min !== undefined ? { min: field.min } : {}),
...(field.max !== undefined ? { max: field.max } : {}),
...(field.maxLength !== undefined ? { maxLength: field.maxLength } : {}),
}));
async getFieldMeta() {
const dynamicOptionsMap = await this.getDefaultCodeFieldOptionsMap();
return WAREHOUSE_SETTING_FIELDS
.filter(field => !field.internal && field.key !== INTERNAL_WAVE_STRATEGY_VERSION_KEY)
.map(field => ({
key: field.key,
name: field.name,
type: field.type,
default: field.default,
required: field.required,
description: field.description,
...((Array.isArray(field.options) || Object.prototype.hasOwnProperty.call(dynamicOptionsMap, field.key))
? {
options: (Array.isArray(field.options) ? field.options.map(o => ({ ...o })) : (dynamicOptionsMap[field.key] || [])).map(o => ({ ...o })),
}
: {}),
...(field.min !== undefined ? { min: field.min } : {}),
...(field.max !== undefined ? { max: field.max } : {}),
...(field.maxLength !== undefined ? { maxLength: field.maxLength } : {}),
...(field.hidden !== undefined ? { hidden: field.hidden } : {}),
...(field.internal !== undefined ? { internal: field.internal } : {}),
}));
}
/**
@ -189,9 +344,11 @@ class SettingWarehouseService extends Service {
throw this.createError('仓库不存在', 404);
}
const normalizedSubjectConfig = this.normalizeSubjectConfigInternalFields(store.subject_config);
return {
warehouse_id: warehouseId,
subject_config: store.subject_config,
subject_config: this.sanitizeSubjectConfigForOutput(normalizedSubjectConfig),
};
}
@ -224,16 +381,23 @@ class SettingWarehouseService extends Service {
throw this.createError('subject_config 参数不能为空且必须是对象', 400);
}
const mergedConfig = {
...(store.subject_config && typeof store.subject_config === 'object' ? store.subject_config : {}),
const nextPatchForMerge = {
...nextPatch,
};
delete nextPatchForMerge[INTERNAL_WAVE_STRATEGY_VERSION_KEY];
const mergedConfig = {
...(store.subject_config && typeof store.subject_config === 'object' ? store.subject_config : {}),
...nextPatchForMerge,
};
const mergedConfigWithInternalDefaults = this.normalizeSubjectConfigInternalFields(mergedConfig);
let normalizedConfig;
try {
normalizedConfig = typeof storeModel.normalizeSubjectConfig === 'function'
? storeModel.normalizeSubjectConfig(mergedConfig)
: mergedConfig;
? storeModel.normalizeSubjectConfig(mergedConfigWithInternalDefaults)
: mergedConfigWithInternalDefaults;
} catch (error) {
throw this.createError(error.message || 'subject_config 参数不合法', Number(error.code) || 400);
}
@ -248,7 +412,7 @@ class SettingWarehouseService extends Service {
return {
warehouse_id: warehouseId,
subject_config: store.subject_config,
subject_config: this.sanitizeSubjectConfigForOutput(store.subject_config),
cache_cleared_warehouse_id: cacheWarehouseId,
};
}

View File

@ -69,7 +69,22 @@ if (process.env.DB_HOST) {
const localConfig = isProduction ? {} : loadEggConfig(path.join(projectRoot, 'config', 'config.local.js'));
const appConfig = mergeDeep(defaultConfig, localConfig);
const clientName = process.env.SEQUELIZE_DB_CLIENT || 'wms';
mysqlClient = resolveMysqlClient(appConfig, clientName);
if (isProduction) {
const sequelizeConfig = appConfig && appConfig.sequelize;
if (sequelizeConfig && sequelizeConfig.host) {
mysqlClient = {
host: sequelizeConfig.host,
port: sequelizeConfig.port || 3306,
user: sequelizeConfig.username || sequelizeConfig.user,
password: sequelizeConfig.password,
database: sequelizeConfig.database || 'wms',
};
} else {
mysqlClient = resolveMysqlClient(appConfig, clientName);
}
} else {
mysqlClient = resolveMysqlClient(appConfig, clientName);
}
}
const baseConfig = {

View File

@ -1,5 +1,28 @@
'use strict';
/**
* 打印迁移阶段对应的数据库连接上下文信息。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {'up'|'down'} phase 迁移阶段。
* @param {string} table 迁移目标表名。
* @return {Promise<void>} 无返回值。
*/
const logMigrationDbContext = async (queryInterface, phase, table) => {
try {
const [ rows ] = await queryInterface.sequelize.query(
'SELECT DATABASE() AS db_name, @@hostname AS db_host, @@port AS db_port, CURRENT_USER() AS db_user'
);
const dbContext = Array.isArray(rows) && rows.length > 0 ? rows[0] : {};
console.log(
`[Migration DB Context] phase=${phase}; table=${table}; db_name=${dbContext.db_name || 'unknown'}; db_host=${dbContext.db_host || 'unknown'}; db_port=${dbContext.db_port || 'unknown'}; db_user=${dbContext.db_user || 'unknown'}`
);
} catch (error) {
console.warn(
`[Migration DB Context] 获取连接信息失败: phase=${phase}; table=${table}; reason=${error.message}`
);
}
};
/**
* Migration: add box_remainder and box_weight to wms_receiving_detail
* - box_remainder: INT NOT NULL DEFAULT 0 COMMENT '箱余数'
@ -16,8 +39,15 @@
*/
module.exports = {
/**
* 执行正向迁移,按需新增收货明细箱字段。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {import('sequelize')} Sequelize Sequelize 实例。
* @return {Promise<void>} 无返回值。
*/
up: async (queryInterface, Sequelize) => {
const table = 'wms_receiving_detail';
await logMigrationDbContext(queryInterface, 'up', table);
const columns = await queryInterface.describeTable(table);
if (!columns.box_remainder) {
@ -39,8 +69,15 @@ module.exports = {
}
},
/**
* 执行回滚迁移,按需删除收货明细箱字段。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {import('sequelize')} Sequelize Sequelize 实例。
* @return {Promise<void>} 无返回值。
*/
down: async (queryInterface, Sequelize) => {
const table = 'wms_receiving_detail';
await logMigrationDbContext(queryInterface, 'down', table);
const columns = await queryInterface.describeTable(table);
if (columns.box_remainder) {

View File

@ -0,0 +1,37 @@
'use strict';
/**
* 将拣货策略表重命名为波次策略表。
* 幂等处理:仅在源表存在且目标表不存在时执行重命名。
*/
module.exports = {
/**
* 升级迁移:wms_picking_strategy -> wms_wave_strategy。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
*/
up: async queryInterface => {
const sourceTable = 'wms_picking_strategy';
const targetTable = 'wms_wave_strategy';
const allTables = await queryInterface.showAllTables();
const tableNames = new Set(allTables.map(table => (typeof table === 'string' ? table : table.tableName)));
if (tableNames.has(sourceTable) && !tableNames.has(targetTable)) {
await queryInterface.renameTable(sourceTable, targetTable);
}
},
/**
* 回滚迁移:wms_wave_strategy -> wms_picking_strategy。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
*/
down: async queryInterface => {
const sourceTable = 'wms_wave_strategy';
const targetTable = 'wms_picking_strategy';
const allTables = await queryInterface.showAllTables();
const tableNames = new Set(allTables.map(table => (typeof table === 'string' ? table : table.tableName)));
if (tableNames.has(sourceTable) && !tableNames.has(targetTable)) {
await queryInterface.renameTable(sourceTable, targetTable);
}
},
};

View File

@ -0,0 +1,70 @@
'use strict';
/**
* Migration: 创建 wms_order_wave_strategy_match 表
*
* 记录每个订单命中的全部波次策略 ID,作为快速扫描结果的副表存储。
* 不与分仓主表做物理外键,靠应用层逻辑维护一致性。
*
* 索引:
* idx_warehouse_order (warehouse_id, order_id) — 按订单删除/查询
* idx_warehouse_strategy (warehouse_id, strategy_id) — 按策略聚合统计
*/
module.exports = {
up: async (queryInterface, Sequelize) => {
const tableExists = await queryInterface.showAllTables()
.then(tables => tables.includes('wms_order_wave_strategy_match'));
if (tableExists) {
return;
}
await queryInterface.createTable('wms_order_wave_strategy_match', {
id: {
type: Sequelize.BIGINT,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键',
},
warehouse_id: {
type: Sequelize.INTEGER(10),
allowNull: false,
comment: '仓库ID',
},
order_id: {
type: Sequelize.BIGINT,
allowNull: false,
comment: '订单ID,逻辑关联分仓主表,不做物理外键',
},
strategy_id: {
type: Sequelize.INTEGER(10),
allowNull: false,
comment: '命中的波次策略ID',
},
create_time: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '写入时间',
},
}, {
charset: 'utf8mb4',
collate: 'utf8mb4_unicode_ci',
comment: '订单波次策略命中明细表',
});
await queryInterface.addIndex('wms_order_wave_strategy_match', [ 'warehouse_id', 'order_id' ], {
name: 'idx_warehouse_order',
});
await queryInterface.addIndex('wms_order_wave_strategy_match', [ 'warehouse_id', 'strategy_id' ], {
name: 'idx_warehouse_strategy',
});
},
down: async queryInterface => {
await queryInterface.dropTable('wms_order_wave_strategy_match');
},
};

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,56 @@
'use strict';
/**
* 获取表字段定义。
*
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {string} tableName 表名。
* @return {Promise<Object>} 字段定义对象。
*/
const getTableColumns = async (queryInterface, tableName) => {
return queryInterface.describeTable(tableName);
};
module.exports = {
/**
* 正向迁移:为波次表新增 source 字段。
*
* 字段语义:0-普通波次 1-管理后台策略任务 2-PDA策略任务
*
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
up: async queryInterface => {
const tableName = 'wms_wave_batch';
const columnsBefore = await getTableColumns(queryInterface, tableName);
if (!columnsBefore.source) {
await queryInterface.sequelize.query(`
ALTER TABLE wms_wave_batch
ADD COLUMN source TINYINT NOT NULL DEFAULT 0
COMMENT '来源:0-普通波次 1-管理后台策略任务 2-PDA策略任务'
AFTER update_time
`);
}
const columnsAfter = await getTableColumns(queryInterface, tableName);
if (!columnsAfter.source) {
throw new Error('迁移失败:wms_wave_batch.source 字段不存在');
}
},
/**
* 回滚迁移:删除波次表 source 字段。
*
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
down: async queryInterface => {
const tableName = 'wms_wave_batch';
const columnsBefore = await getTableColumns(queryInterface, tableName);
if (columnsBefore.source) {
await queryInterface.removeColumn(tableName, 'source');
}
},
};

View File

@ -0,0 +1,50 @@
'use strict';
/**
* 获取表字段定义。
*
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {string} tableName 表名。
* @return {Promise<Object>} 字段定义对象。
*/
const getTableColumns = async (queryInterface, tableName) => {
return queryInterface.describeTable(tableName);
};
module.exports = {
/**
* 正向迁移:为拣货任务表补充 source 字段。
*
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。
* @return {Promise<void>} 无返回值。
*/
up: async (queryInterface, Sequelize) => {
const tableName = 'wms_wave_pick_task';
const columnsBefore = await getTableColumns(queryInterface, tableName);
if (!columnsBefore.source) {
await queryInterface.addColumn(tableName, 'source', {
type: Sequelize.TINYINT,
allowNull: false,
defaultValue: 1,
comment: '任务来源:1-PDA 2-后台',
});
}
},
/**
* 回滚迁移:若 source 字段存在则删除。
*
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
down: async queryInterface => {
const tableName = 'wms_wave_pick_task';
const columnsBefore = await getTableColumns(queryInterface, tableName);
if (columnsBefore.source) {
await queryInterface.removeColumn(tableName, 'source');
}
},
};

View File

@ -0,0 +1,349 @@
'use strict';
/**
* 获取表字段定义。
*
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {string} tableName 表名。
* @return {Promise<Object>} 字段定义对象。
*/
const getTableColumns = async (queryInterface, tableName) => {
return queryInterface.describeTable(tableName);
};
/**
* 返回需要补齐的字段定义映射。
*
* @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。
* @return {Record<string, Record<string, object>>} 表字段映射。
*/
const getRepairColumnDefinitions = Sequelize => ({
wms_wave_pick_task: {
wave_count: {
type: Sequelize.INTEGER,
allowNull: false,
defaultValue: 0,
comment: '波次数量',
},
order_count: {
type: Sequelize.INTEGER,
allowNull: false,
defaultValue: 0,
comment: '订单数量',
},
box_count: {
type: Sequelize.INTEGER,
allowNull: false,
defaultValue: 0,
comment: '框数量',
},
batch_no: {
type: Sequelize.STRING(64),
allowNull: true,
comment: '领单批次号',
},
pick_user_name: {
type: Sequelize.STRING(64),
allowNull: true,
comment: '拣货员名称',
},
review_user_name: {
type: Sequelize.STRING(64),
allowNull: true,
comment: '复核员名称',
},
current_cart_id: {
type: Sequelize.BIGINT,
allowNull: true,
comment: '当前绑定拣货车ID',
},
current_cart_code_snapshot: {
type: Sequelize.STRING(64),
allowNull: true,
comment: '当前绑定车码快照',
},
review_status: {
type: Sequelize.TINYINT,
allowNull: false,
defaultValue: 0,
comment: '复核状态:0-未就绪 1-待复核 2-复核中 3-复核通过 4-复核异常',
},
review_version: {
type: Sequelize.INTEGER,
allowNull: false,
defaultValue: 0,
comment: '复核并发版本号',
},
review_start_time: {
type: Sequelize.DATE,
allowNull: true,
comment: '复核开始时间',
},
review_finish_time: {
type: Sequelize.DATE,
allowNull: true,
comment: '复核结束时间',
},
review_result: {
type: Sequelize.TINYINT,
allowNull: true,
comment: '复核结果:1-通过 2-异常',
},
review_remark: {
type: Sequelize.STRING(255),
allowNull: true,
comment: '复核备注',
},
device_id: {
type: Sequelize.STRING(64),
allowNull: true,
comment: '设备ID',
},
expire_time: {
type: Sequelize.DATE,
allowNull: true,
comment: '任务过期时间',
},
transfer_from_task_id: {
type: Sequelize.BIGINT,
allowNull: true,
comment: '转移来源任务ID',
},
transfer_to_task_id: {
type: Sequelize.BIGINT,
allowNull: true,
comment: '转移目标任务ID',
},
},
wms_wave_pick_task_wave: {
wave_no: {
type: Sequelize.STRING(64),
allowNull: true,
comment: '波次号',
},
box_no: {
type: Sequelize.INTEGER,
allowNull: true,
comment: '框号',
},
status: {
type: Sequelize.TINYINT,
allowNull: false,
defaultValue: 0,
comment: '波次状态:0-待拣 1-已拣 2-异常',
},
bind_time: {
type: Sequelize.DATE,
allowNull: true,
comment: '绑定时间',
},
pick_time: {
type: Sequelize.DATE,
allowNull: true,
comment: '拣货完成时间',
},
},
wms_wave_pick_task_order: {
order_no: {
type: Sequelize.STRING(64),
allowNull: true,
comment: '订单号',
},
box_no: {
type: Sequelize.INTEGER,
allowNull: true,
comment: '框号',
},
cart_id: {
type: Sequelize.BIGINT,
allowNull: true,
comment: '拣货车ID',
},
cart_code_snapshot: {
type: Sequelize.STRING(64),
allowNull: true,
comment: '拣货车码快照',
},
review_user_id: {
type: Sequelize.BIGINT,
allowNull: true,
comment: '复核员ID',
},
review_result: {
type: Sequelize.TINYINT,
allowNull: true,
comment: '复核结果:1-通过 2-异常',
},
review_remark: {
type: Sequelize.STRING(255),
allowNull: true,
comment: '复核备注',
},
exception_reason: {
type: Sequelize.STRING(255),
allowNull: true,
comment: '异常原因',
},
},
wms_wave_pick_task_box: {
box_no: {
type: Sequelize.INTEGER,
allowNull: true,
comment: '框号',
},
box_type: {
type: Sequelize.TINYINT,
allowNull: true,
comment: '框类型:1-SKU框 2-订单框 3-波次框',
},
ref_id: {
type: Sequelize.BIGINT,
allowNull: true,
comment: '关联ID(SKU或订单或波次)',
},
ref_label: {
type: Sequelize.STRING(128),
allowNull: true,
comment: '关联展示标签',
},
required_qty: {
type: Sequelize.INTEGER,
allowNull: false,
defaultValue: 0,
comment: '应放数量',
},
picked_qty: {
type: Sequelize.INTEGER,
allowNull: false,
defaultValue: 0,
comment: '已放数量',
},
},
wms_pick_cart: {
last_seen_time: {
type: Sequelize.DATE,
allowNull: true,
comment: '最近扫码时间',
},
},
wms_pick_task_cart_binding: {
cart_code_snapshot: {
type: Sequelize.STRING(64),
allowNull: true,
comment: '车码快照',
},
bind_type: {
type: Sequelize.TINYINT,
allowNull: false,
defaultValue: 1,
comment: '绑定类型:1-领单绑定 2-换车绑定 3-管理员改绑',
},
},
wms_order_pick_trace: {
cart_id: {
type: Sequelize.BIGINT,
allowNull: true,
comment: '拣货车ID',
},
cart_code_snapshot: {
type: Sequelize.STRING(64),
allowNull: true,
comment: '拣货车码快照',
},
pick_user_id: {
type: Sequelize.BIGINT,
allowNull: true,
comment: '拣货员ID',
},
pick_time: {
type: Sequelize.DATE,
allowNull: true,
comment: '拣货时间',
},
review_user_id: {
type: Sequelize.BIGINT,
allowNull: true,
comment: '复核员ID',
},
review_time: {
type: Sequelize.DATE,
allowNull: true,
comment: '复核时间',
},
review_result: {
type: Sequelize.TINYINT,
allowNull: true,
comment: '复核结果:1-通过 2-异常',
},
},
});
/**
* 按字段映射执行幂等新增列。
*
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {Record<string, Record<string, object>>} repairColumnDefinitions 表字段映射。
* @return {Promise<void>} 无返回值。
*/
const addMissingColumns = async (queryInterface, repairColumnDefinitions) => {
const tableNames = Object.keys(repairColumnDefinitions);
for (const tableName of tableNames) {
const columnsBefore = await getTableColumns(queryInterface, tableName);
const columnEntries = Object.entries(repairColumnDefinitions[tableName]);
for (const [ columnName, columnDefinition ] of columnEntries) {
if (!columnsBefore[columnName]) {
await queryInterface.addColumn(tableName, columnName, columnDefinition);
}
}
}
};
/**
* 按字段映射执行幂等删除列。
*
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {Record<string, Record<string, object>>} repairColumnDefinitions 表字段映射。
* @return {Promise<void>} 无返回值。
*/
const removeExistingColumns = async (queryInterface, repairColumnDefinitions) => {
const tableNames = Object.keys(repairColumnDefinitions);
for (const tableName of tableNames) {
const columnsBefore = await getTableColumns(queryInterface, tableName);
const columnEntries = Object.keys(repairColumnDefinitions[tableName]);
for (const columnName of columnEntries) {
if (columnsBefore[columnName]) {
await queryInterface.removeColumn(tableName, columnName);
}
}
}
};
module.exports = {
/**
* 正向迁移:修复拣货任务相关表的字段漂移问题。
*
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。
* @return {Promise<void>} 无返回值。
*/
up: async (queryInterface, Sequelize) => {
const repairColumnDefinitions = getRepairColumnDefinitions(Sequelize);
await addMissingColumns(queryInterface, repairColumnDefinitions);
},
/**
* 回滚迁移:回退本迁移新增的字段(仅在字段存在时删除)。
*
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。
* @return {Promise<void>} 无返回值。
*/
down: async (queryInterface, Sequelize) => {
const repairColumnDefinitions = getRepairColumnDefinitions(Sequelize);
await removeExistingColumns(queryInterface, repairColumnDefinitions);
},
};

View File

@ -0,0 +1,16 @@
[
{
"version": "2026.05.08-system-06",
"date": "2026-05-08",
"summary": "新增取消拣货任务接口:order.wave.wavePickTaskCancel",
"methods": [
"order.wave.wavePickTaskCancel"
],
"notes": [
"接口功能:取消拣货任务,同时释放关联波次(物理删除波次记录,订单回池)、解绑拣货车、写操作日志。",
"限制:仅允许在任务状态为 0(待开始)、1(拣货中)、2(待复核)时取消;状态为 3(已完成)或 9(已取消)时禁止取消,返回 400。",
"事务内操作:将任务状态更新为 9(已取消)、删除关联波次、清空订单 wave_id(回池)、解绑拣货车、写入 action_log 与 order_pick_trace;若有任一步骤失败则回滚并返回 500。"
],
"type": "added"
}
]

View File

@ -1,4 +1,250 @@
[
{
"version": "2026.05.10-system-04",
"date": "2026-05-10",
"summary": "pick.wavePickTaskDetail 新增按任务类型区分的 picking_view 形态输出",
"methods": [
"pick.wavePickTaskDetail"
],
"notes": [
"新增响应字段:picking_view(object),按 task.pick_mode 区分 5 种形态输出。",
"picking_view 字段说明:mode_code, mode_name, require_box_allocations, group_by, sort_by, items[](每项含 space_id、space_name、location_space、item_code、item_name、stock_id、total_qty、box_allocations[])。",
"当 pick_mode=1/3/4 时 require_box_allocations=true;当 pick_mode=2/5 时 require_box_allocations=false。"
],
"type": "updated"
},
{
"version": "2026.05.10-system-02",
"date": "2026-05-10",
"summary": "order.wave.waveStrategyFetchPda/Admin 返回新增 fetch_state 三态与简短 tip",
"methods": [
"order.wave.waveStrategyFetchPda",
"order.wave.waveStrategyFetchAdmin"
],
"notes": [
"新增返回字段:fetch_state(number)、tip(string)、can_enter_pick_flow(boolean)",
"fetch_state 含义:1=创建成功(返回 task_id/task_no),2=普通失败(task_id=null),3=存在未完成任务(返回 existing task_id/task_no,前端可直接进入拣货流程)",
"当 fetch_state=3 时,字段 can_enter_pick_flow=true,表示前端可直接进入拣货流程;tip 为简短提示文本"
],
"type": "updated"
},
{
"version": "2026.05.10-system-03",
"date": "2026-05-10",
"summary": "裁剪 pick.wavePickTaskDetail 返回:移除 waves/orders,精简 task 并补充 boxes 拣货统计字段",
"methods": [
"pick.wavePickTaskDetail"
],
"notes": [
"移除响应中的 waves 与 orders 子表,接口仅返回精简的 task、boxes、picking_details 与 picking_summary。",
"task 子字段裁剪为:task_id, task_no, status, pick_mode, start_at, finish_at, batch_no。",
"boxes 补充并明确返回:ref_label(箱参考标签)、required_qty(箱内需拣总数)、picked_qty(已拣数量)。",
"本次变更为文档层面的返回裁剪,前端应以新字段集合为准,旧字段可能不再返回。"
],
"type": "updated"
},
{
"version": "2026.05.10-system-01",
"date": "2026-05-10",
"summary": "order.wave.waveStrategyList 新增 strategy_type 最小过滤(散单/团购)",
"methods": [
"order.wave.waveStrategyList"
],
"notes": [
"新增 strategy_type 过滤,仅 1/2",
"支持顶层 strategy_type 和 where.strategy_type,顶层优先",
"当前不引入其他 where 字段"
],
"type": "updated"
},
{
"version": "2026.05.09-system-02",
"date": "2026-05-09",
"summary": "新增 pick.wavePickTaskDetail:按任务ID解析拣货任务详情",
"methods": [
"pick.wavePickTaskDetail"
],
"notes": [
"新增 pick.wavePickTaskDetail:传入 task_id 获取拣货任务完整信息,包含主表字段(task/pick_mode/status/wave_count/order_count/box_count 等)及三张子表数据(waves/orders/boxes)。",
"安全限制:接口会校验当前登录用户(operator_id/employees_id)与任务的 pick_user_id 是否一致;不一致时直接返回 403,不返回任何拣货信息。",
"鉴权配置:noNeedRight=true,noNeedAuth=true,isNeedLogin=true。"
],
"type": "added"
},
{
"version": "2026.05.08-system-05",
"date": "2026-05-08",
"summary": "order.wave.batchList:新增 source 字段并支持 where.source 过滤,返回 list item 中新增 source 字段",
"methods": [
"order.wave.batchList"
],
"notes": [
"新增 where.source(可选,number)用于按来源过滤:0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务;不传则不过滤。",
"响应 list 每条记录新增字段 source(number),用于区分波次来源。",
"仅更新文档,业务代码不在此变更范围。"
],
"type": "updated"
},
{
"version": "2026.05.08-system-04",
"date": "2026-05-08",
"summary": "完善 order.wave.wavePickTaskList 文档:补充入参、分页与返回字段兼容说明",
"methods": [
"order.wave.wavePickTaskList",
"order.wave.wavePickTaskCancel"
],
"notes": [
"入参补充:warehouse_id(必填)、status(支持单值或数组,建议传数组)、source、keyword、page_no、page_size;保留 pagination 对象以兼容旧客户端。",
"兼容说明:接口同时支持历史 where 结构与顶层参数;当存在同名顶层参数时以顶层参数优先;pagination 支持 page/current 与 pageSize/size 别名。",
"返回格式:响应包含 total 与 list;list 每项包含字段:task_id、task_no、status、source、pick_mode、wave_count、order_count、box_count、operator_id、operator_name、start_at、finish_at、created_at。为兼容旧客户端,响应同时保留旧字段:pick_user_id、pick_user_name、start_time、finish_time、create_time。",
"入参 strategy_id 当前主表未存,接口会忽略该过滤,不建议使用。",
"默认排序:create_time desc.",
"文档变更:移除 order.wave.wavePickTaskCancel 的入参 operator_id 与 warehouse_id;入参改为仅支持 task_ids(数组,必填),不再兼容单个 task_id;操作人与仓库由请求上下文(例如当前登录用户上下文)自动获取;若上下文缺失接口将返回错误。响应补充批量结果字段:cancelled_count、task_ids、task_nos(若后端返回)。仅更新文档,未修改业务实现。"
],
"type": "updated"
},
{
"version": "2026.05.08-system-03",
"date": "2026-05-08",
"summary": "升级按策略抓取接口为创建任务主流程:order.wave.waveStrategyFetchPda / order.wave.waveStrategyFetchAdmin",
"methods": [
"order.wave.waveStrategyFetchPda",
"order.wave.waveStrategyFetchAdmin"
],
"notes": [
"将 PDA/Admin 场景的按策略抓取接口由受理壳方法升级为 '创建任务主流程':接口会执行参数校验并在同步响应中创建任务记录(state=created),返回 task_id、task_no、plan 与 plan_summary 供前端展示与后续查询。",
"入参新增/扩展与创建流程相关字段:至少包含 cart_id(关联拣货车/作业车ID)、source(操作来源语义)并保留并透传 strategy_id 与 strategy_params(策略参数),以支持在创建阶段对策略进行局部覆盖或透传。",
"成功返回示例字段:state=created、task_id、task_no、plan(对象)和 plan_summary(字符串);失败场景会返回 validation_errors(数组,每项含 field/message)或 message 描述创建失败原因。",
"边界说明:当前为最小主流程(创建与计划预览),后续扫描/任务执行阶段(如实际抓取订单、写入 wave 等)将在后续版本中追加与完善。"
],
"type": "updated"
},
{
"version": "2026.05.08-system-02",
"date": "2026-05-08",
"summary": "调整按策略抓取壳方法:order.wave.waveStrategyFetch 更名为 order.wave.waveStrategyFetchPda,并新增 order.wave.waveStrategyFetchAdmin",
"methods": [
"order.wave.waveStrategyFetch",
"order.wave.waveStrategyFetchPda",
"order.wave.waveStrategyFetchAdmin"
],
"notes": [
"waveStrategyFetchPda 仅用于 PDA 场景",
"waveStrategyFetchAdmin 仅用于后台管理场景",
"两者当前均为壳子受理方法,不执行真实抓取"
],
"type": "updated"
},
{
"version": "2026.05.08-system-01",
"date": "2026-05-08",
"summary": "新增 order.wave.waveStrategyFetch:按策略提交抓取任务(壳子方法)",
"methods": [
"order.wave.waveStrategyFetch"
],
"notes": [
"当前方法为壳子方法:仅受理并返回任务受理信息,不执行真实抓取逻辑,后续补齐执行链路。"
],
"type": "added"
},
{
"version": "2026.05.07-system-05",
"date": "2026-05-07",
"summary": "新增 order.wave.waveStrategyCreate 与 order.wave.waveStrategyUpdate:波次策略创建与更新接口(含参数校验与版本推进)",
"methods": [
"order.wave.waveStrategyCreate",
"order.wave.waveStrategyUpdate"
],
"notes": [
"仓库 ID 与创建人(creator_name)由当前登录仓库/操作者上下文获取,接口不接受外部覆盖。",
"入参 allowed_owners 与 allowed_expresses 会校验是否在系统可用范围内(基于仓库签约货主或系统快递列表),若存在非法值接口会直接报错(400)。",
"max_same_structure 受仓库配置 min_group_order_fetch_quantity 限制:若传入值 >= min_group_order_fetch_quantity,则自动下调为 min_group_order_fetch_quantity - 1(最小值为 1)。",
"新建/更新成功后会触发仓库的 wave_strategy_version 自增(+1)并失效相关仓库配置缓存,调用方可通过策略版本推进或缓存变化感知策略已生效。"
],
"type": "added"
},
{
"version": "2026.05.07-system-06",
"date": "2026-05-07",
"summary": "收敛 order.wave.waveStrategyFallbackOrderList 返回字段,限定 where 白名单,补充 order.wave.singleFetchByIds 别名与返回语义",
"methods": [
"order.wave.waveStrategyFallbackOrderList",
"order.wave.singleFetchByIds"
],
"notes": [
"收敛 order.wave.waveStrategyFallbackOrderList response.list 字段为 id, delivery_no, tracking_no, items_count, items_total, sys_logistics_name, store_name, province, sys_platform_name, item_snapshot;item_snapshot 格式示例:商品名称*数量|...。",
"限制 order.wave.waveStrategyFallbackOrderList.where 白名单,禁止传入 warehouse_id / warehouseId;传入未列出字段或别名冲突将返回 400。",
"补充 order.wave.singleFetchByIds:明确支持 ids / order_ids / orderIds 三个别名(优先顺序 ids -> order_ids -> orderIds)并说明返回字段 fetched_order_ids、excluded_existing_wave_order_ids、skipped_order_ids、not_found_order_ids 的语义与兼容性。"
],
"type": "updated"
},
{
"version": "2026.05.07-system-04",
"date": "2026-05-07",
"summary": "更新 order.wave.waveStrategyFallbackOrderList,新增商品快照字段 item_snapshot",
"methods": [
"order.wave.waveStrategyFallbackOrderList"
],
"notes": [
"item_snapshot 返回格式为 商品名称1*数量|商品名称2*数量"
],
"type": "updated"
},
{
"version": "2026.05.07-system-03",
"date": "2026-05-07",
"summary": "新增 order.wave.waveStrategyQuickScan 与进度查询接口",
"methods": [
"order.wave.waveStrategyQuickScan",
"order.wave.waveStrategyQuickScanTaskProgress"
],
"notes": [
"同仓只允许一个扫描任务并使用缓存锁;扫描范围为当前表非待审核、未分配波次且订单策略版本与仓库当前版本不一致的订单;命中策略标记 wave_scan_result=1,否则=2"
],
"type": "added"
},
{
"version": "2026.05.07-system-02",
"date": "2026-05-07",
"summary": "新增 order.wave.waveStrategyList:查询当前仓库波次策略列表",
"methods": [
"order.wave.waveStrategyList"
],
"notes": [
"从 wms_wave_strategy 拉取当前仓库的波次策略列表,分页返回"
],
"type": "added"
},
{
"version": "2026.05.07-system-01",
"date": "2026-05-07",
"summary": "移除 order.wave.singleOrderFetchDetailList,新增 order.wave.waveStrategyFallbackOrderList(内置固定筛选条件)",
"methods": [
"order.wave.singleOrderFetchDetailList",
"order.wave.waveStrategyFallbackOrderList"
],
"notes": [
"移除 order.wave.singleOrderFetchDetailList。",
"新增 order.wave.waveStrategyFallbackOrderList。",
"新接口基于订单通用查询口径,固定内置筛选条件:step != 0、wave_id = 0、wave_scan_result = 2。"
],
"type": "updated"
},
{
"version": "2026.05.06-system-06",
"date": "2026-05-06",
"summary": "新增 order.wave.singleOrderFetchDetailList:订单级散单候选明细视图",
"methods": [
"order.wave.singleOrderFetchDetailList"
],
"notes": [
"新增 order.wave.singleOrderFetchDetailList:提供订单级的散单候选明细列表,返回按订单聚合的明细(非分组级)。",
"返回订单级而非分组级;响应每项包含订单 id、group_count、item_detail_machine、item_detail_machine_snapshot、item_detail、item_snapshot、logistics_name、store_id、distinguish_express、create_at 与 status_summary 等关键字段。",
"仍沿用 same_order_quantity 阈值来排除团购命中分组(仅保留 group_count < same_order_quantity 的候选项)。",
"singleOrderFetchList 暂保留以兼容现有前端,前端可在切换到订单级视图后迁移到本接口。"
],
"type": "added"
},
{
"version": "2026.05.06-system-05",
"date": "2026-05-06",
@ -44,8 +290,6 @@
"version": "2026.05.06-system-02",
"date": "2026-05-06",
"summary": "新增 order.wave.singleFetchByIds:按订单ID抓取到一个散单波次",
"date": "2026-05-06",
"summary": "新增 order.wave.singleFetchByIds:按订单ID抓取到一个散单波次",
"methods": [
"order.wave.singleFetchByIds"
],
@ -238,7 +482,7 @@
"接口保留登录态校验,入参仅接受订单 ID 相关字段,响应以服务层返回值为准。",
"该方法用于预留同步链路,后续补齐业务逻辑时再扩展服务层实现。"
],
"type": "added"
"type": "updated"
},
{
"version": "2026.04.22-system-01",
@ -1274,5 +1518,39 @@
"仓库上下文来自当前登录用户(ctx.user.store_id)。"
],
"type": "updated"
},
{
"version": "2026.05.08-system-05",
"date": "2026-05-08",
"summary": "order.wave.batchList:新增 source 字段并支持 where.source 过滤,返回 list item 中新增 source 字段",
"methods": [
"order.wave.batchList"
],
"notes": [
"新增 where.source(可选,number)用于按来源过滤:0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务;不传则不过滤。",
"响应 list 每条记录新增字段 source(number),用于区分波次来源。",
"仅更新文档,业务代码不在此变更范围。"
],
"type": "updated"
}
,
{
"version": "2026.05.09-system-01",
"date": "2026-05-09",
"summary": "新增 order.wave.wavePickTaskCancelSelf;order.wave.waveStrategyList 新增预演计数字段/参数",
"methods": [
"order.wave.wavePickTaskCancelSelf",
"order.wave.waveStrategyList"
],
"notes": [
"新增接口 `order.wave.wavePickTaskCancelSelf`:仅支持单个 `task_id`(number,必填),明确不支持 `task_ids` 批量参数。",
"业务约束:仅允许取消当前登录用户本人创建的拣货任务;若尝试取消非本人创建任务,接口应返回 400 错误(仅允许取消本人创建任务)。",
"返回建议:与现有取消接口风格一致,包含 `cancelled_count`(0/1)、`task_id`、`task_no`(若后端返回)或相应的取消结果汇总。",
"错误码建议:400 参数不合法(task_id 缺失或传了 task_ids);400 仅允许取消本人创建任务;500 取消失败。",
"新增参数:calculate_next_fetch_order_count(number,可选),含别名 calculateNextFetchOrderCount;取值 0=不计算(默认),1=计算并返回每条策略的 next_fetch_order_count,用于前端在策略列表中预览抓取量。",
"新增响应字段:list[*].next_fetch_order_count(number),含义:按当前策略口径预演一次自动抓取时,预计会选中的订单数量;当未开启计算时返回 0。"
],
"type": "added"
}
]

File diff suppressed because it is too large Load Diff

21
script/check_tables.cjs Normal file
View File

@ -0,0 +1,21 @@
(async () => {
try {
const configs = require('../database/config.js');
const env = process.env.NODE_ENV || 'development';
const cfg = configs[env];
if (!cfg) {
console.error('NO_CONFIG_FOR_ENV');
process.exit(2);
}
const mysql = require('mysql2/promise');
const conn = await mysql.createConnection({ host: cfg.host, user: cfg.username, password: cfg.password, database: cfg.database, port: cfg.port || 3306 });
const [rows] = await conn.execute("SELECT TABLE_NAME FROM information_schema.tables WHERE table_schema = ? AND TABLE_NAME IN (?,?)", [cfg.database, 'wms_wave_strategy', 'wms_picking_strategy']);
const exists = { wms_wave_strategy: false, wms_picking_strategy: false };
for (const r of rows) { exists[r.TABLE_NAME] = true; }
console.log(JSON.stringify({ env, database: cfg.database, exists }));
await conn.end();
} catch (err) {
console.error('ERROR', err.message);
process.exit(3);
}
})();

View File

@ -0,0 +1,156 @@
const path = require('path');
const fs = require('fs');
const SequelizeLib = require('sequelize');
(async () => {
const migrationName = '20260507100000-create-wms_order_wave_strategy_match.js';
const migrationPath = path.join(__dirname, '..', 'database', 'migrations', migrationName);
if (!fs.existsSync(migrationPath)) {
console.error('ERROR: migration file not found:', migrationPath);
process.exitCode = 2;
return;
}
const dbConfigFile = path.join(__dirname, '..', 'database', 'config.js');
let dbConfig;
try {
dbConfig = require(dbConfigFile);
} catch (e) {
console.error('ERROR: failed to load database config:', e.message);
process.exitCode = 2;
return;
}
const config = dbConfig.production;
const sequelize = new SequelizeLib(config.database, config.username, config.password, {
host: config.host,
port: config.port,
dialect: config.dialect || 'mysql',
logging: false,
define: config.define,
pool: config.pool,
});
const queryInterface = sequelize.getQueryInterface();
try {
await sequelize.authenticate();
} catch (e) {
console.error('ERROR: DB connection failed:', e.message);
process.exitCode = 2;
return;
}
// list migration files on disk
const migrationsDir = path.join(__dirname, '..', 'database', 'migrations');
const migrationFiles = fs.readdirSync(migrationsDir).filter(f => f.endsWith('.js')).sort();
// ensure SequelizeMeta exists
let tables = await queryInterface.showAllTables();
const normalizeTable = t => (typeof t === 'string' ? t : (t.tableName || t.name || '')).toLowerCase();
const tablesLower = tables.map(normalizeTable);
if (!tablesLower.includes('sequelizemeta')) {
await queryInterface.createTable('SequelizeMeta', { name: { type: SequelizeLib.STRING, allowNull: false, primaryKey: true } });
}
// read applied migrations
const appliedRows = await sequelize.query('SELECT name FROM SequelizeMeta', { type: SequelizeLib.QueryTypes.SELECT });
const appliedNames = appliedRows.map(r => (typeof r === 'string' ? r : r.name)).filter(Boolean);
// detect pending migrations (not yet recorded)
const pending = migrationFiles.filter(f => !appliedNames.includes(f));
const earlierPending = pending.filter(f => f < migrationName);
if (earlierPending.length > 0) {
console.error('ERROR: 存在早于目标迁移的 pending migration,拒绝单独执行。');
console.error('Pending earlier migrations:\n' + earlierPending.join('\n'));
process.exitCode = 3;
return;
}
if (appliedNames.includes(migrationName)) {
console.log('INFO: 迁移已记录在 SequelizeMeta,跳过执行。');
} else {
// run single migration up
const migration = require(migrationPath);
try {
await migration.up(queryInterface, SequelizeLib);
} catch (e) {
console.error('ERROR: migration.up 执行失败:', e && e.message ? e.message : e);
// attempt to collect state for rollback advice
try {
const tablesAfter = await queryInterface.showAllTables();
if (tablesAfter.map(normalizeTable).includes('wms_order_wave_strategy_match')) {
console.error('STATE: 表 wms_order_wave_strategy_match 已存在(可能部分创建)。');
}
} catch (e2) {
// ignore
}
process.exitCode = 4;
return;
}
// record migration in SequelizeMeta
try {
await sequelize.query('INSERT INTO SequelizeMeta(name) VALUES(?)', { replacements: [migrationName] });
} catch (e) {
console.error('ERROR: 无法在 SequelizeMeta 中记录迁移:', e && e.message ? e.message : e);
process.exitCode = 5;
return;
}
console.log('INFO: migration 执行并记录完成。');
}
// 验证:表存在、字段、索引、SequelizeMeta
const result = {
migrationRecorded: false,
tableExists: false,
columns: {},
indexes: {},
};
// migration recorded?
const checkRow = await sequelize.query('SELECT name FROM SequelizeMeta WHERE name = ?', { replacements: [migrationName], type: SequelizeLib.QueryTypes.SELECT });
result.migrationRecorded = (checkRow && checkRow.length > 0);
// table exists?
tables = await queryInterface.showAllTables();
result.tableExists = tables.map(normalizeTable).includes('wms_order_wave_strategy_match');
if (result.tableExists) {
const desc = await queryInterface.describeTable('wms_order_wave_strategy_match');
const needed = ['id', 'warehouse_id', 'order_id', 'strategy_id', 'create_time'];
for (const col of needed) {
result.columns[col] = !!desc[col];
if (desc[col]) {
result.columns[col + '_meta'] = {
type: desc[col].type,
allowNull: desc[col].allowNull,
defaultValue: desc[col].defaultValue,
primaryKey: !!desc[col].primaryKey || !!desc[col].primary_key || false,
autoIncrement: !!desc[col].autoIncrement || !!desc[col].auto_increment || false,
};
}
}
const indexes = await queryInterface.showIndex('wms_order_wave_strategy_match');
const idxNames = (indexes || []).map(i => i.name);
result.indexes.idx_warehouse_order = idxNames.includes('idx_warehouse_order');
result.indexes.idx_warehouse_strategy = idxNames.includes('idx_warehouse_strategy');
// further check fields for each index
for (const idx of (indexes || [])) {
if (idx.name === 'idx_warehouse_order') {
result.indexes.idx_warehouse_order_fields = (idx.fields || []).map(f => f.attribute || f.field || f.column);
}
if (idx.name === 'idx_warehouse_strategy') {
result.indexes.idx_warehouse_strategy_fields = (idx.fields || []).map(f => f.attribute || f.field || f.column);
}
}
}
console.log('\n=== VERIFICATION RESULT ===');
console.log(JSON.stringify(result, null, 2));
// close
await sequelize.close();
process.exitCode = 0;
})();

View File

@ -381,6 +381,65 @@ describe('test/app/service/systemMethods/order.base.step.test.js', () => {
assert.ok(outboundResult.list.every(item => item.warehouse_id === 100000));
});
it('should apply default filters for waveStrategyFallbackOrder in listByModule', async () => {
const { service, captures } = createOrderHarness(OrderBaseService, {
rowsByModule: {
waveStrategyFallbackOrder: [
{
id: 1,
warehouse_id: 100000,
step: 1,
wave_id: 0,
wave_scan_result: 2,
},
{
id: 2,
warehouse_id: 100000,
step: 0,
wave_id: 0,
wave_scan_result: 2,
},
{
id: 3,
warehouse_id: 100000,
step: 1,
wave_id: 99,
wave_scan_result: 2,
},
{
id: 4,
warehouse_id: 100000,
step: 1,
wave_id: 0,
wave_scan_result: 1,
},
{
id: 5,
warehouse_id: 100001,
step: 1,
wave_id: 0,
wave_scan_result: 2,
},
],
},
});
const result = await service.listByModule('waveStrategyFallbackOrder', {
pagination: {
page: 1,
pageSize: 10,
},
});
assert.equal(captures[0].moduleName, 'waveStrategyFallbackOrder');
assert.equal(captures[0].countWhere.warehouse_id, 100000);
assert.equal(captures[0].countWhere.step[Sequelize.Op.ne], 0);
assert.equal(captures[0].countWhere.wave_id, 0);
assert.equal(captures[0].countWhere.wave_scan_result, 2);
assert.deepEqual(result.list.map(item => item.id), [ 1 ]);
assert.equal(result.pagination.total, 1);
});
it('should attach express numbers and normalize sys names in all order lists', async () => {
const rows = buildRows(2, index => ({
id: index + 1,
@ -453,6 +512,42 @@ describe('test/app/service/systemMethods/order.base.step.test.js', () => {
assert.equal(result.list[1].sys_logistics_name, null);
});
it('should include wave fields in list attributes and keep default fields in response', async () => {
const rows = [
{
id: 1,
warehouse_id: 100000,
step: 1,
wave_strategy_version: 7,
wave_scan_result: null,
},
{
id: 2,
warehouse_id: 100000,
step: 1,
},
];
const { service, captures } = createOrderHarness(OrderBaseService, {
rowsByModule: {
order: rows,
},
});
const result = await service.listByModule('order', {
pagination: {
page: 1,
pageSize: 10,
},
});
assert.equal(captures[0].findOptions.attributes.includes('wave_strategy_version'), true);
assert.equal(captures[0].findOptions.attributes.includes('wave_scan_result'), true);
assert.equal(result.list[0].wave_strategy_version, 7);
assert.equal(result.list[0].wave_scan_result, 0);
assert.equal(result.list[1].wave_strategy_version, 0);
assert.equal(result.list[1].wave_scan_result, 0);
});
it('should treat waybill_codes as virtual filter and only append matched order ids to order where', async () => {
const rows = buildRows(3, index => ({
id: index + 1,

View File

@ -0,0 +1,131 @@
'use strict';
const assert = require('node:assert/strict');
const WaveService = require('../../../../../app/service/systemMethods/order/wave');
/**
* 创建 buildTaskBoxRows 测试上下文。
*
* @return {WaveService} 服务实例。
*/
function createService() {
const ctx = {
app: {
config: {},
},
user: {
store_id: 100000,
},
logger: {
info() {},
warn() {},
error() {},
},
};
return new WaveService(ctx);
}
describe('test/app/service/systemMethods/order/wave.buildTaskBoxRows.test.js', () => {
it('buildTaskSkuRows 在 pick_mode=3 时应按 SKU 聚合 required_qty', async () => {
const service = createService();
service.getOrderItemsModelByTableType = async () => ({
async findAll() {
return [
{ order_id: 1001, plan_qty: 2, stock_id: 7001, item_code: 'SKU-A', item_name: '商品A' },
{ order_id: 1001, plan_qty: 3, stock_id: 7001, item_code: 'SKU-A', item_name: '商品A' },
{ order_id: 1002, plan_qty: 1, stock_id: 7002, item_code: 'SKU-B', item_name: '商品B' },
];
},
});
const skuRows = await service.buildTaskSkuRows({
plan: {
warehouse_id: 100000,
pick_mode: 3,
},
selectedOrderIds: [ 1001, 1002 ],
});
assert.equal(skuRows.length, 2);
assert.equal(skuRows[0].ref_id, 7001);
assert.equal(skuRows[0].required_qty, 5);
assert.equal(skuRows[1].ref_id, 7002);
assert.equal(skuRows[1].required_qty, 1);
});
it('pick_mode=3 应优先按 SKU 生成 box_type=1 的框', () => {
const service = createService();
const rows = service.buildTaskBoxRows({
taskId: 501,
taskNo: 'TASK-501',
plan: {
warehouse_id: 100000,
pick_mode: 3,
},
taskOrderRows: [
{ order_id: 1001, box_no: 1 },
{ order_id: 1002, box_no: 2 },
{ order_id: 1003, box_no: 3 },
],
taskSkuRows: [
{ box_no: 1, sku_id: 7001, ref_id: 7001, ref_label: 'SKU-A', required_qty: 5 },
{ box_no: 2, sku_id: 7002, ref_id: 7002, ref_label: 'SKU-B', required_qty: 8 },
],
});
assert.equal(rows.length, 2);
assert.equal(rows[0].box_type, 1);
assert.equal(rows[0].ref_id, 7001);
assert.equal(rows[0].required_qty, 5);
assert.equal(rows[0].box_code, 'TASK-501-S1');
});
it('pick_mode=4 应按订单生成 box_type=2 的框', () => {
const service = createService();
const rows = service.buildTaskBoxRows({
taskId: 601,
taskNo: 'TASK-601',
plan: {
warehouse_id: 100000,
pick_mode: 4,
},
taskOrderRows: [
{ order_id: 2001, box_no: 1 },
],
taskSkuRows: [
{ box_no: 1, sku_id: 8001, ref_id: 8001, ref_label: 'SKU-X', required_qty: 3 },
],
});
assert.equal(rows.length, 1);
assert.equal(rows[0].box_type, 2);
assert.equal(rows[0].order_id, 2001);
assert.equal(rows[0].ref_id, 2001);
assert.equal(rows[0].box_code, 'TASK-601-O1');
});
it('pick_mode=5 应按波次生成 box_type=3 的框', () => {
const service = createService();
const rows = service.buildTaskBoxRows({
taskId: 701,
taskNo: 'TASK-701',
plan: {
warehouse_id: 100000,
pick_mode: 5,
},
taskWaveRows: [
{ wave_id: 9001, wave_no: 'WAVE-9001', box_no: 1 },
],
});
assert.equal(rows.length, 1);
assert.equal(rows[0].box_type, 3);
assert.equal(rows[0].ref_id, 9001);
assert.equal(rows[0].box_code, 'TASK-701-W1');
});
});

View File

@ -63,6 +63,7 @@ function createHarness({ orders = [], storeId = 100000 } = {}) {
const service = new WaveService(ctx);
service.getGroupWavePrefix = async () => 'B';
service.getSingleFetchByIdsWavePrefix = async () => 'A';
service.getMinGroupOrderFetchQuantity = async () => 3;
service.createWaveBatchReady = async params => {
state.createWaveCalls.push({ ...params });
@ -190,17 +191,18 @@ describe('test/app/service/systemMethods/order/wave.singleFetchByIds.test.js', (
assert.equal(result.flag, 'success');
assert.equal(result.wave_id, 9001);
assert.equal(result.wave_no, 'S202605060001');
assert.deepEqual(result.fetched_order_ids, [ 1 ]);
assert.equal(result.fetched_order_count, 1);
assert.equal(result.wave_no, 'A202605060001');
assert.deepEqual(result.fetched_order_ids, [ 1, 3, 4 ]);
assert.equal(result.fetched_order_count, 3);
assert.deepEqual(result.excluded_existing_wave_order_ids, [ 2 ]);
assert.deepEqual(result.not_found_order_ids, [ 5 ]);
assert.equal(state.createWaveCalls.length, 1);
assert.equal(state.createWaveCalls[0].wavePrefix, 'S');
assert.equal(state.createWaveCalls[0].wavePrefix, 'A');
assert.equal(state.createWaveCalls[0].waveType, 2);
assert.equal(state.createWaveCalls[0].distinguishExpress, false);
assert.equal(state.createWaveCalls[0].logisticsName, '');
assert.equal(state.orderLogItems.length, 1);
assert.equal(state.orderLogItems.length, 3);
assert.equal(state.orderLogItems[0].operationCode, 'ORDER_WAVE_ASSIGN');
assert.equal(state.committed, true);
assert.equal(state.rolledBack, false);
@ -225,7 +227,7 @@ describe('test/app/service/systemMethods/order/wave.singleFetchByIds.test.js', (
assert.equal(state.rolledBack, false);
});
it('should exclude group-candidate orders from singleFetchByIds', async () => {
it('should fetch same-structure orders when they are not in any wave', async () => {
const { service, state } = createHarness({
orders: [
{ id: 101, wave_id: 0, wave_no: '', step: 1, status: 'new', outbound_status: 'none', items_hash: 'H-A', items: 'I-A', logistics_name: 'ZTO' },
@ -239,11 +241,49 @@ describe('test/app/service/systemMethods/order/wave.singleFetchByIds.test.js', (
assert.equal(result.flag, 'success');
assert.equal(result.wave_id, 9001);
assert.deepEqual(result.fetched_order_ids, [ 104 ]);
assert.deepEqual(result.excluded_group_order_ids, [ 101 ]);
assert.deepEqual(result.skipped_order_ids, [ 101 ]);
assert.deepEqual(result.fetched_order_ids, [ 101, 104 ]);
assert.deepEqual(result.skipped_order_ids, []);
assert.equal(state.createWaveCalls.length, 1);
assert.equal(state.createWaveCalls[0].wavePrefix, 'A');
assert.equal(state.createWaveCalls[0].waveType, 2);
assert.equal(state.createWaveCalls[0].distinguishExpress, false);
assert.equal(state.committed, true);
assert.equal(state.rolledBack, false);
});
it('should support order_ids alias for delete-by-ids scene', async () => {
const { service, state } = createHarness({
orders: [
{ id: 201, wave_id: 0, wave_no: '', step: 1, status: 'new', outbound_status: 'none' },
{ id: 202, wave_id: 0, wave_no: '', step: 1, status: 'new', outbound_status: 'none' },
],
});
const result = await service.singleFetchByIds({ order_ids: [ 201, 202 ] });
assert.equal(result.flag, 'success');
assert.deepEqual(result.ids, [ 201, 202 ]);
assert.deepEqual(result.fetched_order_ids, [ 201, 202 ]);
assert.equal(result.fetched_order_count, 2);
assert.equal(state.createWaveCalls.length, 1);
assert.equal(state.committed, true);
assert.equal(state.rolledBack, false);
});
it('should support orderIds alias for delete-by-ids scene', async () => {
const { service, state } = createHarness({
orders: [
{ id: 301, wave_id: 0, wave_no: '', step: 1, status: 'new', outbound_status: 'none' },
],
});
const result = await service.singleFetchByIds({ orderIds: [ 301 ] });
assert.equal(result.flag, 'success');
assert.deepEqual(result.ids, [ 301 ]);
assert.deepEqual(result.fetched_order_ids, [ 301 ]);
assert.equal(result.fetched_order_count, 1);
assert.equal(state.createWaveCalls.length, 1);
assert.equal(state.createWaveCalls[0].wavePrefix, 'S');
assert.equal(state.committed, true);
assert.equal(state.rolledBack, false);
});

View File

@ -0,0 +1,143 @@
'use strict';
const assert = require('node:assert/strict');
const WaveService = require('../../../../../app/service/systemMethods/order/wave');
/**
* 创建 wavePickTaskList 测试上下文。
*
* @return {{ service: WaveService, captures: { sqlList: Array<string>, replacementList: Array<Object> } }} 测试对象。
*/
function createHarness() {
const captures = {
sqlList: [],
replacementList: [],
};
const ctx = {
app: {
config: {},
},
user: {
store_id: 100000,
},
model: {
async query(sql, queryOptions = {}) {
const normalizedSql = String(sql || '').replace(/\s+/g, ' ').trim();
captures.sqlList.push(normalizedSql);
captures.replacementList.push(queryOptions.replacements || {});
if (/COUNT\(1\) AS total/i.test(normalizedSql)) {
return [[{ total: 2 }]];
}
return [[{
id: 501,
task_no: 'WPT100000117892299991ABCDEF',
warehouse_id: 100000,
pick_mode: 1,
status: 0,
review_status: 0,
source: 1,
wave_count: 2,
order_count: 10,
box_count: 2,
pick_user_id: 9001,
pick_user_name: 'tester',
review_user_id: 0,
review_user_name: '',
current_cart_id: 11,
current_cart_code_snapshot: 'CART-11',
batch_no: 'BATCH-1',
device_id: 'PDA-1',
start_time: null,
finish_time: null,
review_start_time: null,
review_finish_time: null,
create_time: '2026-05-08 10:00:00',
update_time: '2026-05-08 10:00:00',
}]];
},
},
};
const service = new WaveService(ctx);
return {
service,
captures,
};
}
describe('test/app/service/systemMethods/order/wave.wavePickTaskList.test.js', () => {
it('默认分页应查询成功并返回 list/total/page/page_size', async () => {
const { service } = createHarness();
const result = await service.wavePickTaskList({});
assert.equal(result.flag, 'success');
assert.equal(result.message, 'ok');
assert.equal(result.total, 2);
assert.equal(result.page, 1);
assert.equal(result.page_size, 20);
assert.ok(Array.isArray(result.list));
assert.equal(result.list.length, 1);
assert.deepEqual(result.list[0], {
task_id: 501,
task_no: 'WPT100000117892299991ABCDEF',
warehouse_id: 100000,
pick_mode: 1,
status: 0,
review_status: 0,
source: 1,
wave_count: 2,
order_count: 10,
box_count: 2,
pick_user_id: 9001,
pick_user_name: 'tester',
review_user_id: 0,
review_user_name: '',
current_cart_id: 11,
current_cart_code_snapshot: 'CART-11',
batch_no: 'BATCH-1',
device_id: 'PDA-1',
start_time: null,
finish_time: null,
review_start_time: null,
review_finish_time: null,
create_time: '2026-05-08 10:00:00',
update_time: '2026-05-08 10:00:00',
});
});
it('task_no 与 keyword 过滤应正确拼接到 SQL 与 replacements', async () => {
const { service, captures } = createHarness();
const result = await service.wavePickTaskList({
current: 2,
size: 50,
where: {
task_no: 'WPT100',
keyword: 'tester',
},
});
assert.equal(result.flag, 'success');
assert.equal(captures.sqlList.length, 2);
const listSql = captures.sqlList[0];
const listReplacements = captures.replacementList[0];
assert.ok(listSql.includes('t.task_no LIKE :whereTaskNo'));
assert.ok(listSql.includes('t.task_no LIKE :whereKeyword'));
assert.ok(listSql.includes('t.pick_user_name LIKE :whereKeyword'));
assert.ok(listSql.includes('t.review_user_name LIKE :whereKeyword'));
assert.ok(listSql.includes('t.batch_no LIKE :whereKeyword'));
assert.equal(listReplacements.whereTaskNo, '%WPT100%');
assert.equal(listReplacements.whereKeyword, '%tester%');
assert.equal(listReplacements.limit, 50);
assert.equal(listReplacements.offset, 50);
assert.equal(result.page, 2);
assert.equal(result.page_size, 50);
});
});

View File

@ -0,0 +1,240 @@
'use strict';
const assert = require('node:assert/strict');
const WaveService = require('../../../../../app/service/systemMethods/order/wave');
/**
* 构建 waveStrategyFallbackOrderList 的测试上下文。
*
* @return {{ service: WaveService, captures: { moduleName: string|null, data: Object|null } }} 测试对象。
*/
function createHarness() {
const captures = {
moduleName: null,
data: null,
};
const ctx = {
app: {
config: {},
},
user: {
store_id: 100000,
},
logger: {
warn: () => {},
},
};
const service = new WaveService(ctx);
service.getWarehouseId = () => 1;
service.listByModule = async (moduleName, data) => {
captures.moduleName = moduleName;
captures.data = data;
return {
list: [
{
id: 101,
delivery_order_code: 'FH20260507001',
express_numbers: [ 'YT20260507001' ],
items_count: 2,
items_total: 5,
sys_logistics_name: '系统圆通',
logistics_name: '圆通',
shop_nick: '货主A',
province: '浙江省',
sys_platform_name: '抖音',
wave_scan_result: 2,
tel: '13800000000',
},
],
pagination: {
page: 1,
pageSize: 20,
total: 1,
totalPages: 1,
},
};
};
return {
service,
captures,
};
}
describe('test/app/service/systemMethods/order/wave.waveStrategyFallbackOrderList.test.js', () => {
it('should only return fallback whitelist fields and wrap success response', async () => {
const { service, captures } = createHarness();
const requestData = {
where: {
id: 1001,
delivery_no: 'FH2026',
tracking_no: 'YT2026',
items_count: 2,
items_total: 5,
sys_logistics_name: '圆通',
store_name: '货主A',
province: '浙江',
sys_platform_name: '抖音',
},
pagination: {
page: 2,
pageSize: 10,
},
sort: {
sortField: 'updated_at',
sortOrder: 'DESC',
},
};
const result = await service.waveStrategyFallbackOrderList(requestData);
assert.equal(captures.moduleName, 'waveStrategyFallbackOrder');
assert.equal(result.flag, 'success');
assert.equal(result.message, 'ok');
assert.deepEqual(result.list, [
{
id: 101,
delivery_no: 'FH20260507001',
tracking_no: 'YT20260507001',
items_count: 2,
items_total: 5,
sys_logistics_name: '系统圆通',
store_name: '货主A',
province: '浙江省',
sys_platform_name: '抖音',
item_snapshot: '',
},
]);
assert.deepEqual(result.pagination, {
page: 1,
pageSize: 20,
total: 1,
totalPages: 1,
});
assert.deepEqual(captures.data.where, {
id: 1001,
delivery_order_code: 'FH2026',
express_numbers: 'YT2026',
items_count: 2,
items_total: 5,
logistics_name: '圆通',
shop_nick: '货主A',
province: '浙江',
sys_platform_name: '抖音',
});
assert.deepEqual(captures.data.pagination, {
page: 2,
pageSize: 10,
});
assert.deepEqual(captures.data.sort, {
sortField: 'updated_at',
sortOrder: 'DESC',
});
});
it('should normalize pagination when pagination object is passed directly', async () => {
const { service } = createHarness();
const normalizedPagination = service.normalizePagination({
page: 2,
pageSize: 20,
});
assert.deepEqual(normalizedPagination, {
page: 2,
pageSize: 20,
});
});
it('should fill item_snapshot with 商品名称*数量|... when order items exist', async () => {
const { service } = createHarness();
service.getOrderItemsModelByTableType = async () => ({
findAll: async () => ([
{
order_id: 101,
plan_qty: 1,
stock_id: 1,
item_code: 'A-1',
item_name: '商品A',
item_snapshot: '{"item_name":"商品A","item_code":"A-1"}',
},
{
order_id: 101,
plan_qty: 2,
stock_id: 1,
item_code: 'A-1',
item_name: '商品A',
item_snapshot: '{"item_name":"商品A","item_code":"A-1"}',
},
{
order_id: 101,
plan_qty: 3,
stock_id: 2,
item_code: 'B-1',
item_name: '商品B',
item_snapshot: '{"item_name":"商品B","item_code":"B-1"}',
},
]),
});
const result = await service.waveStrategyFallbackOrderList({});
assert.equal(result.flag, 'success');
assert.equal(result.list[0].item_snapshot, '商品A*3|商品B*3');
assert.deepEqual(Object.keys(result.list[0]).sort(), [
'delivery_no',
'id',
'item_snapshot',
'items_count',
'items_total',
'province',
'store_name',
'sys_logistics_name',
'sys_platform_name',
'tracking_no',
].sort());
});
it('should return empty item_snapshot when no order items found', async () => {
const { service } = createHarness();
service.getOrderItemsModelByTableType = async () => ({
findAll: async () => ([]),
});
const result = await service.waveStrategyFallbackOrderList({});
assert.equal(result.flag, 'success');
assert.equal(result.list[0].item_snapshot, '');
});
it('should reject unsupported where fields', async () => {
const { service } = createHarness();
await assert.rejects(async () => {
await service.waveStrategyFallbackOrderList({
where: {
wave_id: 1,
},
});
}, /where 存在不支持的字段: wave_id/);
});
it('should allow owner_name as where alias and map to shop_nick', async () => {
const { service, captures } = createHarness();
const result = await service.waveStrategyFallbackOrderList({
where: {
owner_name: '货主B',
},
});
assert.equal(result.flag, 'success');
assert.deepEqual(captures.data.where, {
shop_nick: '货主B',
});
});
});

View File

@ -0,0 +1,255 @@
'use strict';
const assert = require('node:assert/strict');
const WaveService = require('../../../../../app/service/systemMethods/order/wave');
/**
* 创建 waveStrategyFetch 测试上下文。
*
* @param {Object} [options={}] 测试选项。
* @param {Object} [options.strategyRow] 策略模型返回行。
* @return {{ service: WaveService, captures: Object }} 测试上下文。
*/
function createHarness(options = {}) {
const strategyRow = options.strategyRow || {
id: 99,
warehouse_id: 100000,
status: 1,
strategy_type: 2,
batch_mode: 0,
group_batch_max_orders: 2,
batch_max_orders: 20,
batch_max_skus: 10,
};
const captures = {
transactionCount: 0,
committed: 0,
rolledBack: 0,
inserts: [],
};
const transaction = {
LOCK: {
UPDATE: 'UPDATE',
},
async commit() {
captures.committed += 1;
},
async rollback() {
captures.rolledBack += 1;
},
};
const ctx = {
app: {
config: {},
},
user: {
store_id: 100000,
id: 9001,
name: 'tester',
},
logger: {
info() {},
warn() {},
error() {},
},
model: {
QueryTypes: {
SELECT: 'SELECT',
},
async transaction() {
captures.transactionCount += 1;
return transaction;
},
async query(sql, queryOptions = {}) {
const compactSql = String(sql || '').replace(/\s+/g, ' ').trim()
.toLowerCase();
if (compactSql.includes('select b.task_id from wms_pick_task_cart_binding')) {
return [];
}
if (compactSql.includes('select id, cart_code, current_task_id from wms_pick_cart')) {
return [{
id: 9,
cart_code: 'CART-09',
current_task_id: null,
}];
}
if (compactSql.includes('insert into wms_wave_pick_task ')) {
captures.inserts.push('wms_wave_pick_task');
return [{ insertId: 501 }, { insertId: 501 }];
}
if (compactSql.includes('insert into wms_wave_pick_task_wave')) {
captures.inserts.push('wms_wave_pick_task_wave');
return [{ affectedRows: 1 }];
}
if (compactSql.includes('insert into wms_wave_pick_task_order')) {
captures.inserts.push('wms_wave_pick_task_order');
return [{ affectedRows: 1 }];
}
if (compactSql.includes('insert into wms_wave_pick_task_box')) {
captures.inserts.push('wms_wave_pick_task_box');
return [{ affectedRows: 1 }];
}
if (compactSql.includes('insert into wms_pick_task_cart_binding')) {
captures.inserts.push('wms_pick_task_cart_binding');
return [{ affectedRows: 1 }];
}
if (compactSql.includes('insert into wms_wave_pick_checkpoint')) {
captures.inserts.push('wms_wave_pick_checkpoint');
return [{ affectedRows: 1 }];
}
if (compactSql.includes('insert into wms_wave_pick_action_log')) {
captures.inserts.push('wms_wave_pick_action_log');
return [{ affectedRows: 1 }];
}
if (compactSql.includes('insert into wms_order_pick_trace')) {
captures.inserts.push('wms_order_pick_trace');
return [{ affectedRows: 1 }];
}
if (compactSql.includes('update wms_pick_cart')) {
captures.inserts.push('wms_pick_cart_update');
return [{ affectedRows: 1 }];
}
if (compactSql.includes('update wms_wave_pick_task')) {
captures.inserts.push('wms_wave_pick_task_update');
return [{ affectedRows: 1 }];
}
if (compactSql.includes('select last_insert_id() as insertid')) {
return [[{ insertId: 501 }]];
}
return queryOptions.type === 'SELECT' ? [] : [{ affectedRows: 0 }];
},
wms_wave_strategy: {
async findOne() {
return strategyRow;
},
},
},
};
const service = new WaveService(ctx);
return {
service,
captures,
};
}
describe('test/app/service/systemMethods/order/wave.waveStrategyFetch.test.js', () => {
it('waveStrategyFetchPda 应进入创建流程并写入核心表', async () => {
const { service, captures } = createHarness();
const result = await service.waveStrategyFetchPda({
strategy_id: 99,
selected_wave_ids: [ 20001 ],
cart_id: 9,
device_id: 'pda-1',
request_id: 'req-1',
});
assert.equal(result.flag, 'success');
assert.equal(result.state, 'created');
assert.equal(result.fetch_state, 1);
assert.equal(result.tip, '任务创建成功');
assert.equal(result.can_enter_pick_flow, false);
assert.equal(result.task_id, 501);
assert.ok(typeof result.task_no === 'string' && result.task_no.length > 0);
assert.equal(captures.transactionCount, 1);
assert.equal(captures.committed, 1);
assert.equal(captures.rolledBack, 0);
const insertedSet = new Set(captures.inserts);
assert.equal(insertedSet.has('wms_wave_pick_task'), true);
assert.equal(insertedSet.has('wms_wave_pick_task_wave'), true);
assert.equal(insertedSet.has('wms_wave_pick_task_box'), true);
assert.equal(insertedSet.has('wms_pick_task_cart_binding'), true);
assert.equal(insertedSet.has('wms_wave_pick_checkpoint'), true);
assert.equal(insertedSet.has('wms_wave_pick_action_log'), true);
assert.equal(insertedSet.has('wms_order_pick_trace'), true);
assert.equal(insertedSet.has('wms_pick_cart_update'), true);
});
it('校验失败时应短路返回 failure 且不进入事务', async () => {
const { service, captures } = createHarness();
const result = await service.waveStrategyFetchPda({
strategy_id: 99,
selected_wave_ids: [],
});
assert.equal(result.flag, 'failure');
assert.equal(result.code, 400);
assert.equal(result.data.fetch_state, 2);
assert.equal(result.data.tip, '创建失败,请重试');
assert.equal(result.data.task_id, null);
assert.equal(result.data.can_enter_pick_flow, false);
assert.equal(captures.transactionCount, 0);
});
it('waveStrategyFetchPda 在存在未完成任务时返回 fetch_state=3 并回填任务ID', async () => {
const { service } = createHarness();
service.createWavePickTaskFromPlan = async () => {
throw new Error('当前用户存在未完成任务,请先完成后再创建(task_id=777,task_no=PK20260510001)');
};
const result = await service.waveStrategyFetchPda({
strategy_id: 99,
selected_wave_ids: [ 20001 ],
cart_id: 9,
});
assert.equal(result.flag, 'success');
assert.equal(result.fetch_state, 3);
assert.equal(result.tip, '存在未完成任务,已返回任务ID,可继续拣货');
assert.equal(result.task_id, 777);
assert.equal(result.task_no, 'PK20260510001');
assert.equal(result.can_enter_pick_flow, true);
assert.equal(result.status, 'failed');
});
it('waveStrategyFetchAdmin 成功时返回 task_id/task_no/state=created', async () => {
const { service } = createHarness({
strategyRow: {
id: 100,
warehouse_id: 100000,
status: 1,
strategy_type: 1,
batch_mode: 1,
group_batch_max_orders: 1,
batch_max_orders: 30,
batch_max_skus: 10,
},
});
const result = await service.waveStrategyFetchAdmin({
strategy_id: 100,
selected_order_ids: [ 3001, 3002 ],
request_id: 'req-admin-1',
});
assert.equal(result.flag, 'success');
assert.equal(result.state, 'created');
assert.equal(result.fetch_state, 1);
assert.equal(result.tip, '任务创建成功');
assert.equal(result.can_enter_pick_flow, false);
assert.equal(result.task_id, 501);
assert.ok(typeof result.task_no === 'string' && result.task_no.length > 0);
});
});

View File

@ -0,0 +1,201 @@
'use strict';
const assert = require('node:assert/strict');
const WaveService = require('../../../../../app/service/systemMethods/order/wave');
/**
* 创建 waveStrategyList 测试上下文。
*
* @param {Object} [options={}] 测试选项。
* @param {number} [options.warehouseId=100000] 当前仓库ID。
* @param {Array<Object>} [options.strategyRows] 自定义策略列表。
* @param {Array<Object>} [options.matchedRows] 命中订单统计查询结果。
* @return {{ service: WaveService, captures: { findOptions: Object|null } }} 测试上下文。
*/
function createHarness(options = {}) {
const warehouseId = Number(options.warehouseId || 100000);
const strategyRows = Array.isArray(options.strategyRows)
? options.strategyRows
: [
{
id: 21,
warehouse_id: warehouseId,
strategy_name: '优先散单',
status: 1,
},
{
id: 20,
warehouse_id: warehouseId,
strategy_name: '团购策略',
status: 0,
},
];
const matchedRows = Array.isArray(options.matchedRows)
? options.matchedRows
: [
{ strategy_id: 21, matched_order_count_filtered: 8 },
];
const captures = {
findOptions: null,
querySql: '',
queryOptions: null,
};
const ctx = {
app: {
config: {},
},
user: {
store_id: warehouseId,
},
model: {
QueryTypes: {
SELECT: 'SELECT',
},
wms_wave_strategy: {
async findAndCountAll(findOptions) {
captures.findOptions = findOptions;
return {
count: 5,
rows: strategyRows,
};
},
},
async query(sql, queryOptions) {
captures.querySql = String(sql || '');
captures.queryOptions = queryOptions;
return matchedRows;
},
},
};
const service = new WaveService(ctx);
service.getOrderModel = async () => ({
getTableName: () => 'wms_order_delivery_test',
});
return {
service,
captures,
};
}
describe('test/app/service/systemMethods/order/wave.waveStrategyList.test.js', () => {
it('should query by current warehouse and wrap success response with pagination', async () => {
const { service, captures } = createHarness({ warehouseId: 200001 });
const result = await service.waveStrategyList({
pagination: {
page: 2,
pageSize: 2,
},
});
assert.deepEqual(captures.findOptions.where, {
warehouse_id: 200001,
});
assert.deepEqual(captures.findOptions.order, [
[ 'status', 'DESC' ],
[ 'id', 'DESC' ],
]);
assert.equal(captures.findOptions.offset, 2);
assert.equal(captures.findOptions.limit, 2);
assert.equal(captures.findOptions.raw, true);
assert.ok(captures.querySql.includes('FROM wms_order_wave_strategy_match m'));
assert.ok(captures.querySql.includes('o.wave_id = 0'));
assert.ok(captures.querySql.includes('o.step != 0'));
assert.ok(captures.querySql.includes('src.wave_id = 0'));
assert.ok(captures.querySql.includes('src.step != 0'));
assert.ok(captures.querySql.includes('COALESCE(NULLIF(TRIM(COALESCE(src.items_hash, \'\')), \'\'), TRIM(COALESCE(src.items, \'\')))'));
assert.ok(captures.querySql.includes('same_structure.same_structure_count >= COALESCE(s.min_same_structure, 0)'));
assert.ok(captures.querySql.includes('(s.max_same_structure IS NULL OR same_structure.same_structure_count <= s.max_same_structure)'));
assert.deepEqual(captures.queryOptions.replacements, {
warehouseId: 200001,
strategyIds: [ 21, 20 ],
});
assert.equal(captures.queryOptions.type, 'SELECT');
assert.equal(result.flag, 'success');
assert.equal(result.message, 'ok');
assert.ok(Array.isArray(result.list));
assert.equal(result.list.length, 2);
assert.equal(result.list[0].warehouse_id, 200001);
assert.equal(result.list[0].matched_order_count_filtered, 8);
assert.equal(result.list[0].next_fetch_order_count, 0);
assert.equal(result.list[1].matched_order_count_filtered, 0);
assert.equal(result.list[1].next_fetch_order_count, 0);
assert.deepEqual(result.pagination, {
page: 2,
pageSize: 2,
total: 5,
totalPages: 3,
hasPrevious: true,
hasNext: true,
});
});
it('should return next_fetch_order_count=0 and skip preview when calculation flag is disabled', async () => {
const { service } = createHarness({ warehouseId: 200002 });
let calledCount = 0;
service.getWaveStrategyNextFetchOrderCountMap = async () => {
calledCount += 1;
return new Map();
};
const result = await service.waveStrategyList({
pagination: {
page: 1,
pageSize: 20,
},
});
assert.equal(calledCount, 0);
assert.ok(Array.isArray(result.list));
assert.equal(result.list[0].next_fetch_order_count, 0);
assert.equal(result.list[1].next_fetch_order_count, 0);
});
it('should calculate next_fetch_order_count when calculate_next_fetch_order_count=1', async () => {
const { service } = createHarness({
warehouseId: 200003,
strategyRows: [
{
id: 31,
warehouse_id: 200003,
strategy_name: '散单策略A',
strategy_type: 1,
batch_mode: 1,
batch_max_orders: 2,
batch_max_skus: 10,
status: 1,
},
],
matchedRows: [
{ strategy_id: 31, matched_order_count_filtered: 3 },
],
});
service.getWaveStrategyFetchCandidateOrders = async () => ([
{ id: 101, items_hash: 'hash_a', items: 'A', logistics_name: 'ZTO', items_count: 1, items_total: 1 },
{ id: 102, items_hash: 'hash_b', items: 'B', logistics_name: 'YTO', items_count: 1, items_total: 1 },
{ id: 103, items_hash: 'hash_c', items: 'C', logistics_name: 'STO', items_count: 1, items_total: 1 },
]);
service.buildWaveStrategyFetchOrderSkuMap = async () => {
throw new Error('pick_mode=2 场景不应触发 SKU 预演');
};
const result = await service.waveStrategyList({
calculate_next_fetch_order_count: 1,
pagination: {
page: 1,
pageSize: 20,
},
});
assert.ok(Array.isArray(result.list));
assert.equal(result.list.length, 1);
assert.equal(result.list[0].matched_order_count_filtered, 3);
assert.equal(result.list[0].next_fetch_order_count, 2);
});
});

View File

@ -0,0 +1,394 @@
'use strict';
const assert = require('node:assert/strict');
const { Op } = require('sequelize');
const WaveService = require('../../../../../app/service/systemMethods/order/wave');
const runWaveStrategyQuickScanRunner = require('../../../../../app/lib/wave_strategy_quick_scan_runner');
/**
* 构建快速扫描测试上下文。
*
* @return {{ service: WaveService, cache: Map<string, Object> }} 服务实例与缓存。
*/
function createHarness() {
const cache = new Map();
const ctx = {
app: {
config: {},
async setCacheAsync(key, payload) {
cache.set(key, payload);
},
async getCacheAsync(key) {
return cache.get(key) || null;
},
async delCacheAsync(key) {
cache.delete(key);
},
},
user: {
store_id: 100000,
},
logger: {
info() {},
warn() {},
error() {},
},
model: {
wms_wave_strategy: {
async findAll() {
return [];
},
},
},
};
return {
service: new WaveService(ctx),
cache,
};
}
describe('test/app/service/systemMethods/order/wave.waveStrategyQuickScan.test.js', () => {
it('传入 warehouse_id 参数时应抛错', async () => {
const { service } = createHarness();
await assert.rejects(
async () => {
await service.waveStrategyQuickScan({ warehouse_id: 100000 });
},
error => {
assert.match(String(error && error.message || ''), /不支持传入 warehouse_id/u);
return true;
}
);
});
it('同仓存在运行任务时应返回已有 task_id 且不重复启动', async () => {
const { service } = createHarness();
const runCalls = [];
service.runWaveStrategyQuickScanTask = async params => {
runCalls.push(params);
await service.setWaveStrategyQuickScanTaskProgress(params.taskId, 'running', {
warehouse_id: 100000,
});
};
const firstResult = await service.waveStrategyQuickScan({});
await new Promise(resolve => setImmediate(resolve));
const secondResult = await service.waveStrategyQuickScan({});
assert.equal(firstResult.flag, 'success');
assert.equal(secondResult.flag, 'success');
assert.equal(secondResult.task_id, firstResult.task_id);
assert.equal(runCalls.length, 1);
});
it('执行任务时应按策略命中写入扫描结果和策略版本', async () => {
const { service } = createHarness();
const updateCalls = [];
const warehouseId = 100000;
const taskId = 'wave_quick_scan_test_task_1';
service.getWarehouseSubjectConfig = async () => ({
subject_config: {
wave_strategy_version: 9,
},
});
service.ctx.model.wms_wave_strategy = {
async findAll() {
return [
{
status: 1,
order_min_sku: 1,
order_max_sku: 1,
order_min_qty: 1,
order_max_qty: 2,
min_same_structure: 1,
max_same_structure: 10,
allowed_owners: [ 11 ],
allowed_expresses: [ 'YD' ],
allowed_platforms: [ 'PDD' ],
allow_cross_owner: true,
require_same_express: false,
},
];
},
};
service.getOrderModel = async () => ({
async findAll() {
return [
{
id: 1,
store_id: 11,
items_count: 1,
items_total: 1,
items_hash: 'hash_a',
items: '',
logistics_code: 'YD',
sys_logistics_code: 'YD',
logistics_name: '韵达',
province: 'zj',
sys_platform_code: 'PDD',
source_platform_code: '',
},
{
id: 2,
store_id: 12,
items_count: 3,
items_total: 6,
items_hash: 'hash_b',
items: '',
logistics_code: 'SF',
sys_logistics_code: 'SF',
logistics_name: '顺丰',
province: 'js',
sys_platform_code: 'TB',
source_platform_code: '',
},
];
},
async update(values, options) {
updateCalls.push({ values, options });
return [ Array.isArray(options.where.id[Op.in]) ? options.where.id[Op.in].length : 0 ];
},
});
await service.setWaveStrategyQuickScanWarehouseLock(warehouseId, taskId, {
state: 'submitted',
});
await service.runWaveStrategyQuickScanTask({
taskId,
warehouseId,
});
const matchedCall = updateCalls.find(item => Number(item.values.wave_scan_result) === 1);
const unmatchedCall = updateCalls.find(item => Number(item.values.wave_scan_result) === 2);
assert.ok(matchedCall);
assert.ok(unmatchedCall);
assert.equal(matchedCall.values.wave_strategy_version, 9);
assert.equal(unmatchedCall.values.wave_strategy_version, 9);
assert.deepEqual(matchedCall.options.where.id[Op.in], [ 1 ]);
assert.deepEqual(unmatchedCall.options.where.id[Op.in], [ 2 ]);
const progress = await service.getWaveStrategyQuickScanTaskProgress(taskId);
assert.equal(progress.state, 'success');
assert.equal(progress.total_order_count, 2);
assert.equal(progress.processed_order_count, 2);
assert.equal(progress.matched_order_count, 1);
assert.equal(progress.unmatched_order_count, 1);
const lockPayload = await service.getWaveStrategyQuickScanWarehouseLock(warehouseId);
assert.equal(lockPayload, null);
});
it('进度查询应返回 running 和 success 的基础字段', async () => {
const { service } = createHarness();
const taskId = 'wave_quick_scan_test_task_2';
await service.setWaveStrategyQuickScanTaskProgress(taskId, 'running', {
warehouse_id: 100000,
total_order_count: 10,
processed_order_count: 3,
matched_order_count: 1,
unmatched_order_count: 2,
progress_percent: 30,
submitted_at: 1000,
start_time: 2000,
end_time: null,
});
const runningResult = await service.waveStrategyQuickScanTaskProgress({
task_id: taskId,
});
assert.equal(runningResult.flag, 'success');
assert.equal(runningResult.state, 'running');
assert.equal(runningResult.total_order_count, 10);
assert.equal(runningResult.processed_order_count, 3);
assert.equal(runningResult.progress_percent, 30);
await service.setWaveStrategyQuickScanTaskProgress(taskId, 'success', {
processed_order_count: 10,
matched_order_count: 4,
unmatched_order_count: 6,
progress_percent: 100,
end_time: 3000,
});
const successResult = await service.waveStrategyQuickScanTaskProgress({
taskId,
});
assert.equal(successResult.flag, 'success');
assert.equal(successResult.state, 'success');
assert.equal(successResult.total_order_count, 10);
assert.equal(successResult.processed_order_count, 10);
assert.equal(successResult.matched_order_count, 4);
assert.equal(successResult.unmatched_order_count, 6);
assert.equal(successResult.progress_percent, 100);
assert.equal(successResult.end_time, 3000);
});
it('allow_cross_owner=false 时应按同结构主货主优先命中', async () => {
const { service } = createHarness();
const orders = [
{
id: 101,
store_id: 11,
items_count: 1,
items_total: 1,
items_hash: 'hash_owner_same_structure',
logistics_code: 'YD',
sys_logistics_code: 'YD',
logistics_name: '韵达',
province: 'zj',
sys_platform_code: 'PDD',
source_platform_code: '',
},
{
id: 102,
store_id: 11,
items_count: 1,
items_total: 1,
items_hash: 'hash_owner_same_structure',
logistics_code: 'YD',
sys_logistics_code: 'YD',
logistics_name: '韵达',
province: 'zj',
sys_platform_code: 'PDD',
source_platform_code: '',
},
{
id: 103,
store_id: 12,
items_count: 1,
items_total: 1,
items_hash: 'hash_owner_same_structure',
logistics_code: 'YD',
sys_logistics_code: 'YD',
logistics_name: '韵达',
province: 'zj',
sys_platform_code: 'PDD',
source_platform_code: '',
},
];
const strategyList = [
{
strategy_id: 1001,
order_min_sku: 1,
order_max_sku: 999,
order_min_qty: 1,
order_max_qty: 999,
min_same_structure: 1,
max_same_structure: 999,
allowed_owners: [],
allowed_expresses: [],
allowed_provinces: [],
allowed_platforms: [],
allow_cross_owner: false,
require_same_express: false,
},
];
const result = await runWaveStrategyQuickScanRunner({
orders,
strategyList,
getStructureKey: order => service.getWaveStrategyQuickScanStructureKey(order),
getExpressKey: order => service.getWaveStrategyQuickScanExpressKey(order),
getMatchedStrategyIds: (order, normalizedStrategyList, context) => service.getWaveStrategyQuickScanMatchedStrategyIds(
order,
normalizedStrategyList,
context
),
});
assert.deepEqual(result.matchedOrderIds, [ 101, 102 ]);
});
it('require_same_express=true 时应按同结构主快递优先命中', async () => {
const { service } = createHarness();
const orders = [
{
id: 201,
store_id: 11,
items_count: 1,
items_total: 1,
items_hash: 'hash_express_same_structure',
logistics_code: 'YD',
sys_logistics_code: 'YD',
logistics_name: '韵达',
province: 'zj',
sys_platform_code: 'PDD',
source_platform_code: '',
},
{
id: 202,
store_id: 11,
items_count: 1,
items_total: 1,
items_hash: 'hash_express_same_structure',
logistics_code: 'YD',
sys_logistics_code: 'YD',
logistics_name: '韵达',
province: 'zj',
sys_platform_code: 'PDD',
source_platform_code: '',
},
{
id: 203,
store_id: 11,
items_count: 1,
items_total: 1,
items_hash: 'hash_express_same_structure',
logistics_code: 'SF',
sys_logistics_code: 'SF',
logistics_name: '顺丰',
province: 'zj',
sys_platform_code: 'PDD',
source_platform_code: '',
},
];
const strategyList = [
{
strategy_id: 1002,
order_min_sku: 1,
order_max_sku: 999,
order_min_qty: 1,
order_max_qty: 999,
min_same_structure: 1,
max_same_structure: 999,
allowed_owners: [],
allowed_expresses: [],
allowed_provinces: [],
allowed_platforms: [],
allow_cross_owner: true,
require_same_express: true,
},
];
const result = await runWaveStrategyQuickScanRunner({
orders,
strategyList,
getStructureKey: order => service.getWaveStrategyQuickScanStructureKey(order),
getExpressKey: order => service.getWaveStrategyQuickScanExpressKey(order),
getMatchedStrategyIds: (order, normalizedStrategyList, context) => service.getWaveStrategyQuickScanMatchedStrategyIds(
order,
normalizedStrategyList,
context
),
});
assert.deepEqual(result.matchedOrderIds, [ 201, 202 ]);
});
});

View File

@ -14,6 +14,15 @@ function createHarness(options = {}) {
max_wave_quantity: 500,
};
const expressRows = Array.isArray(options.expressRows) ? options.expressRows : [
{ code: 'STO', name: '申通快递' },
{ code: 'YTO', name: '圆通快递' },
];
const platformRows = Array.isArray(options.platformRows) ? options.platformRows : [
{ code: 'TB', name: '淘宝' },
{ code: 'JD', name: '京东' },
];
const storeRecord = {
id: Number(options.storeId || 100000),
subject_config: {
@ -51,6 +60,26 @@ function createHarness(options = {}) {
};
},
},
...(options.withoutExpressModel ? {} : {
Express: {
async findAll() {
if (options.expressQueryShouldThrow) {
throw new Error('query express failed');
}
return expressRows;
},
},
}),
...(options.withoutPlatformModel ? {} : {
Platform: {
async findAll() {
if (options.platformQueryShouldThrow) {
throw new Error('query platform failed');
}
return platformRows;
},
},
}),
},
};
@ -101,4 +130,84 @@ describe('test/app/service/systems/setting/warehouse.test.js', () => {
}
);
});
it('外部传入 wave_strategy_version 不应覆盖现有内部版本,且响应不暴露该字段', async () => {
const { ctx, calls } = createHarness({
initialSubjectConfig: {
max_wave_quantity: 500,
wave_strategy_version: 9,
},
});
const service = new SettingWarehouseService(ctx);
const result = await service.saveSettings({
subject_config: {
wave_strategy_version: 2,
max_wave_quantity: 700,
},
});
assert.equal(calls.updatePayload.subject_config.wave_strategy_version, 9);
assert.equal(calls.updatePayload.subject_config.max_wave_quantity, 700);
assert.equal(Object.prototype.hasOwnProperty.call(result.subject_config, 'wave_strategy_version'), false);
});
it('should omit internal wave_strategy_version from getSettings response', async () => {
const { ctx } = createHarness({
initialSubjectConfig: {
max_wave_quantity: 500,
wave_strategy_version: 3,
},
});
const service = new SettingWarehouseService(ctx);
const result = await service.getSettings();
assert.equal(result.warehouse_id, 100000);
assert.equal(Object.prototype.hasOwnProperty.call(result.subject_config, 'wave_strategy_version'), false);
assert.equal(result.subject_config.max_wave_quantity, 500);
});
it('should include dynamic options for default_express_code and default_platform_code', async () => {
const { ctx } = createHarness();
const service = new SettingWarehouseService(ctx);
const list = await service.getFieldMeta();
const defaultExpressField = list.find(item => item.key === 'default_express_code');
const defaultPlatformField = list.find(item => item.key === 'default_platform_code');
assert.ok(defaultExpressField, '字段信息应包含 default_express_code');
assert.ok(defaultPlatformField, '字段信息应包含 default_platform_code');
assert.ok(Array.isArray(defaultExpressField.options), 'default_express_code 应包含 options 数组');
assert.ok(Array.isArray(defaultPlatformField.options), 'default_platform_code 应包含 options 数组');
assert.ok(defaultExpressField.options.every(option => option && typeof option.value === 'string' && typeof option.label === 'string'));
assert.ok(defaultPlatformField.options.every(option => option && typeof option.value === 'string' && typeof option.label === 'string'));
assert.deepEqual(defaultExpressField.options, [
{ value: 'STO', label: '申通快递' },
{ value: 'YTO', label: '圆通快递' },
]);
assert.deepEqual(defaultPlatformField.options, [
{ value: 'TB', label: '淘宝' },
{ value: 'JD', label: '京东' },
]);
});
it('should degrade gracefully when model missing or query fails', async () => {
const { ctx } = createHarness({
withoutExpressModel: true,
platformQueryShouldThrow: true,
});
const service = new SettingWarehouseService(ctx);
const list = await service.getFieldMeta();
const defaultExpressField = list.find(item => item.key === 'default_express_code');
const defaultPlatformField = list.find(item => item.key === 'default_platform_code');
assert.ok(defaultExpressField, '字段信息应包含 default_express_code');
assert.ok(defaultPlatformField, '字段信息应包含 default_platform_code');
assert.deepEqual(defaultExpressField.options, []);
assert.deepEqual(defaultPlatformField.options, []);
});
});

37
tmp/verify_migration.cjs Normal file
View File

@ -0,0 +1,37 @@
'use strict';
(async () => {
try {
const cfg = require('../database/config.js').production;
const mysql = require('mysql2/promise');
const conn = await mysql.createConnection({
host: cfg.host,
user: cfg.username || cfg.user,
password: cfg.password,
database: cfg.database,
port: cfg.port || 3306,
});
const migrationName = '20260507100000-create-wms_order_wave_strategy_match.js';
const schema = cfg.database;
const [metaRows] = await conn.query('SELECT name FROM SequelizeMeta WHERE name = ? LIMIT 1', [migrationName]);
const migrationInMeta = (metaRows.length && metaRows.length > 0) ? true : false;
const [tableRows] = await conn.query('SELECT TABLE_NAME FROM information_schema.tables WHERE table_schema = ? AND table_name = ?', [schema, 'wms_order_wave_strategy_match']);
const tableExists = (tableRows.length && tableRows.length > 0) ? true : false;
const [columnsRows] = await conn.query('SELECT COLUMN_NAME FROM information_schema.columns WHERE table_schema = ? AND table_name = ? AND COLUMN_NAME IN (?,?,?,?,?)', [schema, 'wms_order_wave_strategy_match', 'id','warehouse_id','order_id','strategy_id','create_time']);
const columns = (columnsRows || []).map(r => r.COLUMN_NAME);
const [idxRows] = await conn.query('SELECT DISTINCT INDEX_NAME FROM information_schema.statistics WHERE table_schema = ? AND table_name = ? AND INDEX_NAME IN (?,?)', [schema, 'wms_order_wave_strategy_match', 'idx_warehouse_order', 'idx_warehouse_strategy']);
const indices = (idxRows || []).map(r => r.INDEX_NAME);
console.log(JSON.stringify({ migrationInMeta, tableExists, columns, indices }, null, 2));
await conn.end();
process.exit(0);
} catch (err) {
console.error('ERROR:', err && err.message ? err.message : err);
process.exit(2);
}
})();