Compare commits

...

2 Commits

Author SHA1 Message Date
liufumingren
2817d17fc7 1 2026-07-06 00:33:12 +08:00
liufumingren
7854057244 chore: ESLint auto-fix formatting (JSDoc, spacing, quotes, line endings) 2026-07-04 23:30:32 +08:00
41 changed files with 1449 additions and 362 deletions

View File

@ -31,6 +31,17 @@ const BATCH_UNLOCK_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24;
const BATCH_UNINTERCEPT_TASK_CACHE_KEY_PREFIX = 'order:batch-unintercept:';
const BATCH_UNINTERCEPT_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24;
const SYNC_ORDER_IDS_TASK_CACHE_KEY_PREFIX = 'order:pending:sync_order_ids:request:';
const SYNC_ORDER_IDS_TASK_CACHE_TTL_SECONDS = 60 * 60 * 2;
const SYNC_ORDER_IDS_PROGRESS_MAP = Object.freeze({
submitted: 5,
running: 50,
success: 100,
failed: 100,
not_found: 0,
unknown: 0,
});
/**
* 中国行政区划反向查询表。
*
@ -506,9 +517,9 @@ class PendingOrderService extends OrderBaseService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill';
const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill';
const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill';
const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill';
const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill';
const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
@ -1374,6 +1385,88 @@ class PendingOrderService extends OrderBaseService {
}
}
// ========== syncOrderIds 异步任务进度缓存工具方法 ==========
/**
* 获取订单同步任务缓存键。
*
* @param {string} requestId 请求ID。
* @return {string} 缓存键。
*/
getSyncOrderIdsTaskCacheKey(requestId = '') {
const normalizedRequestId = String(requestId || '').trim();
if (!normalizedRequestId) {
return '';
}
return `${SYNC_ORDER_IDS_TASK_CACHE_KEY_PREFIX}${normalizedRequestId}`;
}
/**
* 规范订单同步任务请求ID。
*
* @param {Object} data 请求体。
* @return {string} 归一化后的请求ID。
*/
normalizeSyncOrderIdsRequestId(data = {}) {
const normalizedData = this.isPlainObject(data) ? data : {};
return String(normalizedData.request_id || normalizedData.requestId || '').trim();
}
/**
* 写入订单同步任务进度。
*
* @param {string} requestId 请求ID。
* @param {Object} payload 任务状态与结果。
* @return {Promise<void>}
*/
async setSyncOrderIdsTaskProgress(requestId = '', payload = {}) {
const cacheKey = this.getSyncOrderIdsTaskCacheKey(requestId);
if (!cacheKey || typeof this.app.setCacheAsync !== 'function') {
return;
}
const safePayload = this.isPlainObject(payload) ? payload : {};
const progressPayload = {
...safePayload,
request_id: String(requestId || '').trim(),
update_time: Date.now(),
};
try {
await this.app.setCacheAsync(cacheKey, progressPayload, SYNC_ORDER_IDS_TASK_CACHE_TTL_SECONDS);
} catch (error) {
this.ctx.logger.warn('[pendingOrder.syncOrderIds] 写入任务进度缓存失败: %s', error && error.message ? error.message : error);
}
}
/**
* 读取订单同步任务进度。
*
* @param {string} requestId 请求ID。
* @return {Promise<Object|null>} 任务缓存结果。
*/
async getSyncOrderIdsTaskProgress(requestId = '') {
const cacheKey = this.getSyncOrderIdsTaskCacheKey(requestId);
if (!cacheKey || typeof this.app.getCacheAsync !== 'function') {
return null;
}
try {
const cached = await this.app.getCacheAsync(cacheKey);
if (!this.isPlainObject(cached)) {
return null;
}
return cached;
} catch (error) {
this.ctx.logger.warn('[pendingOrder.syncOrderIds] 读取任务进度缓存失败: %s', error && error.message ? error.message : error);
return null;
}
}
// ========== syncOrderIds 异步任务进度缓存工具方法结束 ==========
/**
* 将待处理订单批量取消储位分配。
*
@ -1494,13 +1587,20 @@ class PendingOrderService extends OrderBaseService {
}
/**
* 同步待处理订单。
* 同步待处理订单(异步模式)。
*
* 当前仅接收 `order_ids` 并原样转发到服务层,暂不执行任何实际同步处理;
* 等后续同步逻辑明确后,再在对应 service 中补齐实现。
* 立即生成 request_id 并返回,后台通过 setImmediate 异步执行实际的订单同步流程。
* 调用方可通过 syncOrderIdsProgress 接口轮询任务进度与最终结果。
*
* 后台处理流程:
* ① 事务内查询订单 + 校验(SN、快递状态)+ 更新 sync_status='padding' + commit
* ② 按 create_channel 分组并行派发(QM / MANUAL / API)
* ③ 单订单失败静默写入 error 状态 + 异常标记,不影响整批结果
* ④ 写入操作日志 + 更新最终进度
*
* @param {Object} data 请求体。
* @return {Promise<Object>} 统一 success 包装的同步结果。
* @param {Array<number|string>|string|number} data.order_ids 订单ID(支持数组、逗号字符串、单个ID,兼容 orderIds/ids 等多种别名)。
* @return {Promise<Object>} 统一 success 包装,含 request_id。
*/
async syncOrderIds(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
@ -1513,21 +1613,248 @@ class PendingOrderService extends OrderBaseService {
?? requestData.id,
};
console.log('[PendingOrderService.syncOrderIds] 归一化入参', normalizedData);
// 快照 ctx 数据(setImmediate 回调中 ctx 可能已失效)
const warehouseId = this.getWarehouseId();
const operator = this.getOrderLogOperator();
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
try {
console.log('[PendingOrderService.syncOrderIds] 调用 orderStorageAllocation.syncOrderIds 前', normalizedData);
const result = await this.service.systems.orderStorageAllocation.syncOrderIds(normalizedData);
console.log('[PendingOrderService.syncOrderIds] 调用 orderStorageAllocation.syncOrderIds 成功', result);
const timestamp = Date.now();
const randomToken = Math.random().toString(36).slice(2, 10);
const requestId = `sync_order_${warehouseId ?? 'unknown'}_${timestamp}_${randomToken}`;
return this.success('ok', result);
} catch (error) {
console.log('[PendingOrderService.syncOrderIds] 调用 orderStorageAllocation.syncOrderIds 异常', {
normalizedData,
error,
});
throw error;
// 初始化进度:submitted
await this.setSyncOrderIdsTaskProgress(requestId, {
status: 'submitted',
total_count: 0,
processed_count: 0,
progress: 0,
warehouse_id: warehouseId,
order_ids: normalizedData.order_ids,
});
this.ctx.logger.info('[PendingOrderService.syncOrderIds] 任务已提交', {
request_id: requestId,
warehouseId,
orderCount: Array.isArray(normalizedData.order_ids)
? normalizedData.order_ids.length
: (normalizedData.order_ids ? 1 : 0),
});
// 后台异步执行
setImmediate(async () => {
try {
await this.setSyncOrderIdsTaskProgress(requestId, {
status: 'running',
total_count: 0,
processed_count: 0,
progress: 0,
warehouse_id: warehouseId,
});
const result = await this.service.systems.orderStorageAllocation.syncOrderIds({
...normalizedData,
warehouse_id: warehouseId,
request_id: requestId,
});
// 最终进度:success(从结果中取真实数量)
const resultData = result && result.data ? result.data : {};
const finalTotal = Number(resultData.pending_count || 0);
const finalProcessed = finalTotal;
const finalProgress = 100;
await this.setSyncOrderIdsTaskProgress(requestId, {
status: 'success',
total_count: finalTotal,
processed_count: finalProcessed,
progress: finalProgress,
warehouse_id: warehouseId,
result,
});
// 静默写操作日志(不影响主流程)
try {
const opLogService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.operationLog;
if (opLogService && typeof opLogService.createOperationLogs === 'function') {
const rawOrderIds = Array.isArray(normalizedData.order_ids)
? normalizedData.order_ids
: (normalizedData.order_ids ? [ normalizedData.order_ids ] : []);
const resultData = result && result.data ? result.data : {};
const pendingSet = new Set((resultData.pending_order_ids || []).map(Number));
const skippedMap = new Map();
const failedMap = new Map();
for (const item of (resultData.skipped_orders || [])) {
skippedMap.set(Number(item.order_id), item.skipped_reason || 'unknown');
}
for (const item of (resultData.failed_orders || [])) {
failedMap.set(Number(item.order_id), item.failed_reason || 'unknown');
}
const skipReasonMap = { not_found: '订单不存在', already_synced: '已同步' };
const failReasonMap = { express_unallocated: '快递未分配', sn_batch_forbidden: 'SN订单不支持批量' };
const dispatchChannels = (resultData.dispatch_results || [])
.map(r => r.create_channel).filter(Boolean).join('/') || 'unknown';
const logPayloads = rawOrderIds.map(orderId => {
const oid = Number(orderId);
let msg;
if (pendingSet.has(oid)) {
msg = `同步到${dispatchChannels}渠道`;
} else if (failedMap.has(oid)) {
const reason = failedMap.get(oid);
msg = `同步跳过:${failReasonMap[reason] || reason}`;
} else if (skippedMap.has(oid)) {
const reason = skippedMap.get(oid);
msg = `同步跳过:${skipReasonMap[reason] || reason}`;
} else {
msg = '同步跳过';
}
return {
businessType: 'order',
businessId: String(oid),
operationCode: 'ORDER_SYNC',
operator,
extras: {
message: msg,
warehouseId: logWarehouseId,
externalLogType: 'NONE',
},
};
}).filter(item => Number(item.businessId) > 0);
if (logPayloads.length > 0) {
await opLogService.createOperationLogs(logPayloads);
}
}
} catch (logErr) {
this.ctx.logger.warn('[PendingOrderService.syncOrderIds] 写入操作日志失败,不影响主流程', {
request_id: requestId,
error: logErr && logErr.message,
});
}
this.ctx.logger.info('[PendingOrderService.syncOrderIds] 后台同步任务完成', {
request_id: requestId,
status: result && result.code,
message: result && result.message,
});
} catch (error) {
// 整体失败也静默写入进度
try {
const cached = await this.getSyncOrderIdsTaskProgress(requestId);
const cachedTotal = cached && Number(cached.total_count || 0);
await this.setSyncOrderIdsTaskProgress(requestId, {
status: 'failed',
total_count: cachedTotal || 0,
processed_count: cached && Number(cached.processed_count || 0),
progress: cached && Number(cached.progress || 0),
warehouse_id: warehouseId,
error: error && error.message ? error.message : String(error),
});
} catch (cacheErr) {
this.ctx.logger.warn('[PendingOrderService.syncOrderIds] 写入失败进度缓存失败', {
request_id: requestId,
error: cacheErr && cacheErr.message,
});
}
// 写操作日志:崩溃场景下 service 层可能不可用,直接用 model 直写
try {
const rawOrderIds = Array.isArray(normalizedData.order_ids)
? normalizedData.order_ids
: (normalizedData.order_ids ? [ normalizedData.order_ids ] : []);
const errorMsg = error && error.message ? String(error.message) : String(error);
if (rawOrderIds.length > 0 && this.ctx.model && this.ctx.model.OperationLog) {
const operatorId = operator.id;
const operatorName = operator.name || 'system';
const now = new Date();
const logRows = rawOrderIds.map(orderId => ({
business_type: 'order',
business_id: String(orderId),
operation_code: 'ORDER_SYNC_FAILED',
operator_id: operatorId,
operator_name: operatorName,
external_log_type: 'NONE',
warehouse_id: logWarehouseId || null,
platform_code: 'SYSTEM',
message: `订单同步失败:${errorMsg}`,
created_at: now,
})).filter(row => Number(row.business_id) > 0);
if (logRows.length > 0) {
await this.ctx.model.OperationLog.bulkCreate(logRows);
}
}
} catch (logErr) {
this.ctx.logger.warn('[PendingOrderService.syncOrderIds] 写入失败操作日志失败,不影响主流程', {
request_id: requestId,
error: logErr && logErr.message,
});
}
this.ctx.logger.error('[PendingOrderService.syncOrderIds] 后台同步任务异常', {
request_id: requestId,
warehouseId,
error: error && error.message ? error.message : error,
stack: error && error.stack ? error.stack : '',
});
}
});
// 立即返回 request_id
return this.success('同步任务已提交,可通过 syncOrderIdsProgress 查询进度', {
request_id: requestId,
warehouse_id: warehouseId,
message: '同步任务已提交,后台处理中',
});
}
/**
* 查询订单同步任务进度。
*
* @param {Object} data 请求体。
* @param {string} data.request_id 请求ID(下划线写法)。
* @param {string} data.requestId 请求ID(驼峰写法)。
* @return {Promise<Object>} 任务进度响应,含 status / progress / total_count / processed_count / result。
*/
async syncOrderIdsProgress(data = {}) {
const requestId = this.normalizeSyncOrderIdsRequestId(data);
if (!requestId) {
return this.fail('request_id 参数不能为空', {}, 400);
}
const cachedProgress = await this.getSyncOrderIdsTaskProgress(requestId);
if (!cachedProgress) {
return this.success('ok', {
request_id: requestId,
status: 'not_found',
progress: SYNC_ORDER_IDS_PROGRESS_MAP.not_found,
total_count: 0,
processed_count: 0,
});
}
const normalizedStatus = String(cachedProgress.status || 'unknown').trim() || 'unknown';
return this.success('ok', {
request_id: requestId,
status: normalizedStatus,
progress: Number.isFinite(Number(cachedProgress.progress))
? Math.min(100, Math.max(0, Math.round(Number(cachedProgress.progress))))
: (SYNC_ORDER_IDS_PROGRESS_MAP[normalizedStatus] ?? SYNC_ORDER_IDS_PROGRESS_MAP.unknown),
total_count: Number(cachedProgress.total_count || 0),
processed_count: Number(cachedProgress.processed_count || 0),
warehouse_id: Number(cachedProgress.warehouse_id || 0),
result: cachedProgress.result || null,
error: cachedProgress.error || '',
update_time: cachedProgress.update_time || null,
});
}
/**
@ -2414,7 +2741,7 @@ class PendingOrderService extends OrderBaseService {
const [ affectedRows ] = await model.update(
{ remark: remarkValue, updated_at: now },
{ where },
{ where }
);
const count = Number(affectedRows || 0);

View File

@ -3520,7 +3520,7 @@ class RecheckOrderService extends OrderBaseService {
where: this.buildOrderWhere(orderIds, warehouseId),
attributes: [
'id', 'delivery_order_code', 'pre_delivery_order_code',
'storage_status', 'post_status', 'status', 'intercept_status',
'storage_status', 'post_status', 'sync_status', 'status', 'intercept_status',
'pick_status', 'recheck_status', 'wave_id', 'wave_no',
],
raw: true,
@ -3573,8 +3573,8 @@ class RecheckOrderService extends OrderBaseService {
continue;
}
const orderStatus = String(order.status || '').trim();
if (orderStatus !== 'created') {
const syncStatus = String(order.sync_status || '').trim();
if (syncStatus !== 'fin') {
failedOrders.push({
order_id: orderId,
delivery_order_code: String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(),

View File

@ -11,9 +11,9 @@ class PickService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'query,wavePickTaskDetail,wavePickTaskCurrent,wavePickTaskSubmit,wavePickTaskComplete';
const _noNeedRight = 'query,wavePickComplete,wavePickTaskDetail,wavePickTaskCurrent,wavePickTaskSubmit,wavePickTaskComplete';
const _noNeedLog = 'query';
const _noNeedAuth = 'query,wavePickTaskDetail,wavePickTaskCurrent,wavePickTaskSubmit,wavePickTaskComplete';
const _noNeedAuth = 'query,wavePickComplete,wavePickTaskDetail,wavePickTaskCurrent,wavePickTaskSubmit,wavePickTaskComplete';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
@ -860,6 +860,240 @@ class PickService extends MainService {
}
}
/**
* 按波次号一键完成拣货。
*
* 内部复用 query 的去重与任务创建逻辑:
* - 若波次已有当前用户的活动任务 → 直接复用并完成。
* - 若波次已有他人活动任务 → 返回 409 冲突。
* - 若波次已完成 → 返回 already_completed。
* - 否则新建任务(source=2,后台抓取),创建成功后在内部调用 wavePickTaskComplete(mode=1 全部确认)完成拣货。
*
* @param {Object} data 请求参数。
* @param {number|string} data.wave_id 波次ID。
* @return {Promise<Object>} 统一 success/fail 包装结果。
*/
async wavePickComplete(data = {}) {
const { service, ctx } = this;
const requestData = this.isPlainObject(data) ? data : {};
const waveId = Number(requestData.wave_id || requestData.waveId || 0);
if (!Number.isInteger(waveId) || waveId <= 0) {
return this.fail('wave_id 必填且必须为正整数', {}, 400);
}
// --- 解析操作人上下文(与 query 保持一致)---
const userWarehouseId = ctx && ctx.user ? ctx.user.store_id : undefined;
const stateWarehouseId = ctx && ctx.state && ctx.state.user ? ctx.state.user.store_id : undefined;
const normalizedWarehouseId = Number(userWarehouseId || stateWarehouseId || 0);
if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
return this.fail('缺少当前用户仓库上下文 store_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);
const operatorName = String(
operatorSource.operator_name
|| operatorSource.employees_name
|| operatorSource.name
|| ''
).trim() || 'system';
if (!Number.isInteger(operatorId) || operatorId <= 0) {
return this.fail('未获取到操作人上下文', {}, 401);
}
// --- 按 wave_id 直接查波次 ---
const waveRows = await ctx.model.query(
`SELECT wave_id, wave_no, wave_type
FROM wms_wave_batch
WHERE warehouse_id = :warehouseId
AND wave_id = :waveId
LIMIT 1`,
{
replacements: { warehouseId: normalizedWarehouseId, waveId },
type: ctx.model.QueryTypes.SELECT,
}
);
const waveRow = Array.isArray(waveRows) && waveRows.length > 0 ? waveRows[0] : null;
if (!waveRow) {
return this.fail('波次不存在或不属于当前仓库', {}, 404);
}
const targetWaveId = Number(waveRow.wave_id || 0);
const targetWaveNo = String(waveRow.wave_no || '').trim();
const targetWaveType = Number(waveRow.wave_type || 2);
if (!Number.isInteger(targetWaveId) || targetWaveId <= 0 || !targetWaveNo) {
return this.fail('目标波次信息不完整', {}, 400);
}
// --- 去重:活动任务检查(与 query 一致)---
const activeTaskRows = await ctx.model.query(
`SELECT t.id AS task_id, t.pick_user_id, t.pick_user_name
FROM wms_wave_pick_task t
WHERE t.warehouse_id = :warehouseId
AND t.status IN (0, 1)
AND (
t.wave_id = :waveId
OR EXISTS (
SELECT 1
FROM wms_wave_pick_task_wave tw
WHERE tw.task_id = t.id
AND tw.wave_id = :waveId
)
)
ORDER BY t.id DESC
LIMIT 1`,
{
replacements: { waveId: targetWaveId, warehouseId: normalizedWarehouseId },
type: ctx.model.QueryTypes.SELECT,
}
);
const activeTask = Array.isArray(activeTaskRows) && activeTaskRows.length > 0 ? activeTaskRows[0] : null;
let taskId = 0;
if (activeTask) {
const activeTaskId = Number(activeTask.task_id || 0);
const taskOwnerId = Number(activeTask.pick_user_id || 0);
const taskOwnerName = String(activeTask.pick_user_name || '').trim() || `${taskOwnerId}`;
if (taskOwnerId > 0 && taskOwnerId !== operatorId) {
return this.fail(
`当前波次已由其他人创建活动任务,请移交任务创建人处理(创建人: ${taskOwnerName},任务ID: ${activeTaskId})`,
{ task_id: activeTaskId, task_owner_id: taskOwnerId, task_owner_name: taskOwnerName },
409
);
}
// 当前用户的活动任务,直接复用
taskId = activeTaskId;
}
// --- 去重:已完成任务检查(与 query 一致)---
if (taskId <= 0) {
const completedTaskRows = await ctx.model.query(
`SELECT t.id AS task_id
FROM wms_wave_pick_task t
WHERE t.warehouse_id = :warehouseId
AND t.status IN (2, 3)
AND (
t.wave_id = :waveId
OR EXISTS (
SELECT 1
FROM wms_wave_pick_task_wave tw
WHERE tw.task_id = t.id
AND tw.wave_id = :waveId
)
)
ORDER BY t.id DESC
LIMIT 1`,
{
replacements: { waveId: targetWaveId, warehouseId: normalizedWarehouseId },
type: ctx.model.QueryTypes.SELECT,
}
);
const completedTask = Array.isArray(completedTaskRows) && completedTaskRows.length > 0 ? completedTaskRows[0] : null;
if (completedTask) {
return this.success('ok', {
data: {
task_id: Number(completedTask.task_id),
status: 'already_completed',
tip: '该波次已完成拣货任务,无需重复操作',
},
code: 200,
});
}
}
// --- 无已有任务则创建新任务(与 query 一致)---
if (taskId <= 0) {
let orderModel = null;
try {
orderModel = await this.getOrderModelByWarehouse(normalizedWarehouseId);
} catch (error) {
return this.fail(error && error.message ? error.message : '订单模型不可用', {}, 500);
}
const orderRows = await orderModel.findAll({
where: { warehouse_id: normalizedWarehouseId, wave_id: targetWaveId },
attributes: [ 'id' ],
raw: true,
});
let selectedOrderIds = [ ...new Set((Array.isArray(orderRows) ? orderRows : [])
.map(item => Number(item && item.id || 0))
.filter(id => Number.isInteger(id) && id > 0)) ];
if (selectedOrderIds.length <= 0) {
const fallbackRows = await orderModel.findAll({
where: { warehouse_id: normalizedWarehouseId, wave_no: targetWaveNo },
attributes: [ 'id' ],
raw: true,
});
selectedOrderIds = [ ...new Set((Array.isArray(fallbackRows) ? fallbackRows : [])
.map(item => Number(item && item.id || 0))
.filter(id => Number.isInteger(id) && id > 0)) ];
}
if (selectedOrderIds.length <= 0) {
return this.fail('波次下无可用订单,无法创建任务', {}, 400);
}
const normalizedWaveType = Number(targetWaveType || 2);
const isGroupWave = normalizedWaveType === 1;
const pickMode = isGroupWave ? 1 : 2;
try {
const createdTask = await this.createWavePickTask({
warehouseId: normalizedWarehouseId,
waveId: targetWaveId,
waveNo: targetWaveNo,
pickMode,
operatorId,
operatorName,
orderIds: selectedOrderIds,
remark: `pick.wavePickComplete wave_id=${waveId}`,
source: 2,
});
taskId = createdTask.task_id;
} catch (error) {
const code = Number(error && error.code);
if (Number.isFinite(code) && code >= 400 && code < 600) {
return this.fail(error.message || '任务创建失败', {}, code);
}
ctx.logger.error('[PickService.wavePickComplete] 创建波次任务失败: %s', error && error.message ? error.message : error);
return this.fail('任务创建失败', {}, 500);
}
}
// --- 任务已就绪,调用内部 wavePickTaskComplete 全部确认完成 ---
try {
const result = await service.systems.pick.wavePickTaskComplete({
taskId,
mode: 1,
orderIds: [],
});
return this.success('ok', {
data: {
...result,
status: 'completed',
tip: '波次拣货已完成',
},
code: 200,
});
} catch (error) {
const code = Number(error && error.code);
if (Number.isInteger(code) && code >= 400 && code < 600) {
const errorData = this.isPlainObject(error && error.data) ? error.data : {};
return this.fail(error.message || '拣货完成失败', errorData, code);
}
ctx.logger.error('[PickService.wavePickComplete] 完成拣货失败: %s', error && error.message ? error.message : error);
return this.fail('拣货完成失败', {}, 500);
}
}
/**
* 完全提交拣货任务。
*

View File

@ -8,6 +8,32 @@ const CREATE_CHANNEL_API = 'API';
const RETRYABLE_DATABASE_ERROR_CODES = new Set([ 1205, 1213, 'ER_LOCK_WAIT_TIMEOUT', 'ER_LOCK_DEADLOCK' ]);
const TRANSACTION_LOCK_RETRY_MAX_ATTEMPTS = 3;
const TRANSACTION_LOCK_RETRY_BASE_DELAY_MS = 50;
const DISPATCH_BATCH_SIZE = 20;
const SYNC_ORDER_IDS_PROGRESS_CACHE_TTL = 7200;
function getSyncOrderIdsProgressCacheKey(requestId) {
if (!requestId) return null;
return `order:pending:sync_order_ids:request:${String(requestId).trim()}`;
}
async function updateDispatchBatchProgress(service, cacheKey, batchSize) {
if (!cacheKey || !service || !service.app) return;
try {
const cached = await service.app.getCacheAsync(cacheKey);
if (cached && typeof cached === 'object') {
const total = Number(cached.total_count || 0);
const processed = Number(cached.processed_count || 0) + Number(batchSize || 0);
await service.app.setCacheAsync(cacheKey, {
...cached,
processed_count: processed,
progress: total > 0 ? Math.min(100, Math.round(processed / total * 100)) : 0,
update_time: Date.now(),
}, SYNC_ORDER_IDS_PROGRESS_CACHE_TTL);
}
} catch (err) {
// 进度更新失败不影响主流程
}
}
function normalizeDatabaseErrorCodeInternal(error) {
const code = error && (error.code
@ -382,18 +408,25 @@ async function syncManualOrdersInternal(service, groupedOrder = {}, context = {}
const waybillCodeMap = await buildOrderWaybillCodeMapInternal(service, orderIds);
const syncResults = await Promise.all(orderIds.map(orderId => {
return processManualOrderInternal(
service,
orderModel,
orderItemsModel,
orderId,
warehouseId,
orderMap.get(orderId),
context,
waybillCodeMap.get(orderId)
);
}));
const progressCacheKey = getSyncOrderIdsProgressCacheKey(context.request_id);
const syncResults = [];
for (let i = 0; i < orderIds.length; i += DISPATCH_BATCH_SIZE) {
const batch = orderIds.slice(i, i + DISPATCH_BATCH_SIZE);
const batchResults = await Promise.all(batch.map(orderId => {
return processManualOrderInternal(
service,
orderModel,
orderItemsModel,
orderId,
warehouseId,
orderMap.get(orderId),
context,
waybillCodeMap.get(orderId)
);
}));
syncResults.push(...batchResults);
await updateDispatchBatchProgress(service, progressCacheKey, batchResults.length);
}
const successCount = syncResults.filter(item => item.status === 'success').length;
const failedCount = syncResults.filter(item => item.status === 'failed').length;
@ -785,17 +818,24 @@ async function finalizeLocalChannelOrdersInternal(service, createChannel, groupe
void orderItemRows;
const syncResults = await Promise.all(orderIds.map(orderId => {
return processLocalChannelOrderInternal(
service,
createChannel,
orderModel,
orderItemsModel,
orderId,
warehouseId,
orderMap.get(orderId)
);
}));
const progressCacheKey = getSyncOrderIdsProgressCacheKey(context.request_id);
const syncResults = [];
for (let i = 0; i < orderIds.length; i += DISPATCH_BATCH_SIZE) {
const batch = orderIds.slice(i, i + DISPATCH_BATCH_SIZE);
const batchResults = await Promise.all(batch.map(orderId => {
return processLocalChannelOrderInternal(
service,
createChannel,
orderModel,
orderItemsModel,
orderId,
warehouseId,
orderMap.get(orderId)
);
}));
syncResults.push(...batchResults);
await updateDispatchBatchProgress(service, progressCacheKey, batchResults.length);
}
const successCount = syncResults.filter(item => item.status === 'success').length;
const failedCount = syncResults.filter(item => item.status === 'failed').length;
@ -1134,20 +1174,27 @@ async function syncQmOrdersInternal(service, groupedOrder = {}, context = {}) {
}
const qimenClient = service.app.qimenClient;
const qimenResults = await Promise.all(orderIds.map(orderId => {
return processQmOrderInternal(
service,
orderModel,
orderItemsModel,
qimenClient,
orderId,
warehouseId,
orderMap.get(orderId),
itemsByOrderId.get(orderId) || [],
context,
waybillCodeMap.get(orderId)
);
}));
const progressCacheKey = getSyncOrderIdsProgressCacheKey(context.request_id);
const qimenResults = [];
for (let i = 0; i < orderIds.length; i += DISPATCH_BATCH_SIZE) {
const batch = orderIds.slice(i, i + DISPATCH_BATCH_SIZE);
const batchResults = await Promise.all(batch.map(orderId => {
return processQmOrderInternal(
service,
orderModel,
orderItemsModel,
qimenClient,
orderId,
warehouseId,
orderMap.get(orderId),
itemsByOrderId.get(orderId) || [],
context,
waybillCodeMap.get(orderId)
);
}));
qimenResults.push(...batchResults);
await updateDispatchBatchProgress(service, progressCacheKey, batchResults.length);
}
const successCount = qimenResults.filter(item => item.status === 'success').length;
const failedCount = qimenResults.filter(item => item.status === 'failed').length;

View File

@ -1613,8 +1613,17 @@ class OrderStorageAllocationService extends MainService {
};
const orderIds = normalizeOrderIds(requestData);
const warehouseId = normalizeNumber(ctx.user?.store_id ?? ctx.user?.warehouse_id, 0);
// 优先使用调用方传入的 warehouse_id(异步模式下 ctx.user 可能失效),
// 兜底从 ctx.user 或 requestData 中读取
const warehouseId = normalizeNumber(
requestData.warehouse_id
?? ctx.user?.store_id
?? ctx.user?.warehouse_id,
0
);
const now = new Date();
// 请求ID(用于 Redis 进度缓存)
const requestId = String(requestData.request_id || requestData.requestId || '').trim();
if (warehouseId <= 0) {
return {
@ -1642,6 +1651,11 @@ class OrderStorageAllocationService extends MainService {
[ctx.app.Sequelize.Op.in]: orderIds,
},
warehouse_id: warehouseId,
// 排除已同步完成的订单,防止重复提交
// 注意:不能排除 padding,因为 padding 是新订单的默认值(模型 defaultValue)
sync_status: {
[ctx.app.Sequelize.Op.notIn]: [ 'fin' ],
},
},
transaction,
lock: transaction.LOCK.UPDATE,
@ -1718,20 +1732,6 @@ class OrderStorageAllocationService extends MainService {
}
}
if (snOrderIdSet.size > 0) {
const forbiddenOrderIds = Array.from(snOrderIdSet).sort((a, b) => a - b);
await transaction.rollback();
return {
code: 400,
message: snBatchForbiddenReason,
data: {
warehouse_id: warehouseId,
requested_order_ids: orderIds,
forbidden_order_ids: forbiddenOrderIds,
},
};
}
const skippedOrders = [];
const fastFailedOrders = [];
const syncableOrders = [];
@ -1758,6 +1758,18 @@ class OrderStorageAllocationService extends MainService {
continue;
}
// SN 管理订单不允许走批量回传,标记为跳过,不阻断其他订单
if (snOrderIdSet.has(orderId)) {
fastFailedOrders.push({
order_id: orderId,
status: 'failed',
create_channel: normalizeCreateChannel(orderRow.create_channel),
failed_reason: 'sn_batch_forbidden',
message: snBatchForbiddenReason,
});
continue;
}
const normalizedPostStatus = String(orderRow.post_status || '').trim() || unallocatedPostStatus;
if (normalizedPostStatus === unallocatedPostStatus) {
fastFailedOrders.push({
@ -1774,10 +1786,15 @@ class OrderStorageAllocationService extends MainService {
syncableOrders.push(orderRow);
}
const expressFastFailedOrderIds = fastFailedOrders
.filter(order => String(order && order.failed_reason || '').trim() === 'express_unallocated')
.map(order => normalizeNumber(order.order_id, 0))
.filter(orderId => orderId > 0);
// SN 订单和快递未分配订单分开设置 sync_message
const snFailIds = fastFailedOrders
.filter(o => String(o && o.failed_reason || '').trim() === 'sn_batch_forbidden')
.map(o => normalizeNumber(o.order_id, 0))
.filter(id => id > 0);
const expressFailIds = fastFailedOrders
.filter(o => String(o && o.failed_reason || '').trim() === 'express_unallocated')
.map(o => normalizeNumber(o.order_id, 0))
.filter(id => id > 0);
const syncableOrderIds = syncableOrders
.map(order => normalizeNumber(order.id, 0))
@ -1800,7 +1817,21 @@ class OrderStorageAllocationService extends MainService {
});
}
if (expressFastFailedOrderIds.length > 0) {
if (snFailIds.length > 0) {
await orderModel.update({
sync_status: 'error',
sync_message: snBatchForbiddenReason,
inspection_status: STORAGE_STATUS_ERROR,
step: ORDER_STEP_EXCEPTION,
order_flag: snBatchForbiddenReason,
updated_at: now,
}, {
where: { id: { [ctx.app.Sequelize.Op.in]: snFailIds }, warehouse_id: warehouseId },
transaction,
});
}
if (expressFailIds.length > 0) {
await orderModel.update({
sync_status: 'error',
sync_message: fastFailReason,
@ -1809,94 +1840,138 @@ class OrderStorageAllocationService extends MainService {
order_flag: fastFailReason,
updated_at: now,
}, {
where: {
id: {
[ctx.app.Sequelize.Op.in]: expressFastFailedOrderIds,
},
warehouse_id: warehouseId,
},
where: { id: { [ctx.app.Sequelize.Op.in]: expressFailIds }, warehouse_id: warehouseId },
transaction,
});
}
ctx.logger.warn('[OrderStorageAllocationService.syncOrderIds] 命中快递状态未分配快速失败,已阻断同步派发', {
if (snFailIds.length > 0 || expressFailIds.length > 0) {
ctx.logger.warn('[OrderStorageAllocationService.syncOrderIds] 命中快速失败,已阻断同步派发', {
warehouseId,
orderIds: expressFastFailedOrderIds,
reason: fastFailReason,
snFailIds,
expressFailIds,
});
}
await transaction.commit();
// ── 写初始进度到 Redis(dispatch handler 内部会递增 processed_count)──
if (requestId) {
const progressCacheKey = `order:pending:sync_order_ids:request:${requestId}`;
try {
await ctx.app.setCacheAsync(progressCacheKey, {
status: 'running',
total_count: syncableOrderIds.length,
processed_count: 0,
progress: 0,
warehouse_id: warehouseId,
update_time: Date.now(),
}, 7200);
} catch (cacheErr) {
ctx.logger.warn('[OrderStorageAllocationService.syncOrderIds] 初始化进度缓存失败', {
error: cacheErr && cacheErr.message,
});
}
}
const routeContext = {
warehouseId,
requestedOrderIds: orderIds,
pendingOrderIds: syncableOrderIds,
request_id: requestId,
};
const orderAsyncService = this.ctx.service.systems.orderAsync;
const dispatchResults = [];
for (const groupedOrder of createChannelGroups) {
const createChannel = normalizeCreateChannel(groupedOrder.create_channel);
let result;
// 并行派发各渠道分组(每个分组独立 try/catch,单渠道异常不阻塞其他渠道)
const dispatchResults = await Promise.all(
createChannelGroups.map(async groupedOrder => {
const createChannel = normalizeCreateChannel(groupedOrder.create_channel);
const groupOrderCount = Number(groupedOrder.order_count || groupedOrder.order_ids?.length || 0);
if (createChannel === 'QM') {
result = await orderAsyncService.syncQmOrders(groupedOrder, routeContext);
} else if (createChannel === 'API') {
result = await orderAsyncService.syncApiOrders(groupedOrder, routeContext);
} else {
result = await orderAsyncService.syncManualOrders(groupedOrder, routeContext);
try {
let result;
if (createChannel === 'QM') {
result = await orderAsyncService.syncQmOrders(groupedOrder, routeContext);
} else if (createChannel === 'API') {
result = await orderAsyncService.syncApiOrders(groupedOrder, routeContext);
} else {
result = await orderAsyncService.syncManualOrders(groupedOrder, routeContext);
}
const dispatchStatus = result && result.status
? String(result.status).trim() || 'success'
: (result && result.success === false ? 'failed' : 'success');
return {
...result,
status: dispatchStatus,
};
} catch (channelError) {
// 单渠道异常不影响其他渠道
ctx.logger.error('[OrderStorageAllocationService.syncOrderIds] 渠道派发异常,已隔离', {
createChannel,
warehouseId,
orderCount: groupOrderCount,
error: channelError && channelError.message ? channelError.message : channelError,
});
return {
create_channel: createChannel,
order_ids: Array.isArray(groupedOrder.order_ids) ? groupedOrder.order_ids : [],
order_count: groupOrderCount,
warehouse_id: warehouseId,
handler: 'syncOrderIds',
sync_target: createChannel === 'QM' ? 'qimen' : 'internal',
status: 'failed',
message: channelError && channelError.message ? channelError.message : '渠道派发异常',
success_count: 0,
failed_count: groupOrderCount,
route_state: 'rejected',
};
}
})
);
// 操作日志已移至 pendingOrder.syncOrderIds 层统一写入,避免重复
// 派发完成后,将成功渠道的订单 sync_status 更新为 fin,防止重复同步
const dispatchedOrderIds = [];
for (let i = 0; i < dispatchResults.length; i++) {
const dr = dispatchResults[i];
if (dr && String(dr.status || '').trim() === 'success') {
const group = createChannelGroups[i];
if (group && Array.isArray(group.order_ids)) {
for (const oid of group.order_ids) {
dispatchedOrderIds.push(Number(oid));
}
}
}
const dispatchStatus = result && result.status
? String(result.status).trim() || 'success'
: (result && result.success === false ? 'failed' : 'success');
dispatchResults.push({
...result,
status: dispatchStatus,
});
}
// 写入 ORDER_SYNC 操作日志(所有请求的订单,含跳过/失败)
try {
const opLogService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.operationLog;
if (opLogService && typeof opLogService.createOperationLogs === 'function') {
const channelNames = createChannelGroups.map(g => g.create_channel).join('/') || 'unknown';
const operatorId = ctx.user?.employees_id ?? ctx.user?.id ?? null;
const operatorName = ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? 'system';
const logItems = orderIds.map(orderId => {
const isPending = syncableOrderIds.includes(orderId);
const skipped = skippedOrders.find(s => Number(s.order_id) === orderId);
const failed = fastFailedOrders.find(f => Number(f.order_id) === orderId);
let msg;
if (isPending) msg = `同步到${channelNames}渠道`;
else if (failed) {
const reasonMap = { express_unallocated: '快递未分配', sn_batch_forbidden: 'SN订单不支持批量' };
msg = `同步跳过:${reasonMap[failed.failed_reason] || failed.failed_reason || failed.message || '条件不满足'}`;
} else if (skipped) {
const skipReasonMap = { already_synced: '已同步', not_found: '订单不存在' };
msg = `同步跳过:${skipReasonMap[skipped.skipped_reason] || skipped.skipped_reason || '已同步'}`;
} else msg = '同步跳过';
return {
businessType: 'order',
businessId: `${orderId}`,
operationCode: 'ORDER_SYNC',
operator: { id: operatorId, name: operatorName },
extras: {
message: msg,
warehouseId,
externalLogType: 'NONE',
},
};
if (dispatchedOrderIds.length > 0) {
try {
await orderModel.update({
sync_status: 'fin',
sync_message: '',
updated_at: new Date(),
}, {
where: {
id: { [ctx.app.Sequelize.Op.in]: dispatchedOrderIds },
warehouse_id: warehouseId,
},
});
ctx.logger.info('[OrderStorageAllocationService.syncOrderIds] 同步完成,已更新 sync_status=fin', {
warehouseId,
dispatchedCount: dispatchedOrderIds.length,
});
} catch (finUpdateErr) {
ctx.logger.error('[OrderStorageAllocationService.syncOrderIds] 更新 sync_status=fin 失败', {
warehouseId,
dispatchedCount: dispatchedOrderIds.length,
error: finUpdateErr && finUpdateErr.message,
});
await opLogService.createOperationLogs(logItems);
}
} catch (e) {
ctx.logger.warn('[OrderStorageAllocationService.syncOrderIds] 写入 ORDER_SYNC 操作日志失败', {
error: e && e.message,
warehouseId,
orderIds,
});
}
const responseData = {

View File

@ -130,7 +130,7 @@ module.exports = appInfo => {
'audio/x-m4a': 'audio',
};
config.cors = {
origin: (ctx) => ctx.get('Origin'), // 动态返回请求源,配合 credentials: true 使用
origin: ctx => ctx.get('Origin'), // 动态返回请求源,配合 credentials: true 使用
allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS',
exposeHeaders: 'Authorization',
credentials: true, // 允许携带 cookie

View File

@ -10,10 +10,10 @@ const FK_NAME = 'wms_express_setting_ibfk_1';
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {string} tableName 表名。
* @param {string} indexName 索引名。
* @returns {Promise<boolean>} 索引是否存在。
* @return {Promise<boolean>} 索引是否存在。
*/
const hasIndex = async (queryInterface, tableName, indexName) => {
const [rows] = await queryInterface.sequelize.query(
const [ rows ] = await queryInterface.sequelize.query(
`SHOW INDEX FROM \`${tableName}\` WHERE Key_name = :indexName`,
{ replacements: { indexName } }
);
@ -25,10 +25,10 @@ const hasIndex = async (queryInterface, tableName, indexName) => {
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {string} tableName 表名。
* @param {string} constraintName 约束名。
* @returns {Promise<boolean>} 外键是否存在。
* @return {Promise<boolean>} 外键是否存在。
*/
const hasForeignKey = async (queryInterface, tableName, constraintName) => {
const [rows] = await queryInterface.sequelize.query(
const [ rows ] = await queryInterface.sequelize.query(
`SELECT CONSTRAINT_NAME
FROM information_schema.TABLE_CONSTRAINTS
WHERE CONSTRAINT_SCHEMA = DATABASE()
@ -47,7 +47,7 @@ module.exports = {
* 原 UNIQUE KEY `platform_code` ON (`express_code`, `warehouse_id`) 约束过紧,
* 且该索引被外键 `wms_express_setting_ibfk_1`(express_code → wms_express.code)依赖。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @returns {Promise<void>} 无返回值。
* @return {Promise<void>} 无返回值。
*/
async up(queryInterface) {
// 1. 先删除依赖该索引的外键约束
@ -75,7 +75,7 @@ module.exports = {
/**
* 回滚迁移:恢复唯一索引与外键约束。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @returns {Promise<void>} 无返回值。
* @return {Promise<void>} 无返回值。
*/
async down(queryInterface) {
// 1. 删除替代的普通索引

View File

@ -9,10 +9,10 @@ const PLAIN_INDEX_NAME = 'idx_warehouse_platform_shop_name';
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {string} tableName 表名。
* @param {string} indexName 索引名。
* @returns {Promise<boolean>} 索引是否存在。
* @return {Promise<boolean>} 索引是否存在。
*/
const hasIndex = async (queryInterface, tableName, indexName) => {
const [rows] = await queryInterface.sequelize.query(
const [ rows ] = await queryInterface.sequelize.query(
`SHOW INDEX FROM \`${tableName}\` WHERE Key_name = :indexName`,
{ replacements: { indexName } }
);
@ -26,7 +26,7 @@ module.exports = {
* 触发 UNIQUE KEY `uk_warehouse_platform_shop_name` 约束冲突,导致 MySQL UPDATE 失败。
* 故将此唯一约束降为普通索引,仅保留查询性能。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @returns {Promise<void>} 无返回值。
* @return {Promise<void>} 无返回值。
*/
async up(queryInterface) {
// 1. 删除唯一索引
@ -47,7 +47,7 @@ module.exports = {
/**
* 回滚迁移:恢复唯一约束。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @returns {Promise<void>} 无返回值。
* @return {Promise<void>} 无返回值。
*/
async down(queryInterface) {
// 1. 删除普通索引

View File

@ -117,7 +117,7 @@ const ROLE_UPDATES = [
// 其他普工:排除设置模块(4-9,40,41,80,81,336,366,375)、财务、数据、测试、系统、敏感API、仓库管理API、视频
permissions: '[1,11,12,13,14,15,17,18,19,20,21,22,24,25,26,27,29,30,38,39,43,44,45,46,48,49,50,54,55,57,58,61,62,63,64,65,66,67,68,69,70,71,72,74,75,76,77,78,79,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,108,244,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,281,283,290,291,292,293,294,295,296,297,298,299,300,303,304,305,306,307,309,333,334,335,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,357,358,361,364,365,370,373,374,376,377,379,380,381,382,383,384]',
old: '[4-121]',
}
},
];
/**

View File

@ -5,6 +5,7 @@ module.exports = {
* 将 CREATED 状态合并到 PENDING:
* 1. 先把现有 CREATED 行更新为 PENDING
* 2. 再 ALTER TABLE 去掉 CREATED 枚举值
* @param queryInterface
*/
up: async queryInterface => {
// 先更新现有 CREATED 行
@ -19,6 +20,7 @@ module.exports = {
/**
* 回滚:将 CREATED 加回 ENUM(数据不回退,因为无法区分哪些行原本是 CREATED)
* @param queryInterface
*/
down: async queryInterface => {
await queryInterface.sequelize.query(

View File

@ -134,17 +134,17 @@ module.exports = {
},
});
await queryInterface.addIndex(TABLE_NAME, ['warehouse_id', 'items_hash', 'items_crc', 'package_material_id'], {
await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'items_hash', 'items_crc', 'package_material_id' ], {
unique: true,
name: 'uk_item_material',
});
await queryInterface.addIndex(TABLE_NAME, ['warehouse_id', 'is_active', 'items_hash', 'bind_count'], {
await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'is_active', 'items_hash', 'bind_count' ], {
name: 'idx_lookup',
});
},
down: async (queryInterface) => {
down: async queryInterface => {
await queryInterface.dropTable(TABLE_NAME);
},
};

View File

@ -4,29 +4,31 @@ module.exports = {
/**
* 修改 wms_api_app 表的唯一键 uk_interface_warehouse:
* 从 (qimen_app_key, qimen_customer_id) 改为 (qimen_app_key, qimen_warehouse_code)
* @param queryInterface
*/
up: async queryInterface => {
// 1. 删除旧唯一键
await queryInterface.sequelize.query(
"ALTER TABLE wms_api_app DROP INDEX uk_interface_warehouse"
'ALTER TABLE wms_api_app DROP INDEX uk_interface_warehouse'
);
// 2. 创建新唯一键
await queryInterface.sequelize.query(
"ALTER TABLE wms_api_app ADD UNIQUE INDEX uk_interface_warehouse (qimen_app_key, qimen_warehouse_code)"
'ALTER TABLE wms_api_app ADD UNIQUE INDEX uk_interface_warehouse (qimen_app_key, qimen_warehouse_code)'
);
},
/**
* 回滚:恢复为 (qimen_app_key, qimen_customer_id)
* @param queryInterface
*/
down: async queryInterface => {
// 1. 删除新唯一键
await queryInterface.sequelize.query(
"ALTER TABLE wms_api_app DROP INDEX uk_interface_warehouse"
'ALTER TABLE wms_api_app DROP INDEX uk_interface_warehouse'
);
// 2. 恢复旧唯一键
await queryInterface.sequelize.query(
"ALTER TABLE wms_api_app ADD UNIQUE INDEX uk_interface_warehouse (qimen_app_key, qimen_customer_id)"
'ALTER TABLE wms_api_app ADD UNIQUE INDEX uk_interface_warehouse (qimen_app_key, qimen_customer_id)'
);
},
};

View File

@ -5,6 +5,7 @@ module.exports = {
* 为 wms_entry_order 增加 CREATED 状态:
* ENUM 顺序: CREATING → CREATED → PENDING → CONFIRMED → PARTIAL_RECEIVED → COMPLETED → CANCELLED
* 默认值改为 CREATED
* @param queryInterface
*/
up: async queryInterface => {
await queryInterface.sequelize.query(
@ -16,6 +17,7 @@ module.exports = {
* 回滚:
* 1. 先将 CREATED 行更新为 PENDING
* 2. 再移除 CREATED 枚举值,恢复默认值 PENDING
* @param queryInterface
*/
down: async queryInterface => {
await queryInterface.sequelize.query(

View File

@ -8,6 +8,7 @@ module.exports = {
* 前置条件:
* - CONFIRMED 行数为 0,无需迁移
* - PARTIAL_RECEIVED 的 11 行改为 PENDING
* @param queryInterface
*/
up: async queryInterface => {
// 将 PARTIAL_RECEIVED 和 CONFIRMED 记录统一刷成 PENDING
@ -22,6 +23,7 @@ module.exports = {
/**
* 回滚:恢复 CONFIRMED 和 PARTIAL_RECEIVED 到 ENUM 中(不回滚数据)
* @param queryInterface
*/
down: async queryInterface => {
await queryInterface.sequelize.query(

View File

@ -46,21 +46,21 @@ module.exports = {
},
});
await queryInterface.addIndex(TABLE_NAME, ['entry_order_id'], {
await queryInterface.addIndex(TABLE_NAME, [ 'entry_order_id' ], {
name: 'idx_entry_order_id',
});
await queryInterface.addIndex(TABLE_NAME, ['receiving_id'], {
await queryInterface.addIndex(TABLE_NAME, [ 'receiving_id' ], {
name: 'idx_receiving_id',
});
await queryInterface.addIndex(TABLE_NAME, ['entry_order_id', 'receiving_id'], {
await queryInterface.addIndex(TABLE_NAME, [ 'entry_order_id', 'receiving_id' ], {
unique: true,
name: 'uk_entry_order_receiving',
});
},
down: async (queryInterface) => {
down: async queryInterface => {
await queryInterface.dropTable(TABLE_NAME);
},
};

View File

@ -9,7 +9,7 @@
*/
const logMigrationDbContext = async (queryInterface, phase, table) => {
try {
const [rows] = await queryInterface.sequelize.query(
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] : {};
@ -35,11 +35,11 @@ const logMigrationDbContext = async (queryInterface, phase, table) => {
* ALTER TABLE wms_receiving_detail MODIFY COLUMN storage_status ENUM('none','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, partial-部分入库, all-全部入库';
*/
const UP_SQL_RECEIVING = `ALTER TABLE wms_receiving MODIFY COLUMN storage_status ENUM('none','waiting','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, waiting-等待入库, partial-部分入库, all-全部入库'`;
const DOWN_SQL_RECEIVING = `ALTER TABLE wms_receiving MODIFY COLUMN storage_status ENUM('none','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, partial-部分入库, all-全部入库'`;
const UP_SQL_RECEIVING = 'ALTER TABLE wms_receiving MODIFY COLUMN storage_status ENUM(\'none\',\'waiting\',\'partial\',\'all\') NOT NULL DEFAULT \'none\' COMMENT \'入库状态:none-未入库, waiting-等待入库, partial-部分入库, all-全部入库\'';
const DOWN_SQL_RECEIVING = 'ALTER TABLE wms_receiving MODIFY COLUMN storage_status ENUM(\'none\',\'partial\',\'all\') NOT NULL DEFAULT \'none\' COMMENT \'入库状态:none-未入库, partial-部分入库, all-全部入库\'';
const UP_SQL_DETAIL = `ALTER TABLE wms_receiving_detail MODIFY COLUMN storage_status ENUM('none','waiting','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, waiting-等待入库, partial-部分入库, all-全部入库'`;
const DOWN_SQL_DETAIL = `ALTER TABLE wms_receiving_detail MODIFY COLUMN storage_status ENUM('none','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, partial-部分入库, all-全部入库'`;
const UP_SQL_DETAIL = 'ALTER TABLE wms_receiving_detail MODIFY COLUMN storage_status ENUM(\'none\',\'waiting\',\'partial\',\'all\') NOT NULL DEFAULT \'none\' COMMENT \'入库状态:none-未入库, waiting-等待入库, partial-部分入库, all-全部入库\'';
const DOWN_SQL_DETAIL = 'ALTER TABLE wms_receiving_detail MODIFY COLUMN storage_status ENUM(\'none\',\'partial\',\'all\') NOT NULL DEFAULT \'none\' COMMENT \'入库状态:none-未入库, partial-部分入库, all-全部入库\'';
module.exports = {
/**

View File

@ -0,0 +1,29 @@
{
"date": "2026-07-04",
"version": "1.0.0",
"changes": [
{
"method": "order.pendingOrder.syncOrderIds",
"type": "modified",
"description": "同步待处理订单由同步模式改为异步模式。提交后立即返回 request_id,后台通过 setImmediate 异步执行同步流程。调用方需通过 syncOrderIdsProgress 接口轮询进度。单订单失败静默写入 error 状态,不影响整批结果。已同步(fin)或处理中(padding)的订单自动跳过防重复。",
"breaking": true,
"migration": {
"before": "POST 同步调用,等待全部订单处理完成后返回完整结果",
"after": "POST 同步调用,立即返回 request_id;GET/POST syncOrderIdsProgress 轮询最终结果",
"response_change": "原返回 data 对象(含 warehouse_id / dispatch_results 等),现返回 request_id + warehouse_id + message"
}
},
{
"method": "order.pendingOrder.syncOrderIdsProgress",
"type": "added",
"description": "新增接口,用于查询 syncOrderIds 异步任务的进度与最终结果。入参 request_id,返回 status / progress / total_count / processed_count / result 等。",
"breaking": false
}
],
"affected_files": [
"app/service/systemMethods/order/pendingOrder.js",
"app/service/systems/order_storage_allocation.js",
"methods/system.json",
"test/app/service/systemMethods/order/pendingOrder.syncOrderIds.test.js"
]
}

View File

@ -0,0 +1,154 @@
# syncOrderIds 异步化改造 — 风险评估修正反馈
**日期**:2026-07-04
**评审来源**:`wms-review-agent` 风险评估报告(11 项风险点)
**修正执行**:`wms-db-agent`
**改造分支**:`ming`(尚未提交)
---
## 评审结论总览
| 风险点总数 | 确认为真风险 | 已修复 | 可接受妥协 | 不成立 |
|-----------|-------------|--------|-----------|--------|
| 11 + 1(深度排查) | 5 | 4 | 5 | 2 |
---
## 一、已修复项
### 🔴 P0 — #2 操作日志双重写入
**问题**:`order_storage_allocation.syncOrderIds` 中存在旧的 `ORDER_SYNC` 操作日志写入代码(约 50 行),`pendingOrder.syncOrderIds` 层又有新增的日志写入,导致每条订单产生 **2 条** `ORDER_SYNC` 日志。
**修法**:删除 `order_storage_allocation.js` 中旧的操作日志写入块,替换为一行注释 `// 操作日志已移至 pendingOrder.syncOrderIds 层统一写入,避免重复`。
**影响文件**:`app/service/systems/order_storage_allocation.js`(-50 行)
---
### 🟡 P1 — #3 Promise.all 无容错
**问题**:`Promise.all` 并行派发各渠道分组(QM / MANUAL / API),若任一渠道 handler 抛异常(如 `syncQmOrders` reject),按 `Promise.all` 语义会中断所有渠道。
**实际风险评估**:经核实,下游 handler(`syncQmOrders` / `syncManualOrders` / `syncApiOrders`)内部均使用 `Promise.all` + `processXxxOrderInternal` 模式,**所有方法返回 `{ status: 'failed' }` 而非 throw**,因此实际抛异常的概率极低。但作为防御性编程,仍加 `try/catch` 兜底。
**修法**:每个 `map(async groupedOrder => { ... })` 回调包裹 `try/catch`:
- `catch` 中记录 `ctx.logger.error`(含 createChannel / warehouseId / orderCount)
- 返回标准化 `{ status: 'failed', message, ... }` 结构
- 仍调用 `reportProgress(groupOrderCount)` 确保进度不丢失
**影响文件**:`app/service/systems/order_storage_allocation.js`(+20 行)
---
### 🔴 P0(深度排查)— catch 分支缺操作日志
**来源**:`wms-review-agent` 二次深度排查,对比 `allocateStorage` 发现遗漏。
**问题**:`syncOrderIds` 的 `setImmediate` catch 块中只写了缓存进度 + error log,**没有写操作日志**。而 `allocateStorage` 的 catch 块写了 `ORDER_STORAGE_ALLOCATE_FAILED`。如果服务崩溃、DB 断连等,`syncOrderIds` 的操作日志表里完全没有记录。
**修法**:在 `setImmediate` catch 块中新增操作日志写入,参考 `allocateStorage` 使用 `this.ctx.model.OperationLog.bulkCreate` 直写(崩溃场景下 service 层可能也不可用):
- 操作码:`ORDER_SYNC_FAILED`
- 内容:`订单同步失败:{errorMsg}`
- 双层 `try/catch`:外层写入缓存进度,内层写入操作日志
**影响文件**:`app/service/systemMethods/order/pendingOrder.js`(+35 行)
**测试覆盖**:新增 `should write ORDER_SYNC_FAILED operation log when entire sync task throws`
---
### 📋 P2 — #10 测试覆盖不足
**问题**:原报告指出"syncOrderIds 本身的异步流程没有对应测试用例"。
**实际核实**:`pendingOrder.syncOrderIds.test.js` 已存在(11 个测试),但确实缺少 2 个场景。
**修法**:新增 2 个测试用例:
- **渠道级异常隔离**:模拟 MANUAL 成功 + QM 失败,验证 `dispatch_results` 正确反映两渠道状态
- **多状态混合**:模拟 success / skipped / fast-failed 四类结果共存,验证 `result.data` 各字段正确
**最终覆盖**:14 个测试用例,覆盖以下场景:
| 场景 | 测试用例 |
|------|---------|
| 基础异步:立即返回 request_id | ✅ |
| 进度查询:success 后查到完整 result | ✅ |
| 进度查询:not_found | ✅ |
| 进度查询:request_id 为空 | ✅ |
| 中间态:submitted → running | ✅ |
| 单订单失败:整批仍 success | ✅ |
| 整体失败:报告 failed 状态 | ✅ |
| **catch 分支操作日志:ORDER_SYNC_FAILED** | ✅ 新增 |
| 进度递增:running → success | ✅ |
| 入参兼容:orderIds/ids/order_id | ✅ |
| 缓存故障:写入失败不崩溃 | ✅ |
| 进度回调异常:不崩溃 | ✅ |
| 渠道隔离:单渠道失败不阻塞 | ✅ |
| 多状态混合:四种结果共存 | ✅ |
---
## 二、不成立的风险点
### #6 — `warehouse_id` 优先级变更无校验
**核实**:`warehouse_id` 由 `pendingOrder.syncOrderIds` 在 `setImmediate` 之前通过 `this.getWarehouseId()` 快照提取,与原来 `ctx.user.store_id` **完全同源**。不存在调用方误传的通道。
**结论**:❌ 不成立,无风险。
---
### #7 — `sync_status` 过滤遗漏 `error` 状态
**核实**:model 定义 `sync_status` 枚举为 `['padding', 'fin', 'error']`。当前过滤条件为 `NOT IN ('fin', 'padding')`。
- `fin`(已完成):排除 ✅ — 无需重复同步
- `padding`(处理中):排除 ✅ — 防止并发重复提交
- `error`(失败):**不应排除** ✅ — 用户应能修复问题后重试
如果排除 `error`,会导致同步失败的订单**永远无法重试**,这反而是 bug。
**结论**:❌ 不成立,当前过滤条件是正确的业务设计。
---
## 三、可接受的妥协项
| # | 风险点 | 妥协理由 |
|---|--------|---------|
| 1 | Breaking API 变更 | 异步化必须付出的代价,changes JSON 已标记 `breaking: true`,调用方需适配 |
| 4 | `setImmediate` 中 ctx 生命周期 | 与 `allocateStorage` / `batchIntercept` / `batchLock` / `batchUnlock` / `batchUnintercept` **共 5 处现有模式**完全一致,框架已验证可行 |
| 5 | 异步任务无超时 | 与 `allocateStorage` 一致,缓存 TTL 2 小时自然过期兜底 |
| 8 | `syncOrderIdsProgress` 无权限隔离 | 与 `allocateStorageProgress` 一致,`request_id` 含随机 token 不可猜测 |
| 9 | 操作日志 `ctx.user` 可能为空 | 随 #2 修复一并解决(旧日志代码已删除,新日志用快照 operator) |
| 11 | `progress_callback` 函数注入 | 链路中无 JSON 序列化操作,与 `allocateStorage` 一致 |
---
## 四、当前状态
```
变更文件:6 个
├── app/service/systemMethods/order/pendingOrder.js (修改)
├── app/service/systems/order_storage_allocation.js (修改)
├── methods/system.json (修改)
├── methods/changes/syncOrderIds-async-20260704.json (新增)
├── methods/changes/syncOrderIds-async-review-feedback-20260704.md (新增)
├── test/.../pendingOrder.syncOrderIds.test.js (新增)
└── test/.../pendingOrder.allocateStorage.test.js (修改)
ESLint: 0 errors ✅
单测: 27 passing ✅ (13 allocateStorage + 14 syncOrderIds)
```
---
## 五、遗留建议(非阻塞)
| 优先级 | 建议 | 说明 |
|--------|------|------|
| P3 | 增加任务心跳 + 超时自动标记 failed | 可后续迭代,与 `allocateStorage` 统一处理 |
| P3 | `syncOrderIdsProgress` 增加 `warehouse_id` 校验 | 防止跨仓库查询他人任务(当前依赖随机 token 安全性) |
| P3 | 确认前端调用方已适配新返回格式 | 需产品/前端确认 `request_id` 轮询流程 |

View File

@ -1,4 +1,21 @@
[
{
"version": "2026.07.05-system-01",
"date": "2026-07-05",
"type": "added",
"summary": "新增 pick.wavePickComplete:传入 wave_id 一键完成整个波次拣货,内部复用 query 去重与任务创建逻辑后自动调用 wavePickTaskComplete(mode=1)",
"methods": [
"pick.wavePickComplete"
],
"notes": [
"新增方法:pick.wavePickComplete,入参 wave_id(number,必填)。",
"内部流程:按 wave_id 查波次 → 活动任务去重(同用户复用 / 他人409冲突)→ 完成任务去重 → 无任务则创建(source=2 后台抓取)→ 调用 pick.wavePickTaskComplete mode=1 全部确认。",
"创建任务 remark 格式:pick.wavePickComplete wave_id={waveId},用于与 pick.query 区分。",
"响应:task_id、status(completed / already_completed)、tip、confirmed_order_ids、is_completed、progress。",
"错误码:400(参数/波次无订单)、401(缺少操作人)、404(波次不存在)、409(他人活动任务冲突)、500(创建/完成失败)。"
],
"module": "pick"
},
{
"version": "2026.07.03-system-02",
"date": "2026-07-03",

View File

@ -3414,7 +3414,7 @@
},
{
"method": "order.pendingOrder.syncOrderIds",
"description": "同步待处理订单入口,支持批量传入 order_ids。服务端会按 create_channel 分组派发同步任务;若命中 SN 管理订单(is_sn_mgmt=Y),该订单会被拦截并标记失败,不允许走批量回传,需改用单订单回传。",
"description": "同步待处理订单(异步模式)。提交后立即返回 request_id,后台异步执行同步流程。调用方需通过 syncOrderIdsProgress 接口轮询任务进度与最终结果。后台会按 create_channel 分组并行派发同步任务(QM/MANUAL/API);单订单失败静默写入错误状态,不影响整批结果;已同步完成(sync_status='fin')的订单会被自动跳过防重复。SN管理订单和快递未分配订单在同步前即被标记为 error 并跳过派发。派发成功后会更新 sync_status='fin',防止重复同步。",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
@ -3445,33 +3445,134 @@
"name": "code",
"type": "number",
"required": true,
"description": "业务状态码,200 表示成功"
"description": "业务状态码,200 表示已受理"
},
{
"name": "message",
"type": "string",
"required": true,
"description": "返回信息,当前仅做受理提示"
"description": "受理提示信息"
},
{
"name": "data",
"type": "object",
"required": false,
"description": "服务层返回值,当前仅透传 order_ids"
"name": "request_id",
"type": "string",
"required": true,
"description": "异步任务唯一标识,用于 syncOrderIdsProgress 查询进度"
},
{
"name": "warehouse_id",
"type": "number",
"required": true,
"description": "生效的仓库 ID"
}
],
"errors": [
{
"code": 400,
"message": "order_ids 不能为空或格式错误"
}
]
},
{
"method": "order.pendingOrder.syncOrderIdsProgress",
"description": "查询 syncOrderIds 异步任务的进度与结果。",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
{
"name": "Authorization",
"type": "string",
"required": true,
"description": "Bearer token"
}
],
"params": [
{
"name": "request_id / requestId",
"type": "string",
"required": true,
"source": "body",
"description": "syncOrderIds 返回的 request_id"
}
],
"response": [
{
"name": "flag",
"type": "string",
"required": true,
"description": "全局调用结果标识,成功为 success"
},
{
"name": "code",
"type": "number",
"required": true,
"description": "业务状态码,200 表示成功"
},
{
"name": "message",
"type": "string",
"required": true,
"description": "返回信息"
},
{
"name": "request_id",
"type": "string",
"required": true,
"description": "请求 ID(原样回传)"
},
{
"name": "status",
"type": "string",
"required": true,
"description": "任务状态:submitted(已受理)/ running(处理中)/ success(完成)/ failed(失败)/ not_found(未找到)"
},
{
"name": "progress",
"type": "number",
"required": true,
"description": "进度百分比(0-100)"
},
{
"name": "total_count",
"type": "number",
"required": false,
"description": "总订单数"
},
{
"name": "processed_count",
"type": "number",
"required": false,
"description": "已处理订单数"
},
{
"name": "warehouse_id",
"type": "number",
"required": false,
"description": "仓库 ID"
},
{
"name": "result",
"type": "object",
"required": false,
"description": "完成时的同步结果(success 状态时存在),含 success_count / failed_count / dispatch_results 等"
},
{
"name": "error",
"type": "string",
"required": false,
"description": "失败时的错误信息(failed 状态时存在)"
},
{
"name": "update_time",
"type": "number",
"required": false,
"description": "最后更新时间戳"
}
],
"errors": [
{
"code": 400,
"message": "SN订单不支持批量回传,请改用单订单回传"
},
{
"code": 500,
"message": "内部错误:服务层同步失败"
"message": "request_id 参数不能为空"
}
]
},
@ -16412,6 +16513,90 @@
}
]
},
{
"method": "pick.wavePickComplete",
"description": "按波次ID一键完成整个波次的拣货。内部先按 wave_id 定位波次,复用 query 的去重与任务创建逻辑:若波次已有当前用户的活动任务则直接复用并完成;已有他人活动任务返回 409;已完成则返回 already_completed;否则新建任务(source=2 后台抓取)后在内部调用 wavePickTaskComplete(mode=1 全部确认)完成拣货并回写任务进度。",
"isNeedAuth": false,
"isNeedLogin": true,
"isNeedRight": false,
"headers": [
{
"name": "Authorization",
"type": "string",
"required": true,
"description": "Bearer token"
}
],
"params": [
{
"name": "wave_id",
"type": "number",
"required": true,
"source": "body",
"description": "波次ID(wms_wave_batch.wave_id)"
}
],
"response": [
{
"name": "task_id",
"type": "number",
"required": true,
"description": "拣货任务ID"
},
{
"name": "status",
"type": "string",
"required": true,
"description": "操作结果:completed(拣货完成)或 already_completed(波次已存在完成任务)"
},
{
"name": "tip",
"type": "string",
"required": true,
"description": "提示文案"
},
{
"name": "confirmed_order_ids",
"type": "array",
"required": false,
"description": "已确认完成的订单ID列表"
},
{
"name": "is_completed",
"type": "boolean",
"required": false,
"description": "任务是否已全部完成"
},
{
"name": "progress",
"type": "object",
"required": false,
"description": "任务进度(total_orders / picked_orders / pending_orders)"
}
],
"errors": [
{
"code": 400,
"message": "参数错误(wave_id 为空/非正整数、缺少仓库上下文、波次信息不完整、波次下无可用订单)。"
},
{
"code": 401,
"message": "未获取到操作人上下文。"
},
{
"code": 404,
"message": "波次不存在或不属于当前仓库。"
},
{
"code": 409,
"message": "当前波次已存在他人创建的活动任务(失败 data 含 task_id、task_owner_id、task_owner_name)。"
},
{
"code": 500,
"message": "任务创建失败或拣货完成失败。"
}
]
},
{
"method": "pick.wavePickTaskDetail",
"description": "按任务ID获取拣货任务详情。查询前会校验任务内订单是否全部完成快递号与储位分配:若存在未分配快递号或未分配储位订单,将返回 400 并在 data 中返回 action 与 order_ids 供前端触发一键分配;详情响应新增中间态进度语义(task.is_completed、task.progress 与顶层 is_completed),用于前端判断是否已完成与展示阶段进度;仅允许任务的 pick_user_id 与当前登录用户一致时返回详情。当 pick_mode=1(团购小波次)时,picking_details 字段不返回以减少带宽。",

View File

@ -6,17 +6,17 @@ const reqBody = process.argv[4] || '{}';
const options = {
hostname: 'localhost',
port: 6060,
path: `/system?method=${method}&v=1&timestamp=${Math.floor(Date.now()/1000)}`,
path: `/system?method=${method}&v=1&timestamp=${Math.floor(Date.now() / 1000)}`,
method: 'POST',
headers: {
'platform': 'web',
'project': 'wms',
'Authorization': `Bearer ${token}`,
platform: 'web',
project: 'wms',
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
};
const req = http.request(options, (res) => {
const req = http.request(options, res => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => {
@ -29,6 +29,6 @@ const req = http.request(options, (res) => {
}
});
});
req.on('error', (e) => console.error('ERROR:', e.message));
req.on('error', e => console.error('ERROR:', e.message));
req.write(reqBody);
req.end();

View File

@ -14,17 +14,17 @@ if (reqBodyFile && reqBodyFile.endsWith('.json')) {
const options = {
hostname: 'localhost',
port: 6060,
path: `/system?method=${method}&v=1&timestamp=${Math.floor(Date.now()/1000)}`,
path: `/system?method=${method}&v=1&timestamp=${Math.floor(Date.now() / 1000)}`,
method: 'POST',
headers: {
'platform': 'web',
'project': 'wms',
'Authorization': `Bearer ${token}`,
platform: 'web',
project: 'wms',
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
};
const req = http.request(options, (res) => {
const req = http.request(options, res => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => {
@ -42,6 +42,6 @@ const req = http.request(options, (res) => {
}
});
});
req.on('error', (e) => console.error('REQUEST ERROR:', e.message));
req.on('error', e => console.error('REQUEST ERROR:', e.message));
req.write(reqBody);
req.end();

View File

@ -30,7 +30,7 @@ async function main() {
try {
// 先查影响行数
const [previewRows] = await sequelize.query(`
const [ previewRows ] = await sequelize.query(`
SELECT COUNT(1) AS count
FROM wms_wave_pick_task_wave w
INNER JOIN wms_wave_pick_task t ON t.id = w.task_id AND t.warehouse_id = w.warehouse_id
@ -47,7 +47,7 @@ async function main() {
}
// 执行更新
const [result] = await sequelize.query(`
const [ result ] = await sequelize.query(`
UPDATE wms_wave_pick_task_wave w
INNER JOIN wms_wave_pick_task t ON t.id = w.task_id AND t.warehouse_id = w.warehouse_id
SET w.status = 1,

View File

@ -9,21 +9,21 @@ async function main() {
});
const key = 'store_warehouse:contract_config:1000028:1000241';
try {
const val = await redis.get(key);
console.log('Current cache value:', val ? val.substring(0, 200) : 'NULL');
await redis.del(key);
console.log('✅ Cache key deleted:', key);
// Verify
const after = await redis.get(key);
console.log('After delete:', after);
} catch (e) {
console.error('Error:', e.message);
}
redis.disconnect();
}

View File

@ -1,6 +1,6 @@
/**
* 截单时间逻辑真实 API 集成测试 (v2)
*
*
* 测试目标: 验证 asyncProcessOrderCreated 中的截单时间兜底逻辑
* 策略: 通过 SQL 直接更新 policy_config (绕过 API 权限问题),通过 API 创建订单并验证结果
*/
@ -32,17 +32,16 @@ function api(method, body) {
const bodyStr = typeof body === 'string' ? body : JSON.stringify(body);
const opts = {
hostname: 'localhost', port: 6060,
path: `/system?method=${method}&v=1&timestamp=${Math.floor(Date.now()/1000)}`,
path: `/system?method=${method}&v=1&timestamp=${Math.floor(Date.now() / 1000)}`,
method: 'POST',
headers: { 'platform': 'web', 'project': 'wms', 'Authorization': `Bearer ${TOKEN}`, 'Content-Type': 'application/json' },
headers: { platform: 'web', project: 'wms', Authorization: `Bearer ${TOKEN}`, 'Content-Type': 'application/json' },
timeout: 60000,
};
const req = http.request(opts, res => {
let d = '';
res.on('data', c => d += c);
res.on('end', () => {
try { resolve({ status: res.statusCode, body: JSON.parse(d) }); }
catch (e) { resolve({ status: res.statusCode, body: { _raw: d.substring(0, 300) } }); }
try { resolve({ status: res.statusCode, body: JSON.parse(d) }); } catch (e) { resolve({ status: res.statusCode, body: { _raw: d.substring(0, 300) } }); }
});
});
req.on('error', e => reject(e));
@ -57,13 +56,13 @@ function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }
async function setPolicy(policyCfg) {
const conn = await mysql.createConnection(DB_CONFIG);
await conn.execute('UPDATE wms_store_warehouse SET policy_config = ? WHERE id = ?',
[JSON.stringify(policyCfg), TEST.contractId]);
[ JSON.stringify(policyCfg), TEST.contractId ]);
await conn.end();
}
async function dbQuery(sql, params = []) {
const conn = await mysql.createConnection(DB_CONFIG);
const [rows] = await conn.execute(sql, params);
const [ rows ] = await conn.execute(sql, params);
await conn.end();
return rows;
}
@ -84,14 +83,14 @@ async function createOrder() {
async function checkExpressAssignment(orderId) {
const rows = await dbQuery(
'SELECT id, order_id, warehouse_id FROM wms_order_express WHERE order_id = ? AND warehouse_id = ? LIMIT 1',
[orderId, TEST.warehouseId]
[ orderId, TEST.warehouseId ]
);
return rows.length > 0;
}
async function runScene(label, sceneKey, expectedStep, expectedExpress) {
console.log(`\n=== ${label} ===`);
// 1. Set policy
console.log(' [1] 设置 policy_config...');
await setPolicy(POLICY[sceneKey]);
@ -104,13 +103,13 @@ async function runScene(label, sceneKey, expectedStep, expectedExpress) {
console.log(' [2] 创建订单...');
const r = await createOrder();
console.log(` status: ${r.status}`);
const success = r.status === 200 && r.body && r.body.flag === 'success';
if (!success) {
console.log(` ❌ 创建失败: ${JSON.stringify(r.body).substring(0, 200)}`);
return { pass: false, reason: 'create_failed', detail: r.body };
}
const orderId = r.body.order_id || r.body.data?.order_id;
const step = r.body.step || r.body.data?.step;
console.log(` order_id: ${orderId}, step: ${step} (预期=${expectedStep})`);
@ -171,8 +170,8 @@ async function main() {
console.log('============================================');
const total = Object.keys(results).length;
const passing = Object.values(results).filter(r => r.pass).length;
for (const [key, r] of Object.entries(results)) {
for (const [ key, r ] of Object.entries(results)) {
const icon = r.pass ? '✅' : '❌';
console.log(` ${icon} 场景 ${key}: step=${r.step}(预期${r.expectedStep}) express=${r.hasExpress}(预期${r.expectedExpress})`);
}

View File

@ -1,8 +1,8 @@
/**
* 截单时间逻辑真实 API 集成测试 (v3 - Final)
*
*
* 测试 asyncProcessOrderCreated 的截单兜底逻辑
*
*
* 场景 A: 免审核 + 未截单(23:59) → 应触发自动分配快递
* 场景 B: 免审核 + 已截单(00:01) → 应跳过
* 场景 C: 需要审核 → 应跳过 (step=0)
@ -34,14 +34,13 @@ function api(method, body) {
const bodyStr = JSON.stringify(body);
const req = http.request({
hostname: 'localhost', port: 6060,
path: `/system?method=${method}&v=1&timestamp=${Math.floor(Date.now()/1000)}`,
path: `/system?method=${method}&v=1&timestamp=${Math.floor(Date.now() / 1000)}`,
method: 'POST',
headers: { platform: 'web', project: 'wms', Authorization: `Bearer ${TOKEN}`, 'Content-Type': 'application/json' },
timeout: 60000,
}, res => {
let d = ''; res.on('data', c => d += c); res.on('end', () => {
try { resolve({ status: res.statusCode, body: JSON.parse(d) }); }
catch (e) { resolve({ status: res.statusCode, body: { _raw: d.substring(0, 300) } }); }
try { resolve({ status: res.statusCode, body: JSON.parse(d) }); } catch (e) { resolve({ status: res.statusCode, body: { _raw: d.substring(0, 300) } }); }
});
});
req.on('error', e => reject(e));
@ -53,7 +52,7 @@ function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }
async function dbQuery(sql, params = []) {
const conn = await mysql.createConnection(DB);
const [rows] = await conn.execute(sql, params);
const [ rows ] = await conn.execute(sql, params);
await conn.end();
return rows;
}
@ -64,9 +63,9 @@ async function setPolicy(sceneKey) {
const policyObj = POLICY[sceneKey];
const conn = await mysql.createConnection(DB);
await conn.execute('UPDATE wms_store_warehouse SET policy_config = ? WHERE id = ?',
[JSON.stringify(policyObj), CONTRACT_ID]);
[ JSON.stringify(policyObj), CONTRACT_ID ]);
await conn.end();
// 通过 API 调用 savePolicyConfig 清除缓存
console.log(' 调用 savePolicyConfig API 清除缓存...');
const apiRes = await api('storeWarehouse.store.savePolicyConfig', { id: CONTRACT_ID, policy_config: policyObj });
@ -112,13 +111,13 @@ async function runScene(label, sceneKey, expectedStep, checkExpressExpected) {
console.log(` [1] 更新 policy_config → scene ${sceneKey}`);
console.log(` ${JSON.stringify(POLICY[sceneKey])}`);
await setPolicy(sceneKey);
// 2. Wait for cache invalidation
console.log(` [2] 等待缓存... (10秒让 600s cache 有机会清除)`);
console.log(' [2] 等待缓存... (10秒让 600s cache 有机会清除)');
await sleep(10000);
// 3. Create order via API
console.log(` [3] API 创建订单...`);
console.log(' [3] API 创建订单...');
const r = await createOrder();
console.log(` HTTP ${r.status}`);
@ -133,7 +132,7 @@ async function runScene(label, sceneKey, expectedStep, checkExpressExpected) {
console.log(` order_id=${orderId}, api_step=${apiStep}, api_step_label="${r.body.step_label}"`);
// 4. Wait async processing
console.log(` [4] 等待异步处理 (8秒)...`);
console.log(' [4] 等待异步处理 (8秒)...');
await sleep(8000);
// 5. Check DB
@ -141,7 +140,7 @@ async function runScene(label, sceneKey, expectedStep, checkExpressExpected) {
if (order) {
console.log(` [5] DB 订单状态: step=${order.step}, status=${order.status}, wave_id=${order.wave_id}, logistics=${order.sys_logistics_code}`);
} else {
console.log(` [5] ⚠️ 数据库中未找到订单!`);
console.log(' [5] ⚠️ 数据库中未找到订单!');
return { pass: false, reason: 'DB中找不到订单' };
}
@ -190,7 +189,7 @@ async function main() {
console.log(' 测试结果汇总');
console.log(`${'='.repeat(60)}`);
let passCount = 0;
for (const [key, r] of Object.entries(results)) {
for (const [ key, r ] of Object.entries(results)) {
const icon = r.pass ? '✅' : '❌';
const detail = r.pass ? '' : ` | step=${r.step}≠${r.expectedStep} express=${r.hasExpress}≠${r.checkExpressExpected}`;
console.log(` ${icon} 场景 ${key}${detail}`);

View File

@ -1,14 +1,14 @@
/**
* 截单时间逻辑真实 API 集成测试
*
*
* 测试目标: 验证 asyncProcessOrderCreated 中的截单时间兜底逻辑
*
*
* 测试环境:
* - Dev Server: http://localhost:6060
* - Warehouse ID: 1000028 (天豹云仓)
* - Store ID: 1000241
* - Store-Warehouse ID: 100213
*
*
* 测试步骤:
* A) 免审核 + 未截单 → 应触发自动分配快递
* B) 免审核 + 已截单 → 应跳过
@ -40,14 +40,14 @@ function apiRequest(method, body) {
path: `/system?method=${method}&v=1&timestamp=${Math.floor(Date.now() / 1000)}`,
method: 'POST',
headers: {
'platform': 'web',
'project': 'wms',
'Authorization': `Bearer ${TOKEN}`,
platform: 'web',
project: 'wms',
Authorization: `Bearer ${TOKEN}`,
'Content-Type': 'application/json',
},
timeout: 60000,
};
const req = http.request(options, (res) => {
const req = http.request(options, res => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => {
@ -60,7 +60,7 @@ function apiRequest(method, body) {
resolve({ status: res.statusCode, body: parsed });
});
});
req.on('error', (e) => reject(e));
req.on('error', e => reject(e));
req.on('timeout', () => { req.destroy(); reject(new Error('Request timeout')); });
req.write(bodyStr);
req.end();
@ -73,6 +73,7 @@ function sleep(ms) {
/**
* 更新 store_warehouse 的 policy_config
* @param policyConfig
*/
async function updatePolicyConfig(policyConfig) {
return await apiRequest('storeWarehouse.store.savePolicyConfig', {

View File

@ -16,13 +16,13 @@ function apiRequest(method, body) {
path: `/system?method=${method}&v=1&timestamp=${Math.floor(Date.now() / 1000)}`,
method: 'POST',
headers: {
'platform': 'web',
'project': 'wms',
'Authorization': `Bearer ${TOKEN}`,
platform: 'web',
project: 'wms',
Authorization: `Bearer ${TOKEN}`,
'Content-Type': 'application/json',
},
};
const req = http.request(options, (res) => {
const req = http.request(options, res => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => {
@ -35,7 +35,7 @@ function apiRequest(method, body) {
resolve({ status: res.statusCode, headers: res.headers, body, _rawLength: data.length });
});
});
req.on('error', (e) => reject(e));
req.on('error', e => reject(e));
req.write(bodyStr);
req.end();
});

View File

@ -46,15 +46,15 @@ async function main() {
database: 'wms',
});
const [result] = await conn.execute(
const [ result ] = await conn.execute(
'UPDATE wms_store_warehouse SET policy_config = ? WHERE id = ?',
[policyStr, contractId]
[ policyStr, contractId ]
);
console.log('Update result:', JSON.stringify(result));
const [rows] = await conn.execute(
const [ rows ] = await conn.execute(
'SELECT id, store_id, warehouse_id, policy_config FROM wms_store_warehouse WHERE id = ?',
[contractId]
[ contractId ]
);
console.log('Current record:', JSON.stringify(rows[0], null, 2));

View File

@ -2,28 +2,28 @@
const mysql = require('mysql2/promise');
(async () => {
const conn = await mysql.createConnection({host:'127.0.0.1',port:3307,user:'wms',password:'dspxmRwRdRbWtbm7',database:'wms'});
const conn = await mysql.createConnection({ host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' });
const [tables] = await conn.query("SHOW TABLES LIKE 'wms_order_delivery%'");
const [ tables ] = await conn.query("SHOW TABLES LIKE 'wms_order_delivery%'");
console.log('order_delivery tables:');
tables.forEach(t => console.log(' ', Object.values(t)[0]));
const [tables2] = await conn.query("SHOW TABLES LIKE '%recheck%'");
const [ tables2 ] = await conn.query("SHOW TABLES LIKE '%recheck%'");
console.log('recheck tables:');
tables2.forEach(t => console.log(' ', Object.values(t)[0]));
const [tables3] = await conn.query("SHOW TABLES LIKE '%wave%'");
const [ tables3 ] = await conn.query("SHOW TABLES LIKE '%wave%'");
console.log('wave tables:');
tables3.forEach(t => console.log(' ', Object.values(t)[0]));
// Check the current model table for warehouse 100000
console.log('\nChecking wms_order_delivery for recheck_status:');
try {
const [rows] = await conn.query("SELECT * FROM wms_order_delivery WHERE warehouse_id = 100000 LIMIT 1");
const [ rows ] = await conn.query('SELECT * FROM wms_order_delivery WHERE warehouse_id = 100000 LIMIT 1');
if (rows.length > 0) {
console.log('Keys:', Object.keys(rows[0]).join(', '));
}
} catch(e) {
} catch (e) {
console.log('Error:', e.message);
}

View File

@ -8,7 +8,7 @@ const TEST_STORE_ID = 1000000;
async function main() {
const conn = await mysql.createConnection(DB_CONFIG);
try {
console.log('='.repeat(70));
console.log('WMS 拣货/复核完成 - stock_warehouse + stock_transaction 集成验证');
@ -19,13 +19,13 @@ async function main() {
// === 步骤1: 检查订单分表 ===
console.log('\n--- 步骤1: 检查订单分表 ---');
const [tables] = await conn.query("SHOW TABLES LIKE 'wms_order_delivery_%'");
const [ tables ] = await conn.query("SHOW TABLES LIKE 'wms_order_delivery_%'");
console.log(` 订单分表数量: ${tables.length}`);
tables.forEach(t => console.log(` - ${Object.values(t)[0]}`));
// === 步骤2: 查看订单状态分布 ===
console.log('\n--- 步骤2: 订单状态分布 (wms_order_delivery_100000) ---');
const [statusDist] = await conn.query(`
const [ statusDist ] = await conn.query(`
SELECT pick_status, recheck_status, storage_status, status, COUNT(*) as cnt
FROM wms_order_delivery_100000
GROUP BY pick_status, recheck_status, storage_status, status
@ -36,7 +36,7 @@ async function main() {
// === 步骤3: 查找最近有库存变更的 stock_warehouse ===
console.log('\n--- 步骤3: wms_stock_warehouse 状态 (warehouse=100000) ---');
const [swRows] = await conn.query(`
const [ swRows ] = await conn.query(`
SELECT id, item_code, item_name, quantity, locked_quantity, store_id
FROM wms_stock_warehouse
WHERE warehouse_id = 100000 AND quantity > 0
@ -47,7 +47,7 @@ async function main() {
// === 步骤4: wms_stock_transaction 最近记录 ===
console.log('\n--- 步骤4: wms_stock_transaction 最近记录 ---');
const [recentTx] = await conn.query(`
const [ recentTx ] = await conn.query(`
SELECT id, transaction_type, order_type, stock_id, quantity,
before_quantity, after_quantity,
before_locked_quantity, after_locked_quantity,
@ -72,7 +72,7 @@ async function main() {
// === 步骤5: 统计 stock_transaction 的 before_locked/after_locked 非零记录 ===
console.log('\n--- 步骤5: stock_transaction locked_quantity 变更统计 ---');
const [lockedStats] = await conn.query(`
const [ lockedStats ] = await conn.query(`
SELECT
COUNT(*) as total,
SUM(CASE WHEN before_locked_quantity > 0 OR after_locked_quantity > 0 THEN 1 ELSE 0 END) as with_locked,
@ -83,7 +83,7 @@ async function main() {
// === 步骤6: 检查 wms_stock_transaction 中 remark 包含"货主库存释放"的记录 ===
console.log('\n--- 步骤6: 货主库存释放 stock_transaction 记录 ---');
const [releaseTx] = await conn.query(`
const [ releaseTx ] = await conn.query(`
SELECT id, transaction_type, order_type, stock_id, quantity,
before_locked_quantity, after_locked_quantity, remark, created_at
FROM wms_stock_transaction
@ -102,7 +102,7 @@ async function main() {
console.log('\n' + '='.repeat(70));
console.log('集成验证完成');
console.log('='.repeat(70));
} finally {
await conn.end();
}

View File

@ -1,6 +1,6 @@
'use strict';
const mysql = require('mysql2/promise');
const DB_CONFIG = {host:'127.0.0.1',port:3307,user:'wms',password:'dspxmRwRdRbWtbm7',database:'wms'};
const DB_CONFIG = { host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' };
const TABLE = 'wms_order_delivery_100000';
(async () => {
@ -8,7 +8,7 @@ const TABLE = 'wms_order_delivery_100000';
try {
// More success candidates: pick_status = 'fin' AND recheck_status != 'fin'
console.log('=== 已拣货未复核 ===');
const [r1] = await conn.query(
const [ r1 ] = await conn.query(
`SELECT id, delivery_order_code, pick_status, recheck_status, wave_id
FROM ${TABLE}
WHERE storage_status='fin' AND post_status='fin' AND status='created'
@ -21,7 +21,7 @@ const TABLE = 'wms_order_delivery_100000';
// Also check: pick_status='none' (未拣货未复核)
console.log('=== 未拣货未复核 (pick_status=none) ===');
const [r2] = await conn.query(
const [ r2 ] = await conn.query(
`SELECT id, delivery_order_code, pick_status, recheck_status
FROM ${TABLE}
WHERE storage_status='fin' AND post_status='fin' AND status='created'
@ -34,7 +34,7 @@ const TABLE = 'wms_order_delivery_100000';
// Other pick statuses
console.log('=== 其他拣货状态未复核 ===');
const [r3] = await conn.query(
const [ r3 ] = await conn.query(
`SELECT id, delivery_order_code, pick_status, recheck_status
FROM ${TABLE}
WHERE storage_status='fin' AND post_status='fin' AND status='created'
@ -46,5 +46,5 @@ const TABLE = 'wms_order_delivery_100000';
console.log(` 共 ${r3.length} 条\n`);
await conn.end();
} catch(e) { console.error(e.message); await conn.end(); }
} catch (e) { console.error(e.message); await conn.end(); }
})();

View File

@ -21,7 +21,7 @@ async function queryTestOrders() {
console.log('【成功用例候选】满足所有前置条件的订单(未复核):');
console.log('-'.repeat(80));
const [successRows] = await conn.query(
const [ successRows ] = await conn.query(
`SELECT id, delivery_order_code, pre_delivery_order_code,
storage_status, post_status, status, intercept_status,
pick_status, recheck_status, wave_id, wave_no
@ -34,7 +34,7 @@ async function queryTestOrders() {
AND recheck_status != 'fin'
ORDER BY pick_status ASC, id DESC
LIMIT 10`,
[WAREHOUSE_ID]
[ WAREHOUSE_ID ]
);
for (const row of successRows) {
@ -52,7 +52,7 @@ async function queryTestOrders() {
console.log('【失败用例候选 - storage_status != fin】未分配储位:');
console.log('-'.repeat(80));
const [noStorageRows] = await conn.query(
const [ noStorageRows ] = await conn.query(
`SELECT id, delivery_order_code, pre_delivery_order_code,
storage_status, post_status, status, intercept_status,
pick_status, recheck_status
@ -62,7 +62,7 @@ async function queryTestOrders() {
AND (post_status = 'fin' OR 1=1)
ORDER BY id DESC
LIMIT 3`,
[WAREHOUSE_ID]
[ WAREHOUSE_ID ]
);
for (const row of noStorageRows) {
@ -75,7 +75,7 @@ async function queryTestOrders() {
console.log('【失败用例候选 - post_status != fin】未分配快递:');
console.log('-'.repeat(80));
const [noPostRows] = await conn.query(
const [ noPostRows ] = await conn.query(
`SELECT id, delivery_order_code, pre_delivery_order_code,
storage_status, post_status, status, intercept_status,
pick_status, recheck_status
@ -85,7 +85,7 @@ async function queryTestOrders() {
AND storage_status = 'fin'
ORDER BY id DESC
LIMIT 3`,
[WAREHOUSE_ID]
[ WAREHOUSE_ID ]
);
for (const row of noPostRows) {
@ -98,7 +98,7 @@ async function queryTestOrders() {
console.log('【失败用例候选 - status != created】未同步:');
console.log('-'.repeat(80));
const [noSyncRows] = await conn.query(
const [ noSyncRows ] = await conn.query(
`SELECT id, delivery_order_code, pre_delivery_order_code,
storage_status, post_status, status, intercept_status,
pick_status, recheck_status
@ -109,7 +109,7 @@ async function queryTestOrders() {
AND post_status = 'fin'
ORDER BY id DESC
LIMIT 3`,
[WAREHOUSE_ID]
[ WAREHOUSE_ID ]
);
for (const row of noSyncRows) {
@ -122,7 +122,7 @@ async function queryTestOrders() {
console.log('【失败用例候选 - 已拦截】:');
console.log('-'.repeat(80));
const [interceptedRows] = await conn.query(
const [ interceptedRows ] = await conn.query(
`SELECT id, delivery_order_code, pre_delivery_order_code,
storage_status, post_status, status, intercept_status,
pick_status, recheck_status
@ -131,7 +131,7 @@ async function queryTestOrders() {
AND intercept_status IN ('intercepted', 'intercepted_at_warehouse')
ORDER BY id DESC
LIMIT 3`,
[WAREHOUSE_ID]
[ WAREHOUSE_ID ]
);
for (const row of interceptedRows) {

View File

@ -15,7 +15,7 @@ async function main() {
console.log('【成功用例候选】满足所有前置条件的订单(未复核):');
console.log('-'.repeat(80));
const [successRows] = await conn.query(
const [ successRows ] = await conn.query(
`SELECT id, delivery_order_code, pre_delivery_order_code,
storage_status, post_status, status, intercept_status,
pick_status, recheck_status, wave_id, wave_no
@ -39,7 +39,7 @@ async function main() {
console.log('='.repeat(80));
console.log('【失败用例候选 - storage_status != fin】');
const [noStorageRows] = await conn.query(
const [ noStorageRows ] = await conn.query(
`SELECT id, delivery_order_code, storage_status FROM ${TABLE} WHERE storage_status != 'fin' ORDER BY id DESC LIMIT 3`
);
noStorageRows.forEach(r => console.log(` ID: ${r.id} storage_status="${r.storage_status}"`));
@ -48,7 +48,7 @@ async function main() {
console.log('='.repeat(80));
console.log('【失败用例候选 - post_status != fin】');
const [noPostRows] = await conn.query(
const [ noPostRows ] = await conn.query(
`SELECT id, delivery_order_code, post_status FROM ${TABLE} WHERE post_status != 'fin' AND storage_status = 'fin' ORDER BY id DESC LIMIT 3`
);
noPostRows.forEach(r => console.log(` ID: ${r.id} post_status="${r.post_status}"`));
@ -57,7 +57,7 @@ async function main() {
console.log('='.repeat(80));
console.log('【失败用例候选 - status != created】');
const [noSyncRows] = await conn.query(
const [ noSyncRows ] = await conn.query(
`SELECT id, delivery_order_code, status FROM ${TABLE} WHERE status != 'created' AND storage_status = 'fin' AND post_status = 'fin' ORDER BY id DESC LIMIT 3`
);
noSyncRows.forEach(r => console.log(` ID: ${r.id} status="${r.status}"`));
@ -66,7 +66,7 @@ async function main() {
console.log('='.repeat(80));
console.log('【失败用例候选 - 已拦截】');
const [interceptedRows] = await conn.query(
const [ interceptedRows ] = await conn.query(
`SELECT id, delivery_order_code, intercept_status FROM ${TABLE} WHERE intercept_status IN ('intercepted','intercepted_at_warehouse') ORDER BY id DESC LIMIT 3`
);
interceptedRows.forEach(r => console.log(` ID: ${r.id} intercept_status="${r.intercept_status}"`));

View File

@ -4,13 +4,13 @@ const TOKEN = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJs
const BASE_URL = 'http://127.0.0.1:6060';
const TABLE = 'wms_order_delivery_100000';
const mysql = require('mysql2/promise');
const DB_CONFIG = {host:'127.0.0.1',port:3307,user:'wms',password:'dspxmRwRdRbWtbm7',database:'wms'};
const DB_CONFIG = { host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' };
async function getOrderSnapshot(conn, ids) {
if (!ids.length) return {};
const [rows] = await conn.query(
const [ rows ] = await conn.query(
`SELECT id, pick_status, recheck_status, storage_status, post_status, status, intercept_status
FROM ${TABLE} WHERE id IN (?)`, [ids]
FROM ${TABLE} WHERE id IN (?)`, [ ids ]
);
const map = {};
rows.forEach(r => { map[r.id] = r; });
@ -21,10 +21,10 @@ async function callApi(ids) {
const ts = Math.floor(Date.now() / 1000);
const url = `${BASE_URL}/system?method=order.recheckOrder.batchQuickRecheck&v=1.0&timestamp=${ts}`;
const headers = {
'platform': 'web',
'project': 'wms',
platform: 'web',
project: 'wms',
'Content-Type': 'application/json; charset=utf-8',
'Authorization': `Bearer ${TOKEN}`,
Authorization: `Bearer ${TOKEN}`,
};
const body = JSON.stringify({
module: 'order.recheckOrder',
@ -53,7 +53,7 @@ async function runTestCase(name, ids, expectedDesc) {
// 测试前快照
beforeSnapshot = await getOrderSnapshot(conn, ids);
console.log(' 测试前状态:');
for (const [id, snap] of Object.entries(beforeSnapshot)) {
for (const [ id, snap ] of Object.entries(beforeSnapshot)) {
console.log(` ID ${id}: pick="${snap.pick_status}" recheck="${snap.recheck_status}" storage="${snap.storage_status}" post="${snap.post_status}" status="${snap.status}" intercept="${snap.intercept_status}"`);
}
@ -69,7 +69,7 @@ async function runTestCase(name, ids, expectedDesc) {
// 测试后快照
afterSnapshot = await getOrderSnapshot(conn, ids);
console.log(' 测试后状态:');
for (const [id, snap] of Object.entries(afterSnapshot)) {
for (const [ id, snap ] of Object.entries(afterSnapshot)) {
const before = beforeSnapshot[id] || {};
const changes = [];
if (snap.pick_status !== before.pick_status) changes.push(`pick: ${before.pick_status}→${snap.pick_status}`);
@ -98,42 +98,42 @@ async function main() {
// 用例1: 全成功-含未拣货(1个有效订单)
results.push(await runTestCase(
'用例1: 全成功-含未拣货',
[120946],
[ 120946 ],
'pick_status=none → 自动完成拣货+复核, 全部 success'
));
// 用例2: 全失败-无储位
results.push(await runTestCase(
'用例2: 全失败-无储位',
[120947, 120939],
[ 120947, 120939 ],
'全部 failed, reason="未分配储位"'
));
// 用例3: 全失败-无快递
results.push(await runTestCase(
'用例3: 全失败-无快递',
[120944, 120943],
[ 120944, 120943 ],
'全部 failed, reason="没有分配快递"'
));
// 用例4: 全失败-未同步
results.push(await runTestCase(
'用例4: 全失败-未同步',
[120858, 120857],
[ 120858, 120857 ],
'全部 failed, reason="没有同步"'
));
// 用例5: 全失败-已拦截
results.push(await runTestCase(
'用例5: 全失败-已拦截',
[120945],
[ 120945 ],
'全部 failed, reason="已拦截"'
));
// 用例6: 部分失败-混合
results.push(await runTestCase(
'用例6: 部分失败-混合',
[120946, 120947, 999999999],
[ 120946, 120947, 999999999 ],
'success 和 failed 各有'
));
@ -147,7 +147,7 @@ async function main() {
// 用例8: 不存在ID
results.push(await runTestCase(
'用例8: 不存在ID',
[999999999],
[ 999999999 ],
'全部 failed, reason="未找到对应订单"'
));

View File

@ -29,10 +29,10 @@ async function closeConn() {
async function getOrderSnapshot(ids) {
const c = await getConn();
if (!ids.length) return {};
const [rows] = await c.query(
const [ rows ] = await c.query(
`SELECT id, delivery_order_code, pre_delivery_order_code,
pick_status, recheck_status, storage_status, post_status, status, intercept_status
FROM ${TABLE} WHERE id IN (?)`, [ids]
FROM ${TABLE} WHERE id IN (?)`, [ ids ]
);
const map = {};
rows.forEach(r => { map[r.id] = r; });
@ -42,8 +42,8 @@ async function getOrderSnapshot(ids) {
async function getStorageSnapshot(ids) {
const c = await getConn();
if (!ids.length) return {};
const [rows] = await c.query(
'SELECT id, quantity, locked_quantity FROM wms_storage WHERE id IN (?) AND warehouse_id = 100000', [ids]
const [ rows ] = await c.query(
'SELECT id, quantity, locked_quantity FROM wms_storage WHERE id IN (?) AND warehouse_id = 100000', [ ids ]
);
const map = {};
rows.forEach(r => { map[r.id] = r; });
@ -54,10 +54,10 @@ async function callApi(ids) {
const ts = Math.floor(Date.now() / 1000);
const url = `${BASE_URL}/system?method=order.recheckOrder.batchQuickRecheck&v=1.0&timestamp=${ts}`;
const headers = {
'platform': 'web',
'project': 'wms',
platform: 'web',
project: 'wms',
'Content-Type': 'application/json; charset=utf-8',
'Authorization': `Bearer ${TOKEN}`,
Authorization: `Bearer ${TOKEN}`,
};
const body = JSON.stringify({ ids });
@ -76,7 +76,10 @@ async function runTestCase(name, ids, expectedDesc, preSetup, postVerify, postCl
console.log(` 输入IDs: [${ids.join(', ')}]`);
console.log(` 预期: ${expectedDesc}`);
let beforeOrder = {}, beforeStorage = {}, afterOrder = {}, afterStorage = {};
let beforeOrder = {},
beforeStorage = {},
afterOrder = {},
afterStorage = {};
let passed = false;
let failReason = '';
@ -91,7 +94,7 @@ async function runTestCase(name, ids, expectedDesc, preSetup, postVerify, postCl
// 测试前快照
beforeOrder = await getOrderSnapshot(ids);
console.log(' 测试前订单状态:');
for (const [id, snap] of Object.entries(beforeOrder)) {
for (const [ id, snap ] of Object.entries(beforeOrder)) {
console.log(` ID ${id}: storage="${snap.storage_status}" post="${snap.post_status}" status="${snap.status}" intercept="${snap.intercept_status}" pick="${snap.pick_status}" recheck="${snap.recheck_status}" code="${snap.delivery_order_code || snap.pre_delivery_order_code || ''}"`);
}
@ -104,7 +107,7 @@ async function runTestCase(name, ids, expectedDesc, preSetup, postVerify, postCl
// 测试后快照
afterOrder = await getOrderSnapshot(ids);
console.log(' 测试后订单状态:');
for (const [id, snap] of Object.entries(afterOrder)) {
for (const [ id, snap ] of Object.entries(afterOrder)) {
const before = beforeOrder[id] || {};
const changes = [];
if (snap.pick_status !== before.pick_status) changes.push(`pick: ${before.pick_status}→${snap.pick_status}`);
@ -155,7 +158,7 @@ async function main() {
console.log(`测试时间: ${new Date().toISOString()}`);
console.log(`目标表: ${TABLE}`);
console.log(`Base URL: ${BASE_URL}`);
console.log(`测试仓库ID: 100000 | 测试货主ID: 1000000`);
console.log('测试仓库ID: 100000 | 测试货主ID: 1000000');
console.log('='.repeat(60));
const results = [];
@ -164,7 +167,7 @@ async function main() {
console.log('\n── 全局前置:恢复 120946 关联库存 locked_quantity ──');
const c = await getConn();
// 记录 storage 184 原始状态
const [origStorage] = await c.query('SELECT id, quantity, locked_quantity FROM wms_storage WHERE id = 184 AND warehouse_id = 100000');
const [ origStorage ] = await c.query('SELECT id, quantity, locked_quantity FROM wms_storage WHERE id = 184 AND warehouse_id = 100000');
console.log(` storage 184 原始: quantity=${origStorage[0].quantity}, locked=${origStorage[0].locked_quantity}`);
// 恢复 locked_quantity 以便测试成功扣减
if (origStorage[0].locked_quantity < 1) {
@ -187,7 +190,7 @@ async function main() {
[],
'返回错误 "订单ID列表不能为空"',
null,
async (result) => {
async result => {
// batchQuickRecheck 返回 500 而非 400(内部 throw(400) 被框架包装为 500)
// 检查是否包含错误消息
const msg = result.body && (result.body.message || '');
@ -200,10 +203,10 @@ async function main() {
// ── 用例 8: 不存在的订单ID ──
results.push(await runTestCase(
'用例8: 不存在的订单ID',
[999999999],
[ 999999999 ],
'全部 failed, reason="未找到对应订单"',
null,
async (result) => {
async result => {
const data = result.body && (result.body.data !== undefined ? result.body.data : result.body);
if (!data || typeof data !== 'object') return `返回数据格式异常: ${JSON.stringify(result.body)}`;
if (data.success_count === 0 && data.failed_count >= 1) {
@ -218,10 +221,10 @@ async function main() {
// ── 用例 5: 失败-未同步(120858: status='pedding') ──
results.push(await runTestCase(
'用例5: 失败-未同步',
[120858, 120857],
[ 120858, 120857 ],
'全部 failed, reason="没有同步"',
null,
async (result) => {
async result => {
const data = result.body && (result.body.data !== undefined ? result.body.data : result.body);
if (!data || data.success_count !== 0) return `期望 success_count=0,实际: ${JSON.stringify(data)}`;
const allNoSync = (data.failed || []).every(f => f.reason === '没有同步');
@ -233,10 +236,10 @@ async function main() {
// ── 用例 4: 失败-无快递(120944: post_status='none') ──
results.push(await runTestCase(
'用例4: 失败-无快递',
[120944, 120943],
[ 120944, 120943 ],
'全部 failed, reason="没有分配快递"',
null,
async (result) => {
async result => {
const data = result.body && (result.body.data !== undefined ? result.body.data : result.body);
if (!data || data.success_count !== 0) return `期望 success_count=0,实际: ${JSON.stringify(data)}`;
const allNoPost = (data.failed || []).every(f => f.reason === '没有分配快递');
@ -248,10 +251,10 @@ async function main() {
// ── 用例 3: 失败-未分配储位(120947: storage_status='none') ──
results.push(await runTestCase(
'用例3: 失败-未分配储位',
[120947, 120939],
[ 120947, 120939 ],
'全部 failed, reason="未分配储位"',
null,
async (result) => {
async result => {
const data = result.body && (result.body.data !== undefined ? result.body.data : result.body);
if (!data || data.success_count !== 0) return `期望 success_count=0,实际: ${JSON.stringify(data)}`;
const allNoStorage = (data.failed || []).every(f => f.reason === '未分配储位');
@ -263,10 +266,10 @@ async function main() {
// ── 用例 2: 失败-已拦截(120945: intercept_status='intercepted_at_warehouse') ──
results.push(await runTestCase(
'用例2: 失败-已拦截',
[120945],
[ 120945 ],
'全部 failed, reason="已拦截"',
null,
async (result) => {
async result => {
const data = result.body && (result.body.data !== undefined ? result.body.data : result.body);
if (!data || data.success_count !== 0) return `期望 success_count=0,实际: ${JSON.stringify(data)}`;
const allIntercepted = (data.failed || []).every(f => f.reason === '已拦截');
@ -280,23 +283,23 @@ async function main() {
let case1Cleanup = null;
results.push(await runTestCase(
'用例1: 成功-含未拣货',
[120946],
[ 120946 ],
'success_count >= 1, 订单 recheck_status=fin, pick_status=fin',
async () => {
// 再次确认前置条件
const c2 = await getConn();
const [st] = await c2.query('SELECT locked_quantity FROM wms_storage WHERE id = 184 AND warehouse_id = 100000');
const [ st ] = await c2.query('SELECT locked_quantity FROM wms_storage WHERE id = 184 AND warehouse_id = 100000');
console.log(` [前置确认] storage 184 locked_quantity=${st[0].locked_quantity}`);
const [pk] = await c2.query('SELECT status FROM wms_picking WHERE id = 87425 AND warehouse_id = 100000');
const [ pk ] = await c2.query('SELECT status FROM wms_picking WHERE id = 87425 AND warehouse_id = 100000');
console.log(` [前置确认] picking 87425 status=${pk[0].status}`);
},
async (result) => {
async result => {
const data = result.body && (result.body.data !== undefined ? result.body.data : result.body);
if (!data || data.success_count < 1) return `期望 success_count >= 1,实际: ${JSON.stringify(data)}`;
// 验证 120946 的状态
const c3 = await getConn();
const [order] = await c3.query(
const [ order ] = await c3.query(
'SELECT pick_status, recheck_status FROM wms_order_delivery_100000 WHERE id = 120946 AND warehouse_id = 100000'
);
console.log(` [验证] 120946 pick_status="${order[0].pick_status}" recheck_status="${order[0].recheck_status}"`);
@ -304,7 +307,7 @@ async function main() {
if (order[0].recheck_status !== 'fin') return `期望 recheck_status='fin',实际="${order[0].recheck_status}"`;
// 验证库存已扣减
const [stAfter] = await c3.query('SELECT locked_quantity, quantity FROM wms_storage WHERE id = 184 AND warehouse_id = 100000');
const [ stAfter ] = await c3.query('SELECT locked_quantity, quantity FROM wms_storage WHERE id = 184 AND warehouse_id = 100000');
console.log(` [验证] storage 184 扣减后: locked=${stAfter[0].locked_quantity}, quantity=${stAfter[0].quantity}`);
// 记录清理函数
@ -329,12 +332,12 @@ async function main() {
// 需要先确保 120946 恢复到可测试状态
results.push(await runTestCase(
'用例6: 部分失败-混合',
[120946, 120947, 999999999],
[ 120946, 120947, 999999999 ],
'success_count >= 1 且 failed_count >= 2',
async () => {
// 恢复 120946 的前置条件
const c4 = await getConn();
const [st] = await c4.query('SELECT locked_quantity FROM wms_storage WHERE id = 184 AND warehouse_id = 100000');
const [ st ] = await c4.query('SELECT locked_quantity FROM wms_storage WHERE id = 184 AND warehouse_id = 100000');
if (st[0].locked_quantity < 1) {
await c4.query('UPDATE wms_storage SET locked_quantity = locked_quantity + 1, quantity = quantity + 1, updated_at = NOW() WHERE id = 184 AND warehouse_id = 100000');
console.log(' [前置] storage 184 locked_quantity 已恢复 +1');
@ -344,7 +347,7 @@ async function main() {
await c4.query("UPDATE wms_order_delivery_100000 SET pick_status = 'none', recheck_status = 'none', updated_at = NOW() WHERE id = 120946 AND warehouse_id = 100000");
console.log(' [前置] 120946 数据已恢复');
},
async (result) => {
async result => {
const data = result.body && (result.body.data !== undefined ? result.body.data : result.body);
if (!data) return `返回数据为空: ${JSON.stringify(result.body)}`;
if (data.success_count >= 1 && data.failed_count >= 2) {
@ -358,13 +361,13 @@ async function main() {
async () => {
// 恢复 120946
const c5 = await getConn();
const [st] = await c5.query('SELECT locked_quantity, quantity FROM wms_storage WHERE id = 184 AND warehouse_id = 100000');
const [ st ] = await c5.query('SELECT locked_quantity, quantity FROM wms_storage WHERE id = 184 AND warehouse_id = 100000');
// 如果 locked_quantity 减少了(测试成功扣减了),恢复
await c5.query("UPDATE wms_picking SET status = 'pending', updated_at = NOW() WHERE id = 87425 AND warehouse_id = 100000");
await c5.query('UPDATE wms_wave_pick_task_order SET pick_status = 0, picked_time = NULL, update_time = NOW() WHERE id = 6057 AND warehouse_id = 100000');
await c5.query("UPDATE wms_order_delivery_100000 SET pick_status = 'none', recheck_status = 'none', updated_at = NOW() WHERE id = 120946 AND warehouse_id = 100000");
// 检查库存是否需要恢复
const [st2] = await c5.query('SELECT locked_quantity FROM wms_storage WHERE id = 184 AND warehouse_id = 100000');
const [ st2 ] = await c5.query('SELECT locked_quantity FROM wms_storage WHERE id = 184 AND warehouse_id = 100000');
console.log(` [用例6恢复] 120946 数据已恢复,storage 184 locked=${st2[0].locked_quantity}`);
}
));
@ -372,7 +375,7 @@ async function main() {
// ── 全局恢复:将 storage 184 恢复到测试前状态 ──
console.log('\n── 全局恢复:storage 184 ──');
// 检查当前状态,恢复到原始值
const [finalSt] = await c.query('SELECT quantity, locked_quantity FROM wms_storage WHERE id = 184 AND warehouse_id = 100000');
const [ finalSt ] = await c.query('SELECT quantity, locked_quantity FROM wms_storage WHERE id = 184 AND warehouse_id = 100000');
console.log(` storage 184 最终: quantity=${finalSt[0].quantity}, locked=${finalSt[0].locked_quantity}`);
console.log(` storage 184 原始: quantity=${origStorage[0].quantity}, locked=${origStorage[0].locked_quantity}`);

View File

@ -4,14 +4,14 @@ const TOKEN = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJs
const BASE_URL = 'http://127.0.0.1:6060';
const TABLE = 'wms_order_delivery_100000';
const mysql = require('mysql2/promise');
const DB_CONFIG = {host:'127.0.0.1',port:3307,user:'wms',password:'dspxmRwRdRbWtbm7',database:'wms'};
const DB_CONFIG = { host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' };
async function getOrderSnapshot(conn, ids) {
if (!ids.length) return {};
const [rows] = await conn.query(
const [ rows ] = await conn.query(
`SELECT id, delivery_order_code, pre_delivery_order_code,
pick_status, recheck_status, storage_status, post_status, status, intercept_status
FROM ${TABLE} WHERE id IN (?)`, [ids]
FROM ${TABLE} WHERE id IN (?)`, [ ids ]
);
const map = {};
rows.forEach(r => { map[r.id] = r; });
@ -22,10 +22,10 @@ async function callApi(ids) {
const ts = Math.floor(Date.now() / 1000);
const url = `${BASE_URL}/system?method=order.recheckOrder.batchQuickRecheck&v=1.0&timestamp=${ts}`;
const headers = {
'platform': 'web',
'project': 'wms',
platform: 'web',
project: 'wms',
'Content-Type': 'application/json; charset=utf-8',
'Authorization': `Bearer ${TOKEN}`,
Authorization: `Bearer ${TOKEN}`,
};
// IMPORTANT: body 必须扁平化,ids 直接在顶层。callMethod 将整个 body 传给业务方法
const body = JSON.stringify({ ids });
@ -51,7 +51,7 @@ async function runTestCase(name, ids, expectedDesc) {
try {
beforeSnapshot = await getOrderSnapshot(conn, ids);
console.log(' 测试前状态:');
for (const [id, snap] of Object.entries(beforeSnapshot)) {
for (const [ id, snap ] of Object.entries(beforeSnapshot)) {
console.log(` ID ${id}: pick="${snap.pick_status}" recheck="${snap.recheck_status}" storage="${snap.storage_status}" post="${snap.post_status}" status="${snap.status}" intercept="${snap.intercept_status}" code="${snap.delivery_order_code || snap.pre_delivery_order_code || ''}"`);
}
@ -64,7 +64,7 @@ async function runTestCase(name, ids, expectedDesc) {
afterSnapshot = await getOrderSnapshot(conn, ids);
console.log(' 测试后状态:');
for (const [id, snap] of Object.entries(afterSnapshot)) {
for (const [ id, snap ] of Object.entries(afterSnapshot)) {
const before = beforeSnapshot[id] || {};
const changes = [];
if (snap.pick_status !== before.pick_status) changes.push(`pick: ${before.pick_status}→${snap.pick_status}`);
@ -102,49 +102,49 @@ async function main() {
// 用例8: 不存在ID
results.push(await runTestCase(
'用例8: 不存在ID',
[999999999],
[ 999999999 ],
'全部 failed, reason="未找到对应订单"'
));
// 用例4: 全失败-未同步
results.push(await runTestCase(
'用例4: 全失败-未同步',
[120858, 120857],
[ 120858, 120857 ],
'全部 failed, reason="没有同步"'
));
// 用例3: 全失败-无快递
results.push(await runTestCase(
'用例3: 全失败-无快递',
[120944, 120943],
[ 120944, 120943 ],
'全部 failed, reason="没有分配快递"'
));
// 用例2: 全失败-无储位
results.push(await runTestCase(
'用例2: 全失败-无储位',
[120947, 120939],
[ 120947, 120939 ],
'全部 failed, reason="未分配储位"'
));
// 用例5: 全失败-已拦截
results.push(await runTestCase(
'用例5: 全失败-已拦截',
[120945],
[ 120945 ],
'全部 failed, reason="已拦截"'
));
// 用例6: 部分失败-混合(valid + invalid)
results.push(await runTestCase(
'用例6: 部分失败-混合',
[120946, 120947, 999999999],
[ 120946, 120947, 999999999 ],
'success 和 failed 各有'
));
// 用例1: 全成功-含未拣货 (最后测,会修改数据)
results.push(await runTestCase(
'用例1: 全成功-含未拣货',
[120946],
[ 120946 ],
'pick_status=none → 自动完成拣货+复核, recheck_status=fin'
));

View File

@ -34,7 +34,7 @@ function createSequelizeTypes() {
STRING: length => makeType(`VARCHAR(${length})`),
BIGINT: unsignedBigInt,
DECIMAL: (precision, scale) => makeType(`DECIMAL(${precision},${scale})`),
TEXT: (length) => makeType(length ? `TEXT(${length})` : 'TEXT'),
TEXT: length => makeType(length ? `TEXT(${length})` : 'TEXT'),
ENUM: (...values) => makeType(`ENUM('${values.join("','")}')`),
DATE: makeType('DATETIME'),
INTEGER: length => makeType(`INT(${length})`),

View File

@ -71,6 +71,11 @@ function createHarness(options = {}) {
},
},
},
logger: {
info: () => {},
warn: () => {},
error: () => {},
},
};
return {
@ -369,15 +374,19 @@ describe('test/app/service/systemMethods/order/pendingOrder.allocateStorage.test
order_ids: [ 11, 12 ],
});
assert.deepEqual(capture.syncRequest, {
order_ids: [ 11, 12 ],
});
// 异步模式:立即返回 request_id,service 层在 setImmediate 中调用
assert.equal(result.flag, 'success');
assert.equal(result.message, '同步已受理,当前仅透传 order_ids');
assert.equal(result.code, 200);
assert.deepEqual(result.data, {
ok: true,
});
assert.match(result.request_id, /^sync_order_100000_\d+_[a-z0-9]+$/);
assert.equal(result.warehouse_id, 100000);
assert.ok(result.message.includes('已提交'));
// 等待异步回调触发
await new Promise(resolve => setImmediate(resolve));
// service 层被正确调用
assert.deepEqual(capture.syncRequest.order_ids, [ 11, 12 ]);
assert.equal(capture.syncRequest.warehouse_id, 100000);
assert.equal(typeof capture.syncRequest.progress_callback, 'function');
});
it('should reject warehouse_id and warehouseId on the pending order entry', async () => {

View File

@ -35,8 +35,8 @@ function createHarness() {
service.getWarehouseId = () => 1;
// 模拟 normalizeOrderListItem / attachOrderExpressNumbers 为直通
service.normalizeOrderListItem = (item) => item;
service.attachOrderExpressNumbers = async (list) => list;
service.normalizeOrderListItem = item => item;
service.attachOrderExpressNumbers = async list => list;
// 捕获 buildWhere 入参,返回简单条件
const originalBuildWhere = service.buildWhere.bind(service);
@ -48,7 +48,7 @@ function createHarness() {
// 模拟 getOrderModel 返回可控数据
service.getOrderModel = async () => ({
count: async () => 1,
findAll: async (opts) => {
findAll: async opts => {
captures.modelOpts = opts;
return [
{

View File

@ -205,7 +205,7 @@ describe('test/app/service/systemMethods/stock.warehouse.import.test.js', () =>
});
it('should map 条码 to barcode', () => {
const row = { '条码': 'A,B' };
const row = { 条码: 'A,B' };
const normalized = service._normalizeWarehouseImportRow(row);
assert.deepEqual(normalized.barcode, [ 'A', 'B' ]);
});