Compare commits
11 Commits
adb7405396
...
403a73b250
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
403a73b250 | ||
|
|
a5eba20a5e | ||
|
|
d6d7b23f52 | ||
|
|
4ddcbe60a4 | ||
|
|
33a92bdc8d | ||
|
|
59eb736740 | ||
|
|
fd565fda7b | ||
|
|
f2fe5311aa | ||
|
|
80c73bb34b | ||
|
|
a2dce0d520 | ||
|
|
f8915a5733 |
1
.gitignore
vendored
1
.gitignore
vendored
@ -38,3 +38,4 @@ versioning/*
|
||||
!versioning/.gitkeep
|
||||
|
||||
app/public/exports/
|
||||
script/debug-*.cjs
|
||||
|
||||
@ -133,8 +133,10 @@ rg "class .*Service|module.exports" app/service/qimenMethods
|
||||
- ping, ssoCodeToId, getStoreEmployees
|
||||
- app/service/inbox/ai.js (3)
|
||||
- callDeepSeek, getConversationHistory, processWithAI
|
||||
- app/service/inbox/functions.js (5)
|
||||
- registerBuiltinFunctions, register, callFunction, _getRecordingComputerId, _buildVideoUrl
|
||||
- app/service/inbox/functions.js (3)
|
||||
- registerBuiltinFunctions, register, callFunction
|
||||
- app/service/inbox/tools.js (2)
|
||||
- getRecordingComputerId, buildVideoUrl
|
||||
- app/service/inbox/groups.js (4)
|
||||
- resolveActiveGroups, isFunctionAvailable, getFunctionList, buildFunctionListText
|
||||
- app/service/inbox/index.js (5)
|
||||
@ -147,7 +149,7 @@ rg "class .*Service|module.exports" app/service/qimenMethods
|
||||
- receive
|
||||
- app/service/main.js (18)
|
||||
- success, fail, normalizeDate, setInfo, getInfo, isPlainObject, normalizeWhereCondition, normalizeWhereParams, extractWhereValues, prepareWhereContext, findQimenAppWithContract, queryFromDatabase, checkAuth, checkApiPermission, extractApiPermissionState, collectApiPermissionValue, setUserContext, systemInit
|
||||
- app/service/openapi.js (9)
|
||||
- app/service/openapiEntry.js (9)
|
||||
- resolveOpenapiMethod, getOpenapiMethodService, resolveOpenapiContract, getInfo, dispatchOpenapiMethod, validateOpenapiParams, parseJsonBody, normalizeSignFields, processRequest
|
||||
- app/service/openapi/callback.js (4)
|
||||
- signCallback, sendWithRetry, sendByAppKey, logCallback
|
||||
|
||||
@ -30,7 +30,7 @@ class OpenapiController extends Controller {
|
||||
const { ctx } = this;
|
||||
|
||||
try {
|
||||
const result = await ctx.service.openapi.processRequest();
|
||||
const result = await ctx.service.openapiEntry.processRequest();
|
||||
if (result.ok) {
|
||||
ctx.status = Number(result.httpStatus) || 200;
|
||||
ctx.body = toSuccess(result.data, result.message || 'ok');
|
||||
|
||||
@ -17,8 +17,8 @@ module.exports = app => {
|
||||
},
|
||||
account_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '账号ID,关联 wms_account.id',
|
||||
allowNull: true,
|
||||
comment: '账号ID,关联 wms_account.id;未知账号为 NULL(唯一索引对 NULL 不生效,允许多名无账号打包人)',
|
||||
},
|
||||
account_name: {
|
||||
type: STRING(128),
|
||||
|
||||
@ -60,6 +60,12 @@ module.exports = app => {
|
||||
allowNull: true,
|
||||
comment: '备注',
|
||||
},
|
||||
is_notified: {
|
||||
type: app.Sequelize.TINYINT(1),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '登记是否已通知货主群:0=未通知,1=已通知',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_return_received',
|
||||
comment: '退回收到登记表',
|
||||
|
||||
102
app/model/waybill_allocate_queue.js
Normal file
102
app/model/waybill_allocate_queue.js
Normal file
@ -0,0 +1,102 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 订单创建后自动分配快递的消费队列模型。
|
||||
*
|
||||
* 订单创建后的异步流程只入队(截单/未审核不入队),由定时任务
|
||||
* app/schedule/consume_waybill_allocate_queue.js 按仓库+货主串行批量消费,
|
||||
* 避免高并发逐单取号时的 InnoDB AB-BA 死锁。
|
||||
*
|
||||
* @param {import('egg').Application} app Egg 应用实例。
|
||||
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} Sequelize 模型。
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, INTEGER, STRING, DATE } = app.Sequelize;
|
||||
|
||||
const WaybillAllocateQueue = app.model.define('waybill_allocate_queue', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键',
|
||||
},
|
||||
order_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '订单ID(关联订单分表)',
|
||||
},
|
||||
business_key: {
|
||||
type: INTEGER(3),
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '业务键(与 wms_order_express.business_key 一致)',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '仓库ID(消费分组与数据隔离维度)',
|
||||
},
|
||||
store_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '货主ID(消费分组维度)',
|
||||
},
|
||||
status: {
|
||||
type: STRING(20),
|
||||
allowNull: false,
|
||||
defaultValue: 'pending',
|
||||
comment: '状态:pending/processing/done/failed',
|
||||
},
|
||||
retry_count: {
|
||||
type: INTEGER(3),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '重试次数',
|
||||
},
|
||||
next_retry_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '下次可消费时间(失败退避)',
|
||||
},
|
||||
error_message: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '最近一次失败原因',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '更新时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_waybill_allocate_queue',
|
||||
freezeTableName: true,
|
||||
underscored: true,
|
||||
timestamps: false,
|
||||
comment: '订单创建后自动分配快递消费队列',
|
||||
indexes: [
|
||||
{
|
||||
name: 'uk_order_id_business_key',
|
||||
unique: true,
|
||||
fields: [ 'order_id', 'business_key' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_status_id',
|
||||
fields: [ 'status', 'id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_status_updated_at',
|
||||
fields: [ 'status', 'updated_at' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return WaybillAllocateQueue;
|
||||
};
|
||||
255
app/schedule/consume_waybill_allocate_queue.js
Normal file
255
app/schedule/consume_waybill_allocate_queue.js
Normal file
@ -0,0 +1,255 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 定时消费订单创建时入队的自动分配快递队列(wms_waybill_allocate_queue)。
|
||||
*
|
||||
* 背景:订单创建后的异步流程逐单直接取号,大批量订单创建时 N 条并发取号事务
|
||||
* 与结算事务产生 wms_store_warehouse / wms_order_express 的 AB-BA 死锁。
|
||||
* 本任务按仓库+货主串行消费,保证同一签约关系下同一时刻只有一个取号事务在跑。
|
||||
*
|
||||
* 截单语义:订单创建时已判定(截单/未审核不入队),已入队的正常消费,消费侧不再校验截单。
|
||||
* 间隔 15 秒、type: worker(仅一个 worker 执行),带重入保护。
|
||||
*/
|
||||
|
||||
const MAX_CONSUME_ROWS_PER_WINDOW = 200;
|
||||
const MAX_RETRY_COUNT = 3;
|
||||
const RETRY_BASE_DELAY_MS = 60 * 1000;
|
||||
const PROCESSING_STALE_MS = 10 * 60 * 1000;
|
||||
const MAX_ERROR_MESSAGE_LENGTH = 500;
|
||||
|
||||
module.exports = {
|
||||
schedule: {
|
||||
interval: '15s',
|
||||
type: 'worker',
|
||||
immediate: false,
|
||||
disable: false,
|
||||
},
|
||||
|
||||
async task(ctx) {
|
||||
// 防止重入
|
||||
if (ctx.app._consumeWaybillAllocateQueueRunning) return;
|
||||
ctx.app._consumeWaybillAllocateQueueRunning = true;
|
||||
|
||||
try {
|
||||
await consumePendingRows(ctx);
|
||||
} catch (err) {
|
||||
ctx.logger.error(`[consume-waybill-allocate-queue] 消费异常: ${err.message}`, { stack: err.stack });
|
||||
} finally {
|
||||
ctx.app._consumeWaybillAllocateQueueRunning = false;
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* 批量更新队列行状态。
|
||||
* @param {Object} ctx Egg 上下文。
|
||||
* @param {Array<Object>} rows 队列行(含 id)。
|
||||
* @param {string} status 目标状态。
|
||||
* @param {string|null} errorMessage 失败原因。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async function updateQueueRowsStatus(ctx, rows, status, errorMessage) {
|
||||
const queueModel = ctx.model && ctx.model.WaybillAllocateQueue;
|
||||
if (!queueModel || !Array.isArray(rows) || rows.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { Op } = ctx.app.Sequelize;
|
||||
const ids = rows.map(row => Number(row.id)).filter(id => Number.isInteger(id) && id > 0);
|
||||
if (ids.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
await queueModel.update({
|
||||
status,
|
||||
error_message: errorMessage ? String(errorMessage).slice(0, MAX_ERROR_MESSAGE_LENGTH) : null,
|
||||
updated_at: new Date(),
|
||||
}, {
|
||||
where: {
|
||||
id: {
|
||||
[Op.in]: ids,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 组消费失败或未完成时:重试次数+1,未超限退回 pending(带退避),超限转 failed。
|
||||
* @param {Object} ctx Egg 上下文。
|
||||
* @param {Array<Object>} rows 队列行。
|
||||
* @param {string} errorMessage 失败原因。
|
||||
* @param {boolean} failImmediately 是否立即判失败(如 warehouse_id 缺失,重试无意义)。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async function markGroupRetryOrFailed(ctx, rows, errorMessage, failImmediately) {
|
||||
const queueModel = ctx.model && ctx.model.WaybillAllocateQueue;
|
||||
if (!queueModel || !Array.isArray(rows) || rows.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const normalizedErrorMessage = String(errorMessage || '运单分配失败');
|
||||
|
||||
for (const row of rows) {
|
||||
const rowId = Number(row.id);
|
||||
if (!Number.isInteger(rowId) || rowId <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const retryCount = Number(row.retry_count) || 0;
|
||||
if (failImmediately || retryCount + 1 >= MAX_RETRY_COUNT) {
|
||||
await queueModel.update({
|
||||
status: 'failed',
|
||||
retry_count: retryCount + 1,
|
||||
error_message: normalizedErrorMessage.slice(0, MAX_ERROR_MESSAGE_LENGTH),
|
||||
updated_at: new Date(),
|
||||
}, {
|
||||
where: { id: rowId },
|
||||
});
|
||||
} else {
|
||||
const delay = (retryCount + 1) * RETRY_BASE_DELAY_MS;
|
||||
await queueModel.update({
|
||||
status: 'pending',
|
||||
retry_count: retryCount + 1,
|
||||
next_retry_at: new Date(Date.now() + delay),
|
||||
error_message: null,
|
||||
updated_at: new Date(),
|
||||
}, {
|
||||
where: { id: rowId },
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取并消费待分配队列。
|
||||
* @param {Object} ctx Egg 上下文。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async function consumePendingRows(ctx) {
|
||||
const queueModel = ctx.model && ctx.model.WaybillAllocateQueue;
|
||||
const expressService = ctx.service && ctx.service.systems && ctx.service.systems.express;
|
||||
if (!queueModel || typeof queueModel.findAll !== 'function'
|
||||
|| !expressService || typeof expressService.createWaybillCodePipeline !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
const { Op } = ctx.app.Sequelize;
|
||||
|
||||
// 1) 兜底恢复:上次运行中断遗留的 processing 行退回 pending
|
||||
await queueModel.update({
|
||||
status: 'pending',
|
||||
updated_at: new Date(),
|
||||
}, {
|
||||
where: {
|
||||
status: 'processing',
|
||||
updated_at: {
|
||||
[Op.lt]: new Date(Date.now() - PROCESSING_STALE_MS),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// 2) 拉取待消费行
|
||||
const now = new Date();
|
||||
const pendingRows = await queueModel.findAll({
|
||||
where: {
|
||||
status: 'pending',
|
||||
[Op.or]: [
|
||||
{ next_retry_at: null },
|
||||
{ next_retry_at: { [Op.lte]: now } },
|
||||
],
|
||||
},
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
limit: MAX_CONSUME_ROWS_PER_WINDOW,
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (!Array.isArray(pendingRows) || pendingRows.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 3) 标记消费中(单 worker + 重入保护下仅作状态记录)
|
||||
const pendingIds = pendingRows.map(row => Number(row.id)).filter(id => Number.isInteger(id) && id > 0);
|
||||
if (pendingIds.length > 0) {
|
||||
await queueModel.update({
|
||||
status: 'processing',
|
||||
updated_at: new Date(),
|
||||
}, {
|
||||
where: {
|
||||
id: {
|
||||
[Op.in]: pendingIds,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// 4) 按 warehouse_id + store_id 分组,逐组串行消费
|
||||
const groupMap = new Map();
|
||||
for (const row of pendingRows) {
|
||||
const warehouseId = Number(row.warehouse_id) || 0;
|
||||
const storeId = Number(row.store_id) || 0;
|
||||
const groupKey = `${warehouseId}:${storeId}`;
|
||||
if (!groupMap.has(groupKey)) {
|
||||
groupMap.set(groupKey, {
|
||||
warehouseId,
|
||||
storeId,
|
||||
rows: [],
|
||||
});
|
||||
}
|
||||
groupMap.get(groupKey).rows.push(row);
|
||||
}
|
||||
|
||||
const orderExpressModel = ctx.model && ctx.model.OrderExpress;
|
||||
|
||||
for (const group of groupMap.values()) {
|
||||
const orders = group.rows
|
||||
.map(row => {
|
||||
const orderId = Number(row.order_id);
|
||||
const businessKey = Number(row.business_key) || 1;
|
||||
return { order_id: orderId, business_key: businessKey };
|
||||
})
|
||||
.filter(order => Number.isInteger(order.order_id) && order.order_id > 0);
|
||||
|
||||
if (group.warehouseId <= 0 || orders.length === 0) {
|
||||
await markGroupRetryOrFailed(ctx, group.rows, '队列数据缺少有效 warehouse_id/order_id', true);
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
await expressService.createWaybillCodePipeline(orders, {
|
||||
awaitTasks: true,
|
||||
warehouseId: group.warehouseId,
|
||||
});
|
||||
|
||||
// 5) 判定结果:取到单号(status=1)的订单视为完成
|
||||
const doneKeySet = new Set();
|
||||
if (orderExpressModel && typeof orderExpressModel.findAll === 'function') {
|
||||
const doneRows = await orderExpressModel.findAll({
|
||||
where: {
|
||||
warehouse_id: group.warehouseId,
|
||||
[Op.or]: orders.map(order => ({
|
||||
order_id: order.order_id,
|
||||
business_key: order.business_key,
|
||||
})),
|
||||
status: 1,
|
||||
},
|
||||
attributes: [ 'order_id', 'business_key' ],
|
||||
raw: true,
|
||||
});
|
||||
for (const doneRow of Array.isArray(doneRows) ? doneRows : []) {
|
||||
doneKeySet.add(`${Number(doneRow.order_id)}:${Number(doneRow.business_key)}`);
|
||||
}
|
||||
}
|
||||
|
||||
const doneRows = group.rows.filter(row => doneKeySet.has(`${Number(row.order_id)}:${Number(row.business_key) || 1}`));
|
||||
const restRows = group.rows.filter(row => !doneKeySet.has(`${Number(row.order_id)}:${Number(row.business_key) || 1}`));
|
||||
|
||||
await updateQueueRowsStatus(ctx, doneRows, 'done', null);
|
||||
await markGroupRetryOrFailed(ctx, restRows, '运单分配未完成', false);
|
||||
|
||||
ctx.logger.info(`[consume-waybill-allocate-queue] 组消费完成 warehouse_id=${group.warehouseId} store_id=${group.storeId} total=${group.rows.length} done=${doneRows.length} rest=${restRows.length}`);
|
||||
} catch (error) {
|
||||
ctx.logger.error(`[consume-waybill-allocate-queue] 组消费失败 warehouse_id=${group.warehouseId} store_id=${group.storeId}: ${error.message}`);
|
||||
await markGroupRetryOrFailed(ctx, group.rows, error && error.message ? error.message : String(error), false);
|
||||
}
|
||||
}
|
||||
}
|
||||
40
app/schedule/notify_return_received.js
Normal file
40
app/schedule/notify_return_received.js
Normal file
@ -0,0 +1,40 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 退回收件登记聚合通知定时任务。
|
||||
* 每分钟在单 worker 中扫描一次:对"登记时间超过防抖窗口(默认 5 分钟)且未通知"的登记,
|
||||
* 只对货主查退回时登记过的运单,按 仓库+货主 聚合推送到货主售后群,并标记 is_notified=1。
|
||||
*/
|
||||
module.exports = {
|
||||
schedule: {
|
||||
interval: '1m',
|
||||
type: 'worker',
|
||||
immediate: false,
|
||||
disable: false,
|
||||
},
|
||||
|
||||
/**
|
||||
* 执行退回收件登记聚合通知。
|
||||
*
|
||||
* @param {Object} ctx Egg 上下文。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async task(ctx) {
|
||||
if (ctx.app._returnReceivedNotifyRunning) {
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.app._returnReceivedNotifyRunning = true;
|
||||
|
||||
try {
|
||||
const result = await ctx.service.systems.returnReceived.notifyPending();
|
||||
ctx.logger.info(
|
||||
`[notify-return-received] 聚合通知完成 notified=${result && result.notified || 0} skipped=${result && result.skipped || 0}`
|
||||
);
|
||||
} catch (error) {
|
||||
ctx.logger.error(`[notify-return-received] 任务执行失败: ${error.message}`);
|
||||
} finally {
|
||||
ctx.app._returnReceivedNotifyRunning = false;
|
||||
}
|
||||
},
|
||||
};
|
||||
@ -270,7 +270,7 @@ ${historyContext}
|
||||
- 【规则 - handleStoreFeedback】货主售后群中客户反馈"错发/发错""破损/坏了""多发/发多""少发/漏发"且提供了运单号时,调用 handleStoreFeedback 创建售后工单(初始状态未开始处理,不通知快递群);若消息中无运单号,先向客户确认运单号再调用
|
||||
- 【规则 - handleExpressFeedback】快递售后群中,快递客服反馈处理进度/结果(如"已通知网点""网点正在处理""已拦截""已联系收件人""改地址失败/无法改""已签收""加急处理"等)且消息含运单号时,必须调用 handleExpressFeedback(keyword=运单号,多个用逗号分隔)。该函数会自动查找已有售后工单追加反馈并回信到相关群,无工单则自动创建。严禁把快递客服的进度/结果反馈判定为无需处理而 silent;若消息无运单号,先用 recallHistory 或询问确认运单号,严禁跳过
|
||||
- 【规则 - handleExpressFeedback 证据核实】快递售后群中快递方发消息要求"提供交易记录截图/未收到依据/核实签收/带日期单号"等证据类诉求且消息含运单号时,同样必须调用 handleExpressFeedback(as_sub_type=verify_delivery),由函数创建售后工单并回信到货主售后群;严禁仅回复"收到/已记录"等确认话术而不调用函数
|
||||
- 【规则 - changeAddr】货主售后群中客户消息含"改地址/改电话/改联系人/改收件人/地址更改/改手机/催退回/尽快安排派送/催促退回"等诉求且提供了运单号时,调用 changeAddr(issue_type:addr=改地址类诉求,return=催退回类诉求);函数会创建售后工单并把客户原文转发到对应快递群,返回的 data.message 是模板消息必须原样回复;若消息中无运单号,先向客户确认运单号再调用
|
||||
- 【规则 - changeAddr】货主售后群中客户消息含"改地址/改电话/改联系人/改收件人/地址更改/改手机/催退回/催促退回/催件/催派送/尽快安排派送"等诉求且提供了运单号时,调用 changeAddr(issue_type:addr=改地址类诉求,return=催退回类诉求,urge=催件/催派送类诉求;注意区分:"催退回/催促退回"用 return,"催件/催派送/尽快安排派送"用 urge,严禁把催件判定为 return);函数会创建售后工单并把客户原文转发到对应快递群,返回的 data.message 是模板消息必须原样回复;若消息中无运单号,先向客户确认运单号再调用
|
||||
- 【规则 - weishoudao】货主售后群中客户消息含"核实签收/未收到/是否发出/是否已经发货/核实/没有找到快递"等诉求且提供了运单号时,调用 weishoudao 创建核实签收售后工单,并把"运单号+核实签收"转发到对应快递群;返回的 data.message 是模板消息必须原样回复;若消息中无运单号,先向客户确认运单号再调用
|
||||
- 【规则 - changeExpress】货主售后群中客户要求"改快递/换快递/改圆通/改中通/改顺丰"等且提供了订单号时,调用 changeExpress(keyword=订单号,express=目标快递名称或编码);仅待处理表中未分配快递的订单可以修改,已分配快递或不在待处理表的订单不能修改;返回的 data.message 是模板消息必须原样回复;若消息中缺订单号或目标快递,先向客户确认再调用
|
||||
- 【规则 - queryPackVideo】用户询问"打包视频/打包录像/装箱视频"且提供了运单号时,调用 queryPackVideo 查询(散单按订单、团购单按波次找打包记录);仅查询不建工单;返回的 data.message 是模板消息必须原样回复;若消息中无运单号,先向客户确认运单号再调用
|
||||
|
||||
@ -1513,11 +1513,11 @@ class InboxFunctionsService extends Service {
|
||||
});
|
||||
|
||||
this.register('queryReturn', {
|
||||
description: '查询退回包裹明细(查退回)。用户发送"查退回+运单号"时调用。传入运单号,查询退回收到/退回拆包/未退回登记状态:已拆包返回拆包明细与录像地址模板消息,未退回则自动登记到退回查询表。注意:仅查询退回状态使用,与 interceptWaybill 拦截、queryOrder 订单查询不同',
|
||||
description: '查询退回包裹明细(查退回)。用户发送"查退回+运单号"时调用,支持多行/多个运单号(换行、逗号、空格分隔),每个单号分别返回一条结果。传入运单号,查询退回收到/退回拆包/未退回登记状态:已拆包返回拆包明细与录像地址模板消息,未退回则自动登记到退回查询表。注意:仅查询退回状态使用,与 interceptWaybill 拦截、queryOrder 订单查询不同',
|
||||
weight: 90,
|
||||
keywords: [ '查退回', '查退件', '退回查询', '退回明细', '查拆包', '退件查询', '退回进度' ],
|
||||
params: {
|
||||
waybill_code: { type: 'string', required: true, description: '退回包裹运单号,如"查退回 465570943491370"中的465570943491370' },
|
||||
waybill_code: { type: 'string', required: true, description: '退回包裹运单号,支持多个(换行/逗号/空格分隔),如"查退回 465570943491370\nSF123456"' },
|
||||
},
|
||||
groups: [ GROUP.COMMON ],
|
||||
handler: async (params = {}) => {
|
||||
@ -1531,71 +1531,91 @@ class InboxFunctionsService extends Service {
|
||||
// 兼容把"查退回 123456"整体传入的情况
|
||||
const match = raw.match(/查退[回件]\s*[::]?\s*(.+)$/);
|
||||
if (match) raw = String(match[1]).trim();
|
||||
// 去掉空白与常见中文标点,保留运单号本体(字母/数字/横线等)
|
||||
const waybill = raw.replace(/[\s,,。;;]+/g, '');
|
||||
if (!waybill) return { success: false, error: '未解析到有效运单号' };
|
||||
|
||||
// 解析多个单号:换行/逗号/空格/常见中文标点分隔,去重保序
|
||||
const waybills = [ ...new Set(
|
||||
raw.split(/[\s,,。;;]+/)
|
||||
.map(s => s.trim())
|
||||
.filter(Boolean)
|
||||
) ];
|
||||
if (waybills.length === 0) return { success: false, error: '未解析到有效运单号' };
|
||||
if (!warehouseId) return { success: false, error: '无法获取仓库信息' };
|
||||
|
||||
try {
|
||||
const result = await ctx.service.systems.returnUnpack.queryByWaybill({
|
||||
waybill_code: waybill,
|
||||
warehouse_id: warehouseId,
|
||||
store_id: storeId,
|
||||
});
|
||||
const messages = [];
|
||||
const statuses = [];
|
||||
for (const waybill of waybills) {
|
||||
try {
|
||||
const result = await ctx.service.systems.returnUnpack.queryByWaybill({
|
||||
waybill_code: waybill,
|
||||
warehouse_id: warehouseId,
|
||||
store_id: storeId,
|
||||
});
|
||||
|
||||
const warehouseLabel = result.warehouse_name || '仓库';
|
||||
let message = '';
|
||||
const warehouseLabel = result.warehouse_name || '仓库';
|
||||
let message = '';
|
||||
|
||||
if (result.status === 'unpacked') {
|
||||
const unpack = result.unpack || {};
|
||||
const details = result.details || [];
|
||||
const videos = result.videos || [];
|
||||
const orderInfo = result.order_info || {};
|
||||
if (result.status === 'unpacked') {
|
||||
const unpack = result.unpack || {};
|
||||
const details = result.details || [];
|
||||
const videos = result.videos || [];
|
||||
const orderInfo = result.order_info || {};
|
||||
|
||||
const lines = [];
|
||||
lines.push(`${waybill}已在已退件中登记,登记信息为:`);
|
||||
lines.push('');
|
||||
lines.push(`运单号:${waybill}`);
|
||||
lines.push(`是否原单:${unpack.order_express_id ? '是' : '否'}`);
|
||||
lines.push(`交易单号:${orderInfo.trade_no || ''}`);
|
||||
lines.push(`快递:${orderInfo.express || ''}`);
|
||||
lines.push(`店铺名称:${orderInfo.shop_name || ''}`);
|
||||
lines.push(`${warehouseLabel}收到且已拆包,拆包明细为:`);
|
||||
if (details.length > 0) {
|
||||
for (const detail of details) {
|
||||
lines.push(`商品名称:${detail.item_name || ''}`);
|
||||
lines.push(`条码:${detail.barcode || ''}`);
|
||||
lines.push(`数量:${detail.quantity || 0}`);
|
||||
lines.push(`是否破损:${detail.product_status === 'damaged' ? '是' : '否'}`);
|
||||
const lines = [];
|
||||
lines.push(`${waybill}已在已退件中登记,登记信息为:`);
|
||||
lines.push('');
|
||||
lines.push(`运单号:${waybill}`);
|
||||
lines.push(`是否原单:${unpack.order_express_id ? '是' : '否'}`);
|
||||
lines.push(`交易单号:${orderInfo.trade_no || ''}`);
|
||||
lines.push(`快递:${orderInfo.express || ''}`);
|
||||
lines.push(`店铺名称:${orderInfo.shop_name || ''}`);
|
||||
lines.push(`${warehouseLabel}收到且已拆包,拆包明细为:`);
|
||||
if (details.length > 0) {
|
||||
for (const detail of details) {
|
||||
lines.push(`商品名称:${detail.item_name || ''}`);
|
||||
lines.push(`条码:${detail.barcode || ''}`);
|
||||
lines.push(`数量:${detail.quantity || 0}`);
|
||||
lines.push(`是否破损:${detail.product_status === 'damaged' ? '是' : '否'}`);
|
||||
}
|
||||
} else {
|
||||
lines.push('暂无拆包明细,拆包完成后可再次查询');
|
||||
}
|
||||
lines.push('');
|
||||
lines.push('退件录像地址为:');
|
||||
if (videos.length > 0) {
|
||||
for (const video of videos) {
|
||||
if (video.video_url) lines.push(String(video.video_url));
|
||||
}
|
||||
} else {
|
||||
lines.push('暂无');
|
||||
}
|
||||
lines.push('拆包视频保存会有延迟,可以在稍后发送:查退回+运单号,查询');
|
||||
message = lines.join('\n');
|
||||
} else if (result.status === 'received') {
|
||||
message = `包裹${waybill}已收到未拆包,拆包登记后,将自动发送通知拆包信息`;
|
||||
} else if (result.status === 'not_returned') {
|
||||
message = `${waybill}尚未退回仓库,已在未退回表中登记成功,等待包裹退件登记后,将自动发送通知包裹信息`;
|
||||
} else {
|
||||
message = `未查询到运单号${waybill}的退回信息,请核实单号后重试`;
|
||||
}
|
||||
} else {
|
||||
lines.push('暂无拆包明细,拆包完成后可再次查询');
|
||||
|
||||
messages.push(message);
|
||||
statuses.push(result.status);
|
||||
} catch (error) {
|
||||
ctx.logger.warn(`[inbox functions] 退回查询单号失败 ${waybill}: ${error.message}`);
|
||||
messages.push(`${waybill}退回查询失败:${error.message}`);
|
||||
statuses.push('error');
|
||||
}
|
||||
lines.push('');
|
||||
lines.push('退件录像地址为:');
|
||||
if (videos.length > 0) {
|
||||
for (const video of videos) {
|
||||
if (video.video_url) lines.push(String(video.video_url));
|
||||
}
|
||||
} else {
|
||||
lines.push('暂无');
|
||||
}
|
||||
lines.push('拆包视频保存会有延迟,可以在稍后发送:查退回+运单号,查询');
|
||||
message = lines.join('\n');
|
||||
} else if (result.status === 'received') {
|
||||
message = `包裹${waybill}已收到未拆包,拆包登记后,将自动发送通知拆包信息`;
|
||||
} else if (result.status === 'not_returned') {
|
||||
message = `${waybill}尚未退回仓库,已在未退回表中登记成功,等待包裹退件登记后,将自动发送通知包裹信息`;
|
||||
} else {
|
||||
message = `未查询到运单号${waybill}的退回信息,请核实单号后重试`;
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
status: result.status,
|
||||
waybill_code: waybill,
|
||||
message,
|
||||
status: statuses[0],
|
||||
waybill_code: waybills[0],
|
||||
total: waybills.length,
|
||||
message: messages[0], // 兼容单条回复(AI 兜底路径取首条)
|
||||
messages, // 规则引擎多行回复:每个单号一条消息
|
||||
direct_reply: true,
|
||||
},
|
||||
};
|
||||
@ -2079,12 +2099,12 @@ class InboxFunctionsService extends Service {
|
||||
});
|
||||
|
||||
this.register('changeAddr', {
|
||||
description: '货主售后群改地址/催退回处理。客户消息含"改地址/改电话/改联系人/改收件人/地址更改/改手机/催退回/尽快安排派送/催促退回"等诉求且提供了运单号时调用:创建售后工单(改地址/催退回),并将客户原文转发到对应快递的售后群通知快递处理',
|
||||
description: '货主售后群改地址/催退回/催件处理。客户消息含"改地址/改电话/改联系人/改收件人/地址更改/改手机/催退回/催促退回/催件/催派送/尽快安排派送"等诉求且提供了运单号时调用:创建售后工单(改地址/催退回/催件),并将客户原文转发到对应快递的售后群通知快递处理',
|
||||
weight: 89,
|
||||
keywords: [ '改地址', '改电话', '改联系人', '改收件人', '地址更改', '改手机', '催退回', '尽快安排派送', '催促退回' ],
|
||||
keywords: [ '改地址', '改电话', '改联系人', '改收件人', '地址更改', '改手机', '催退回', '催促退回', '催件', '催派送', '尽快安排派送' ],
|
||||
params: {
|
||||
keyword: { type: 'string', required: true, description: '运单号,多个用逗号或空格分隔,如 SF111,SF222' },
|
||||
issue_type: { type: 'string', required: true, description: '诉求类型:addr(改地址类诉求)/return(催退回类诉求)' },
|
||||
issue_type: { type: 'string', required: true, description: '诉求类型:addr(改地址类诉求)/return(催退回类诉求)/urge(催件/催派送类诉求),注意区分:催退回用 return,催件/催派送用 urge' },
|
||||
},
|
||||
groups: [ GROUP.BOUND_STORE_AFTER_SALES ],
|
||||
handler: async (params = {}) => {
|
||||
@ -2106,6 +2126,8 @@ class InboxFunctionsService extends Service {
|
||||
改地址: { sub_type: 'change_address', label: '改地址' },
|
||||
return: { sub_type: 'rejected', label: '催退回' },
|
||||
催退回: { sub_type: 'rejected', label: '催退回' },
|
||||
urge: { sub_type: 'urge', label: '催件' },
|
||||
催件: { sub_type: 'urge', label: '催件' },
|
||||
};
|
||||
const issue = ISSUE_TYPE_MAP[issueTypeRaw] || ISSUE_TYPE_MAP.addr;
|
||||
|
||||
@ -2278,11 +2300,14 @@ class InboxFunctionsService extends Service {
|
||||
}
|
||||
|
||||
// 第六步:客户回信模板(单号+诉求,区分是否已通知快递)
|
||||
// key 必须与 issue.sub_type 对齐(change_address/rejected/urge),
|
||||
// 此前误用 addr/return 导致永远回退到改地址文案
|
||||
const REPLY_TEXT = {
|
||||
addr: { done: '修改地址已经登记', notify: '并已通知快递修改' },
|
||||
return: { done: '催退回已经登记', notify: '并已通知快递处理' },
|
||||
change_address: { done: '修改地址已经登记', notify: '并已通知快递修改' },
|
||||
rejected: { done: '催退回已经登记', notify: '并已通知快递处理' },
|
||||
urge: { done: '催件已经登记', notify: '并已通知快递处理' },
|
||||
};
|
||||
const replyText = REPLY_TEXT[issue.sub_type] || REPLY_TEXT.addr;
|
||||
const replyText = REPLY_TEXT[issue.sub_type] || REPLY_TEXT.change_address;
|
||||
const lines = expressList.map(e => {
|
||||
const head = `运单${e.waybill_code}${replyText.done}`;
|
||||
return notifiedWaybillIds.has(e.id)
|
||||
@ -3171,10 +3196,11 @@ class InboxFunctionsService extends Service {
|
||||
raw: true,
|
||||
});
|
||||
// 视频地址拼接 CDN 域名(与 order.packing.list、queryReturn 对齐)
|
||||
const recordingComputerId = await this._getRecordingComputerId(warehouseId);
|
||||
const inboxTools = ctx.service.inbox.tools;
|
||||
const recordingComputerId = await inboxTools.getRecordingComputerId(warehouseId);
|
||||
const urls = videos
|
||||
.filter(v => String(v.status || '') !== 'failed')
|
||||
.map(v => this._buildVideoUrl(warehouseId, recordingComputerId, v.video_url))
|
||||
.map(v => inboxTools.buildVideoUrl(warehouseId, recordingComputerId, v.video_url))
|
||||
.filter(Boolean);
|
||||
|
||||
if (urls.length === 0) {
|
||||
@ -3924,45 +3950,6 @@ class InboxFunctionsService extends Service {
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取仓库的录制电脑 ID(带缓存)。
|
||||
* @param {number} warehouseId 仓库ID
|
||||
* @return {Promise<number|null>} 录制电脑ID,找不到返回 null
|
||||
*/
|
||||
async _getRecordingComputerId(warehouseId) {
|
||||
const cacheKey = `_recordingComputer_${warehouseId}`;
|
||||
if (this[cacheKey] !== undefined) {
|
||||
return this[cacheKey];
|
||||
}
|
||||
const row = await this.ctx.model.PrintComputer.findOne({
|
||||
where: { warehouse_id: warehouseId, is_recording: true, deleted_at: null },
|
||||
attributes: [ 'id' ],
|
||||
raw: true,
|
||||
});
|
||||
this[cacheKey] = row ? row.id : null;
|
||||
return this[cacheKey];
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建视频完整 URL。
|
||||
* 格式:http://w{warehouseId}-c{recordingComputerId}.o.gztbyc.com{videoPath}
|
||||
* @param {number} warehouseId 仓库ID
|
||||
* @param {number|null} recordingComputerId 录制电脑ID
|
||||
* @param {string} videoPath 视频路径
|
||||
* @return {string} 完整 URL
|
||||
*/
|
||||
_buildVideoUrl(warehouseId, recordingComputerId, videoPath) {
|
||||
const path = String(videoPath || '').trim();
|
||||
if (!path || !recordingComputerId) {
|
||||
return path;
|
||||
}
|
||||
// 已是完整 URL 时原样返回,避免重复拼接
|
||||
if (/^https?:\/\//i.test(path)) {
|
||||
return path;
|
||||
}
|
||||
return `http://w${warehouseId}-c${recordingComputerId}.o.gztbyc.com${path}`;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = InboxFunctionsService;
|
||||
|
||||
@ -139,7 +139,9 @@ class InboxGroupsService extends Service {
|
||||
const storeId = Number(ctx.inboxContext?.store_id || 0);
|
||||
|
||||
const gtDef = GROUP_TYPES.find(gt => gt.type === groupType);
|
||||
if (gtDef && (groupType === 'express' || storeId > 0)) {
|
||||
// warehouse/express 群不绑定货主(store_id 允许为空),无条件激活主分组;
|
||||
// store 群必须有货主归属(storeId > 0)才激活,防止未绑定货主的群越权调用函数。
|
||||
if (gtDef && (groupType === 'express' || groupType === 'warehouse' || storeId > 0)) {
|
||||
groups.push(gtDef.mainGroup);
|
||||
const subMap = VALID_SUB_TYPES[groupType];
|
||||
if (subMap && subMap[subType]) {
|
||||
|
||||
@ -14,17 +14,11 @@ const DEFAULT_HISTORY_MESSAGE_MAX_AGE_MS = 10 * 60 * 1000;
|
||||
*/
|
||||
class InboxProcessorService extends Service {
|
||||
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
/**
|
||||
* 群信息缓存(groupId:warehouseId → { group_type, sub_type, ai_enabled, ext_data })。
|
||||
* 生命周期跟随进程,写回 ext_data 时清除对应条目。
|
||||
*/
|
||||
this._groupCache = new Map();
|
||||
}
|
||||
|
||||
/**
|
||||
* 从缓存或 DB 拉取群信息。若群 ext_data 为空且消息携带 ext_data,自动写回并清缓存。
|
||||
* 从数据库拉取群信息(不缓存)。
|
||||
* Egg Service 按请求实例化,进程内缓存无法跨请求共享,
|
||||
* 直接查库可保证 inbox.group.update/reset 修改群配置后下一条消息立即生效。
|
||||
* 若群 ext_data 为空且消息携带 ext_data,自动写回群配置。
|
||||
* @param {string} groupId 外部群ID
|
||||
* @param {number} warehouseId 仓库ID
|
||||
* @param {Object|null} msgExtData 入站消息的 ext_data
|
||||
@ -32,11 +26,6 @@ class InboxProcessorService extends Service {
|
||||
*/
|
||||
async _loadGroupInfo(groupId, warehouseId, msgExtData) {
|
||||
const { ctx } = this;
|
||||
const cacheKey = `${groupId}:${warehouseId}`;
|
||||
|
||||
// 命中缓存直接返回
|
||||
const cached = this._groupCache.get(cacheKey);
|
||||
if (cached) return cached;
|
||||
|
||||
let group = null;
|
||||
try {
|
||||
@ -72,8 +61,6 @@ class InboxProcessorService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
// 写入缓存
|
||||
this._groupCache.set(cacheKey, info);
|
||||
return info;
|
||||
}
|
||||
|
||||
@ -246,7 +233,70 @@ class InboxProcessorService extends Service {
|
||||
// 5.2 注入入站消息ID,供下游函数(如 interceptWaybill)关联工单
|
||||
ctx.inboxContext.inbound_message_id = parentId || null;
|
||||
|
||||
// 6. DeepSeek 两步交互(AI 内部自行判断真人接管)
|
||||
// 6. 关键词规则引擎(主回复路径,不走 AI,节省推理费用)
|
||||
const ruleResult = await ctx.service.inbox.rules.handle(String(data.content || '').trim());
|
||||
if (ruleResult.handled) {
|
||||
// 记录规则命中轨迹到入站消息,便于排查
|
||||
if (ruleResult.thoughts && ruleResult.thoughts.length > 0) {
|
||||
try {
|
||||
await InboxMessage.update(
|
||||
{ ai_thoughts: ruleResult.thoughts },
|
||||
{ where: { ext_id: extId } }
|
||||
);
|
||||
} catch (e) {
|
||||
ctx.logger.warn(`[inbox processor] 保存规则处理记录失败: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (ruleResult.silent) {
|
||||
ctx.logger.info(`[inbox processor] 规则静默(无需回复) ext_id=${extId}`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (ruleResult.reply) {
|
||||
// 支持多条回复(如查退回多单号):逐条独立回信
|
||||
const replies = Array.isArray(ruleResult.reply) ? ruleResult.reply : [ ruleResult.reply ];
|
||||
ctx.logger.info(
|
||||
`[inbox processor] 规则引擎处理完成 ext_id=${extId} ` +
|
||||
`fn=${ruleResult.fn || '-'} key=${ruleResult.matchedKey || '-'} replies=${replies.length}`
|
||||
);
|
||||
// 快递群:仅执行函数,不回信
|
||||
if (groupType === 'express') {
|
||||
ctx.logger.info(`[inbox processor] 快递群规则处理完成(不回信) ext_id=${extId}`);
|
||||
return;
|
||||
}
|
||||
for (let idx = 0; idx < replies.length; idx++) {
|
||||
const replyContent = replies[idx];
|
||||
// 多条回复时每条独立 ext_id,避免回执唯一键冲突
|
||||
const replyExtId = replies.length > 1 ? `${extId}:r${idx}` : extId;
|
||||
await this.writeOutboundReply({
|
||||
warehouse_id: warehouseId,
|
||||
ext_id: replyExtId,
|
||||
parent_id: parentId,
|
||||
ext_data: data.ext_data || null,
|
||||
group_id: ctx.inboxContext?.group_id || data.group_id || null,
|
||||
user_id: ctx.inboxContext?.user_id || data.user_id || null,
|
||||
group_name: ctx.inboxContext?.group_name || data.group_name || null,
|
||||
user_name: ctx.inboxContext?.user_name || data.user_name || null,
|
||||
}, replyContent, 'rule_reply');
|
||||
}
|
||||
} else {
|
||||
ctx.logger.info(`[inbox processor] 规则已执行但无回复内容 ext_id=${extId} fn=${ruleResult.fn || '-'}`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// 6.5 AI 兜底(默认关闭,config.inbox.aiFallback=true 时启用)
|
||||
const aiFallback = !!(this.app.config.inbox && this.app.config.inbox.aiFallback);
|
||||
if (!aiFallback) {
|
||||
ctx.logger.info(
|
||||
`[inbox processor] 规则未命中且AI兜底关闭,静默 ext_id=${extId} ` +
|
||||
`content=${String(data.content || '').slice(0, 80)}`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// 7. DeepSeek 两步交互(AI 兜底,内部自行判断真人接管)
|
||||
const aiResult = await ctx.service.inbox.ai.processWithAI({
|
||||
content: data.content || '',
|
||||
ext_data: data.ext_data || null,
|
||||
@ -277,7 +327,7 @@ class InboxProcessorService extends Service {
|
||||
`function=${aiResult.functionName || 'direct'} reply_length=${replyContent.length}`
|
||||
);
|
||||
|
||||
// 7. AI 推理写入入站消息(便于排查)
|
||||
// 7.1 AI 推理写入入站消息(便于排查)
|
||||
if (aiResult.thoughts && aiResult.thoughts.length > 0) {
|
||||
try {
|
||||
await InboxMessage.update(
|
||||
@ -289,13 +339,13 @@ class InboxProcessorService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
// 8. 快递群:仅执行函数,不回信
|
||||
// 8. 快递群:仅执行函数,不回信(AI 兜底分支)
|
||||
if (groupType === 'express') {
|
||||
ctx.logger.info(`[inbox processor] 快递群AI处理完成(不回信) ext_id=${extId}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// 9. 统一回信
|
||||
// 9. 统一回信(AI 兜底分支)
|
||||
await this.writeOutboundReply({
|
||||
warehouse_id: warehouseId,
|
||||
ext_id: extId,
|
||||
|
||||
466
app/service/inbox/rules.js
Normal file
466
app/service/inbox/rules.js
Normal file
@ -0,0 +1,466 @@
|
||||
'use strict';
|
||||
|
||||
/* eslint-disable no-use-before-define */
|
||||
/* 规则表/常量按“配置在后、逻辑在前”组织,类方法通过函数声明提升访问,此处禁用声明顺序检查 */
|
||||
|
||||
const Service = require('egg').Service;
|
||||
|
||||
/**
|
||||
* 站内信关键词规则引擎(主回复路径,替代 AI 推理)。
|
||||
*
|
||||
* 设计参考 PHP Chat.php 的规则表结构:
|
||||
* - 按群类型(store/warehouse/express)维护规则表,顺序即优先级,先命中先执行;
|
||||
* - 每条规则:关键词数组 → inbox 函数,命中后从消息中提取运单号/订单号直接调用函数;
|
||||
* - 函数返回的模板消息(direct_reply/message)原样回信;
|
||||
* - 确认/感谢类短消息、未命中消息默认静默,不触发 AI,节省推理费用;
|
||||
* - AI 仅在 config.inbox.aiFallback=true 时作为兜底。
|
||||
*/
|
||||
class InboxRulesService extends Service {
|
||||
|
||||
/**
|
||||
* 规则引擎主入口:关键词匹配 + 参数提取 + 函数调用。
|
||||
*
|
||||
* @param {string} content 消息正文。
|
||||
* @return {Promise<Object>} 处理结果:
|
||||
* - { handled: false }:未命中任何规则(由调用方决定是否 AI 兜底/静默)。
|
||||
* - { handled: true, silent: true }:命中静默规则,不回复。
|
||||
* - { handled: true, reply: string, fn, params, result, matchedKey, thoughts }:已执行函数并生成回复。
|
||||
*/
|
||||
async handle(content) {
|
||||
const { ctx } = this;
|
||||
const text = String(content || '').trim();
|
||||
if (!text) return { handled: false };
|
||||
|
||||
const groupType = String(ctx.inboxContext?.group_type || '').trim();
|
||||
const rules = RULE_TABLES[groupType];
|
||||
if (!Array.isArray(rules) || rules.length === 0) {
|
||||
ctx.logger.info(`[inbox rules] 无规则表 group_type=${groupType || '-'}`);
|
||||
return { handled: false };
|
||||
}
|
||||
|
||||
const groupsSvc = ctx.service.inbox.groups;
|
||||
const funcSvc = ctx.service.inbox.functions;
|
||||
const activeGroups = groupsSvc.resolveActiveGroups();
|
||||
|
||||
// 收集所有命中规则:命中关键词最长者优先(长词优先)。
|
||||
// 相反语义的短词(如“拦截”vs“取消拦截”)不再依赖人工排序,
|
||||
// 长词“取消拦截”天然排在短词“拦截”之前,短词不会吞掉长词语义。
|
||||
const candidates = [];
|
||||
for (const rule of rules) {
|
||||
if (rule.any) {
|
||||
candidates.push({ rule, key: 'any', keyLen: Infinity });
|
||||
continue;
|
||||
}
|
||||
const hitKey = rule.keys.find(k => text.includes(k));
|
||||
if (hitKey) candidates.push({ rule, key: hitKey, keyLen: hitKey.length });
|
||||
}
|
||||
// 稳定排序:keyLen 相同保持规则表顺序(先定义者优先)
|
||||
candidates.sort((a, b) => b.keyLen - a.keyLen);
|
||||
|
||||
for (const cand of candidates) {
|
||||
const rule = cand.rule;
|
||||
|
||||
// 防误判守卫(如拦截 vs 查询物流)
|
||||
if (rule.guard && !rule.guard(text)) {
|
||||
ctx.logger.info(`[inbox rules] 规则 ${rule.fn} 未通过防误判守卫: ${text.slice(0, 50)}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// 内置帮助指令
|
||||
if (rule.fn === '__help__') {
|
||||
const reply = HELP_TEXTS[groupType] || '当前群暂无可用的快捷指令';
|
||||
return {
|
||||
handled: true, reply, fn: '__help__', params: {}, result: null, matchedKey: 'help',
|
||||
thoughts: [{ round: 0, action: 'rule', function: '__help__', params: {}, reason: '帮助指令命中: help', functionResult: null }],
|
||||
};
|
||||
}
|
||||
|
||||
// 函数可用性校验(复用群分组权限,防止越权调用)
|
||||
const def = funcSvc.registry.get(rule.fn);
|
||||
if (!def || !groupsSvc.isFunctionAvailable(def, activeGroups)) {
|
||||
ctx.logger.info(
|
||||
`[inbox rules] 函数 ${rule.fn} 当前群不可用,跳过 groups=${def ? def.groups.join(',') : '-'} active=${activeGroups.join(',')}`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
// 参数提取
|
||||
const params = {};
|
||||
if (rule.waybill) {
|
||||
const waybills = extractWaybills(text);
|
||||
if (waybills.length === 0) {
|
||||
if (rule.noWaybillSilent) {
|
||||
return { handled: true, silent: true };
|
||||
}
|
||||
return {
|
||||
handled: true,
|
||||
reply: rule.tip || '请提供运单号(发送:指令+运单号,多个单号用逗号或空格分隔)',
|
||||
fn: rule.fn, params: {}, result: null, matchedKey: rule.keys?.[0],
|
||||
thoughts: [{ round: 0, action: 'rule', function: rule.fn, params: {}, reason: '参数不足-引导提示', functionResult: null }],
|
||||
};
|
||||
}
|
||||
// 默认参数名 keyword,个别函数(如 queryReturn)用 waybill_code
|
||||
params[rule.paramName || 'keyword'] = waybills.join(',');
|
||||
}
|
||||
if (rule.order) {
|
||||
const orders = extractOrders(text);
|
||||
if (orders.length === 0) {
|
||||
return {
|
||||
handled: true,
|
||||
reply: rule.tip || '请提供订单号(发货单号或平台单号)',
|
||||
fn: rule.fn, params: {}, result: null, matchedKey: rule.keys?.[0],
|
||||
thoughts: [{ round: 0, action: 'rule', function: rule.fn, params: {}, reason: '参数不足-引导提示', functionResult: null }],
|
||||
};
|
||||
}
|
||||
params[rule.paramName || 'keyword'] = orders.join(',');
|
||||
}
|
||||
if (rule.issueType) params.issue_type = rule.issueType;
|
||||
if (rule.express) params.express = rule.express;
|
||||
if (rule.expressSubType) {
|
||||
const sub = resolveExpressSubType(text);
|
||||
if (sub) params.as_sub_type = sub;
|
||||
}
|
||||
if (rule.expressFromText) {
|
||||
const expressName = extractExpressName(text);
|
||||
if (!expressName) {
|
||||
return {
|
||||
handled: true,
|
||||
reply: rule.tip || '请指定目标快递(圆通/中通/申通/顺丰/韵达/极兔/邮政/EMS/京东)',
|
||||
fn: rule.fn, params: {}, result: null, matchedKey: rule.keys?.[0],
|
||||
thoughts: [{ round: 0, action: 'rule', function: rule.fn, params: {}, reason: '参数不足-引导提示', functionResult: null }],
|
||||
};
|
||||
}
|
||||
params.express = expressName;
|
||||
}
|
||||
if (rule.stockSearch) {
|
||||
const kw = stripKeyword(text, rule.keys || []);
|
||||
if (!kw) {
|
||||
return {
|
||||
handled: true,
|
||||
reply: rule.tip || '请提供商品名称、编码或条码',
|
||||
fn: rule.fn, params: {}, result: null, matchedKey: rule.keys?.[0],
|
||||
thoughts: [{ round: 0, action: 'rule', function: rule.fn, params: {}, reason: '参数不足-引导提示', functionResult: null }],
|
||||
};
|
||||
}
|
||||
params.keyword = kw;
|
||||
}
|
||||
|
||||
// 执行函数
|
||||
const result = await funcSvc.callFunction(rule.fn, params);
|
||||
const reply = this.buildReply(rule.fn, result);
|
||||
|
||||
const matchedKey = cand.key;
|
||||
ctx.logger.info(
|
||||
`[inbox rules] HIT fn=${rule.fn} key=${matchedKey} params=${JSON.stringify(params)} success=${!!result.success}`
|
||||
);
|
||||
|
||||
return {
|
||||
handled: true,
|
||||
fn: rule.fn,
|
||||
params,
|
||||
result,
|
||||
reply,
|
||||
matchedKey,
|
||||
thoughts: [{
|
||||
round: 0,
|
||||
action: 'rule',
|
||||
function: rule.fn,
|
||||
params,
|
||||
reason: `关键词规则命中: ${matchedKey}`,
|
||||
functionResult: result,
|
||||
}],
|
||||
};
|
||||
}
|
||||
|
||||
// 确认/感谢类短消息 → 静默(PHP nothing 规则)
|
||||
if (SILENT_RE.test(text)) {
|
||||
ctx.logger.info(`[inbox rules] 静默规则命中: ${text.slice(0, 50)}`);
|
||||
return { handled: true, silent: true };
|
||||
}
|
||||
|
||||
return { handled: false };
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据函数执行结果构建回复文本。
|
||||
* 优先 direct_reply 模板消息(支持 messages 数组多行回复),其次 data.message,商品搜索做格式化,失败返回错误文案。
|
||||
*
|
||||
* @param {string} fn 函数名。
|
||||
* @param {Object} result callFunction 返回结果。
|
||||
* @return {string|string[]|null} 回复文本(数组表示多条消息逐个回复),null 表示无需回复。
|
||||
*/
|
||||
buildReply(fn, result) {
|
||||
if (!result || typeof result !== 'object') return null;
|
||||
if (result.success === false) {
|
||||
return String(result.error || '操作失败,请联系客服处理');
|
||||
}
|
||||
const data = result.data || {};
|
||||
if (data.direct_reply === true && Array.isArray(data.messages) && data.messages.length > 0) {
|
||||
return data.messages.map(m => String(m));
|
||||
}
|
||||
if (data.direct_reply === true && typeof data.message === 'string' && data.message) {
|
||||
return data.message;
|
||||
}
|
||||
if (typeof data.message === 'string' && data.message) {
|
||||
return data.message;
|
||||
}
|
||||
if (fn === 'searchStock' || fn === 'searchWarehouseStock') {
|
||||
return this.formatStock(data);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 商品搜索结果的纯文本格式化。
|
||||
* @param {Object} data 函数返回的 data。
|
||||
* @return {string} 格式化文本。
|
||||
*/
|
||||
formatStock(data = {}) {
|
||||
const items = Array.isArray(data.items) ? data.items : [];
|
||||
if (items.length === 0) {
|
||||
return String(data.hint || '未找到匹配商品,请尝试其他关键词');
|
||||
}
|
||||
const lines = items.slice(0, 10).map((s, i) => {
|
||||
const code = s.item_code || '';
|
||||
const name = s.item_name || '';
|
||||
const available = s.stock_available != null ? s.stock_available : 0;
|
||||
const extra = s.prohibited_type ? `(违禁品:${s.prohibited_type})` : '';
|
||||
return `${i + 1}. ${code} ${name} 可用库存:${available}${extra}`;
|
||||
});
|
||||
return `找到 ${items.length} 个商品:\n${lines.join('\n')}`;
|
||||
}
|
||||
}
|
||||
|
||||
// ============================ 提取工具 ============================
|
||||
|
||||
/**
|
||||
* 提取运单号(参考 PHP Chat.php getPostNums,结合 Node 运单特征)。
|
||||
* 排除:售后工单号(AS开头)、手机号、日期时间戳、纯字母串。
|
||||
* @param {string} text 消息正文。
|
||||
* @return {string[]} 去重后的运单号列表。
|
||||
*/
|
||||
function extractWaybills(text) {
|
||||
const raw = text.match(/[A-Za-z0-9_-]{10,24}/g) || [];
|
||||
return [ ...new Set(raw) ].filter(t => {
|
||||
if (/^AS\d+$/i.test(t)) return false; // 售后工单号
|
||||
if (/^1\d{10}$/.test(t)) return false; // 手机号
|
||||
if (/^\+?86[- ]?1\d{10}$/.test(t)) return false; // 国际区号手机(含/不含 +)
|
||||
if (/^\d{3,4}-\d{7,8}$/.test(t)) return false; // 座机带横线(020-12345678)
|
||||
if (/^0\d{9,11}$/.test(t)) return false; // 0开头座机/服务号(02012345678)
|
||||
if (/^400\d{7}$/.test(t)) return false; // 400 服务电话
|
||||
if (/^\d{4}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{4,}$/.test(t)) return false; // 日期时间戳
|
||||
if (/^[A-Za-z_-]+$/.test(t)) return false; // 纯字母
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取订单号(发货单/平台单)。
|
||||
* 优先 SYS/SO/DD 前缀及字母数字混合号,兜底 12~20 位纯数字。
|
||||
* 前缀需独立成词(前不能紧邻字母数字),避免从长字符串中截取尾部
|
||||
* (如 NOTEXISTPOSTNUM20260814 误截成 TPOSTNUM20260814)。
|
||||
* @param {string} text 消息正文。
|
||||
* @return {string[]} 去重后的订单号列表。
|
||||
*/
|
||||
function extractOrders(text) {
|
||||
const raw = text.match(/(?<![A-Za-z0-9])SYS\d{4,}|(?<![A-Za-z0-9])SO[A-Za-z0-9-]{4,}|(?<![A-Za-z0-9])DD[A-Za-z0-9-]{4,}|(?<![A-Za-z0-9])[A-Z]{2,8}-?\d{4,}/g) || [];
|
||||
const list = [ ...new Set(raw) ];
|
||||
if (list.length > 0) return list;
|
||||
const nums = text.match(/(?<!\d)\d{12,20}(?!\d)/g) || [];
|
||||
return [ ...new Set(nums) ].filter(t => !/^1\d{10}$/.test(t));
|
||||
}
|
||||
|
||||
/** 改快递规则支持的目标快递名(长名在前,优先提取完整名称,避免“中通快运”被短名截断) */
|
||||
const EXPRESS_NAMES = [ '中通快运', '中通快递', '极兔速递', '京东快递', '圆通快递', '申通快递', '顺丰速运', '韵达快递', '邮政小包', '圆通', '中通', '申通', '顺丰', '韵达', '极兔', '邮政', 'EMS', '京东', '德邦' ];
|
||||
|
||||
/**
|
||||
* 快递反馈 → 售后子类型映射(长词优先,避免“核实签收”被“签收”截断)。
|
||||
* 未命中保持默认 logistics_issue(物流异常)。
|
||||
*/
|
||||
const EXPRESS_SUB_TYPE_RULES = [
|
||||
{ keys: [ '核实签收', '签收核实', '已签收', '签收' ], sub: 'verify_delivery' },
|
||||
{ keys: [ '破损', '坏了', '破损件' ], sub: 'damage' },
|
||||
{ keys: [ '少发', '漏发', '发少' ], sub: 'missing_item' },
|
||||
{ keys: [ '改地址', '地址更改', '改址' ], sub: 'change_address' },
|
||||
{ keys: [ '换快递', '改快递' ], sub: 'change_carrier' },
|
||||
{ keys: [ '催件', '催派', '催促' ], sub: 'urge' },
|
||||
{ keys: [ '发货延迟', '延迟发货', '催发货' ], sub: 'delivery_delay' },
|
||||
{ keys: [ '拒收' ], sub: 'rejected' },
|
||||
];
|
||||
|
||||
/**
|
||||
* 从快递反馈文本推断售后子类型(长词优先)。
|
||||
* @param {string} text 消息正文。
|
||||
* @return {string|null} 售后子类型,未命中返回 null(由函数默认 logistics_issue)。
|
||||
*/
|
||||
function resolveExpressSubType(text) {
|
||||
let best = null;
|
||||
let bestLen = 0;
|
||||
for (const item of EXPRESS_SUB_TYPE_RULES) {
|
||||
for (const k of item.keys) {
|
||||
if (text.includes(k) && k.length > bestLen) {
|
||||
best = item.sub;
|
||||
bestLen = k.length;
|
||||
}
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从消息文本中解析目标快递名称(通用“改快递/换快递”规则用)。
|
||||
* @param {string} text 消息正文。
|
||||
* @return {string|null} 快递名称,未命中返回 null。
|
||||
*/
|
||||
function extractExpressName(text) {
|
||||
const lower = String(text || '').toLowerCase();
|
||||
return EXPRESS_NAMES.find(name => lower.includes(name.toLowerCase())) || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 去除命中的关键词,取剩余文本作为查询词(查库存场景)。
|
||||
* @param {string} text 消息正文。
|
||||
* @param {string[]} keys 命中关键词列表。
|
||||
* @return {string} 剩余文本。
|
||||
*/
|
||||
function stripKeyword(text, keys) {
|
||||
let t = String(text || '');
|
||||
for (const k of keys) {
|
||||
t = t.split(k).join(' ');
|
||||
}
|
||||
return t.replace(/\s+/g, ' ').trim();
|
||||
}
|
||||
|
||||
/** 确认/感谢类短消息 → 静默 */
|
||||
const SILENT_RE = /^(好|好的|好的呢|好嘞|嗯|嗯嗯|哦|哦哦|ok|okay|收到|谢谢|感谢|谢谢啦|谢了|好了|可以|行|行了|对啊|是的|对|知道了|明白|了解了|1)\s*[!!。.,~~👍🙏❤️]*$/i;
|
||||
|
||||
// ============================ 规则表(顺序即优先级) ============================
|
||||
|
||||
/**
|
||||
* 拦截类规则的防误判守卫:询问物流进度/查快递等不是拦截请求,
|
||||
* 取消/撤销类语义属于 cancelIntercept(双保险,长词优先已能保证)
|
||||
* @param {string} t 消息正文
|
||||
* @return {boolean} 是否允许命中拦截规则
|
||||
*/
|
||||
const INTERCEPT_GUARD = t => !/(到哪|在哪|哪里|快递到|物流|轨迹|查单|查快递|查物流|到哪里|取消拦截|撤销拦截|解除拦截|不拦截|不用拦截)/.test(t);
|
||||
|
||||
/** 货主群(store) */
|
||||
const STORE_RULES = [
|
||||
{ keys: [ '取消拦截', '撤销拦截', '解除拦截', '不拦截', '不用拦截' ], fn: 'cancelIntercept', waybill: true,
|
||||
tip: '如需取消拦截,发送:取消拦截+运单号(多个单号用逗号或空格分隔)\n例:取消拦截 SF123,SF456' },
|
||||
{ keys: [ '拦截', '追回', '召回' ], fn: 'interceptWaybill', waybill: true, guard: INTERCEPT_GUARD,
|
||||
tip: '如需拦截运单,发送:拦截+运单号(多个单号用逗号或空格分隔)\n例:拦截 SF123,SF456' },
|
||||
{ keys: [ '揽收', '上门取件', '退货取件', '让快递来拿' ], fn: 'requestPickup', waybill: true,
|
||||
tip: '如需安排上门揽收,发送:揽收+运单号\n例:揽收 SF123' },
|
||||
{ keys: [ '少发', '发少' ], fn: 'handleStoreFeedback', issueType: 'missing', waybill: true,
|
||||
tip: '如需反馈少发,发送:少发+运单号\n例:少发 SF123' },
|
||||
{ keys: [ '重量', '查重', '核实重量', '核重', '称重' ], fn: 'queryWeight', waybill: true,
|
||||
tip: '如需查询库内称重,发送:称重+运单号\n例:称重 SF123' },
|
||||
{ keys: [ '错发', '发错' ], fn: 'handleStoreFeedback', issueType: 'wrong', waybill: true,
|
||||
tip: '如需反馈错发,发送:错发+运单号\n例:错发 SF123' },
|
||||
{ keys: [ '破损', '坏了' ], fn: 'handleStoreFeedback', issueType: 'damaged', waybill: true,
|
||||
tip: '如需反馈破损,发送:破损+运单号\n例:破损 SF123' },
|
||||
{ keys: [ '多发', '发多' ], fn: 'handleStoreFeedback', issueType: 'multiple', waybill: true,
|
||||
tip: '如需反馈多发,发送:多发+运单号\n例:多发 SF123' },
|
||||
{ keys: [ '改地址', '改电话', '改联系人', '改收件人', '地址更改', '改手机' ], fn: 'changeAddr', issueType: 'addr', waybill: true,
|
||||
tip: '如需修改地址,发送:改地址+运单号\n例:改地址 SF123' },
|
||||
// 注意顺序:催退回/催促退回 必须在 催件/催促 之前("催促退回"含"催促")
|
||||
{ keys: [ '催退回', '催促退回' ], fn: 'changeAddr', issueType: 'return', waybill: true,
|
||||
tip: '如需催退回,发送:催退回+运单号\n例:催退回 SF123' },
|
||||
{ keys: [ '催件', '催派', '催促', '尽快安排派送', '未中转', '物流停滞' ], fn: 'changeAddr', issueType: 'urge', waybill: true,
|
||||
tip: '如需催件,发送:催件+运单号\n例:催件 SF123' },
|
||||
{ keys: [ '查退回', '是否已退回' ], fn: 'queryReturn', waybill: true, paramName: 'waybill_code',
|
||||
tip: '如需查退回,发送:查退回+运单号\n例:查退回 SF123' },
|
||||
{ keys: [ '退回', '拒收' ], fn: 'queryReturn', waybill: true, paramName: 'waybill_code',
|
||||
tip: '如需查退回,发送:查退回+运单号\n例:查退回 SF123' },
|
||||
{ keys: [ '核实签收', '未收到', '是否发出', '是否已经发货', '没有找到快递' ], fn: 'weishoudao', waybill: true,
|
||||
tip: '如需核实签收,发送:核实签收+运单号\n例:核实签收 SF123' },
|
||||
{ keys: [ '出单', '打单', '打印单', '催发货', '分配快递号' ], fn: 'createPostnum', order: true,
|
||||
tip: '如需出单/分配快递号,发送:出单+订单号\n例:出单 SYS2026010100001' },
|
||||
// 通用格式:改快递+订单号+快递名(放在固定“改圆通”等规则之前,两者关键词互不冲突)
|
||||
{ keys: [ '改快递', '换快递' ], fn: 'changeExpress', expressFromText: true, order: true,
|
||||
tip: '如需改快递,发送:改快递+订单号+快递名称\n例:改快递 SYS2026010100001 圆通' },
|
||||
{ keys: [ '改圆通' ], fn: 'changeExpress', express: '圆通', order: true,
|
||||
tip: '如需改快递,发送:改圆通+订单号\n例:改圆通 SYS2026010100001' },
|
||||
{ keys: [ '改中通' ], fn: 'changeExpress', express: '中通', order: true,
|
||||
tip: '如需改快递,发送:改中通+订单号' },
|
||||
{ keys: [ '改申通' ], fn: 'changeExpress', express: '申通', order: true,
|
||||
tip: '如需改快递,发送:改申通+订单号' },
|
||||
{ keys: [ '改极兔' ], fn: 'changeExpress', express: '极兔', order: true,
|
||||
tip: '如需改快递,发送:改极兔+订单号' },
|
||||
{ keys: [ '改韵达' ], fn: 'changeExpress', express: '韵达', order: true,
|
||||
tip: '如需改快递,发送:改韵达+订单号' },
|
||||
{ keys: [ '改顺丰' ], fn: 'changeExpress', express: '顺丰', order: true,
|
||||
tip: '如需改快递,发送:改顺丰+订单号' },
|
||||
{ keys: [ '改邮政' ], fn: 'changeExpress', express: '邮政', order: true,
|
||||
tip: '如需改快递,发送:改邮政+订单号' },
|
||||
{ keys: [ '改EMS', '改ems' ], fn: 'changeExpress', express: 'EMS', order: true,
|
||||
tip: '如需改快递,发送:改EMS+订单号' },
|
||||
{ keys: [ '改京东' ], fn: 'changeExpress', express: '京东', order: true,
|
||||
tip: '如需改快递,发送:改京东+订单号' },
|
||||
{ keys: [ '仓库地址', '退货地址', '退件地址', '寄回地址', '收货地址' ], fn: 'queryWarehouseAddress' },
|
||||
{ keys: [ '打包视频', '装箱视频' ], fn: 'queryPackVideo', waybill: true,
|
||||
tip: '如需查询打包视频,发送:打包视频+运单号\n例:打包视频 SF123' },
|
||||
{ keys: [ '查库存' ], fn: 'searchStock', stockSearch: true,
|
||||
tip: '如需查库存,发送:查库存+商品名称/编码/条码' },
|
||||
{ keys: [ 'help', '指令', '帮助' ], fn: '__help__' },
|
||||
];
|
||||
|
||||
/** 仓库内部群(warehouse,客服子类型可用的函数较多,不可用函数自动跳过) */
|
||||
const WAREHOUSE_RULES = [
|
||||
{ keys: [ '取消拦截', '撤销拦截', '解除拦截', '不拦截', '不用拦截' ], fn: 'cancelIntercept', waybill: true,
|
||||
tip: '如需取消拦截,发送:取消拦截+运单号' },
|
||||
{ keys: [ '拦截', '追回', '召回' ], fn: 'interceptWaybill', waybill: true, guard: INTERCEPT_GUARD,
|
||||
tip: '如需拦截运单,发送:拦截+运单号' },
|
||||
{ keys: [ '揽收', '上门取件' ], fn: 'requestPickup', waybill: true,
|
||||
tip: '如需安排上门揽收,发送:揽收+运单号' },
|
||||
{ keys: [ '查退回', '是否已退回' ], fn: 'queryReturn', waybill: true, paramName: 'waybill_code',
|
||||
tip: '如需查退回,发送:查退回+运单号' },
|
||||
{ keys: [ '重量', '查重', '核实重量', '核重', '称重' ], fn: 'queryWeight', waybill: true,
|
||||
tip: '如需查询库内称重,发送:称重+运单号' },
|
||||
{ keys: [ '打包视频', '装箱视频' ], fn: 'queryPackVideo', waybill: true,
|
||||
tip: '如需查询打包视频,发送:打包视频+运单号' },
|
||||
{ keys: [ '仓库地址', '退货地址', '退件地址', '寄回地址', '收货地址' ], fn: 'queryWarehouseAddress' },
|
||||
{ keys: [ '查库存' ], fn: 'searchWarehouseStock', stockSearch: true,
|
||||
tip: '如需查库存,发送:查库存+商品名称/编码/条码' },
|
||||
{ keys: [ 'help', '指令', '帮助' ], fn: '__help__' },
|
||||
];
|
||||
|
||||
/** 快递售后群(express)规则表:消息含运单号即按反馈处理(按关键词推断子类型),无运单号静默 */
|
||||
const EXPRESS_RULES = [
|
||||
{ any: true, fn: 'handleExpressFeedback', waybill: true, noWaybillSilent: true, expressSubType: true },
|
||||
];
|
||||
|
||||
/** 规则表:按群类型选择 */
|
||||
const RULE_TABLES = {
|
||||
store: STORE_RULES,
|
||||
warehouse: WAREHOUSE_RULES,
|
||||
express: EXPRESS_RULES,
|
||||
};
|
||||
|
||||
// ============================ 帮助文本 ============================
|
||||
|
||||
const HELP_TEXTS = {
|
||||
store: '当前群支持以下指令(发送:指令+单号,多个单号用逗号或空格分隔):\n'
|
||||
+ '· 拦截+运单号 / 取消拦截+运单号\n'
|
||||
+ '· 揽收+运单号\n'
|
||||
+ '· 催件+运单号 / 催退回+运单号\n'
|
||||
+ '· 改地址+运单号\n'
|
||||
+ '· 称重+运单号 / 查退回+运单号 / 核实签收+运单号\n'
|
||||
+ '· 打包视频+运单号\n'
|
||||
+ '· 少发/错发/破损/多发+运单号\n'
|
||||
+ '· 出单+订单号\n'
|
||||
+ '· 改圆通/改中通/改申通/改顺丰/改韵达/改极兔/改邮政/改EMS/改京东+订单号\n'
|
||||
+ '· 仓库地址\n'
|
||||
+ '· 查库存+商品名称或条码',
|
||||
warehouse: '当前群支持以下指令:\n'
|
||||
+ '· 拦截+运单号 / 取消拦截+运单号\n'
|
||||
+ '· 揽收+运单号\n'
|
||||
+ '· 查退回+运单号 / 称重+运单号\n'
|
||||
+ '· 打包视频+运单号\n'
|
||||
+ '· 仓库地址\n'
|
||||
+ '· 查库存+商品名称或条码',
|
||||
express: '发送运单号+处理情况,系统将自动记录并回信货主群。',
|
||||
};
|
||||
|
||||
module.exports = InboxRulesService;
|
||||
51
app/service/inbox/tools.js
Normal file
51
app/service/inbox/tools.js
Normal file
@ -0,0 +1,51 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
|
||||
/**
|
||||
* 站内信工具方法集合(与业务函数无关的辅助逻辑)。
|
||||
* 从 inbox/functions.js 拆出,保持 functions.js 只负责业务函数注册与执行。
|
||||
*/
|
||||
class InboxToolsService extends Service {
|
||||
|
||||
/**
|
||||
* 获取仓库的录制电脑 ID(带缓存)。
|
||||
* @param {number} warehouseId 仓库ID
|
||||
* @return {Promise<number|null>} 录制电脑ID,找不到返回 null
|
||||
*/
|
||||
async getRecordingComputerId(warehouseId) {
|
||||
const cacheKey = `_recordingComputer_${warehouseId}`;
|
||||
if (this[cacheKey] !== undefined) {
|
||||
return this[cacheKey];
|
||||
}
|
||||
const row = await this.ctx.model.PrintComputer.findOne({
|
||||
where: { warehouse_id: warehouseId, is_recording: true, deleted_at: null },
|
||||
attributes: [ 'id' ],
|
||||
raw: true,
|
||||
});
|
||||
this[cacheKey] = row ? row.id : null;
|
||||
return this[cacheKey];
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建视频完整 URL。
|
||||
* 格式:http://w{warehouseId}-c{recordingComputerId}.o.gztbyc.com{videoPath}
|
||||
* @param {number} warehouseId 仓库ID
|
||||
* @param {number|null} recordingComputerId 录制电脑ID
|
||||
* @param {string} videoPath 视频路径
|
||||
* @return {string} 完整 URL
|
||||
*/
|
||||
buildVideoUrl(warehouseId, recordingComputerId, videoPath) {
|
||||
const path = String(videoPath || '').trim();
|
||||
if (!path || !recordingComputerId) {
|
||||
return path;
|
||||
}
|
||||
// 已是完整 URL 时原样返回,避免重复拼接
|
||||
if (/^https?:\/\//i.test(path)) {
|
||||
return path;
|
||||
}
|
||||
return `http://w${warehouseId}-c${recordingComputerId}.o.gztbyc.com${path}`;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = InboxToolsService;
|
||||
@ -32,6 +32,8 @@ class OrderIndexService extends OrderBaseService {
|
||||
* @param {string} [data.module_name] 订单模块名(下划线写法)。
|
||||
* @param {string} [data.export_mode] 导出模式:waybill(默认,按运单展开)或 item(按商品明细展开)。
|
||||
* @param {string} [data.exportMode] 导出模式(驼峰写法)。
|
||||
* @param {Array<string>} [data.export_columns] 导出表头字段白名单(中文表头数组),不传或空数组输出全部列;非法表头会报错。
|
||||
* @param {Array<string>} [data.exportColumns] 导出表头字段白名单(驼峰写法)。
|
||||
* @param {Object} [data.where] 查询条件。
|
||||
* @param {Object} [data.sort] 排序参数。
|
||||
* @return {Promise<Object>} 统一成功包装响应。
|
||||
@ -45,6 +47,8 @@ class OrderIndexService extends OrderBaseService {
|
||||
module_name: moduleNameSnake,
|
||||
export_mode: exportModeSnake,
|
||||
exportMode: exportModeCamel,
|
||||
export_columns: exportColumnsSnake,
|
||||
exportColumns: exportColumnsCamel,
|
||||
where,
|
||||
sort,
|
||||
} = requestData;
|
||||
@ -78,10 +82,14 @@ class OrderIndexService extends OrderBaseService {
|
||||
});
|
||||
|
||||
const exportMode = exportModeSnake || exportModeCamel || '';
|
||||
const exportColumns = Array.isArray(exportColumnsSnake)
|
||||
? exportColumnsSnake
|
||||
: (Array.isArray(exportColumnsCamel) ? exportColumnsCamel : []);
|
||||
const result = await this.service.systems.orderExport.exportOrders({
|
||||
tableType,
|
||||
moduleName: module,
|
||||
export_mode: exportMode,
|
||||
export_columns: exportColumns,
|
||||
where: this.isPlainObject(where) ? { ...where } : {},
|
||||
sort: this.isPlainObject(sort) ? { ...sort } : {},
|
||||
onProgress: async progress => {
|
||||
|
||||
@ -2388,6 +2388,10 @@ class PendingOrderService extends OrderBaseService {
|
||||
/**
|
||||
* 将待处理订单取消,并关闭到已取消状态。
|
||||
* 仅允许取消当前仓库内处于待审核、待处理、待处理异常语义的订单。
|
||||
*
|
||||
* 取消、波次清理、储位释放与创建锁释放在同一事务内完成:
|
||||
* 任一环节失败整体回滚,避免"已取消但库存锁定未释放"的中间态。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {number[]} data.ids 订单ID 数组。
|
||||
* @return {Promise<Object>} 更新后的订单信息。
|
||||
@ -2403,91 +2407,106 @@ class PendingOrderService extends OrderBaseService {
|
||||
|
||||
const model = await this.getOrderModel('order', warehouseId);
|
||||
const where = this.buildOrderWhere(orderIds, warehouseId);
|
||||
const existingOrders = await model.findAll({
|
||||
where,
|
||||
raw: true,
|
||||
});
|
||||
const transaction = await this.ctx.model.transaction();
|
||||
let normalizedOrders = [];
|
||||
let firstOrder = null;
|
||||
let affectedRows = 0;
|
||||
|
||||
if (!Array.isArray(existingOrders) || existingOrders.length === 0) {
|
||||
return this.success('取消成功', {
|
||||
updated_count: 0,
|
||||
ids: [],
|
||||
try {
|
||||
// 锁定订单行后读取最新状态,与储位分配事务串行化,避免读到过期快照
|
||||
const existingOrders = await model.findAll({
|
||||
where,
|
||||
transaction,
|
||||
lock: transaction.LOCK.UPDATE,
|
||||
raw: true,
|
||||
});
|
||||
}
|
||||
|
||||
if (existingOrders.length !== orderIds.length) {
|
||||
throw new Error('订单不存在或不属于当前仓库');
|
||||
}
|
||||
if (!Array.isArray(existingOrders) || existingOrders.length === 0) {
|
||||
await transaction.rollback();
|
||||
return this.success('取消成功', {
|
||||
updated_count: 0,
|
||||
ids: [],
|
||||
});
|
||||
}
|
||||
|
||||
const nonCancelableOrder = existingOrders.find(order => !this.isCancelablePendingOrder(order));
|
||||
if (nonCancelableOrder) {
|
||||
throw new Error('订单当前状态不允许取消');
|
||||
}
|
||||
if (existingOrders.length !== orderIds.length) {
|
||||
throw new Error('订单不存在或不属于当前仓库');
|
||||
}
|
||||
|
||||
// 已同步订单不允许取消,转为拦截处理
|
||||
const syncedOrders = existingOrders.filter(
|
||||
order => String(order.sync_status || '').trim() === 'fin'
|
||||
);
|
||||
if (syncedOrders.length > 0) {
|
||||
const syncedOrderIds = syncedOrders.map(order => Number(order.id)).filter(
|
||||
id => Number.isInteger(id) && id > 0
|
||||
const nonCancelableOrder = existingOrders.find(order => !this.isCancelablePendingOrder(order));
|
||||
if (nonCancelableOrder) {
|
||||
throw new Error('订单当前状态不允许取消');
|
||||
}
|
||||
|
||||
// 已同步订单不允许取消,转为拦截处理
|
||||
const syncedOrders = existingOrders.filter(
|
||||
order => String(order.sync_status || '').trim() === 'fin'
|
||||
);
|
||||
if (syncedOrderIds.length > 0) {
|
||||
const syncNow = new Date();
|
||||
await model.update(
|
||||
{
|
||||
intercept_status: 'requested',
|
||||
updated_at: syncNow,
|
||||
},
|
||||
{
|
||||
where: {
|
||||
id: syncedOrderIds,
|
||||
},
|
||||
}
|
||||
if (syncedOrders.length > 0) {
|
||||
const syncedOrderIds = syncedOrders.map(order => Number(order.id)).filter(
|
||||
id => Number.isInteger(id) && id > 0
|
||||
);
|
||||
// 同步更新运单表拦截标记
|
||||
try {
|
||||
const { Op: cancelOp } = this.app.Sequelize;
|
||||
await this.ctx.model.OrderExpress.update(
|
||||
{ is_intercept: 'Y' },
|
||||
{ where: { order_id: { [cancelOp.in]: syncedOrderIds }, warehouse_id: warehouseId } }
|
||||
if (syncedOrderIds.length > 0) {
|
||||
const syncNow = new Date();
|
||||
await model.update(
|
||||
{
|
||||
intercept_status: 'requested',
|
||||
updated_at: syncNow,
|
||||
},
|
||||
{
|
||||
where: {
|
||||
id: syncedOrderIds,
|
||||
},
|
||||
transaction,
|
||||
}
|
||||
);
|
||||
} catch (expressErr) {
|
||||
this.ctx.logger.warn(
|
||||
`[PendingOrderService.cancelOrder] 更新运单拦截标记失败, count=${syncedOrderIds.length}, error=${expressErr.message}`
|
||||
// 同步更新运单表拦截标记
|
||||
try {
|
||||
const { Op: cancelOp } = this.app.Sequelize;
|
||||
await this.ctx.model.OrderExpress.update(
|
||||
{ is_intercept: 'Y' },
|
||||
{ where: { order_id: { [cancelOp.in]: syncedOrderIds }, warehouse_id: warehouseId }, transaction }
|
||||
);
|
||||
} catch (expressErr) {
|
||||
this.ctx.logger.warn(
|
||||
`[PendingOrderService.cancelOrder] 更新运单拦截标记失败, count=${syncedOrderIds.length}, error=${expressErr.message}`
|
||||
);
|
||||
}
|
||||
this.ctx.logger.info(
|
||||
`[PendingOrderService.cancelOrder] 订单已同步,不可取消,已转为拦截处理,订单ID: ${syncedOrderIds.join(',')}`
|
||||
);
|
||||
}
|
||||
this.ctx.logger.info(
|
||||
`[PendingOrderService.cancelOrder] 订单已同步,不可取消,已转为拦截处理,订单ID: ${syncedOrderIds.join(',')}`
|
||||
);
|
||||
|
||||
// 拦截标记已写入,提交后抛出业务错误(调用方按"已转拦截"处理)
|
||||
await transaction.commit();
|
||||
|
||||
const syncedCodes = syncedOrders
|
||||
.map(order => String(order.delivery_order_code || order.pre_delivery_order_code || order.id || '').trim())
|
||||
.filter(Boolean)
|
||||
.join(', ');
|
||||
throw new Error(`订单已同步,不可取消,已转为拦截处理:${syncedCodes}`);
|
||||
}
|
||||
const syncedCodes = syncedOrders
|
||||
.map(order => String(order.delivery_order_code || order.pre_delivery_order_code || order.id || '').trim())
|
||||
.filter(Boolean)
|
||||
.join(', ');
|
||||
throw new Error(`订单已同步,不可取消,已转为拦截处理:${syncedCodes}`);
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const updateValues = {
|
||||
status: PENDING_CANCEL_STATUS,
|
||||
step: PENDING_CANCEL_STEP,
|
||||
outbound_status: PENDING_OUTBOUND_STATUS,
|
||||
updated_at: now,
|
||||
};
|
||||
const now = new Date();
|
||||
const updateValues = {
|
||||
status: PENDING_CANCEL_STATUS,
|
||||
step: PENDING_CANCEL_STEP,
|
||||
outbound_status: PENDING_OUTBOUND_STATUS,
|
||||
updated_at: now,
|
||||
};
|
||||
|
||||
const updateResult = await model.update(updateValues, {
|
||||
where,
|
||||
});
|
||||
const updateResult = await model.update(updateValues, {
|
||||
where,
|
||||
transaction,
|
||||
});
|
||||
|
||||
const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0);
|
||||
if (affectedRows <= 0) {
|
||||
throw new Error('订单不存在或不属于当前仓库');
|
||||
}
|
||||
affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0);
|
||||
if (affectedRows <= 0) {
|
||||
throw new Error('订单不存在或不属于当前仓库');
|
||||
}
|
||||
|
||||
const ordersWithWave = existingOrders.filter(order => Number(order.wave_id) > 0);
|
||||
if (ordersWithWave.length > 0) {
|
||||
try {
|
||||
const ordersWithWave = existingOrders.filter(order => Number(order.wave_id) > 0);
|
||||
if (ordersWithWave.length > 0) {
|
||||
const { Op } = this.app.Sequelize;
|
||||
const WaveBatch = this.ctx.model.WaveBatch;
|
||||
|
||||
@ -2509,13 +2528,14 @@ class PendingOrderService extends OrderBaseService {
|
||||
},
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
transaction,
|
||||
}
|
||||
);
|
||||
|
||||
await this.ctx.service.systemMethods.order.wave.deleteOrderWaveIndexByOrderIds({
|
||||
warehouseId,
|
||||
orderIds: waveOrderIds,
|
||||
transaction: undefined,
|
||||
transaction,
|
||||
});
|
||||
|
||||
// 重建受影响波次的订单索引(wave_index 重新排序)
|
||||
@ -2527,6 +2547,7 @@ class PendingOrderService extends OrderBaseService {
|
||||
warehouseId,
|
||||
waveIds: affectedWaveIds,
|
||||
orderModel: model,
|
||||
transaction,
|
||||
});
|
||||
}
|
||||
}
|
||||
@ -2551,6 +2572,7 @@ class PendingOrderService extends OrderBaseService {
|
||||
[Op.gt]: 0,
|
||||
},
|
||||
},
|
||||
transaction,
|
||||
});
|
||||
|
||||
const wave = await WaveBatch.findOne({
|
||||
@ -2560,6 +2582,7 @@ class PendingOrderService extends OrderBaseService {
|
||||
},
|
||||
attributes: [ 'wave_id', 'total_orders', 'wave_status' ],
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
|
||||
if (!wave) {
|
||||
@ -2580,6 +2603,7 @@ class PendingOrderService extends OrderBaseService {
|
||||
wave_id: waveId,
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
transaction,
|
||||
}
|
||||
);
|
||||
} else {
|
||||
@ -2592,61 +2616,66 @@ class PendingOrderService extends OrderBaseService {
|
||||
wave_id: waveId,
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
transaction,
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (waveErr) {
|
||||
this.ctx.logger.warn('[PendingOrderService.cancelOrder] 清理波次关联失败,不影响订单取消', waveErr);
|
||||
}
|
||||
}
|
||||
|
||||
// 释放储位分配和库存锁定
|
||||
try {
|
||||
// 释放储位分配和库存锁定(复用同一事务,取消与释放原子生效)
|
||||
await this.service.systems.orderStorageAllocation.cancelAllocateStorage({
|
||||
order_ids: orderIds,
|
||||
transaction,
|
||||
});
|
||||
} catch (allocErr) {
|
||||
this.ctx.logger.warn('[PendingOrderService.cancelOrder] 释放储位分配失败,不影响订单取消', allocErr);
|
||||
}
|
||||
|
||||
// 释放创建锁(lockItemStorages 加的锁,不含 picking 锁)
|
||||
try {
|
||||
// 释放创建锁(lockItemStorages 加的锁,不含 picking 锁)
|
||||
await this.releaseCreationLockForCancel({
|
||||
orderIds,
|
||||
warehouseId,
|
||||
transaction,
|
||||
});
|
||||
} catch (releaseErr) {
|
||||
this.ctx.logger.warn('[PendingOrderService.cancelOrder] 释放创建锁失败,不影响订单取消', releaseErr);
|
||||
|
||||
const updatedOrders = await model.findAll({
|
||||
where,
|
||||
transaction,
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (!Array.isArray(updatedOrders) || updatedOrders.length === 0) {
|
||||
throw new Error('订单不存在或不属于当前仓库');
|
||||
}
|
||||
|
||||
const orderMap = new Map(updatedOrders.map(order => [ Number(order.id), order ]));
|
||||
normalizedOrders = orderIds
|
||||
.map(orderId => orderMap.get(orderId))
|
||||
.filter(Boolean)
|
||||
.map(order => ({
|
||||
id: order.id,
|
||||
status: order.status,
|
||||
step: Number(order.step ?? PENDING_CANCEL_STEP),
|
||||
updated_at: order.updated_at,
|
||||
}));
|
||||
|
||||
if (normalizedOrders.length === 0) {
|
||||
throw new Error('订单不存在或不属于当前仓库');
|
||||
}
|
||||
|
||||
firstOrder = normalizedOrders[0];
|
||||
|
||||
await transaction.commit();
|
||||
} catch (error) {
|
||||
if (!transaction.finished) {
|
||||
try {
|
||||
await transaction.rollback();
|
||||
} catch (rollbackError) {
|
||||
this.ctx.logger.error('[PendingOrderService.cancelOrder] 事务回滚失败', rollbackError);
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
const updatedOrders = await model.findAll({
|
||||
where,
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (!Array.isArray(updatedOrders) || updatedOrders.length === 0) {
|
||||
throw new Error('订单不存在或不属于当前仓库');
|
||||
}
|
||||
|
||||
const orderMap = new Map(updatedOrders.map(order => [ Number(order.id), order ]));
|
||||
const normalizedOrders = orderIds
|
||||
.map(orderId => orderMap.get(orderId))
|
||||
.filter(Boolean)
|
||||
.map(order => ({
|
||||
id: order.id,
|
||||
status: order.status,
|
||||
step: Number(order.step ?? PENDING_CANCEL_STEP),
|
||||
updated_at: order.updated_at,
|
||||
}));
|
||||
|
||||
if (normalizedOrders.length === 0) {
|
||||
throw new Error('订单不存在或不属于当前仓库');
|
||||
}
|
||||
|
||||
const firstOrder = normalizedOrders[0];
|
||||
|
||||
// 写入取消操作日志(不影响主流程)
|
||||
try {
|
||||
const operator = this.getOrderLogOperator();
|
||||
@ -6409,9 +6438,10 @@ ${numbered}`;
|
||||
* @param {Object} options - 释放参数。
|
||||
* @param {number[]} options.orderIds - 订单ID 数组。
|
||||
* @param {number} options.warehouseId - 仓库ID。
|
||||
* @param {Object} [options.transaction] - 可选外部事务;传入时复用,由调用方负责提交与回滚。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async releaseCreationLockForCancel({ orderIds, warehouseId } = {}) {
|
||||
async releaseCreationLockForCancel({ orderIds, warehouseId, transaction: externalTransaction } = {}) {
|
||||
const { ctx, app } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
|
||||
@ -6431,7 +6461,7 @@ ${numbered}`;
|
||||
return;
|
||||
}
|
||||
|
||||
const transaction = await ctx.model.transaction();
|
||||
const transaction = externalTransaction || await ctx.model.transaction();
|
||||
|
||||
try {
|
||||
// 直接从 order_items 读取 plan_qty,按 stock_id 汇总
|
||||
@ -6446,7 +6476,9 @@ ${numbered}`;
|
||||
});
|
||||
|
||||
if (!Array.isArray(orderItems) || orderItems.length === 0) {
|
||||
await transaction.commit();
|
||||
if (!externalTransaction) {
|
||||
await transaction.commit();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@ -6461,7 +6493,9 @@ ${numbered}`;
|
||||
}
|
||||
|
||||
if (stockReleaseMap.size === 0) {
|
||||
await transaction.commit();
|
||||
if (!externalTransaction) {
|
||||
await transaction.commit();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@ -6482,12 +6516,16 @@ ${numbered}`;
|
||||
}
|
||||
}
|
||||
|
||||
await transaction.commit();
|
||||
if (!externalTransaction) {
|
||||
await transaction.commit();
|
||||
}
|
||||
} catch (error) {
|
||||
try {
|
||||
await transaction.rollback();
|
||||
} catch (rollbackError) {
|
||||
ctx.logger.error('[PendingOrderService.releaseCreationLockForCancel] 回滚失败', rollbackError);
|
||||
if (!externalTransaction) {
|
||||
try {
|
||||
await transaction.rollback();
|
||||
} catch (rollbackError) {
|
||||
ctx.logger.error('[PendingOrderService.releaseCreationLockForCancel] 回滚失败', rollbackError);
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
@ -27,6 +27,7 @@ class StorageManagementMethodService extends MainService {
|
||||
* @param {Object} [data={}] 请求参数。
|
||||
* @param {Object} [data.pagination] 分页参数。
|
||||
* @param {Object} [data.sort] 排序参数。
|
||||
* @param {number|number[]} [data.store_id] 货主筛选:单值或数组(正整数),也可通过 data.where.store_id 传入;不传时返回全部货主。
|
||||
* @return {Promise<Object>} 统一 success 包装的补货需求明细、汇总与分页信息。
|
||||
*/
|
||||
async replenishmentDemand(data = {}) {
|
||||
@ -34,9 +35,33 @@ class StorageManagementMethodService extends MainService {
|
||||
const requestData = this.isPlainObject(data) ? data : {};
|
||||
const pagination = requestData.pagination || {};
|
||||
const sort = requestData.sort || requestData.order || {};
|
||||
const where = this.isPlainObject(requestData.where) ? requestData.where : {};
|
||||
|
||||
// 货主筛选:支持顶层 store_id / store_ids,或 where.store_id(单值/数组)
|
||||
const rawStoreIdValue = requestData.store_id !== undefined && requestData.store_id !== null
|
||||
? requestData.store_id
|
||||
: (requestData.store_ids !== undefined && requestData.store_ids !== null
|
||||
? requestData.store_ids
|
||||
: where.store_id);
|
||||
|
||||
let storeIds = [];
|
||||
if (rawStoreIdValue !== undefined && rawStoreIdValue !== null && rawStoreIdValue !== '') {
|
||||
const rawList = Array.isArray(rawStoreIdValue) ? rawStoreIdValue : [ rawStoreIdValue ];
|
||||
const normalizedStoreIds = new Set();
|
||||
for (const item of rawList) {
|
||||
const value = Number(item);
|
||||
if (!Number.isFinite(value) || value <= 0 || !Number.isInteger(value)) {
|
||||
throw new Error(`store_id 必须是正整数,非法值: ${item}`);
|
||||
}
|
||||
normalizedStoreIds.add(value);
|
||||
}
|
||||
storeIds = Array.from(normalizedStoreIds);
|
||||
}
|
||||
|
||||
const result = await service.systems.storage.management.replenishmentDemand({
|
||||
pagination,
|
||||
sort,
|
||||
storeIds,
|
||||
});
|
||||
return this.success('补货需求计算完成', result);
|
||||
}
|
||||
|
||||
@ -1862,6 +1862,63 @@ class DeliveryOrderService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 将订单入队到自动分配快递消费队列(wms_waybill_allocate_queue)。
|
||||
*
|
||||
* 仅写入队列不取号,由定时任务 app/schedule/consume_waybill_allocate_queue.js
|
||||
* 按仓库+货主串行批量消费。入队幂等(uk_order_id_business_key),重复入队忽略。
|
||||
* 调用方需保证截单/未审核订单不会走到此方法。
|
||||
*
|
||||
* @param {Object} context 异步处理上下文。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async enqueueAutoWaybillAllocation(context) {
|
||||
const queueModel = this.ctx.model && this.ctx.model.WaybillAllocateQueue;
|
||||
if (!queueModel || typeof queueModel.findOrCreate !== 'function') {
|
||||
this.ctx.logger.warn('[DeliveryOrderService.enqueueAutoWaybillAllocation] 运单分配队列模型未初始化,跳过入队');
|
||||
return;
|
||||
}
|
||||
|
||||
const orderId = Number(context && context.orderId || 0);
|
||||
const warehouseId = Number(context && context.warehouseId || 0);
|
||||
const storeId = Number(context && context.storeId || 0);
|
||||
if (!Number.isInteger(orderId) || orderId <= 0 || !Number.isInteger(warehouseId) || warehouseId <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await queueModel.findOrCreate({
|
||||
where: {
|
||||
order_id: orderId,
|
||||
business_key: 1,
|
||||
},
|
||||
defaults: {
|
||||
order_id: orderId,
|
||||
business_key: 1,
|
||||
warehouse_id: warehouseId,
|
||||
store_id: storeId > 0 ? storeId : 0,
|
||||
status: 'pending',
|
||||
retry_count: 0,
|
||||
next_retry_at: null,
|
||||
error_message: null,
|
||||
created_at: new Date(),
|
||||
updated_at: new Date(),
|
||||
},
|
||||
});
|
||||
this.ctx.logger.info('[DeliveryOrderService.enqueueAutoWaybillAllocation] 订单已入队等待批量分配快递', {
|
||||
orderId,
|
||||
warehouseId,
|
||||
storeId,
|
||||
});
|
||||
} catch (error) {
|
||||
// 唯一键冲突(重复入队)或 DB 异常仅记录,不阻断订单创建后续异步流程
|
||||
this.ctx.logger.warn('[DeliveryOrderService.enqueueAutoWaybillAllocation] 入队失败: %s', error.message, {
|
||||
orderId,
|
||||
error: error.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建储位分配显式请求体。
|
||||
*
|
||||
@ -2540,13 +2597,9 @@ class DeliveryOrderService extends Service {
|
||||
|
||||
if (isAutoAllocateExpressEnabled) {
|
||||
await this.runAsyncProcessStep('allocateExpress', async () => {
|
||||
const request = this.buildExpressAllocateRequest(context);
|
||||
await this.withPatchedCtxUser({
|
||||
store_id: context.warehouseId,
|
||||
warehouse_id: context.warehouseId,
|
||||
}, async () => {
|
||||
await this.ctx.service.systemMethods.order.pendingOrder.allocateExpressCode(request);
|
||||
});
|
||||
// 不再逐单直接取号:改为写入消费队列,由定时任务按仓库+货主串行批量消费,
|
||||
// 避免大批量订单创建时 N 条并发取号事务的 AB-BA 死锁。截单/未审核订单在此处不会入队。
|
||||
await this.enqueueAutoWaybillAllocation(context);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@ -1560,6 +1560,10 @@ class ExpressPlatformService extends MainService {
|
||||
});
|
||||
try {
|
||||
await this.ctx.model.transaction(async transaction => {
|
||||
// 统一加锁顺序:先锁 store_warehouse 再更新 order_express,
|
||||
// 与 createWaybillCode 回写事务一致,避免 AB-BA 死锁
|
||||
await this.lockAndDeductWaybillSettlement(settlementRelationMap, storeWarehouseModel, transaction);
|
||||
|
||||
for (const item of successUpdates) {
|
||||
const warehouseId = Number(item.warehouse_id) || 0;
|
||||
const orderId = Number(item.order_id) || 0;
|
||||
@ -1587,78 +1591,6 @@ class ExpressPlatformService extends MainService {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (storeWarehouseModel
|
||||
&& typeof storeWarehouseModel.findAll === 'function'
|
||||
&& settlementRelationMap.size > 0) {
|
||||
const { Op } = this.app.Sequelize;
|
||||
const relationList = Array.from(settlementRelationMap.values());
|
||||
const relationRows = await storeWarehouseModel.findAll({
|
||||
attributes: [ 'id', 'store_id', 'warehouse_id', 'print_quantity', 'print_quantity_locked' ],
|
||||
where: {
|
||||
[Op.or]: relationList.map(item => ({
|
||||
store_id: item.store_id,
|
||||
warehouse_id: item.warehouse_id,
|
||||
})),
|
||||
},
|
||||
raw: true,
|
||||
transaction,
|
||||
lock: transaction.LOCK.UPDATE,
|
||||
});
|
||||
|
||||
const relationRowMap = new Map();
|
||||
for (const row of Array.isArray(relationRows) ? relationRows : []) {
|
||||
const relationKey = `${Number(row && row.store_id) || 0}:${Number(row && row.warehouse_id) || 0}`;
|
||||
if (relationKey !== '0:0') {
|
||||
relationRowMap.set(relationKey, row);
|
||||
}
|
||||
}
|
||||
|
||||
for (const item of relationList) {
|
||||
const relationKey = `${item.store_id}:${item.warehouse_id}`;
|
||||
const row = relationRowMap.get(relationKey);
|
||||
if (!row) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const currentPrintQuantity = Number(row.print_quantity || 0);
|
||||
const currentLockedQuantity = Math.max(0, Number(row.print_quantity_locked || 0));
|
||||
const successCount = Number(item.success_count || 0);
|
||||
if (successCount <= 0) {
|
||||
continue;
|
||||
}
|
||||
const printDecrement = successCount;
|
||||
const lockedDecrement = Math.min(currentLockedQuantity, printDecrement);
|
||||
const nextPrintQuantity = currentPrintQuantity - printDecrement;
|
||||
const nextLockedQuantity = Math.max(0, currentLockedQuantity - lockedDecrement);
|
||||
await storeWarehouseModel.update({
|
||||
print_quantity: nextPrintQuantity,
|
||||
print_quantity_locked: nextLockedQuantity,
|
||||
}, {
|
||||
where: {
|
||||
id: row.id,
|
||||
},
|
||||
transaction,
|
||||
});
|
||||
|
||||
await this.ctx.model.StoreWarehousePrintQuantityLog.create({
|
||||
contract_id: Number(row.id || 0),
|
||||
store_id: Number(row.store_id || 0),
|
||||
warehouse_id: Number(row.warehouse_id || 0),
|
||||
change_type: 'order_deduct',
|
||||
business_type: 'order_express',
|
||||
business_id: null,
|
||||
change_quantity: -printDecrement,
|
||||
balance_before: Math.max(0, currentPrintQuantity),
|
||||
balance_after: Math.max(0, nextPrintQuantity),
|
||||
reason: '获取快递号成功扣减',
|
||||
operator_id: null,
|
||||
created_by: null,
|
||||
}, {
|
||||
transaction,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
this.ctx.logger.error('[expressPlatform.polyapi] DB 回写事务异常', {
|
||||
@ -2239,6 +2171,97 @@ class ExpressPlatformService extends MainService {
|
||||
return settlementRelationMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* 事务内按 store:warehouse 扣减打印余量并写扣减流水。
|
||||
*
|
||||
* 必须在结算事务内最先执行:先锁 wms_store_warehouse,再更新 wms_order_express,
|
||||
* 与 createWaybillCode 回写事务(先锁 store_warehouse 后锁 order_express)保持
|
||||
* 一致加锁顺序,消除两类事务间的 AB-BA 死锁。
|
||||
*
|
||||
* @param {Map<string, {store_id: number, warehouse_id: number, success_count: number}>} settlementRelationMap 结算关系聚合。
|
||||
* @param {Object} storeWarehouseModel 签约关系模型。
|
||||
* @param {Object} transaction Sequelize 事务。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async lockAndDeductWaybillSettlement(settlementRelationMap = new Map(), storeWarehouseModel, transaction) {
|
||||
if (!storeWarehouseModel
|
||||
|| typeof storeWarehouseModel.findAll !== 'function'
|
||||
|| !settlementRelationMap
|
||||
|| settlementRelationMap.size === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { Op } = this.app.Sequelize;
|
||||
const relationList = Array.from(settlementRelationMap.values());
|
||||
const relationRows = await storeWarehouseModel.findAll({
|
||||
attributes: [ 'id', 'store_id', 'warehouse_id', 'print_quantity', 'print_quantity_locked' ],
|
||||
where: {
|
||||
[Op.or]: relationList.map(item => ({
|
||||
store_id: item.store_id,
|
||||
warehouse_id: item.warehouse_id,
|
||||
})),
|
||||
},
|
||||
raw: true,
|
||||
transaction,
|
||||
lock: transaction.LOCK.UPDATE,
|
||||
});
|
||||
|
||||
const relationRowMap = new Map();
|
||||
for (const row of Array.isArray(relationRows) ? relationRows : []) {
|
||||
const relationKey = `${Number(row && row.store_id) || 0}:${Number(row && row.warehouse_id) || 0}`;
|
||||
if (relationKey !== '0:0') {
|
||||
relationRowMap.set(relationKey, row);
|
||||
}
|
||||
}
|
||||
|
||||
for (const item of relationList) {
|
||||
const relationKey = `${item.store_id}:${item.warehouse_id}`;
|
||||
const row = relationRowMap.get(relationKey);
|
||||
if (!row) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const currentPrintQuantity = Number(row.print_quantity || 0);
|
||||
const currentLockedQuantity = Math.max(0, Number(row.print_quantity_locked || 0));
|
||||
const successCount = Number(item.success_count || 0);
|
||||
if (successCount <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const printDecrement = successCount;
|
||||
const lockedDecrement = Math.min(currentLockedQuantity, printDecrement);
|
||||
const nextPrintQuantity = currentPrintQuantity - printDecrement;
|
||||
const nextLockedQuantity = Math.max(0, currentLockedQuantity - lockedDecrement);
|
||||
|
||||
await storeWarehouseModel.update({
|
||||
print_quantity: nextPrintQuantity,
|
||||
print_quantity_locked: nextLockedQuantity,
|
||||
}, {
|
||||
where: {
|
||||
id: row.id,
|
||||
},
|
||||
transaction,
|
||||
});
|
||||
|
||||
await this.ctx.model.StoreWarehousePrintQuantityLog.create({
|
||||
contract_id: Number(row.id || 0),
|
||||
store_id: Number(row.store_id || 0),
|
||||
warehouse_id: Number(row.warehouse_id || 0),
|
||||
change_type: 'order_deduct',
|
||||
business_type: 'order_express',
|
||||
business_id: null,
|
||||
change_quantity: -printDecrement,
|
||||
balance_before: Math.max(0, currentPrintQuantity),
|
||||
balance_after: Math.max(0, nextPrintQuantity),
|
||||
reason: '获取快递号成功扣减',
|
||||
operator_id: null,
|
||||
created_by: null,
|
||||
}, {
|
||||
transaction,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 回写成功获取的面单结果,并扣减打印余量与写入操作日志。
|
||||
*
|
||||
@ -2258,6 +2281,10 @@ class ExpressPlatformService extends MainService {
|
||||
|
||||
if (typeof this.ctx.model.transaction === 'function') {
|
||||
await this.ctx.model.transaction(async transaction => {
|
||||
// 统一加锁顺序:先锁 store_warehouse 再更新 order_express,
|
||||
// 与 createWaybillCode 回写事务一致,避免 AB-BA 死锁
|
||||
await this.lockAndDeductWaybillSettlement(settlementRelationMap, storeWarehouseModel, transaction);
|
||||
|
||||
for (const item of normalizedSuccessUpdates) {
|
||||
if (!item.warehouse_id || !item.order_id || !item.business_key) {
|
||||
throw new Error('平台接口返回 object_id 无法解析');
|
||||
@ -2282,80 +2309,6 @@ class ExpressPlatformService extends MainService {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (storeWarehouseModel
|
||||
&& typeof storeWarehouseModel.findAll === 'function'
|
||||
&& settlementRelationMap.size > 0) {
|
||||
const { Op } = this.app.Sequelize;
|
||||
const relationList = Array.from(settlementRelationMap.values());
|
||||
const relationRows = await storeWarehouseModel.findAll({
|
||||
attributes: [ 'id', 'store_id', 'warehouse_id', 'print_quantity', 'print_quantity_locked' ],
|
||||
where: {
|
||||
[Op.or]: relationList.map(item => ({
|
||||
store_id: item.store_id,
|
||||
warehouse_id: item.warehouse_id,
|
||||
})),
|
||||
},
|
||||
raw: true,
|
||||
transaction,
|
||||
lock: transaction.LOCK.UPDATE,
|
||||
});
|
||||
|
||||
const relationRowMap = new Map();
|
||||
for (const row of Array.isArray(relationRows) ? relationRows : []) {
|
||||
const relationKey = `${Number(row && row.store_id) || 0}:${Number(row && row.warehouse_id) || 0}`;
|
||||
if (relationKey !== '0:0') {
|
||||
relationRowMap.set(relationKey, row);
|
||||
}
|
||||
}
|
||||
|
||||
for (const item of relationList) {
|
||||
const relationKey = `${item.store_id}:${item.warehouse_id}`;
|
||||
const row = relationRowMap.get(relationKey);
|
||||
if (!row) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const currentPrintQuantity = Number(row.print_quantity || 0);
|
||||
const currentLockedQuantity = Math.max(0, Number(row.print_quantity_locked || 0));
|
||||
const successCount = Number(item.success_count || 0);
|
||||
if (successCount <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const printDecrement = successCount;
|
||||
const lockedDecrement = Math.min(currentLockedQuantity, printDecrement);
|
||||
const nextPrintQuantity = currentPrintQuantity - printDecrement;
|
||||
const nextLockedQuantity = Math.max(0, currentLockedQuantity - lockedDecrement);
|
||||
|
||||
await storeWarehouseModel.update({
|
||||
print_quantity: nextPrintQuantity,
|
||||
print_quantity_locked: nextLockedQuantity,
|
||||
}, {
|
||||
where: {
|
||||
id: row.id,
|
||||
},
|
||||
transaction,
|
||||
});
|
||||
|
||||
await this.ctx.model.StoreWarehousePrintQuantityLog.create({
|
||||
contract_id: Number(row.id || 0),
|
||||
store_id: Number(row.store_id || 0),
|
||||
warehouse_id: Number(row.warehouse_id || 0),
|
||||
change_type: 'order_deduct',
|
||||
business_type: 'order_express',
|
||||
business_id: null,
|
||||
change_quantity: -printDecrement,
|
||||
balance_before: Math.max(0, currentPrintQuantity),
|
||||
balance_after: Math.max(0, nextPrintQuantity),
|
||||
reason: '获取快递号成功扣减',
|
||||
operator_id: null,
|
||||
created_by: null,
|
||||
}, {
|
||||
transaction,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@ -2661,6 +2614,10 @@ class ExpressPlatformService extends MainService {
|
||||
const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse;
|
||||
if (typeof this.ctx.model.transaction === 'function' && successUpdates.length > 0) {
|
||||
await this.ctx.model.transaction(async transaction => {
|
||||
// 统一加锁顺序:先锁 store_warehouse 再更新 order_express,
|
||||
// 与 createWaybillCode 回写事务一致,避免 AB-BA 死锁
|
||||
await this.lockAndDeductWaybillSettlement(settlementRelationMap, storeWarehouseModel, transaction);
|
||||
|
||||
for (const item of successUpdates) {
|
||||
if (!item.warehouse_id || !item.order_id || !item.business_key) {
|
||||
throw new Error('拼多多平台接口返回 object_id 无法解析');
|
||||
@ -2685,80 +2642,6 @@ class ExpressPlatformService extends MainService {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (storeWarehouseModel
|
||||
&& typeof storeWarehouseModel.findAll === 'function'
|
||||
&& settlementRelationMap.size > 0) {
|
||||
const { Op } = this.app.Sequelize;
|
||||
const relationList = Array.from(settlementRelationMap.values());
|
||||
const relationRows = await storeWarehouseModel.findAll({
|
||||
attributes: [ 'id', 'store_id', 'warehouse_id', 'print_quantity', 'print_quantity_locked' ],
|
||||
where: {
|
||||
[Op.or]: relationList.map(item => ({
|
||||
store_id: item.store_id,
|
||||
warehouse_id: item.warehouse_id,
|
||||
})),
|
||||
},
|
||||
raw: true,
|
||||
transaction,
|
||||
lock: transaction.LOCK.UPDATE,
|
||||
});
|
||||
|
||||
const relationRowMap = new Map();
|
||||
for (const row of Array.isArray(relationRows) ? relationRows : []) {
|
||||
const relationKey = `${Number(row && row.store_id) || 0}:${Number(row && row.warehouse_id) || 0}`;
|
||||
if (relationKey !== '0:0') {
|
||||
relationRowMap.set(relationKey, row);
|
||||
}
|
||||
}
|
||||
|
||||
for (const item of relationList) {
|
||||
const relationKey = `${item.store_id}:${item.warehouse_id}`;
|
||||
const row = relationRowMap.get(relationKey);
|
||||
if (!row) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const currentPrintQuantity = Number(row.print_quantity || 0);
|
||||
const currentLockedQuantity = Math.max(0, Number(row.print_quantity_locked || 0));
|
||||
const successCount = Number(item.success_count || 0);
|
||||
if (successCount <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const printDecrement = successCount;
|
||||
const lockedDecrement = Math.min(currentLockedQuantity, printDecrement);
|
||||
const nextPrintQuantity = currentPrintQuantity - printDecrement;
|
||||
const nextLockedQuantity = Math.max(0, currentLockedQuantity - lockedDecrement);
|
||||
|
||||
await storeWarehouseModel.update({
|
||||
print_quantity: nextPrintQuantity,
|
||||
print_quantity_locked: nextLockedQuantity,
|
||||
}, {
|
||||
where: {
|
||||
id: row.id,
|
||||
},
|
||||
transaction,
|
||||
});
|
||||
|
||||
await this.ctx.model.StoreWarehousePrintQuantityLog.create({
|
||||
contract_id: Number(row.id || 0),
|
||||
store_id: Number(row.store_id || 0),
|
||||
warehouse_id: Number(row.warehouse_id || 0),
|
||||
change_type: 'order_deduct',
|
||||
business_type: 'order_express',
|
||||
business_id: null,
|
||||
change_quantity: -printDecrement,
|
||||
balance_before: Math.max(0, currentPrintQuantity),
|
||||
balance_after: Math.max(0, nextPrintQuantity),
|
||||
reason: '获取快递号成功扣减',
|
||||
operator_id: null,
|
||||
created_by: null,
|
||||
}, {
|
||||
transaction,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@ -1156,9 +1156,12 @@ class InboundDirectLogService extends Service {
|
||||
);
|
||||
}
|
||||
|
||||
// 回写收货单和收货明细的入库状态
|
||||
// 回写收货单和收货明细的入库状态(绑定模式:按 receiving_detail_id 优先扣减)
|
||||
await this._syncReceivingStorageStatus({ entryItemIds, transaction });
|
||||
|
||||
// 非绑定模式剩余导入量:按 stock_id 匹配绑定收货单明细占用(绑定模式优先,剩余兜底)
|
||||
await this._applyReceivingStockOccupancy({ entryOrder: eo, directLogs, transaction });
|
||||
|
||||
// 更新入库单状态为 COMPLETED
|
||||
await eo.update({
|
||||
order_status: 'COMPLETED',
|
||||
@ -1682,6 +1685,71 @@ class InboundDirectLogService extends Service {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 非绑定模式收货单占用:导入记录未携带 receiving_detail_id 时,
|
||||
* 将剩余导入量按 stock_id(=收货明细 system_product_id)匹配到绑定收货单明细上,
|
||||
* 依次占用剩余可入数量(actual_quantity - stored_quantity),
|
||||
* 回写 stored_quantity/storage_status 并汇总收货单主表 storage_status。
|
||||
* 携带 receiving_detail_id 的导入记录已由 _syncReceivingStorageStatus 优先处理,
|
||||
* 本方法只处理未携带 receiving_detail_id 的剩余部分(必须先调用前者)。
|
||||
*
|
||||
* @param {Object} params 参数
|
||||
* @param {Object} params.entryOrder 入库单实例
|
||||
* @param {Array<Object>} params.directLogs 入库单下所有未删除的导入/PDA 入库记录
|
||||
* @param {Object} params.transaction Sequelize 事务对象
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async _applyReceivingStockOccupancy({ entryOrder, directLogs, transaction }) {
|
||||
const { ctx, app } = this;
|
||||
|
||||
// 1. 入库单未绑定收货单 → 跳过
|
||||
const bindings = await ctx.model.EntryOrderReceiving.findAll({
|
||||
where: { entry_order_id: entryOrder.id, deleted_at: null },
|
||||
attributes: [ 'receiving_id' ],
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
const receivingIds = [ ...new Set((bindings || []).map(b => Number(b.receiving_id)).filter(Boolean)) ];
|
||||
if (receivingIds.length === 0) return;
|
||||
|
||||
// 2. 汇总未携带 receiving_detail_id 的导入量(绑定模式已优先处理,这里只取剩余部分)
|
||||
const stockInboundQtyMap = new Map();
|
||||
for (const log of directLogs) {
|
||||
if (log.receiving_detail_id) continue;
|
||||
const stockId = Number(log.stock_id);
|
||||
const qty = Number(log.quantity) || 0;
|
||||
if (!stockId || qty <= 0) continue;
|
||||
stockInboundQtyMap.set(
|
||||
stockId,
|
||||
{ inboundQty: (stockInboundQtyMap.get(stockId)?.inboundQty || 0) + qty }
|
||||
);
|
||||
}
|
||||
if (stockInboundQtyMap.size === 0) return;
|
||||
|
||||
// 3. 查询绑定收货单明细(事务内读取,stored_quantity 已包含绑定模式扣减结果)
|
||||
const boundDetails = await ctx.model.ReceivingDetail.findAll({
|
||||
where: {
|
||||
receiving_id: { [app.Sequelize.Op.in]: receivingIds },
|
||||
system_product_id: { [app.Sequelize.Op.ne]: null },
|
||||
},
|
||||
attributes: [ 'id', 'receiving_id', 'system_product_id', 'actual_quantity', 'stored_quantity' ],
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
if (!boundDetails || boundDetails.length === 0) return;
|
||||
|
||||
// 4. 复用 storage.entry 的收货单占用逻辑(与 quickInbound 一致,事务内行锁防并发超分)
|
||||
await ctx.service.systems.storage.entry._applyReceivingInboundUsage({
|
||||
receivingDetailRows: boundDetails,
|
||||
stockInboundQtyMap,
|
||||
transaction,
|
||||
});
|
||||
|
||||
ctx.logger.info(
|
||||
`[InboundDirectLog] 非绑定模式导入已按 stock_id 占用收货单明细,entryOrderId=${entryOrder.id}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = InboundDirectLogService;
|
||||
|
||||
@ -8,7 +8,10 @@ const path = require('node:path');
|
||||
const ExcelJS = require('exceljs');
|
||||
const OrderBaseService = require('../systemMethods/order/base');
|
||||
|
||||
const DEFAULT_EXPORT_PAGE_SIZE = 200;
|
||||
const DEFAULT_EXPORT_PAGE_SIZE = 1000;
|
||||
const ORDER_EXPORT_QUERY_CONCURRENCY = 2;
|
||||
const ORDER_EXPORT_MAX_ROWS_PER_SHEET = 1000000;
|
||||
const ORDER_EXPORT_UPLOAD_MAX_SIZE_BYTES = 1024 * 1024 * 1024; // 订单导出上传文件上限 1GB
|
||||
const ORDER_EXPORT_WORKSHEET_NAME = '订单导出';
|
||||
const ORDER_EXPORT_ALLOWED_TABLE_TYPES = new Set([ 'current', 'history', 'dispatch', 'outsourced' ]);
|
||||
const ORDER_EXPORT_MODULE_MAP = Object.freeze({
|
||||
@ -118,6 +121,14 @@ const ORDER_EXPORT_ITEM_COLUMNS = Object.freeze([
|
||||
{ header: '归档时间', key: 'archive_time', width: 20 },
|
||||
]);
|
||||
|
||||
/** 全部可导出表头字段(waybill 与 item 两种模式的并集,用于入参校验) */
|
||||
const ORDER_EXPORT_ALL_COLUMN_HEADERS = Object.freeze(
|
||||
new Set([
|
||||
...ORDER_EXPORT_COLUMNS.map(column => column.header),
|
||||
...ORDER_EXPORT_ITEM_COLUMNS.map(column => column.header),
|
||||
])
|
||||
);
|
||||
|
||||
/** 订单状态中文翻译映射 */
|
||||
const ORDER_STATUS_LABELS = Object.freeze({
|
||||
status: {
|
||||
@ -251,11 +262,45 @@ class OrderExportService extends OrderBaseService {
|
||||
/**
|
||||
* 获取订单导出列配置。
|
||||
* @param {string} [mode='waybill'] 导出模式:'waybill'(按运单展开)或 'item'(按商品明细展开)。
|
||||
* @param {Array<string>} [selectedHeaders=[]] 表头字段白名单(中文);不传/空数组返回全部列。
|
||||
* @return {Array<Object>} 导出列配置。
|
||||
*/
|
||||
getOrderExportColumns(mode = 'waybill') {
|
||||
getOrderExportColumns(mode = 'waybill', selectedHeaders = []) {
|
||||
const columns = mode === 'item' ? ORDER_EXPORT_ITEM_COLUMNS : ORDER_EXPORT_COLUMNS;
|
||||
return columns.map(column => ({ ...column }));
|
||||
const safeHeaders = Array.isArray(selectedHeaders) ? selectedHeaders : [];
|
||||
const headerSet = new Set(
|
||||
safeHeaders.map(header => String(header || '').trim()).filter(Boolean)
|
||||
);
|
||||
if (headerSet.size === 0) {
|
||||
return columns.map(column => ({ ...column }));
|
||||
}
|
||||
return columns
|
||||
.filter(column => headerSet.has(column.header))
|
||||
.map(column => ({ ...column }));
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验并规范导出表头字段入参(中文表头数组)。
|
||||
* 不传/空数组返回空数组(表示输出全部列);存在非法表头时抛错。
|
||||
* @param {Array<string>|*} rawColumns 原始入参。
|
||||
* @return {Array<string>} 去重后的表头数组。
|
||||
*/
|
||||
normalizeExportColumns(rawColumns) {
|
||||
if (!Array.isArray(rawColumns)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const selectedHeaders = [ ...new Set(
|
||||
rawColumns.map(header => String(header || '').trim()).filter(Boolean)
|
||||
) ];
|
||||
const invalidHeaders = selectedHeaders.filter(
|
||||
header => !ORDER_EXPORT_ALL_COLUMN_HEADERS.has(header)
|
||||
);
|
||||
if (invalidHeaders.length > 0) {
|
||||
throw new Error(`不支持的导出表头字段: ${invalidHeaders.join(', ')}`);
|
||||
}
|
||||
|
||||
return selectedHeaders;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -330,7 +375,7 @@ class OrderExportService extends OrderBaseService {
|
||||
|
||||
/**
|
||||
* 映射订单导出数据行。
|
||||
* - waybill 模式:按运单号展开,每个运单一组。
|
||||
* - waybill 模式:按运单号展开,每个运单一组;商品种数/件数仅主单号行体现,子单号行置 0。
|
||||
* - item 模式:按商品明细展开,每个商品一行;运单信息汇总填充。
|
||||
* @param {Object} orderRow 订单行。
|
||||
* @param {Object} [context] 导出上下文,包含批量查询的辅助数据。
|
||||
@ -507,20 +552,26 @@ class OrderExportService extends OrderBaseService {
|
||||
}];
|
||||
}
|
||||
|
||||
return expressList.map(exp => ({
|
||||
...commonFields,
|
||||
items_detail: this.normalizeExportCellValue(itemsDetail),
|
||||
waybill_code: exp.waybill_code || '',
|
||||
business_type: Number(exp.business_key) === 1 ? '主单号' : '子单号',
|
||||
logistics_interface_name: this.normalizeExportCellValue(exp.logistics_interface_name),
|
||||
package_material_id: exp.package_material_id != null ? Number(exp.package_material_id) : '',
|
||||
package_material_code: this.normalizeExportCellValue(
|
||||
exp.package_material_id != null ? (safePackageMaterialMap.get(Number(exp.package_material_id)) || '') : ''
|
||||
),
|
||||
package_material_name: this.normalizeExportCellValue(exp.package_material_name_snapshot),
|
||||
waybill_allocated_at: formatDateSafe(exp.create_at),
|
||||
weighing_weight: exp.weighing_weight != null ? Number(exp.weighing_weight) : '',
|
||||
}));
|
||||
return expressList.map(exp => {
|
||||
const isMainWaybill = Number(exp.business_key) === 1;
|
||||
return {
|
||||
...commonFields,
|
||||
items_detail: this.normalizeExportCellValue(itemsDetail),
|
||||
// 商品种数/件数为订单级数据,仅主单号行体现;子单号行置 0,避免与主单号重复
|
||||
items_count: isMainWaybill ? commonFields.items_count : 0,
|
||||
items_total: isMainWaybill ? commonFields.items_total : 0,
|
||||
waybill_code: exp.waybill_code || '',
|
||||
business_type: isMainWaybill ? '主单号' : '子单号',
|
||||
logistics_interface_name: this.normalizeExportCellValue(exp.logistics_interface_name),
|
||||
package_material_id: exp.package_material_id != null ? Number(exp.package_material_id) : '',
|
||||
package_material_code: this.normalizeExportCellValue(
|
||||
exp.package_material_id != null ? (safePackageMaterialMap.get(Number(exp.package_material_id)) || '') : ''
|
||||
),
|
||||
package_material_name: this.normalizeExportCellValue(exp.package_material_name_snapshot),
|
||||
waybill_allocated_at: formatDateSafe(exp.create_at),
|
||||
weighing_weight: exp.weighing_weight != null ? Number(exp.weighing_weight) : '',
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@ -557,6 +608,7 @@ class OrderExportService extends OrderBaseService {
|
||||
key: uploadKey,
|
||||
category: 'document',
|
||||
mimetype: 'xls,xlsx,csv',
|
||||
maxSizeBytes: ORDER_EXPORT_UPLOAD_MAX_SIZE_BYTES,
|
||||
});
|
||||
|
||||
let fileRecord = null;
|
||||
@ -586,13 +638,231 @@ class OrderExportService extends OrderBaseService {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建单个导出页:分页查询订单 + 批量富化 + 映射导出行。
|
||||
* @param {Object} options 分页构建参数。
|
||||
* @param {number} options.page 页码(从 1 开始)。
|
||||
* @param {number} options.pageSize 分页大小。
|
||||
* @param {Object} options.queryWhere 查询条件。
|
||||
* @param {Array<Array<string>>} options.order 排序参数。
|
||||
* @param {Object} options.orderModel 订单头模型。
|
||||
* @param {Object} options.target 导出目标。
|
||||
* @param {number|string} options.warehouseId 仓库ID。
|
||||
* @param {string} options.mode 导出模式:'waybill' 或 'item'。
|
||||
* @return {Promise<{exportRows: Array<Object>, orderCount: number}>} 导出行数组与订单数。
|
||||
*/
|
||||
async buildOrderExportPage(options = {}) {
|
||||
const safeOptions = this.isPlainObject(options) ? options : {};
|
||||
const {
|
||||
page,
|
||||
pageSize,
|
||||
queryWhere,
|
||||
order,
|
||||
orderModel,
|
||||
target,
|
||||
warehouseId,
|
||||
mode,
|
||||
} = safeOptions;
|
||||
|
||||
const rows = await orderModel.findAll({
|
||||
where: queryWhere,
|
||||
limit: pageSize,
|
||||
offset: (page - 1) * pageSize,
|
||||
order,
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (!Array.isArray(rows) || rows.length === 0) {
|
||||
return { exportRows: [], orderCount: 0 };
|
||||
}
|
||||
|
||||
const normalizedRows = rows.map(row =>
|
||||
this.normalizeOrderListItem(this.toPlainRow(row))
|
||||
);
|
||||
const rowsWithWaveIndex = await this.attachOrderWaveIndex(normalizedRows);
|
||||
|
||||
const orderIds = rowsWithWaveIndex.map(r => Number(r.id || 0)).filter(id => id > 0);
|
||||
|
||||
// 批量查询商品明细(wms_order_items)
|
||||
const itemsMap = new Map();
|
||||
if (orderIds.length > 0) {
|
||||
try {
|
||||
const itemsModel = await this.getOrderItemsModelByTableType(target.tableType, warehouseId);
|
||||
const itemsRows = await itemsModel.findAll({
|
||||
where: { order_id: { [this.app.Sequelize.Op.in]: orderIds } },
|
||||
attributes: [ 'order_id', 'item_name', 'plan_qty', 'stock_id' ],
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
});
|
||||
for (const item of (Array.isArray(itemsRows) ? itemsRows : [])) {
|
||||
const oid = Number(item.order_id || 0);
|
||||
if (oid > 0) {
|
||||
if (!itemsMap.has(oid)) {
|
||||
itemsMap.set(oid, []);
|
||||
}
|
||||
itemsMap.get(oid).push(item);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
this.app.logger.warn(`[order_export] 批量查询订单商品明细失败: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 批量查询仓库商品名称、条码与图片(复用 getStockDetails 缓存)
|
||||
const stockNameMap = new Map();
|
||||
const barcodeMap = new Map();
|
||||
const imageUrlMap = new Map();
|
||||
if (itemsMap.size > 0 && this.ctx && this.ctx.model && this.ctx.model.StockWarehouse) {
|
||||
try {
|
||||
const stockIds = [
|
||||
...new Set(
|
||||
[ ...itemsMap.values() ]
|
||||
.flat()
|
||||
.map(item => Number(item.stock_id || 0))
|
||||
.filter(id => id > 0)
|
||||
),
|
||||
];
|
||||
if (stockIds.length > 0) {
|
||||
const stockDetails = await this.ctx.service.systems.stockWarehouse.getStockDetails(
|
||||
stockIds,
|
||||
{ warehouseId }
|
||||
);
|
||||
for (const detail of stockDetails) {
|
||||
const sid = Number(detail.id || 0);
|
||||
if (sid > 0) {
|
||||
stockNameMap.set(sid, String(detail.item_name || '').trim());
|
||||
// 从 getStockDetails 的 barcodes 中提取条码并转为逗号拼接
|
||||
const barcodesRaw = Array.isArray(detail.barcodes)
|
||||
? detail.barcodes.map(bc => String(bc.barcode || '').trim()).filter(Boolean)
|
||||
: [];
|
||||
if (barcodesRaw.length > 0) {
|
||||
barcodeMap.set(sid, [ ...new Set(barcodesRaw) ].join(', '));
|
||||
}
|
||||
// 图片字段(有图片标记但实际 URL 需要额外查询)
|
||||
if (detail.is_images === 'Y') {
|
||||
imageUrlMap.set(sid, '');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
this.app.logger.warn(`[order_export] 批量查询商品详情失败: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 批量查询货主备注(wms_store_warehouse.store_remask)
|
||||
const storeRemarkMap = new Map();
|
||||
if (orderIds.length > 0 && this.ctx && this.ctx.model && this.ctx.model.StoreWarehouse) {
|
||||
try {
|
||||
const storeIds = [
|
||||
...new Set(
|
||||
rowsWithWaveIndex
|
||||
.map(r => Number(r.store_id || 0))
|
||||
.filter(id => id > 0)
|
||||
),
|
||||
];
|
||||
if (storeIds.length > 0) {
|
||||
const swRows = await this.ctx.model.StoreWarehouse.findAll({
|
||||
where: {
|
||||
store_id: { [this.app.Sequelize.Op.in]: storeIds },
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
attributes: [ 'store_id', 'store_remask' ],
|
||||
raw: true,
|
||||
});
|
||||
for (const sw of (Array.isArray(swRows) ? swRows : [])) {
|
||||
const sid = Number(sw.store_id || 0);
|
||||
if (sid > 0 && !storeRemarkMap.has(sid)) {
|
||||
storeRemarkMap.set(sid, String(sw.store_remask || '').trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
this.app.logger.warn(`[order_export] 批量查询货主备注失败: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 批量查询运单数据(wms_order_express),按订单ID分组
|
||||
const expressMap = new Map();
|
||||
if (orderIds.length > 0 && this.ctx && this.ctx.model && this.ctx.model.OrderExpress) {
|
||||
try {
|
||||
const expressRows = await this.ctx.model.OrderExpress.findAll({
|
||||
where: {
|
||||
order_id: { [this.app.Sequelize.Op.in]: orderIds },
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
attributes: [ 'id', 'order_id', 'waybill_code', 'business_key', 'logistics_interface_name', 'package_material_id', 'package_material_name_snapshot', 'create_at', 'weighing_weight' ],
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
});
|
||||
for (const exp of (Array.isArray(expressRows) ? expressRows : [])) {
|
||||
const oid = Number(exp.order_id || 0);
|
||||
if (oid > 0) {
|
||||
if (!expressMap.has(oid)) {
|
||||
expressMap.set(oid, []);
|
||||
}
|
||||
expressMap.get(oid).push(exp);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
this.app.logger.warn(`[order_export] 批量查询运单数据失败: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 批量查询包材编码(wms_package_material),按 package_material_id 分组
|
||||
const packageMaterialMap = new Map();
|
||||
if (expressMap.size > 0 && this.ctx && this.ctx.model && this.ctx.model.PackageMaterial) {
|
||||
try {
|
||||
const materialIds = [
|
||||
...new Set(
|
||||
[ ...expressMap.values() ]
|
||||
.flat()
|
||||
.map(exp => Number(exp.package_material_id || 0))
|
||||
.filter(id => id > 0)
|
||||
),
|
||||
];
|
||||
if (materialIds.length > 0) {
|
||||
const pmRows = await this.ctx.model.PackageMaterial.findAll({
|
||||
where: { id: { [this.app.Sequelize.Op.in]: materialIds } },
|
||||
attributes: [ 'id', 'material_code' ],
|
||||
raw: true,
|
||||
});
|
||||
for (const pm of (Array.isArray(pmRows) ? pmRows : [])) {
|
||||
const pid = Number(pm.id || 0);
|
||||
if (pid > 0 && !packageMaterialMap.has(pid)) {
|
||||
packageMaterialMap.set(pid, String(pm.material_code || '').trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
this.app.logger.warn(`[order_export] 批量查询包材编码失败: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
const exportContext = { itemsMap, storeRemarkMap, stockNameMap, barcodeMap, imageUrlMap, expressMap, packageMaterialMap };
|
||||
|
||||
const exportRows = [];
|
||||
for (const row of rowsWithWaveIndex) {
|
||||
const rowExportRows = this.mapOrderExportRow(row, exportContext, mode);
|
||||
exportRows.push(...rowExportRows);
|
||||
}
|
||||
|
||||
return { exportRows, orderCount: rowsWithWaveIndex.length };
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出订单列表。
|
||||
* 查询采用 ORDER_EXPORT_QUERY_CONCURRENCY 个 worker 并发分页查询,
|
||||
* 先查询完成的页先入 FIFO 队列,由单一串行 writer 按入队顺序写入文件(行序按完成顺序,非列表顺序)。
|
||||
* 单个 sheet 最多写入 ORDER_EXPORT_MAX_ROWS_PER_SHEET 行数据,超出后自动新建下一个 sheet 续写。
|
||||
* @param {Object} options 导出参数。
|
||||
* @param {string} [options.tableType] 表类型。
|
||||
* @param {string} [options.moduleName] 模块名。
|
||||
* @param {Object} [options.where] 查询条件。
|
||||
* @param {Object} [options.sort] 排序参数。
|
||||
* @param {string} [options.export_mode] 导出模式:waybill 或 item。
|
||||
* @param {Array<string>} [options.export_columns] 导出表头字段白名单(中文表头数组),不传输出全部列。
|
||||
* @param {Array<string>} [options.exportColumns] 导出表头字段白名单(驼峰写法)。
|
||||
* @param {Function} [options.onProgress] 进度回调。
|
||||
* @return {Promise<Object>} 上传结果与统计信息。
|
||||
*/
|
||||
@ -619,7 +889,8 @@ class OrderExportService extends OrderBaseService {
|
||||
});
|
||||
const { where: sanitizedWhere, expressNumbers } = this.extractOrderListExpressVirtualFilter(where);
|
||||
const { where: whereAfterBuyerMessage, buyerMessageHas } = this.extractBuyerMessageHasVirtualFilter(sanitizedWhere);
|
||||
const { where: whereAfterWaveIndex, waveIndexCondition } = this.extractWaveIndexVirtualFilter(whereAfterBuyerMessage);
|
||||
const { where: whereAfterStockQuery, stockQuery } = this.extractStockQueryVirtualFilter(whereAfterBuyerMessage);
|
||||
const { where: whereAfterWaveIndex, waveIndexCondition } = this.extractWaveIndexVirtualFilter(whereAfterStockQuery);
|
||||
const { where: whereAfterWaveScope, waveScope } = this.extractWaveScopeVirtualFilter(whereAfterWaveIndex);
|
||||
const mergedWhere = this.mergeWhereObjects(
|
||||
target.defaultWhereModuleName ? this.getDefaultWhere(target.defaultWhereModuleName) : {},
|
||||
@ -643,6 +914,13 @@ class OrderExportService extends OrderBaseService {
|
||||
queryWhere = this.appendConditionToWhere(queryWhere, buyerMessageCondition);
|
||||
}
|
||||
|
||||
if (stockQuery) {
|
||||
// 仅传 table_type 时推导出与当前表类型一致的模块名,保证 order_items 表类型正确
|
||||
const stockQueryModuleName = target.defaultWhereModuleName || target.sortModuleName || 'order';
|
||||
const stockOrderIds = await this.findOrderIdsByStockQuery(stockQuery, stockQueryModuleName, warehouseId);
|
||||
queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, stockOrderIds);
|
||||
}
|
||||
|
||||
if (waveIndexCondition) {
|
||||
const waveIndexOrderIds = await this.findOrderIdsByWaveIndexCondition(waveIndexCondition, warehouseId);
|
||||
queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, waveIndexOrderIds);
|
||||
@ -668,10 +946,35 @@ class OrderExportService extends OrderBaseService {
|
||||
const worksheet = workbook.addWorksheet(ORDER_EXPORT_WORKSHEET_NAME);
|
||||
const exportMode = String(safeOptions.export_mode || '').trim() || 'waybill';
|
||||
const mode = exportMode === 'item' ? 'item' : 'waybill';
|
||||
worksheet.columns = this.getOrderExportColumns(mode);
|
||||
const selectedHeaders = this.normalizeExportColumns(
|
||||
safeOptions.export_columns ?? safeOptions.exportColumns
|
||||
);
|
||||
const resolvedColumns = this.getOrderExportColumns(mode, selectedHeaders);
|
||||
worksheet.columns = resolvedColumns;
|
||||
|
||||
let currentCount = 0;
|
||||
let page = 1;
|
||||
// 分 sheet 写入:每个 sheet 最多 ORDER_EXPORT_MAX_ROWS_PER_SHEET 行数据,
|
||||
// 超出后提交当前 sheet 并新建下一个 sheet(名称:订单导出、订单导出2、…),新 sheet 同样带表头。
|
||||
let currentWorksheet = worksheet;
|
||||
let currentSheetIndex = 1;
|
||||
let currentSheetRows = 0;
|
||||
|
||||
const ensureSheetCapacity = () => {
|
||||
if (currentSheetRows < ORDER_EXPORT_MAX_ROWS_PER_SHEET) {
|
||||
return;
|
||||
}
|
||||
currentWorksheet.commit();
|
||||
currentSheetIndex += 1;
|
||||
currentWorksheet = workbook.addWorksheet(`${ORDER_EXPORT_WORKSHEET_NAME}${currentSheetIndex}`);
|
||||
currentWorksheet.columns = resolvedColumns;
|
||||
currentSheetRows = 0;
|
||||
};
|
||||
|
||||
const writeExportRow = exportRow => {
|
||||
ensureSheetCapacity();
|
||||
currentWorksheet.addRow(exportRow).commit();
|
||||
currentSheetRows += 1;
|
||||
};
|
||||
|
||||
try {
|
||||
await progressHandler({
|
||||
@ -682,205 +985,124 @@ class OrderExportService extends OrderBaseService {
|
||||
message: totalCount > 0 ? `已命中 ${totalCount} 条订单,开始导出` : '未命中数据,开始生成空文件',
|
||||
});
|
||||
|
||||
while (currentCount < totalCount) {
|
||||
const rows = await orderModel.findAll({
|
||||
where: queryWhere,
|
||||
limit: pageSize,
|
||||
offset: (page - 1) * pageSize,
|
||||
order,
|
||||
raw: true,
|
||||
});
|
||||
const totalPages = totalCount > 0 ? Math.ceil(totalCount / pageSize) : 0;
|
||||
|
||||
if (!Array.isArray(rows) || rows.length === 0) {
|
||||
break;
|
||||
// FIFO 队列:各 worker 查询完成的页按完成顺序入队,由单一 writer 串行落盘
|
||||
const exportPageQueue = [];
|
||||
let exportQueueHead = 0;
|
||||
let pagesCompleted = 0;
|
||||
let queueDone = false;
|
||||
let queueWake = null;
|
||||
let firstError = null;
|
||||
|
||||
const wakeWriter = () => {
|
||||
if (queueWake) {
|
||||
const resolveWake = queueWake;
|
||||
queueWake = null;
|
||||
resolveWake();
|
||||
}
|
||||
};
|
||||
const enqueueExportRows = exportRows => {
|
||||
if (Array.isArray(exportRows) && exportRows.length > 0) {
|
||||
exportPageQueue.push(exportRows);
|
||||
wakeWriter();
|
||||
}
|
||||
};
|
||||
const finishExportQueue = () => {
|
||||
queueDone = true;
|
||||
wakeWriter();
|
||||
};
|
||||
const waitForQueueWake = () => new Promise(resolve => {
|
||||
queueWake = resolve;
|
||||
});
|
||||
|
||||
const normalizedRows = rows.map(row =>
|
||||
this.normalizeOrderListItem(this.toPlainRow(row))
|
||||
);
|
||||
const rowsWithWaveIndex = await this.attachOrderWaveIndex(normalizedRows);
|
||||
// 串行 writer:按入队顺序写入 ExcelJS 流,避免并发 commit 导致的行序竞态
|
||||
const writerLoop = (async () => {
|
||||
try {
|
||||
for (;;) {
|
||||
while (exportQueueHead < exportPageQueue.length) {
|
||||
const exportRows = exportPageQueue[exportQueueHead];
|
||||
exportQueueHead += 1;
|
||||
for (const exportRow of exportRows) {
|
||||
writeExportRow(exportRow);
|
||||
}
|
||||
}
|
||||
if (exportQueueHead > 0) {
|
||||
if (exportQueueHead >= exportPageQueue.length) {
|
||||
exportPageQueue.length = 0;
|
||||
exportQueueHead = 0;
|
||||
} else {
|
||||
exportPageQueue.splice(0, exportQueueHead);
|
||||
exportQueueHead = 0;
|
||||
}
|
||||
}
|
||||
if (queueDone || firstError) {
|
||||
break;
|
||||
}
|
||||
await waitForQueueWake();
|
||||
}
|
||||
} catch (err) {
|
||||
if (!firstError) {
|
||||
firstError = err;
|
||||
}
|
||||
queueDone = true;
|
||||
wakeWriter();
|
||||
}
|
||||
})();
|
||||
|
||||
const orderIds = rowsWithWaveIndex.map(r => Number(r.id || 0)).filter(id => id > 0);
|
||||
|
||||
// 批量查询商品明细(wms_order_items)
|
||||
const itemsMap = new Map();
|
||||
if (orderIds.length > 0) {
|
||||
// 有界并发查询:限制 2 个 worker,先查询完成的页先入队
|
||||
let nextPage = 1;
|
||||
const runWorker = async () => {
|
||||
while (!firstError) {
|
||||
const page = nextPage;
|
||||
nextPage += 1;
|
||||
if (page > totalPages) {
|
||||
break;
|
||||
}
|
||||
try {
|
||||
const itemsModel = await this.getOrderItemsModelByTableType(target.tableType, warehouseId);
|
||||
const itemsRows = await itemsModel.findAll({
|
||||
where: { order_id: { [this.app.Sequelize.Op.in]: orderIds } },
|
||||
attributes: [ 'order_id', 'item_name', 'plan_qty', 'stock_id' ],
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
const pageResult = await this.buildOrderExportPage({
|
||||
page,
|
||||
pageSize,
|
||||
queryWhere,
|
||||
order,
|
||||
orderModel,
|
||||
target,
|
||||
warehouseId,
|
||||
mode,
|
||||
});
|
||||
for (const item of (Array.isArray(itemsRows) ? itemsRows : [])) {
|
||||
const oid = Number(item.order_id || 0);
|
||||
if (oid > 0) {
|
||||
if (!itemsMap.has(oid)) {
|
||||
itemsMap.set(oid, []);
|
||||
}
|
||||
itemsMap.get(oid).push(item);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
this.app.logger.warn(`[order_export] 批量查询订单商品明细失败: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 批量查询仓库商品名称、条码与图片(复用 getStockDetails 缓存)
|
||||
const stockNameMap = new Map();
|
||||
const barcodeMap = new Map();
|
||||
const imageUrlMap = new Map();
|
||||
if (itemsMap.size > 0 && this.ctx && this.ctx.model && this.ctx.model.StockWarehouse) {
|
||||
try {
|
||||
const stockIds = [
|
||||
...new Set(
|
||||
[ ...itemsMap.values() ]
|
||||
.flat()
|
||||
.map(item => Number(item.stock_id || 0))
|
||||
.filter(id => id > 0)
|
||||
),
|
||||
];
|
||||
if (stockIds.length > 0) {
|
||||
const stockDetails = await this.ctx.service.systems.stockWarehouse.getStockDetails(
|
||||
stockIds,
|
||||
{ warehouseId }
|
||||
);
|
||||
for (const detail of stockDetails) {
|
||||
const sid = Number(detail.id || 0);
|
||||
if (sid > 0) {
|
||||
stockNameMap.set(sid, String(detail.item_name || '').trim());
|
||||
// 从 getStockDetails 的 barcodes 中提取条码并转为逗号拼接
|
||||
const barcodesRaw = Array.isArray(detail.barcodes)
|
||||
? detail.barcodes.map(bc => String(bc.barcode || '').trim()).filter(Boolean)
|
||||
: [];
|
||||
if (barcodesRaw.length > 0) {
|
||||
barcodeMap.set(sid, [ ...new Set(barcodesRaw) ].join(', '));
|
||||
}
|
||||
// 图片字段(有图片标记但实际 URL 需要额外查询)
|
||||
if (detail.is_images === 'Y') {
|
||||
imageUrlMap.set(sid, '');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
this.app.logger.warn(`[order_export] 批量查询商品详情失败: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 批量查询货主备注(wms_store_warehouse.store_remask)
|
||||
const storeRemarkMap = new Map();
|
||||
if (orderIds.length > 0 && this.ctx && this.ctx.model && this.ctx.model.StoreWarehouse) {
|
||||
try {
|
||||
const storeIds = [
|
||||
...new Set(
|
||||
rowsWithWaveIndex
|
||||
.map(r => Number(r.store_id || 0))
|
||||
.filter(id => id > 0)
|
||||
),
|
||||
];
|
||||
if (storeIds.length > 0) {
|
||||
const swRows = await this.ctx.model.StoreWarehouse.findAll({
|
||||
where: {
|
||||
store_id: { [this.app.Sequelize.Op.in]: storeIds },
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
attributes: [ 'store_id', 'store_remask' ],
|
||||
raw: true,
|
||||
});
|
||||
for (const sw of (Array.isArray(swRows) ? swRows : [])) {
|
||||
const sid = Number(sw.store_id || 0);
|
||||
if (sid > 0 && !storeRemarkMap.has(sid)) {
|
||||
storeRemarkMap.set(sid, String(sw.store_remask || '').trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
this.app.logger.warn(`[order_export] 批量查询货主备注失败: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 批量查询运单数据(wms_order_express),按订单ID分组
|
||||
const expressMap = new Map();
|
||||
if (orderIds.length > 0 && this.ctx && this.ctx.model && this.ctx.model.OrderExpress) {
|
||||
try {
|
||||
const expressRows = await this.ctx.model.OrderExpress.findAll({
|
||||
where: {
|
||||
order_id: { [this.app.Sequelize.Op.in]: orderIds },
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
attributes: [ 'id', 'order_id', 'waybill_code', 'business_key', 'logistics_interface_name', 'package_material_id', 'package_material_name_snapshot', 'create_at', 'weighing_weight' ],
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
enqueueExportRows(pageResult.exportRows);
|
||||
currentCount += pageResult.orderCount;
|
||||
pagesCompleted += 1;
|
||||
await progressHandler({
|
||||
status: 'running',
|
||||
progress: Math.min(99, Math.max(5, Math.round((currentCount / Math.max(totalCount, 1)) * 90))),
|
||||
currentCount,
|
||||
totalCount,
|
||||
message: `已完成 ${currentCount}/${totalCount} 条订单查询(${pagesCompleted}/${totalPages} 页)`,
|
||||
});
|
||||
for (const exp of (Array.isArray(expressRows) ? expressRows : [])) {
|
||||
const oid = Number(exp.order_id || 0);
|
||||
if (oid > 0) {
|
||||
if (!expressMap.has(oid)) {
|
||||
expressMap.set(oid, []);
|
||||
}
|
||||
expressMap.get(oid).push(exp);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
this.app.logger.warn(`[order_export] 批量查询运单数据失败: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 批量查询包材编码(wms_package_material),按 package_material_id 分组
|
||||
const packageMaterialMap = new Map();
|
||||
if (expressMap.size > 0 && this.ctx && this.ctx.model && this.ctx.model.PackageMaterial) {
|
||||
try {
|
||||
const materialIds = [
|
||||
...new Set(
|
||||
[ ...expressMap.values() ]
|
||||
.flat()
|
||||
.map(exp => Number(exp.package_material_id || 0))
|
||||
.filter(id => id > 0)
|
||||
),
|
||||
];
|
||||
if (materialIds.length > 0) {
|
||||
const pmRows = await this.ctx.model.PackageMaterial.findAll({
|
||||
where: { id: { [this.app.Sequelize.Op.in]: materialIds } },
|
||||
attributes: [ 'id', 'material_code' ],
|
||||
raw: true,
|
||||
});
|
||||
for (const pm of (Array.isArray(pmRows) ? pmRows : [])) {
|
||||
const pid = Number(pm.id || 0);
|
||||
if (pid > 0 && !packageMaterialMap.has(pid)) {
|
||||
packageMaterialMap.set(pid, String(pm.material_code || '').trim());
|
||||
}
|
||||
}
|
||||
if (!firstError) {
|
||||
firstError = err;
|
||||
}
|
||||
} catch (err) {
|
||||
this.app.logger.warn(`[order_export] 批量查询包材编码失败: ${err.message}`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const exportContext = { itemsMap, storeRemarkMap, stockNameMap, barcodeMap, imageUrlMap, expressMap, packageMaterialMap };
|
||||
const workers = Array.from(
|
||||
{ length: Math.min(ORDER_EXPORT_QUERY_CONCURRENCY, totalPages) },
|
||||
() => runWorker()
|
||||
);
|
||||
|
||||
for (const row of rowsWithWaveIndex) {
|
||||
const exportRows = this.mapOrderExportRow(row, exportContext, mode);
|
||||
for (const exportRow of exportRows) {
|
||||
worksheet.addRow(exportRow).commit();
|
||||
}
|
||||
}
|
||||
await Promise.all(workers);
|
||||
finishExportQueue();
|
||||
await writerLoop;
|
||||
|
||||
currentCount += rowsWithWaveIndex.length;
|
||||
|
||||
await progressHandler({
|
||||
status: 'running',
|
||||
progress: Math.min(99, Math.max(5, Math.round((currentCount / Math.max(totalCount, 1)) * 90))),
|
||||
currentCount,
|
||||
totalCount,
|
||||
message: `正在导出第 ${page} 页,共 ${Math.ceil(totalCount / pageSize) || 1} 页`,
|
||||
});
|
||||
|
||||
page += 1;
|
||||
if (firstError) {
|
||||
throw firstError;
|
||||
}
|
||||
|
||||
worksheet.commit();
|
||||
currentWorksheet.commit();
|
||||
await workbook.commit();
|
||||
|
||||
const uploadResult = await this.uploadOrderExportFile({
|
||||
@ -905,6 +1127,7 @@ class OrderExportService extends OrderBaseService {
|
||||
module_name: target.defaultWhereModuleName || '',
|
||||
current_count: currentCount,
|
||||
total_count: totalCount,
|
||||
sheet_count: currentSheetIndex,
|
||||
};
|
||||
} catch (error) {
|
||||
const workbookStream = workbook.stream;
|
||||
|
||||
@ -832,10 +832,12 @@ class OrderStorageAllocationService extends MainService {
|
||||
as: 'locationType',
|
||||
required: true,
|
||||
attributes: [ 'id', 'type_code', 'type_name', 'allow_allocation', 'is_active' ],
|
||||
where: {
|
||||
allow_allocation: 1,
|
||||
is_active: 1,
|
||||
},
|
||||
...(allowStorageLocation ? {} : {
|
||||
where: {
|
||||
allow_allocation: 1,
|
||||
is_active: 1,
|
||||
},
|
||||
}),
|
||||
},
|
||||
],
|
||||
},
|
||||
@ -851,6 +853,7 @@ class OrderStorageAllocationService extends MainService {
|
||||
stockIdCount: stockIds.length,
|
||||
stockIdSample: stockIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT),
|
||||
storageRowCount: Array.isArray(storageRows) ? storageRows.length : 0,
|
||||
allowStorageLocation,
|
||||
});
|
||||
|
||||
const storageRowsByStockId = new Map();
|
||||
@ -1057,15 +1060,19 @@ class OrderStorageAllocationService extends MainService {
|
||||
});
|
||||
|
||||
if (candidateStorageRows.length === 0) {
|
||||
shortageDiagnostics = await diagnoseStorageTypeRestriction({
|
||||
ctx,
|
||||
Op,
|
||||
warehouseId,
|
||||
stockId,
|
||||
transaction,
|
||||
cache: shortageReasonCache,
|
||||
});
|
||||
shortageReason = String(shortageDiagnostics.reason || '').trim();
|
||||
shortageDiagnostics = allowStorageLocation
|
||||
? null
|
||||
: await diagnoseStorageTypeRestriction({
|
||||
ctx,
|
||||
Op,
|
||||
warehouseId,
|
||||
stockId,
|
||||
transaction,
|
||||
cache: shortageReasonCache,
|
||||
});
|
||||
shortageReason = shortageDiagnostics
|
||||
? String(shortageDiagnostics.reason || '').trim()
|
||||
: '';
|
||||
|
||||
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 无候选库位,标记缺货原因', {
|
||||
orderId,
|
||||
@ -2143,13 +2150,16 @@ class OrderStorageAllocationService extends MainService {
|
||||
};
|
||||
}
|
||||
|
||||
const transaction = await ctx.model.transaction();
|
||||
// 支持外部事务:由调用方(如取消订单流程)传入时复用,保证"取消+释放"原子生效
|
||||
const externalTransaction = data && data.transaction ? data.transaction : null;
|
||||
const transaction = externalTransaction || await ctx.model.transaction();
|
||||
const { Op } = app.Sequelize;
|
||||
const now = new Date();
|
||||
|
||||
writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 事务已创建', {
|
||||
warehouseId,
|
||||
orderIds,
|
||||
hasExternalTransaction: Boolean(externalTransaction),
|
||||
});
|
||||
|
||||
try {
|
||||
@ -2228,7 +2238,9 @@ class OrderStorageAllocationService extends MainService {
|
||||
});
|
||||
|
||||
if (eligibleOrderIds.length === 0) {
|
||||
await transaction.commit();
|
||||
if (!externalTransaction) {
|
||||
await transaction.commit();
|
||||
}
|
||||
return {
|
||||
code: 200,
|
||||
message: '没有需要取消分配的订单',
|
||||
@ -2307,7 +2319,9 @@ class OrderStorageAllocationService extends MainService {
|
||||
}
|
||||
|
||||
if (cancellableOrderIds.length === 0) {
|
||||
await transaction.commit();
|
||||
if (!externalTransaction) {
|
||||
await transaction.commit();
|
||||
}
|
||||
return {
|
||||
code: 200,
|
||||
message: '没有需要取消分配的订单',
|
||||
@ -2514,7 +2528,9 @@ class OrderStorageAllocationService extends MainService {
|
||||
stock_unlock_summary: [],
|
||||
};
|
||||
|
||||
await transaction.commit();
|
||||
if (!externalTransaction) {
|
||||
await transaction.commit();
|
||||
}
|
||||
|
||||
writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 事务提交完成', {
|
||||
warehouseId,
|
||||
@ -2529,17 +2545,19 @@ class OrderStorageAllocationService extends MainService {
|
||||
data: responseData,
|
||||
};
|
||||
} catch (error) {
|
||||
writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 发生异常,准备回滚事务', {
|
||||
warehouseId,
|
||||
orderIds,
|
||||
error,
|
||||
});
|
||||
await transaction.rollback();
|
||||
writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 事务回滚完成', {
|
||||
warehouseId,
|
||||
orderIds,
|
||||
error,
|
||||
});
|
||||
if (!externalTransaction) {
|
||||
writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 发生异常,准备回滚事务', {
|
||||
warehouseId,
|
||||
orderIds,
|
||||
error,
|
||||
});
|
||||
await transaction.rollback();
|
||||
writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 事务回滚完成', {
|
||||
warehouseId,
|
||||
orderIds,
|
||||
error,
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@ -98,6 +98,35 @@ class ReturnReceivedService extends Service {
|
||||
ctx.logger.warn(`[returnReceived.create] 反查原运单失败: ${err.message}`);
|
||||
}
|
||||
|
||||
// 非原单退回:匹配货主登记表(wms_return_query_log,货主查询/登记过退回的运单),把件归属到对应货主
|
||||
// 兼容一单多件分段单号:精确 + 剥尾段 + 前缀段
|
||||
if (!orderExpressId && !storeId) {
|
||||
try {
|
||||
const base = waybillCode.replace(/(?:-\d+){2,}-?$/, '');
|
||||
const queryLog = await ctx.model.ReturnQueryLog.findOne({
|
||||
where: {
|
||||
warehouse_id: warehouseId,
|
||||
store_id: { [Op.gt]: 0 },
|
||||
[Op.or]: [
|
||||
{ waybill_code: waybillCode },
|
||||
...(base !== waybillCode ? [{ waybill_code: base }] : []),
|
||||
{ waybill_code: { [Op.like]: `${base}-%` } },
|
||||
],
|
||||
},
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
raw: true,
|
||||
});
|
||||
if (queryLog && Number(queryLog.store_id) > 0) {
|
||||
storeId = Number(queryLog.store_id);
|
||||
ctx.logger.info(
|
||||
`[returnReceived.create] 匹配货主登记表归属: ${waybillCode} -> store_id=${storeId}`
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[returnReceived.create] 匹配货主登记表失败: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
const created = await ctx.model.ReturnReceived.create({
|
||||
warehouse_id: warehouseId,
|
||||
waybill_code: waybillCode,
|
||||
@ -132,6 +161,9 @@ class ReturnReceivedService extends Service {
|
||||
|
||||
const createdRow = created && typeof created.toJSON === 'function' ? created.toJSON() : created;
|
||||
const enriched = await this._enrichReturn(createdRow);
|
||||
|
||||
// 通知不在此处即时发送:由定时任务聚合(等 delayMs 无新登记后,按货主合并推送,只对货主查退回时登记过的运单通知)
|
||||
|
||||
return {
|
||||
record: enriched,
|
||||
is_original_return: Boolean(enriched.order_express_id),
|
||||
@ -140,6 +172,125 @@ class ReturnReceivedService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 聚合通知待通知的登记(定时任务调用)。
|
||||
* 规则:
|
||||
* 1. 只通知登记时间早于阈值(默认 5 分钟)的登记,等待新登记防抖合并;
|
||||
* 2. 只对货主在退回查询登记表(wms_return_query_log)登记过的运单通知;
|
||||
* 3. 按 仓库+货主 分组,合并成一条消息推送到货主售后群;
|
||||
* 4. 推送后标记 is_notified=1,不重复通知。
|
||||
*
|
||||
* @param {Object} [opts] 可选参数。
|
||||
* @param {number} [opts.delayMs] 防抖窗口毫秒数,不传用 config.inbox.returnReceivedNotifyDelayMs(默认 5 分钟)。
|
||||
* @return {Promise<Object>} { notified, skipped }。
|
||||
*/
|
||||
async notifyPending(opts = {}) {
|
||||
const { ctx, app } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
|
||||
const delayNum = Number(opts.delayMs);
|
||||
const delayMs = Number.isFinite(delayNum) && delayNum >= 0
|
||||
? delayNum
|
||||
: (Number(app.config.inbox?.returnReceivedNotifyDelayMs) || 5 * 60 * 1000);
|
||||
const before = new Date(Date.now() - delayMs);
|
||||
|
||||
// 待通知登记:已过防抖窗口、有货主、未通知
|
||||
const rows = await ctx.model.ReturnReceived.findAll({
|
||||
attributes: [ 'id', 'warehouse_id', 'waybill_code', 'store_id' ],
|
||||
where: {
|
||||
is_notified: 0,
|
||||
store_id: { [Op.gt]: 0 },
|
||||
created_at: { [Op.lte]: before },
|
||||
},
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
limit: 200,
|
||||
raw: true,
|
||||
});
|
||||
if (rows.length === 0) {
|
||||
return { notified: 0, skipped: 0 };
|
||||
}
|
||||
|
||||
// 过滤:只对货主查退回时登记过的运单通知(匹配货主登记表,兼容分段单号)
|
||||
const candidates = [];
|
||||
for (const row of rows) {
|
||||
const base = String(row.waybill_code || '').replace(/(?:-\d+){2,}-?$/, '');
|
||||
try {
|
||||
const log = await ctx.model.ReturnQueryLog.findOne({
|
||||
attributes: [ 'id' ],
|
||||
where: {
|
||||
warehouse_id: row.warehouse_id,
|
||||
[Op.or]: [
|
||||
{ waybill_code: row.waybill_code },
|
||||
...(base && base !== row.waybill_code ? [{ waybill_code: base }] : []),
|
||||
...(base ? [{ waybill_code: { [Op.like]: `${base}-%` } }] : []),
|
||||
],
|
||||
},
|
||||
raw: true,
|
||||
});
|
||||
if (log) candidates.push(row);
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[returnReceived.notifyPending] 查货主登记表失败 ${row.waybill_code}: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
const skipped = rows.length - candidates.length;
|
||||
if (candidates.length === 0) {
|
||||
return { notified: 0, skipped };
|
||||
}
|
||||
|
||||
// 按 仓库+货主 分组聚合
|
||||
const buckets = new Map();
|
||||
for (const row of candidates) {
|
||||
const key = `${row.warehouse_id}:${row.store_id}`;
|
||||
if (!buckets.has(key)) {
|
||||
buckets.set(key, { warehouse_id: row.warehouse_id, store_id: row.store_id, ids: [], waybills: [] });
|
||||
}
|
||||
const bucket = buckets.get(key);
|
||||
bucket.ids.push(row.id);
|
||||
bucket.waybills.push(row.waybill_code);
|
||||
}
|
||||
|
||||
let notified = 0;
|
||||
for (const bucket of buckets.values()) {
|
||||
try {
|
||||
const groups = await ctx.service.systems.inbox.group.findStoreAfterSalesGroups({
|
||||
storeIds: [ bucket.store_id ],
|
||||
warehouseId: bucket.warehouse_id,
|
||||
});
|
||||
if (groups.length === 0) {
|
||||
ctx.logger.info(
|
||||
`[returnReceived.notifyPending] 未找到货主售后群 warehouse=${bucket.warehouse_id} store=${bucket.store_id}`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const content = `退回包裹已扫描登记:\n${bucket.waybills.join('\n')}\n仓库将安排拆包,拆包完成后将自动通知拆包明细`;
|
||||
for (const g of groups) {
|
||||
ctx.service.inbox.processor.pushSystemNotification({
|
||||
warehouse_id: bucket.warehouse_id,
|
||||
group_id: g.group_id,
|
||||
group_name: g.group_name,
|
||||
content,
|
||||
ext_data: g.ext_data || null,
|
||||
store_id: g.store_id || null,
|
||||
});
|
||||
}
|
||||
await ctx.model.ReturnReceived.update(
|
||||
{ is_notified: 1 },
|
||||
{ where: { id: { [Op.in]: bucket.ids } } }
|
||||
);
|
||||
notified += bucket.ids.length;
|
||||
ctx.logger.info(
|
||||
`[returnReceived.notifyPending] 聚合通知 warehouse=${bucket.warehouse_id} store=${bucket.store_id} ` +
|
||||
`groups=${groups.length} count=${bucket.ids.length} waybills=${bucket.waybills.join(',')}`
|
||||
);
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[returnReceived.notifyPending] 通知失败: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
return { notified, skipped };
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理退回运单关联的未完结拦截工单(写入「退回包裹已收到」并完结)。
|
||||
* 仅更新工单状态,不处理库存信息(参考库内拦截 interceptScan 的工单处理部分)。
|
||||
|
||||
@ -528,16 +528,20 @@ class ReturnUnpackService extends Service {
|
||||
{ where: { id: unpack.id } }
|
||||
);
|
||||
|
||||
// 同步更新退回查询记录:按 warehouse_id + waybill_code 反查命中则 is_back=1
|
||||
// 同步更新退回查询记录:按 warehouse_id + 运单号(兼容分段单号)反查命中则 is_back=1
|
||||
const { Op } = ctx.app.Sequelize;
|
||||
try {
|
||||
await ctx.model.ReturnQueryLog.update(
|
||||
{ is_back: 1 },
|
||||
{ where: { warehouse_id: unpack.warehouse_id, waybill_code: unpack.waybill_code } }
|
||||
{ where: { warehouse_id: unpack.warehouse_id, [Op.or]: this._buildWaybillMatch(unpack.waybill_code) } }
|
||||
);
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[returnUnpack.submit] 更新退回查询记录 is_back 失败: ${err.message}`);
|
||||
}
|
||||
|
||||
// 拆包完成后通知货主群:登记表/拆包单有货主归属且未通知的,推送到货主售后群并标记 is_notified=1
|
||||
await this._notifyUnpacked(unpack);
|
||||
|
||||
const updated = await ctx.model.ReturnUnpack.findOne({
|
||||
where: { id: unpack.id },
|
||||
raw: true,
|
||||
@ -548,6 +552,91 @@ class ReturnUnpackService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 拆包完成后通知货主群。
|
||||
* 通知集合:仅退回查询登记表中该运单已退回(is_back=1)且未通知(is_notified=0)、有货主归属的记录;
|
||||
* 货主从未查询过退回(登记表无匹配)的不通知。推送成功后标记 is_notified=1。
|
||||
*
|
||||
* @param {Object} unpack 拆包单主表记录
|
||||
* @return {Promise<void>} 异常仅记日志不阻塞主流程
|
||||
*/
|
||||
async _notifyUnpacked(unpack) {
|
||||
const { ctx } = this;
|
||||
const { Op } = ctx.app.Sequelize;
|
||||
const warehouseId = Number(unpack.warehouse_id || 0);
|
||||
try {
|
||||
const logs = await ctx.model.ReturnQueryLog.findAll({
|
||||
attributes: [ 'id', 'store_id', 'waybill_code' ],
|
||||
where: {
|
||||
warehouse_id: warehouseId,
|
||||
[Op.or]: this._buildWaybillMatch(unpack.waybill_code),
|
||||
is_back: 1,
|
||||
is_notified: 0,
|
||||
},
|
||||
raw: true,
|
||||
});
|
||||
|
||||
// 通知对象:store_id → 运单号集合(仅货主查询过退回的登记,store_id 必须有归属)
|
||||
const notifyMap = new Map();
|
||||
for (const log of logs) {
|
||||
const sid = Number(log.store_id || 0);
|
||||
if (sid <= 0) continue;
|
||||
if (!notifyMap.has(sid)) notifyMap.set(sid, new Set());
|
||||
notifyMap.get(sid).add(log.waybill_code || unpack.waybill_code);
|
||||
}
|
||||
|
||||
if (notifyMap.size === 0) {
|
||||
ctx.logger.info(
|
||||
`[returnUnpack._notifyUnpacked] 无货主查询过退回的登记,跳过通知 waybill=${unpack.waybill_code}`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// 查货主售后群
|
||||
const storeIds = [ ...notifyMap.keys() ];
|
||||
const groups = await ctx.service.systems.inbox.group.findStoreAfterSalesGroups({
|
||||
storeIds,
|
||||
warehouseId,
|
||||
});
|
||||
if (groups.length === 0) {
|
||||
ctx.logger.info(
|
||||
`[returnUnpack._notifyUnpacked] 未找到货主售后群,跳过通知 storeIds=${storeIds.join(',')}`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// 按群推送(一条消息含该货主的全部运单)
|
||||
for (const g of groups) {
|
||||
const waybills = [ ...(notifyMap.get(Number(g.store_id)) || new Set()) ];
|
||||
if (waybills.length === 0) continue;
|
||||
const content = `退回包裹已拆包完成:\n${waybills.join('\n')}\n发送:查退回+运单号,可查看拆包明细`;
|
||||
ctx.service.inbox.processor.pushSystemNotification({
|
||||
warehouse_id: warehouseId,
|
||||
group_id: g.group_id,
|
||||
group_name: g.group_name,
|
||||
content,
|
||||
ext_data: g.ext_data || null,
|
||||
store_id: g.store_id || null,
|
||||
});
|
||||
}
|
||||
|
||||
// 标记已通知
|
||||
const notifiedIds = logs.map(l => l.id);
|
||||
if (notifiedIds.length > 0) {
|
||||
await ctx.model.ReturnQueryLog.update(
|
||||
{ is_notified: 1 },
|
||||
{ where: { id: { [Op.in]: notifiedIds } } }
|
||||
);
|
||||
}
|
||||
ctx.logger.info(
|
||||
`[returnUnpack._notifyUnpacked] 拆包通知完成 waybill=${unpack.waybill_code} ` +
|
||||
`groups=${groups.length} logs=${notifiedIds.length}`
|
||||
);
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[returnUnpack._notifyUnpacked] 拆包通知失败: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 强制重新录制拆包视频:重置视频记录状态并推送打印服务强制录制。
|
||||
* 参考 order.packing.forceRecord:校验仓库录制电脑在线后,将视频记录重置为
|
||||
@ -889,6 +978,51 @@ class ReturnUnpackService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建运单号灵活匹配条件:精确单号 + 剥尾段单号 + 前缀段单号。
|
||||
* 兼容京东等一单多件的分段单号(如 JDX057904621547-1-1- 与 JDX057904621547 互相匹配)。
|
||||
* @param {string} waybillCode 运单号
|
||||
* @return {Array<Object>} Sequelize Op.or 条件数组
|
||||
*/
|
||||
_buildWaybillMatch(waybillCode) {
|
||||
const { Op } = this.app.Sequelize;
|
||||
const code = String(waybillCode || '').trim();
|
||||
// 剥掉尾部多段数字段(一单多件格式:-包裹序号-总件数[-])
|
||||
const base = code.replace(/(?:-\d+){2,}-?$/, '');
|
||||
// 转义 like 通配符,避免输入中的 % _ 扩大匹配范围
|
||||
const escapedBase = String(base || '').replace(/[%_\\]/g, m => `\\${m}`);
|
||||
const or = [{ waybill_code: code }];
|
||||
if (base && base !== code) or.push({ waybill_code: base });
|
||||
if (escapedBase) or.push({ waybill_code: { [Op.like]: `${escapedBase}-%` } });
|
||||
return or;
|
||||
}
|
||||
|
||||
/**
|
||||
* 运单号灵活查询:精确单号优先,其次剥尾段单号,再次前缀段。
|
||||
* @param {Object} model Sequelize 模型
|
||||
* @param {Object} extraWhere 额外查询条件
|
||||
* @param {string} waybillCode 运单号
|
||||
* @param {string[]} [attributes] 返回字段
|
||||
* @param {Array<Array>} [order] 排序(默认 created_at DESC, id DESC)
|
||||
* @return {Promise<Object|null>} 命中的行,未命中返回 null
|
||||
*/
|
||||
async _findWaybillFlexible(model, extraWhere, waybillCode, attributes, order) {
|
||||
const { Op } = this.app.Sequelize;
|
||||
const code = String(waybillCode || '').trim();
|
||||
const base = code.replace(/(?:-\d+){2,}-?$/, '');
|
||||
const options = {
|
||||
where: { ...extraWhere, [Op.or]: this._buildWaybillMatch(code) },
|
||||
order: order && order.length > 0 ? order : [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]],
|
||||
limit: 5,
|
||||
raw: true,
|
||||
};
|
||||
if (Array.isArray(attributes) && attributes.length > 0) options.attributes = attributes;
|
||||
const rows = await model.findAll(options);
|
||||
if (!rows || rows.length === 0) return null;
|
||||
const rank = row => (row.waybill_code === code ? 0 : (row.waybill_code === base ? 1 : 2));
|
||||
return rows.slice().sort((a, b) => rank(a) - rank(b))[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询退回明细(按运单号,跨退回相关表汇总)。
|
||||
* 依次查询:拆包主表+明细+视频(已拆包)→ 退回收到表(已收到未拆包)→ 退回查询登记表(未退回)。
|
||||
@ -919,15 +1053,12 @@ class ReturnUnpackService extends Service {
|
||||
const warehouseName = await this._resolveWarehouseName(warehouseId);
|
||||
|
||||
// 1. 已拆包:同一运单号取最新一条有效拆包单(跳过已作废)
|
||||
const unpack = await ctx.model.ReturnUnpack.findOne({
|
||||
where: {
|
||||
warehouse_id: warehouseId,
|
||||
waybill_code: waybillCode,
|
||||
status: { [Op.ne]: 'cancelled' },
|
||||
},
|
||||
order: [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]],
|
||||
raw: true,
|
||||
});
|
||||
// 兼容一单多件分段单号:JDX057904621547 可命中 JDX057904621547-1-1-
|
||||
const unpack = await this._findWaybillFlexible(
|
||||
ctx.model.ReturnUnpack,
|
||||
{ warehouse_id: warehouseId, status: { [Op.ne]: 'cancelled' } },
|
||||
waybillCode
|
||||
);
|
||||
|
||||
if (unpack) {
|
||||
// 货主隔离:限定货主查询且拆包单已归属其他货主 → 不暴露数据
|
||||
@ -982,12 +1113,12 @@ class ReturnUnpackService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
// 2. 已收到未拆包:退回收到表登记过
|
||||
const received = await ctx.model.ReturnReceived.findOne({
|
||||
where: { warehouse_id: warehouseId, waybill_code: waybillCode },
|
||||
order: [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]],
|
||||
raw: true,
|
||||
});
|
||||
// 2. 已收到未拆包:退回收到表登记过(兼容分段单号)
|
||||
const received = await this._findWaybillFlexible(
|
||||
ctx.model.ReturnReceived,
|
||||
{ warehouse_id: warehouseId },
|
||||
waybillCode
|
||||
);
|
||||
|
||||
if (received) {
|
||||
if (storeId > 0 && Number(received.store_id || 0) > 0 && Number(received.store_id) !== storeId) {
|
||||
@ -1056,11 +1187,11 @@ class ReturnUnpackService extends Service {
|
||||
}
|
||||
|
||||
// 3. 未退回:查询退回查询登记表,无登记则自动登记(等待拆包后处理)
|
||||
const queryLog = await ctx.model.ReturnQueryLog.findOne({
|
||||
where: { warehouse_id: warehouseId, waybill_code: waybillCode },
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
raw: true,
|
||||
});
|
||||
const queryLog = await this._findWaybillFlexible(
|
||||
ctx.model.ReturnQueryLog,
|
||||
{ warehouse_id: warehouseId },
|
||||
waybillCode
|
||||
);
|
||||
|
||||
if (queryLog) {
|
||||
return {
|
||||
@ -1143,11 +1274,14 @@ class ReturnUnpackService extends Service {
|
||||
async _resolveStoreIdByWaybill(waybillCode, warehouseId) {
|
||||
const { ctx } = this;
|
||||
try {
|
||||
const express = await ctx.model.OrderExpress.findOne({
|
||||
where: { waybill_code: waybillCode, warehouse_id: warehouseId },
|
||||
attributes: [ 'store_id' ],
|
||||
raw: true,
|
||||
});
|
||||
// 兼容一单多件分段单号(京东 JDX...-1-1- 等)
|
||||
const express = await this._findWaybillFlexible(
|
||||
ctx.model.OrderExpress,
|
||||
{ warehouse_id: warehouseId },
|
||||
waybillCode,
|
||||
[ 'store_id', 'waybill_code' ],
|
||||
[[ 'id', 'DESC' ]]
|
||||
);
|
||||
return express && Number(express.store_id) > 0 ? Number(express.store_id) : 0;
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`[returnUnpack._resolveStoreIdByWaybill] 反查货主失败: ${err.message}`);
|
||||
|
||||
@ -576,7 +576,9 @@ class EntryService extends Service {
|
||||
* @param {number} data.id 入库单主键 ID(必填)
|
||||
* @param {string} [mode='warehouse'] 查询维度:'warehouse' 按仓库校验权限(默认),'store' 按货主校验权限
|
||||
* @return {Promise<Object>} code/data/message 结构
|
||||
* - data.entryOrder: { id, entry_order_code, order_status, store_remask }
|
||||
* - data.entryOrder: { id, entry_order_code, order_status, total_order_lines, store_remask }
|
||||
* - data.total_quantity: 应入库总数量(明细 planned 之和)
|
||||
* - data.received_quantity: 已入库总数量(明细 completed 之和)
|
||||
* - data.items: [{ id, stock_id, planned, completed, stock, bindings }]
|
||||
* - data.receivingBindings: [{ id, receiving_id, receiving }]
|
||||
*/
|
||||
@ -827,8 +829,11 @@ class EntryService extends Service {
|
||||
id: entryOrder.id,
|
||||
entry_order_code: entryOrder.entry_order_code,
|
||||
order_status: entryOrder.order_status,
|
||||
total_order_lines: entryOrder.total_order_lines,
|
||||
store_remask: (storeWarehouse && storeWarehouse.store_remask) || '',
|
||||
},
|
||||
total_quantity: items.reduce((sum, item) => sum + (Number(item.planned) || 0), 0),
|
||||
received_quantity: items.reduce((sum, item) => sum + (Number(item.completed) || 0), 0),
|
||||
items,
|
||||
receivingBindings,
|
||||
},
|
||||
@ -1411,7 +1416,107 @@ class EntryService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 快捷直入/虚拟入库:将入库单的所有商品按明细数量全部直入到虚拟库位(space_id=2),跳过收货、质检等正常流程。
|
||||
* 快捷直入后回写绑定收货单的明细已入库数量与入库状态(事务内)。
|
||||
* 按 stock_id(=收货明细 system_product_id)把本次入库量依次分配到收货明细上,
|
||||
* 每个明细最多分配其剩余可入数量(actual_quantity - stored_quantity),
|
||||
* 分配后更新明细 stored_quantity/storage_status,并按各明细实际入库量
|
||||
* (stored_quantity 与 actual_quantity 比较)汇总更新收货单主表 storage_status:
|
||||
* 全部明细均已足量入库才置 all,否则有部分入库置 partial,全部未入库置 none。
|
||||
* @param {Object} params 参数
|
||||
* @param {Array<Object>} params.receivingDetailRows 收货明细快照 [{ id, receiving_id, system_product_id, actual_quantity, stored_quantity }]
|
||||
* @param {Map<number, {inboundQty: number}>} params.stockInboundQtyMap stock_id -> 本次入库量
|
||||
* @param {Object} params.transaction Sequelize 事务对象
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async _applyReceivingInboundUsage({ receivingDetailRows, stockInboundQtyMap, transaction }) {
|
||||
const { ctx, app } = this;
|
||||
|
||||
if (!receivingDetailRows || receivingDetailRows.length === 0) return;
|
||||
|
||||
// 1. 事务内行锁重新读取收货明细,避免并发超额分配
|
||||
const detailIds = receivingDetailRows.map(d => d.id);
|
||||
const lockedDetails = await ctx.model.ReceivingDetail.findAll({
|
||||
where: { id: { [app.Sequelize.Op.in]: detailIds } },
|
||||
lock: transaction.LOCK.UPDATE,
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
transaction,
|
||||
raw: true,
|
||||
});
|
||||
|
||||
// 2. 按 system_product_id(=stock_id)分组,同一商品多条明细按 id 升序依次分配
|
||||
const detailsByStock = new Map();
|
||||
for (const d of lockedDetails) {
|
||||
const spid = Number(d.system_product_id);
|
||||
if (!spid) continue;
|
||||
if (!detailsByStock.has(spid)) detailsByStock.set(spid, []);
|
||||
detailsByStock.get(spid).push(d);
|
||||
}
|
||||
|
||||
const touchedReceivingIds = new Set();
|
||||
|
||||
// 3. 逐商品分配本次入库量:使用了多少就写多少
|
||||
for (const [ stockId, plan ] of stockInboundQtyMap) {
|
||||
let left = Number(plan.inboundQty) || 0;
|
||||
const details = detailsByStock.get(Number(stockId)) || [];
|
||||
for (const detail of details) {
|
||||
if (left <= 0) break;
|
||||
const actual = Number(detail.actual_quantity) || 0;
|
||||
const stored = Number(detail.stored_quantity) || 0;
|
||||
const remain = Math.max(0, actual - stored);
|
||||
if (remain <= 0) continue;
|
||||
const delta = Math.min(left, remain);
|
||||
const newStored = stored + delta;
|
||||
const storageStatus = newStored >= actual ? 'all' : 'partial';
|
||||
await ctx.model.ReceivingDetail.update({
|
||||
stored_quantity: newStored,
|
||||
storage_status: storageStatus,
|
||||
updated_at: new Date(),
|
||||
}, {
|
||||
where: { id: detail.id },
|
||||
transaction,
|
||||
});
|
||||
touchedReceivingIds.add(Number(detail.receiving_id));
|
||||
left -= delta;
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 按实际入库量汇总更新收货单主表 storage_status:
|
||||
// 全部明细均已足量入库(stored >= actual)→ all;存在部分入库 → partial;全部未入库 → none
|
||||
for (const receivingId of touchedReceivingIds) {
|
||||
const allDetails = await ctx.model.ReceivingDetail.findAll({
|
||||
where: { receiving_id: receivingId },
|
||||
attributes: [ 'actual_quantity', 'stored_quantity' ],
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
|
||||
let masterStatus = 'none';
|
||||
const fullyStored = allDetails.length > 0
|
||||
&& allDetails.every(d => (Number(d.stored_quantity) || 0) >= (Number(d.actual_quantity) || 0));
|
||||
if (fullyStored) {
|
||||
masterStatus = 'all';
|
||||
} else if (allDetails.some(d => (Number(d.stored_quantity) || 0) > 0)) {
|
||||
masterStatus = 'partial';
|
||||
}
|
||||
|
||||
await ctx.model.Receiving.update({
|
||||
storage_status: masterStatus,
|
||||
updated_at: new Date(),
|
||||
}, {
|
||||
where: { id: receivingId },
|
||||
transaction,
|
||||
});
|
||||
}
|
||||
|
||||
ctx.logger.info(
|
||||
`[storage.entry] 已回写收货单入库状态,receivingIds=[${[ ...touchedReceivingIds ].join(',')}]`
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 快捷直入/虚拟入库:将入库单明细直入到虚拟库位(space_id=2),跳过收货、质检等正常流程。
|
||||
* 有绑定收货单时,只取收货单中与入库单明细有交集(按 stock_id 判断)且剩余可入数量的部分直入,
|
||||
* 并回写收货单明细已入库数量;未绑定收货单时按明细计划数量全量直入。
|
||||
* 采用"先同步后写库"两段式:① 先发奇门/OpenAPI 回传,② 回传成功后再开启事务写库存。
|
||||
* @param {Object} data 请求体
|
||||
* @param {number} data.id 入库单ID
|
||||
@ -1474,18 +1579,79 @@ class EntryService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
// 2.1 查询绑定收货单("已绑定"状态),按 stock_id 聚合收货明细剩余可入数量
|
||||
const bindings = await ctx.model.EntryOrderReceiving.findAll({
|
||||
where: { entry_order_id: entryOrder.id, deleted_at: null },
|
||||
attributes: [ 'receiving_id' ],
|
||||
raw: true,
|
||||
});
|
||||
const receivingIds = [ ...new Set((bindings || []).map(b => Number(b.receiving_id)).filter(Boolean)) ];
|
||||
|
||||
// 收货明细快照(用于事务内行锁回写),stockRemainingMap: null=未绑定(全量直入)
|
||||
let receivingDetailsSnapshot = [];
|
||||
let stockRemainingMap = null;
|
||||
if (receivingIds.length > 0) {
|
||||
const boundDetails = await ctx.model.ReceivingDetail.findAll({
|
||||
where: {
|
||||
receiving_id: { [app.Sequelize.Op.in]: receivingIds },
|
||||
system_product_id: { [app.Sequelize.Op.ne]: null },
|
||||
},
|
||||
attributes: [ 'id', 'receiving_id', 'system_product_id', 'actual_quantity', 'stored_quantity' ],
|
||||
raw: true,
|
||||
});
|
||||
receivingDetailsSnapshot = boundDetails;
|
||||
stockRemainingMap = new Map();
|
||||
for (const d of boundDetails) {
|
||||
const spid = Number(d.system_product_id);
|
||||
const remaining = Math.max(0, (Number(d.actual_quantity) || 0) - (Number(d.stored_quantity) || 0));
|
||||
stockRemainingMap.set(spid, (stockRemainingMap.get(spid) || 0) + remaining);
|
||||
}
|
||||
}
|
||||
|
||||
// 2.2 按入库单明细计算实际直入数量:有绑定时只取收货单中有交集(stock_id)且剩余可入的数量
|
||||
const inboundPlans = entryItems.map(item => {
|
||||
const planQty = Number(item.count) || 0;
|
||||
let inboundQty = planQty;
|
||||
if (stockRemainingMap) {
|
||||
const stockId = Number(item.stock_id) || 0;
|
||||
if (!stockId || !stockRemainingMap.has(stockId)) {
|
||||
inboundQty = 0; // 收货单无交集商品,跳过
|
||||
} else {
|
||||
const remaining = stockRemainingMap.get(stockId) || 0;
|
||||
inboundQty = Math.min(planQty, remaining);
|
||||
stockRemainingMap.set(stockId, remaining - inboundQty);
|
||||
}
|
||||
}
|
||||
return { item, planQty, inboundQty };
|
||||
});
|
||||
|
||||
const effectivePlans = inboundPlans.filter(p => p.inboundQty > 0);
|
||||
if (effectivePlans.length === 0) {
|
||||
return {
|
||||
code: 400,
|
||||
message: stockRemainingMap
|
||||
? '收货单中无交集商品或剩余可入数量不足,无法快捷直入'
|
||||
: '入库明细数量均为0,无法快捷直入',
|
||||
data: { id: entryOrder.id, entry_order_code: entryOrder.entry_order_code },
|
||||
};
|
||||
}
|
||||
|
||||
// 存在被截断/跳过的明细时按部分入库回传(confirmType=1, PARTFULFILLED)
|
||||
const isPartialInbound = inboundPlans.some(p => p.inboundQty < p.planQty);
|
||||
|
||||
// ===== 阶段一 + 阶段二合并为统一调用 =====
|
||||
const syncResult = await ctx.service.systems.inboundDirectLog.qimenEntrySync({
|
||||
entryOrder,
|
||||
orderLines: entryItems.map((item, idx) => ({
|
||||
orderLines: effectivePlans.map((plan, idx) => ({
|
||||
orderLineNo: idx + 1,
|
||||
ownerCode: item.owner_code || '',
|
||||
itemCode: item.item_code || '',
|
||||
itemId: item.item_id || '',
|
||||
inventoryType: item.inventory_type || 'ZP',
|
||||
planQty: Number(item.count) || 0,
|
||||
actualQty: Number(item.count) || 0,
|
||||
ownerCode: plan.item.owner_code || '',
|
||||
itemCode: plan.item.item_code || '',
|
||||
itemId: plan.item.item_id || '',
|
||||
inventoryType: plan.item.inventory_type || 'ZP',
|
||||
planQty: plan.planQty,
|
||||
actualQty: plan.inboundQty,
|
||||
})),
|
||||
isFin: !isPartialInbound,
|
||||
outBizCode: `DIRECT_INBOUND_${Date.now()}`,
|
||||
remark: '导入/PDA直接入库提交',
|
||||
operator: {
|
||||
@ -1501,27 +1667,39 @@ class EntryService extends Service {
|
||||
|
||||
const processedStockIds = new Set();
|
||||
let totalInboundQty = 0;
|
||||
let totalPlanQty = 0;
|
||||
|
||||
// 按 stock_id 汇总本次实际入库量与库存类型(有绑定收货单时实际入库量 ≤ 计划量)
|
||||
const stockPlanMap = new Map();
|
||||
for (const plan of inboundPlans) {
|
||||
totalPlanQty += plan.planQty;
|
||||
if (plan.inboundQty <= 0) continue;
|
||||
const stockId = Number(plan.item.stock_id);
|
||||
if (!stockId) continue;
|
||||
const cur = stockPlanMap.get(stockId) || { inboundQty: 0, inventoryType: plan.item.inventory_type || 'ZP' };
|
||||
cur.inboundQty += plan.inboundQty;
|
||||
stockPlanMap.set(stockId, cur);
|
||||
totalInboundQty += plan.inboundQty;
|
||||
}
|
||||
|
||||
if (totalInboundQty <= 0) {
|
||||
throw new Error('无有效可入明细,快捷直入失败');
|
||||
}
|
||||
|
||||
try {
|
||||
for (const item of entryItems) {
|
||||
const stockId = item.stock_id;
|
||||
if (!stockId) continue;
|
||||
|
||||
const planQty = Number(item.count) || 0;
|
||||
if (planQty <= 0) continue;
|
||||
|
||||
const inventoryType = item.inventory_type || 'ZP';
|
||||
|
||||
// 回写入库单明细:本次实际入库多少写多少(跳过明细写 0)
|
||||
for (const plan of inboundPlans) {
|
||||
await ctx.model.EntryItems.update({
|
||||
received_quantity: planQty,
|
||||
received_quantity: plan.inboundQty,
|
||||
}, {
|
||||
where: { id: item.id },
|
||||
where: { id: plan.item.id },
|
||||
transaction,
|
||||
});
|
||||
}
|
||||
|
||||
if (processedStockIds.has(String(stockId))) continue;
|
||||
processedStockIds.add(String(stockId));
|
||||
totalInboundQty += planQty;
|
||||
for (const [ stockId, plan ] of stockPlanMap) {
|
||||
const planQty = plan.inboundQty;
|
||||
const inventoryType = plan.inventoryType;
|
||||
|
||||
const stockRecord = await ctx.model.StockWarehouse.findOne({
|
||||
where: { id: stockId, is_valid: 'Y', deleted_at: null },
|
||||
@ -1653,12 +1831,22 @@ class EntryService extends Service {
|
||||
}, { transaction });
|
||||
}
|
||||
|
||||
// 回写绑定收货单明细已入库数量与入库状态(有绑定收货单时)
|
||||
if (receivingDetailsSnapshot.length > 0) {
|
||||
await this._applyReceivingInboundUsage({
|
||||
receivingDetailRows: receivingDetailsSnapshot,
|
||||
stockInboundQtyMap: stockPlanMap,
|
||||
transaction,
|
||||
});
|
||||
}
|
||||
|
||||
await eo.update({
|
||||
order_status: 'COMPLETED',
|
||||
sync_status: 'SUCCESS',
|
||||
sync_message: JSON.stringify({
|
||||
completedAt: new Date(),
|
||||
totalQuantity: totalInboundQty,
|
||||
planQuantity: totalPlanQty,
|
||||
itemCount: processedStockIds.size,
|
||||
source: 'quick_inbound',
|
||||
}),
|
||||
@ -1710,8 +1898,9 @@ class EntryService extends Service {
|
||||
entry_order_code: entryOrder.entry_order_code,
|
||||
order_status: 'COMPLETED',
|
||||
sync_status: 'SUCCESS',
|
||||
items_count: entryItems.length,
|
||||
total_quantity: entryItems.reduce((s, item) => s + (Number(item.count) || 0), 0),
|
||||
items_count: effectivePlans.length,
|
||||
total_quantity: effectivePlans.reduce((s, p) => s + p.inboundQty, 0),
|
||||
plan_quantity: entryItems.reduce((s, item) => s + (Number(item.count) || 0), 0),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@ -54,12 +54,17 @@ class StorageManagementService extends Service {
|
||||
* @param {Object} [options.sort] 排序参数。
|
||||
* @param {string} [options.sort.sortField='shortage'] 排序字段,默认 shortage。
|
||||
* @param {string} [options.sort.sortOrder='DESC'] 排序方向,ASC/DESC。
|
||||
* @param {number[]} [options.storeIds] 货主筛选:仅返回指定货主的 SKU,空数组表示不筛选。
|
||||
* @return {Promise<Object>} 补货需求明细、汇总与分页信息。
|
||||
*/
|
||||
async replenishmentDemand(options = {}) {
|
||||
const { ctx, app } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
|
||||
// 货主筛选集合(空数组 = 不筛选)
|
||||
const storeIds = Array.isArray(options.storeIds) ? options.storeIds : [];
|
||||
const storeFilterSet = storeIds.length > 0 ? new Set(storeIds) : null;
|
||||
|
||||
// 仓库上下文:从用户上下文获取
|
||||
const warehouseId = toNumber(ctx.user?.store_id ?? ctx.user?.warehouse_id, 0);
|
||||
|
||||
@ -127,7 +132,7 @@ class StorageManagementService extends Service {
|
||||
is_valid: 'Y',
|
||||
deleted_at: null,
|
||||
},
|
||||
attributes: [ 'id', 'item_code', 'item_name' ],
|
||||
attributes: [ 'id', 'item_code', 'item_name', 'store_id' ],
|
||||
raw: true,
|
||||
})
|
||||
: [];
|
||||
@ -139,6 +144,7 @@ class StorageManagementService extends Service {
|
||||
const stockId = toNumber(row.id, 0);
|
||||
if (stockId <= 0) continue;
|
||||
stockInfoMap.set(stockId, {
|
||||
store_id: toNumber(row.store_id, 0),
|
||||
stock_code: String(row.item_code || ''),
|
||||
stock_name: String(row.item_name || ''),
|
||||
});
|
||||
@ -153,7 +159,7 @@ class StorageManagementService extends Service {
|
||||
id: { [Op.in]: missedStockIds },
|
||||
deleted_at: null,
|
||||
},
|
||||
attributes: [ 'id', 'item_code', 'item_name' ],
|
||||
attributes: [ 'id', 'item_code', 'item_name', 'store_id' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
@ -161,6 +167,7 @@ class StorageManagementService extends Service {
|
||||
const stockId = toNumber(row.id, 0);
|
||||
if (stockId <= 0 || stockInfoMap.has(stockId)) continue;
|
||||
stockInfoMap.set(stockId, {
|
||||
store_id: toNumber(row.store_id, 0),
|
||||
stock_code: String(row.item_code || ''),
|
||||
stock_name: String(row.item_name || ''),
|
||||
});
|
||||
@ -174,7 +181,7 @@ class StorageManagementService extends Service {
|
||||
where: {
|
||||
id: { [Op.in]: stillMissedStockIds },
|
||||
},
|
||||
attributes: [ 'id', 'item_code', 'item_name' ],
|
||||
attributes: [ 'id', 'item_code', 'item_name', 'store_id' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
@ -182,12 +189,72 @@ class StorageManagementService extends Service {
|
||||
const stockId = toNumber(row.id, 0);
|
||||
if (stockId <= 0 || stockInfoMap.has(stockId)) continue;
|
||||
stockInfoMap.set(stockId, {
|
||||
store_id: toNumber(row.store_id, 0),
|
||||
stock_code: String(row.item_code || ''),
|
||||
stock_name: String(row.item_name || ''),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 4.5) 查询货主名称与 SKU 条码
|
||||
const ownerStoreIds = Array.from(
|
||||
new Set(
|
||||
Array.from(stockInfoMap.values())
|
||||
.map(info => toNumber(info.store_id, 0))
|
||||
.filter(id => id > 0)
|
||||
)
|
||||
);
|
||||
|
||||
const [ storeWarehouseRows, storeRows, barcodeRows ] = await Promise.all([
|
||||
ownerStoreIds.length > 0
|
||||
? ctx.model.StoreWarehouse.findAll({
|
||||
where: {
|
||||
store_id: { [Op.in]: ownerStoreIds },
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
attributes: [ 'store_id', 'store_remask' ],
|
||||
raw: true,
|
||||
})
|
||||
: [],
|
||||
ownerStoreIds.length > 0
|
||||
? ctx.model.Store.findAll({
|
||||
where: { id: { [Op.in]: ownerStoreIds } },
|
||||
attributes: [ 'id', 'company_name' ],
|
||||
raw: true,
|
||||
})
|
||||
: [],
|
||||
ctx.model.StockBarcode.findAll({
|
||||
where: { stock_id: { [Op.in]: allStockIds } },
|
||||
attributes: [ 'id', 'stock_id', 'barcode' ],
|
||||
raw: true,
|
||||
}),
|
||||
]);
|
||||
|
||||
// 货主名称:签约表备注名 store_remask 优先,商家表 company_name 兜底
|
||||
const storeNameMap = new Map();
|
||||
for (const row of Array.isArray(storeRows) ? storeRows : []) {
|
||||
const storeId = toNumber(row.id, 0);
|
||||
if (storeId > 0) storeNameMap.set(storeId, String(row.company_name || ''));
|
||||
}
|
||||
for (const row of Array.isArray(storeWarehouseRows) ? storeWarehouseRows : []) {
|
||||
const storeId = toNumber(row.store_id, 0);
|
||||
const remask = String(row.store_remask || '').trim();
|
||||
if (storeId > 0 && remask) storeNameMap.set(storeId, remask);
|
||||
}
|
||||
|
||||
// SKU 条码按 stock_id 分组
|
||||
const barcodeMap = new Map();
|
||||
for (const row of Array.isArray(barcodeRows) ? barcodeRows : []) {
|
||||
const stockId = toNumber(row.stock_id, 0);
|
||||
if (stockId <= 0) continue;
|
||||
const barcodeList = barcodeMap.get(stockId) || [];
|
||||
barcodeList.push({
|
||||
id: toNumber(row.id, 0),
|
||||
barcode: String(row.barcode || ''),
|
||||
});
|
||||
barcodeMap.set(stockId, barcodeList);
|
||||
}
|
||||
|
||||
// 5) 查询所有可用库存(不区分分拣/存货区),再按库位类型分类汇总
|
||||
const storageRows = allStockIds.length > 0
|
||||
? await ctx.model.Storage.findAll({
|
||||
@ -263,6 +330,10 @@ class StorageManagementService extends Service {
|
||||
|
||||
for (const stockId of allStockIds) {
|
||||
const info = stockInfoMap.get(stockId) || { stock_code: `SKU#${stockId}`, stock_name: `商品#${stockId}` };
|
||||
|
||||
// 货主筛选:仅返回指定货主的 SKU
|
||||
if (storeFilterSet && !storeFilterSet.has(info.store_id || 0)) continue;
|
||||
|
||||
const totalDemand = demandByStockId.get(stockId) || 0;
|
||||
const pickZoneQty = pickZoneQtyByStockId.get(stockId) || 0;
|
||||
const storageZoneQty = storageZoneQtyByStockId.get(stockId) || 0;
|
||||
@ -280,6 +351,9 @@ class StorageManagementService extends Service {
|
||||
stock_id: stockId,
|
||||
stock_code: info.stock_code,
|
||||
stock_name: info.stock_name,
|
||||
store_id: info.store_id || 0,
|
||||
store_name: storeNameMap.get(info.store_id) || '',
|
||||
barcodes: barcodeMap.get(stockId) || [],
|
||||
pick_zone_quantity: pickZoneQty,
|
||||
storage_zone_quantity: storageZoneQty,
|
||||
total_demand: totalDemand,
|
||||
|
||||
@ -220,6 +220,21 @@ class UploadService extends Service {
|
||||
policyHash,
|
||||
};
|
||||
}
|
||||
/**
|
||||
* 解析单次上传的文件大小上限。
|
||||
* 优先使用调用方传入的 options.maxSizeBytes,否则回退到 cos.maxsize 配置。
|
||||
* @param {Object} options 上传选项。
|
||||
* @return {number} 文件大小上限(字节)。
|
||||
*/
|
||||
resolveUploadMaxSizeBytes(options = {}) {
|
||||
const requested = options && options.maxSizeBytes;
|
||||
if (typeof requested === 'number' && Number.isFinite(requested) && requested > 0) {
|
||||
return requested;
|
||||
}
|
||||
|
||||
const { maxsize } = this.getCosConfig();
|
||||
return this.parseSizeToBytes(maxsize);
|
||||
}
|
||||
/**
|
||||
* 验证文件信息
|
||||
* @param {Object} root0 文件信息对象
|
||||
@ -229,7 +244,7 @@ class UploadService extends Service {
|
||||
validateFileInfo({ fileName, fileSize }) {
|
||||
const { maxsize, mimetype } = this.getCosConfig();
|
||||
|
||||
// 验证文件大小
|
||||
// 验证文件大小(使用 cos.maxsize 配置)
|
||||
const maxSizeBytes = this.parseSizeToBytes(maxsize);
|
||||
if (fileSize > maxSizeBytes) {
|
||||
throw new Error(`文件大小不能超过 ${this.formatFileSize(maxSizeBytes)}`);
|
||||
@ -394,10 +409,11 @@ class UploadService extends Service {
|
||||
* @param {Object} options 上传选项
|
||||
*/
|
||||
validateFile(fileStream, options = {}) {
|
||||
const { maxsize, mimetype } = this.getCosConfig();
|
||||
const { mimetype } = this.getCosConfig();
|
||||
const { filename, fileSize } = fileStream;
|
||||
|
||||
const maxSizeBytes = this.parseSizeToBytes(maxsize);
|
||||
// 验证文件大小:单次上传可通过 options.maxSizeBytes 覆盖上限,否则使用 cos.maxsize 配置
|
||||
const maxSizeBytes = this.resolveUploadMaxSizeBytes(options);
|
||||
if (fileSize > maxSizeBytes) {
|
||||
throw new Error(`文件大小不能超过 ${this.formatFileSize(maxSizeBytes)}`);
|
||||
}
|
||||
|
||||
@ -684,13 +684,30 @@ class WorkbenchService extends Service {
|
||||
const users = Array.isArray(usersParam) ? usersParam : [];
|
||||
let operatorText = '';
|
||||
if (users.length > 0) {
|
||||
const packerRecords = users.map((user, idx) => ({
|
||||
pack_task_id: packTask.id,
|
||||
account_id: user.wms_account_id != null ? parseInt(user.wms_account_id) || 0 : 0,
|
||||
account_name: user.real_name || '',
|
||||
seq: idx,
|
||||
}));
|
||||
await ctx.model.PackTaskPacker.bulkCreate(packerRecords);
|
||||
// account_id 未知时写 null(表列允许 NULL):唯一索引 uix_pack_task_account 对
|
||||
// NULL 不生效,避免多人打包(account_id 全为 0)时违反唯一约束导致主流程中断。
|
||||
// 真实账号仍按 account_id 去重;无账号时按姓名去重。
|
||||
const seenPackerKeys = new Set();
|
||||
const packerRecords = [];
|
||||
for (const user of users) {
|
||||
const accountIdRaw = user.wms_account_id != null
|
||||
? user.wms_account_id
|
||||
: (user.id != null ? user.id : null);
|
||||
const accountId = accountIdRaw != null ? (parseInt(accountIdRaw) || null) : null;
|
||||
const accountName = user.real_name || '';
|
||||
const dedupeKey = accountId !== null ? `id:${accountId}` : `name:${accountName}`;
|
||||
if (seenPackerKeys.has(dedupeKey)) continue;
|
||||
seenPackerKeys.add(dedupeKey);
|
||||
packerRecords.push({
|
||||
pack_task_id: packTask.id,
|
||||
account_id: accountId,
|
||||
account_name: accountName,
|
||||
seq: packerRecords.length,
|
||||
});
|
||||
}
|
||||
if (packerRecords.length > 0) {
|
||||
await ctx.model.PackTaskPacker.bulkCreate(packerRecords);
|
||||
}
|
||||
operatorText = users.map(u => u.real_name || '').filter(Boolean).join(',');
|
||||
// 回写 operator_text 到打包任务
|
||||
await packTask.update({ operator_text: operatorText });
|
||||
|
||||
@ -58,6 +58,10 @@ module.exports = appInfo => {
|
||||
imageBaseUrl: '', // 商品图片域名,为空时用请求 ctx.host
|
||||
// 历史消息过滤:消息原始发送时间距今超过该阈值(毫秒)则跳过 AI 处理,防止补推历史消息被当成新工单
|
||||
historyMessageMaxAgeMs: 10 * 60 * 1000,
|
||||
// AI 兜底开关:规则引擎未命中时是否回退 AI 推理(默认关闭,节省费用;开启后未命中消息走 AI)
|
||||
aiFallback: false,
|
||||
// 退回收件登记聚合通知防抖窗口(毫秒):等该时长无新登记后合并推送,默认 5 分钟
|
||||
returnReceivedNotifyDelayMs: 5 * 60 * 1000,
|
||||
};
|
||||
|
||||
config.tencentCloud = {
|
||||
|
||||
@ -0,0 +1,50 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_NAME = 'wms_pack_task_packer';
|
||||
|
||||
/**
|
||||
* 允许 account_id 为 NULL。
|
||||
* 背景:打包任务写入多名打包人时,PDA 上传的 wms_account_id 可能为 null,
|
||||
* 旧代码统一兜底为 0,多人场景下多条 (pack_task_id, account_id=0) 违反
|
||||
* 唯一索引 uix_pack_task_account,导致 bulkCreate 抛 UniqueConstraintError,
|
||||
* 进而中断 _packOrder 后续步骤(OSD 下发、操作日志)。
|
||||
* MySQL 唯一索引对 NULL 不生效,故未知账号改为写 NULL。
|
||||
*/
|
||||
module.exports = {
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
const tableInfo = await queryInterface.describeTable(TABLE_NAME);
|
||||
const col = tableInfo.account_id;
|
||||
if (!col) {
|
||||
throw new Error(`[Migration] ${TABLE_NAME}.account_id 不存在`);
|
||||
}
|
||||
if (col.allowNull === false) {
|
||||
await queryInterface.changeColumn(TABLE_NAME, 'account_id', {
|
||||
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '账号ID,关联 wms_account.id;未知账号为 NULL',
|
||||
});
|
||||
console.log(`[Migration] ${TABLE_NAME}.account_id 已改为允许 NULL`);
|
||||
} else {
|
||||
console.log(`[Migration] ${TABLE_NAME}.account_id 已允许 NULL,跳过`);
|
||||
}
|
||||
},
|
||||
|
||||
down: async (queryInterface, Sequelize) => {
|
||||
const tableInfo = await queryInterface.describeTable(TABLE_NAME);
|
||||
const col = tableInfo.account_id;
|
||||
if (!col) return;
|
||||
|
||||
if (col.allowNull === true) {
|
||||
// 回滚前把 NULL 归位为 0,避免改回 NOT NULL 失败
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE ${TABLE_NAME} SET account_id = 0 WHERE account_id IS NULL`
|
||||
);
|
||||
await queryInterface.changeColumn(TABLE_NAME, 'account_id', {
|
||||
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '账号ID,关联 wms_account.id',
|
||||
});
|
||||
console.log(`[Migration] ${TABLE_NAME}.account_id 已恢复为 NOT NULL`);
|
||||
}
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,107 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 创建订单创建后自动分配快递的消费队列表 wms_waybill_allocate_queue。
|
||||
*
|
||||
* 背景:订单创建后的异步流程原为逐单直接取号,大批量订单创建时会产生 N 条并发
|
||||
* createWaybillCode 回写事务与结算事务的 AB-BA 死锁(wms_store_warehouse 与
|
||||
* wms_order_express 锁序相反)。改造为创建时只入队(截单/未审核不入队),由定时
|
||||
* 任务按仓库+货主串行批量消费。
|
||||
*
|
||||
* 字段:
|
||||
* - order_id / business_key:待分配运单的订单与业务键(与 wms_order_express 一致)
|
||||
* - warehouse_id / store_id:消费分组与数据隔离维度
|
||||
* - status:pending(待消费)/ processing(消费中)/ done(完成)/ failed(超限失败)
|
||||
* - retry_count / next_retry_at / error_message:重试与失败信息
|
||||
*
|
||||
* 索引:
|
||||
* - uk_order_id_business_key:幂等入队唯一键
|
||||
* - idx_status_id:消费拉取(status=pending 按 id 升序)
|
||||
* - idx_status_updated_at:处理中兜底恢复扫描
|
||||
*/
|
||||
|
||||
const TABLE_NAME = 'wms_waybill_allocate_queue';
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
const { BIGINT, INTEGER, STRING, DATE } = Sequelize;
|
||||
await queryInterface.createTable(TABLE_NAME, {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键',
|
||||
},
|
||||
order_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '订单ID(关联订单分表)',
|
||||
},
|
||||
business_key: {
|
||||
type: INTEGER(3),
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '业务键(与 wms_order_express.business_key 一致)',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '仓库ID(消费分组与数据隔离维度)',
|
||||
},
|
||||
store_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '货主ID(消费分组维度)',
|
||||
},
|
||||
status: {
|
||||
type: STRING(20),
|
||||
allowNull: false,
|
||||
defaultValue: 'pending',
|
||||
comment: '状态:pending/processing/done/failed',
|
||||
},
|
||||
retry_count: {
|
||||
type: INTEGER(3),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '重试次数',
|
||||
},
|
||||
next_retry_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '下次可消费时间(失败退避)',
|
||||
},
|
||||
error_message: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '最近一次失败原因',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '更新时间',
|
||||
},
|
||||
});
|
||||
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'order_id', 'business_key' ], {
|
||||
name: 'uk_order_id_business_key',
|
||||
unique: true,
|
||||
});
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'status', 'id' ], {
|
||||
name: 'idx_status_id',
|
||||
});
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'status', 'updated_at' ], {
|
||||
name: 'idx_status_updated_at',
|
||||
});
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.dropTable(TABLE_NAME);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,29 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE = 'wms_return_received';
|
||||
|
||||
/**
|
||||
* 退回收件登记表新增 is_notified 字段:
|
||||
* 标记"登记已通知货主群"(0=未通知,1=已通知)。
|
||||
* 供定时任务聚合通知(等 5 分钟无新登记后按货主合并推送,只对货主查退回时登记过的运单通知)。
|
||||
*/
|
||||
module.exports = {
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
const columns = await queryInterface.describeTable(TABLE);
|
||||
if (!columns.is_notified) {
|
||||
await queryInterface.addColumn(TABLE, 'is_notified', {
|
||||
type: Sequelize.TINYINT(1),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '登记是否已通知货主群:0=未通知,1=已通知',
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
down: async queryInterface => {
|
||||
const columns = await queryInterface.describeTable(TABLE);
|
||||
if (columns.is_notified) {
|
||||
await queryInterface.removeColumn(TABLE, 'is_notified');
|
||||
}
|
||||
},
|
||||
};
|
||||
@ -1,4 +1,16 @@
|
||||
[
|
||||
{
|
||||
"version": "2026.08.27-openapi-service-conflict-fix",
|
||||
"date": "2026-08-27",
|
||||
"summary": "修复 Egg 服务命名冲突:app/service/openapi.js 重命名为 openapiEntry.js,恢复 ctx.service.openapi.callback 可用",
|
||||
"methods": [],
|
||||
"notes": [
|
||||
"根因:app/service/openapi.js 文件与 app/service/openapi/ 目录同名,Egg ContextLoader 把目录里的 callback/callbackRegistry 挂成 OpenapiService 类的静态属性,实例上不可见,导致运行时 ctx.service.openapi.callback 为 undefined",
|
||||
"修复:openapi.js 重命名为 openapiEntry.js(服务路径 ctx.service.openapiEntry),app/controller/openapi.js 的 processRequest 引用同步更新,AI_METHOD_ROUTING.md 同步",
|
||||
"影响:storage.entry.quickInbound 对 API 来源直入单回传 entry_order_direct_inbound_completed 事件不再报 Cannot read properties of undefined (reading 'sendWithRetry'),库存两段式(先回传后写库)可正常执行"
|
||||
],
|
||||
"type": "fixed"
|
||||
},
|
||||
{
|
||||
"version": "2026.06.04-openapi-04",
|
||||
"date": "2026-06-04",
|
||||
|
||||
@ -1,4 +1,137 @@
|
||||
[
|
||||
{
|
||||
"version": "2026.08.27-order-allocateStorage-allow-storage-location",
|
||||
"date": "2026-08-27",
|
||||
"type": "fixed",
|
||||
"summary": "order.pendingOrder.allocateStorage 修复 allow_storage_location=true 未生效:分配储位时仍强制校验库位类型 allow_allocation=1/is_active=1,存储储位被过滤。现在 allow_storage_location=true 时直接分配储位,无视库位类型的可分配/启用限制",
|
||||
"methods": [
|
||||
"order.pendingOrder.allocateStorage"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systems/order_storage_allocation.js allocatePicking:storageRows 查询的 locationType include where(allow_allocation:1/is_active:1)改为仅当 allowStorageLocation=false 时生效;true 时不再过滤库位类型限制",
|
||||
"无候选库位时的缺货诊断 diagnoseStorageTypeRestriction 仅在 allowStorageLocation=false 时执行,避免「库位类型不可分配/未启用」被误报为缺货原因",
|
||||
"可分配库存查询完成日志补充 allowStorageLocation 字段",
|
||||
"同步更新 methods/system.json:order.pendingOrder.allocateStorage 描述与 allow_storage_location 参数说明"
|
||||
],
|
||||
"module": "order"
|
||||
},
|
||||
{
|
||||
"version": "2026.08.27-order-export-stock-query",
|
||||
"date": "2026-08-27",
|
||||
"type": "fixed",
|
||||
"summary": "order.export 修复携带产品查询(where.stock_query)时导出失败(Unknown column ... in where clause):导出链路补齐 stock_query 虚拟筛选提取,按商品编码/名称/ID/条码解析为订单ID集合后注入主查询,与 order.list 语义一致",
|
||||
"methods": [
|
||||
"order.export"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systems/order_export.js exportOrders:在 extractBuyerMessageHasVirtualFilter 之后新增 extractStockQueryVirtualFilter,从 where 提取并移除 stock_query,避免其残留在 where 中经 buildWhere/parseWhereConditions 被当作数据库字段解析,导致 SQL Unknown column 报错",
|
||||
"stockQuery 非空时调用 findOrderIdsByStockQuery(商品编码/名称/ID/条码模糊匹配 → stock_id 集合 → order_items 关联订单ID),再经 appendOrderIdsFilterToWhere 注入主查询;无匹配商品时导出结果为空,与 order.list 行为一致",
|
||||
"stockQuery 模块名取 target.defaultWhereModuleName || target.sortModuleName || 'order',保证仅传 table_type 时按表类型推导对应模块(current/history 等)的 order_items 表类型"
|
||||
],
|
||||
"module": "order"
|
||||
},
|
||||
{
|
||||
"version": "2026.08.27-storage-entry-get-total-order-lines",
|
||||
"date": "2026-08-27",
|
||||
"type": "enhanced",
|
||||
"summary": "storage.entry.get 响应新增 total_order_lines(entryOrder 内)、total_quantity(应入库总数量)、received_quantity(已入库总数量)字段",
|
||||
"methods": [
|
||||
"storage.entry.get",
|
||||
"storage.entry.getStore"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systems/storage/entry.js get:返回 data.entryOrder 新增 total_order_lines(直接取 wms_entry_order.total_order_lines)",
|
||||
"data 顶层新增 total_quantity = 明细 planned 之和(应入库总数量)、received_quantity = 明细 completed 之和(已入库总数量)",
|
||||
"getStore 共用同一底层实现,自动获得这些字段",
|
||||
"同步更新 get 方法 JSDoc 注释"
|
||||
],
|
||||
"module": "storage.entry"
|
||||
},
|
||||
{
|
||||
"version": "2026.08.27-directInbound-receiving-stock-occupancy",
|
||||
"date": "2026-08-27",
|
||||
"type": "enhanced",
|
||||
"summary": "storage.entry.commit 导入/PDA 入库支持绑定收货单占用:带 receiving_detail_id 的导入记录优先按明细扣减,未带 receiving_detail_id 的剩余导入量按 stock_id 匹配收货单明细占用并回写收货单入库状态",
|
||||
"methods": [
|
||||
"storage.entry.commit",
|
||||
"storage.directInbound.commit"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systems/inbound_direct_log.js commit onSuccess 事务内新增 _applyReceivingStockOccupancy:绑定收货单(wms_entry_order_receiving)存在时,汇总未携带 receiving_detail_id 的导入记录数量,按 stock_id(=收货明细 system_product_id)匹配占用",
|
||||
"优先级:携带 receiving_detail_id 的记录先由 _syncReceivingStorageStatus 按明细扣减,随后剩余量复用 storage.entry._applyReceivingInboundUsage 按 stock_id 依次占用收货明细剩余可入数量(actual_quantity - stored_quantity),事务内行锁防并发超分",
|
||||
"占用后回写收货明细 stored_quantity/storage_status(all/partial),并汇总更新收货单主表 storage_status",
|
||||
"未绑定收货单或无剩余导入量时跳过,不影响原有非绑定模式入库行为",
|
||||
"storage.entry._applyReceivingInboundUsage 日志前缀由 [storage.entry.quickInbound] 改为 [storage.entry](方法现被 quickInbound 与 commit 两个流程复用)"
|
||||
],
|
||||
"module": "storage.entry"
|
||||
},
|
||||
{
|
||||
"version": "2026.08.27-storage-management-replenishmentDemand-owner-filter",
|
||||
"date": "2026-08-27",
|
||||
"type": "enhanced",
|
||||
"summary": "storage.management.replenishmentDemand 新增货主筛选:store_id(单值或数组)或 where.store_id 传入,仅返回指定货主的 SKU,summary 同步只统计筛选后数据",
|
||||
"methods": [
|
||||
"storage.management.replenishmentDemand"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systemMethods/storage/management.js replenishmentDemand:解析 store_id / store_ids / where.store_id(单值/数组),归一化为正整数数组去重,非法值(非正整数)抛错;空值不筛选。",
|
||||
"app/service/systems/storage/management.js replenishmentDemand:options.storeIds 构建 Set,组装输出循环内非命中货主 SKU 直接跳过,list 与 summary 统计口径一致(仅含筛选货主)。",
|
||||
"同步更新 methods/system.json 参数文档(新增 store_id 参数说明)。"
|
||||
],
|
||||
"module": "storage.management"
|
||||
},
|
||||
{
|
||||
"version": "2026.08.27-quickInbound-receiving-intersection",
|
||||
"date": "2026-08-27",
|
||||
"type": "enhanced",
|
||||
"summary": "storage.entry.quickInbound 支持绑定收货单交集直入:有绑定时按 stock_id 只取收货单中剩余可入数量(actual_quantity - stored_quantity)与入库明细的较小值直入,并回写收货单明细已入库数量与收货单入库状态",
|
||||
"methods": [
|
||||
"storage.entry.quickInbound"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systems/storage/entry.js quickInbound:新增绑定收货单查询(wms_entry_order_receiving),按 stock_id(=收货明细 system_product_id)聚合剩余可入数量 actual_quantity - stored_quantity",
|
||||
"入库明细实际直入量 = min(计划数量, 剩余可入数量);无交集商品跳过(明细 received_quantity 写 0),全部无交集或剩余为 0 时返回 400「收货单中无交集商品或剩余可入数量不足,无法快捷直入」",
|
||||
"未绑定收货单保持原行为:按明细计划数量全量直入",
|
||||
"存在截断/跳过明细时 isFin=false(confirmType=1, PARTFULFILLED)回传奇门/API",
|
||||
"新增 _applyReceivingInboundUsage 事务内回写:行锁重读收货明细,按明细 id 升序分配本次入库量(每个明细最多分配其剩余可入数量),更新 stored_quantity(使用了多少写多少)与 storage_status(all/partial),并汇总更新收货单主表 storage_status",
|
||||
"收货单主表 storage_status 按实际数量判定:全部明细 stored_quantity >= actual_quantity 才置 all;有部分入库置 partial;全部未入库置 none——收货单未全部使用所有商品时不会转为全部入库",
|
||||
"入库单明细 received_quantity 改为写实际入库量(原来写计划数量)",
|
||||
"响应新增 plan_quantity(计划入库总数量),total_quantity 语义改为实际入库总数量,items_count 语义改为实际入库明细条目数"
|
||||
],
|
||||
"module": "storage.entry"
|
||||
},
|
||||
{
|
||||
"version": "2026.08.27-storage-management-replenishmentDemand-owner-barcode",
|
||||
"date": "2026-08-27",
|
||||
"type": "enhanced",
|
||||
"summary": "storage.management.replenishmentDemand 响应 list 每项新增 store_id(货主ID)、store_name(货主名称)、barcodes(SKU 条码列表)字段",
|
||||
"methods": [
|
||||
"storage.management.replenishmentDemand"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systems/storage/management.js replenishmentDemand:StockWarehouse 三处查询(严格/宽松/终极兜底)attributes 均新增 store_id,stockInfoMap 记录货主ID。",
|
||||
"新增货主名称查询:StoreWarehouse(store_remask 签约表备注名)优先、Store(company_name 商家公司名)兜底;新增 StockBarcode 按 stock_id 批量查询条码并分组为 barcodes: [{id, barcode}]。",
|
||||
"货主与条码查询与库存查询为顺序执行(货主/条码三表在 Promise.all 内并行)。",
|
||||
"响应字段:store_id (number) 货主ID;store_name (string) 货主名称;barcodes (array) 条码列表,children: id (number)/barcode (string)。",
|
||||
"同步更新 methods/system.json 响应文档。"
|
||||
],
|
||||
"module": "storage.management"
|
||||
},
|
||||
{
|
||||
"version": "2026.08.27-order-export-columns",
|
||||
"date": "2026-08-27",
|
||||
"type": "enhanced",
|
||||
"summary": "order.export 新增 export_columns/exportColumns 导出表头字段白名单参数(中文表头数组):不传或空数组输出全部列;传入时仅输出指定列;校验枚举覆盖 waybill/item 两种模式全部 51 个中文表头,非法表头抛错并列出非法值。",
|
||||
"methods": [
|
||||
"order.export"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systems/order_export.js:新增 ORDER_EXPORT_ALL_COLUMN_HEADERS(waybill/item 两种模式表头并集,共 51 个);getOrderExportColumns(mode, selectedHeaders) 支持按中文表头过滤;新增 normalizeExportColumns(数组去重/trim/非法值抛错);exportOrders 读取 export_columns/exportColumns(下划线优先)并作用到初始 sheet 与自动续写的后续 sheet(resolvedColumns 复用)",
|
||||
"app/service/systemMethods/order/index.js export:解构 export_columns/exportColumns 并透传数组,未传时传空数组(输出全部列)",
|
||||
"methods/system.json order.export 新增 export_columns/exportColumns 参数文档:枚举全量 51 个中文表头,并标注仅 waybill 模式输出(系统订单号、外部订单号、平台单号、抓取波次号、商品明细)与仅 item 模式输出(订单ID、订单号、外部单号、波次号、仓库商品名称、商品条码、商品图片、数量)的字段"
|
||||
],
|
||||
"module": "order"
|
||||
},
|
||||
{
|
||||
"version": "2026.08.26-wave-batchList-store-id-filter",
|
||||
"date": "2026-08-26",
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
{
|
||||
"module": "system",
|
||||
"description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内",
|
||||
"version": "0.3.36",
|
||||
"updatedAt": "2026-08-25",
|
||||
"version": "0.3.37",
|
||||
"updatedAt": "2026-08-27",
|
||||
"headers": [
|
||||
{
|
||||
"name": "platform",
|
||||
@ -2537,6 +2537,13 @@
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "导出模式:waybill(默认,按运单展开,items_detail 列汇总商品)或 item(按商品明细展开,每商品一行);支持 export_mode 与 exportMode 两种写法"
|
||||
},
|
||||
{
|
||||
"name": "export_columns / exportColumns",
|
||||
"type": "array",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "导出表头字段白名单(中文表头字符串数组,如 [\"系统订单号\",\"外部订单号\"]);不传或空数组时输出全部列。枚举(共 51 个,校验不区分导出模式):系统订单号、外部订单号、平台单号、订单ID、订单号、外部单号、订单状态、抓取波次号、波次号、波次序号、货主、平台、店铺昵称、收件人、收件人电话、省、市、区、镇、详细地址、商品明细、仓库商品名称、商品条码、商品图片、数量、物流公司、运单号、业务类型、运单接口、包材ID、包材编码、包材名称、分配时间、商品种数、商品件数、商品重量、称重重量(g)、订单金额、实收金额、创建时间、支付时间、发货时间、出库状态、复核状态、复核完成状态、配货状态、打包状态、备注、买家留言、卖家留言、归档时间。其中仅 waybill 模式输出:系统订单号、外部订单号、平台单号、抓取波次号、商品明细;仅 item 模式输出:订单ID、订单号、外部单号、波次号、仓库商品名称、商品条码、商品图片、数量;其余为两种模式通用(选了当前模式不存在的表头时该列自动忽略)。传入非法表头会报错(错误信息列出非法值);支持 export_columns 与 exportColumns 两种写法"
|
||||
}
|
||||
],
|
||||
"response": [
|
||||
@ -3412,7 +3419,7 @@
|
||||
},
|
||||
{
|
||||
"method": "order.pendingOrder.allocateStorage",
|
||||
"description": "按订单批量分配储位(迁移自 order.storageAllocation.allocateStorage)。这是一个异步提交接口:调用后接口立即返回受理信息(包含 request_id),后端异步执行实际的储位分配与锁定操作;仓库上下文由当前登录用户提供(ctx.user.store_id)。接口不会在同步响应中返回分配明细(如 requested_order_ids、allocated_order_ids 等),客户端可通过请求 ID 或事件/查询链路获取最终结果。已锁定订单(lock_status 非 none)会在分配流水线中被跳过(底层分配结果 skipped_orders 中记录 skipped_reason='locked')。",
|
||||
"description": "按订单批量分配储位(迁移自 order.storageAllocation.allocateStorage)。这是一个异步提交接口:调用后接口立即返回受理信息(包含 request_id),后端异步执行实际的储位分配与锁定操作;仓库上下文由当前登录用户提供(ctx.user.store_id)。接口不会在同步响应中返回分配明细(如 requested_order_ids、allocated_order_ids 等),客户端可通过请求 ID 或事件/查询链路获取最终结果。已锁定订单(lock_status 非 none)会在分配流水线中被跳过(底层分配结果 skipped_orders 中记录 skipped_reason='locked')。默认仅从库位类型允许分配且启用的储位中分配;传入 allow_storage_location=true 时直接分配储位,无视库位类型的 allow_allocation/is_active 限制。",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
"headers": [
|
||||
@ -3429,7 +3436,7 @@
|
||||
"type": "boolean",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "是否允许使用存储储位,支持多种字段别名。"
|
||||
"description": "是否允许使用存储储位,支持多种字段别名。为 true 时直接分配储位,无视库位类型的 allow_allocation/is_active 限制;缺省时仅校验可分配储位。"
|
||||
},
|
||||
{
|
||||
"name": "order_ids / orderIds / ids / order_id / orderId / id",
|
||||
@ -22579,7 +22586,7 @@
|
||||
},
|
||||
{
|
||||
"method": "storage.entry.quickInbound",
|
||||
"description": "快捷直入(虚拟入库):将入库单所有商品按明细数量一键直入到虚拟库位(space_id=2),跳过收货/质检流程,入库单状态变为COMPLETED。仅支持 CREATED 状态的入库单;CANCELLED(已作废)、COMPLETED(已完成)、PENDING 等其他状态均拒绝操作。事务内操作:更新入库明细收货量、累加库存总量、写入库存流水、写入虚拟库位库存、变更入库单状态为 COMPLETED。事务外异步回传奇门/API。",
|
||||
"description": "快捷直入(虚拟入库):将入库单商品直入到虚拟库位(space_id=2),跳过收货/质检流程。有绑定收货单时,只取收货单中与入库单明细有交集(按 stock_id 判断)且剩余可入数量(actual_quantity - stored_quantity)的商品直入,实际入库量 = min(明细计划数量, 收货单剩余可入数量),并在事务内回写收货单明细已入库数量与收货单入库状态;未绑定收货单时按明细计划数量全量直入。仅支持 CREATED 状态的入库单;CANCELLED(已作废)、COMPLETED(已完成)、PENDING 等其他状态均拒绝操作。事务内操作:更新入库明细收货量、累加库存总量、写入库存流水、写入虚拟库位库存、回写收货单明细、变更入库单状态为 COMPLETED。事务外异步回传奇门/API。",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
"headers": [],
|
||||
@ -22621,13 +22628,19 @@
|
||||
"name": "items_count",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "入库明细条目数"
|
||||
"description": "实际入库明细条目数(有绑定收货单时为与收货单有交集且实际入库量大于0的明细数)"
|
||||
},
|
||||
{
|
||||
"name": "total_quantity",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "入库总数量"
|
||||
"description": "实际入库总数量(有绑定收货单时=与收货单交集部分的实际直入数量)"
|
||||
},
|
||||
{
|
||||
"name": "plan_quantity",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "计划入库总数量"
|
||||
}
|
||||
],
|
||||
"errors": [
|
||||
@ -22654,6 +22667,14 @@
|
||||
{
|
||||
"code": 400,
|
||||
"message": "请先添加入库明细"
|
||||
},
|
||||
{
|
||||
"code": 400,
|
||||
"message": "收货单中无交集商品或剩余可入数量不足,无法快捷直入"
|
||||
},
|
||||
{
|
||||
"code": 400,
|
||||
"message": "入库明细数量均为0,无法快捷直入"
|
||||
}
|
||||
]
|
||||
},
|
||||
@ -25579,6 +25600,13 @@
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "排序参数,支持 sortField / sortOrder。sortField 可选值:stock_id / pick_zone_quantity / storage_zone_quantity / total_demand / shortage / replenishment_needed,默认 shortage;sortOrder 可选 ASC / DESC,默认 DESC"
|
||||
},
|
||||
{
|
||||
"name": "store_id",
|
||||
"type": "number|array",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "货主筛选:支持单值或数组(正整数),也可通过 where.store_id 传入;不传时返回全部货主;非法值(非正整数)报错"
|
||||
}
|
||||
],
|
||||
"response": [
|
||||
@ -25606,6 +25634,38 @@
|
||||
"required": true,
|
||||
"description": "SKU 名称"
|
||||
},
|
||||
{
|
||||
"name": "store_id",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "货主ID"
|
||||
},
|
||||
{
|
||||
"name": "store_name",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "货主名称(货主签约表备注名优先,商家表公司名称兜底)"
|
||||
},
|
||||
{
|
||||
"name": "barcodes",
|
||||
"type": "array",
|
||||
"required": true,
|
||||
"description": "SKU 条码列表",
|
||||
"children": [
|
||||
{
|
||||
"name": "id",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "条码记录ID"
|
||||
},
|
||||
{
|
||||
"name": "barcode",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "条码内容"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "pick_zone_quantity",
|
||||
"type": "number",
|
||||
|
||||
@ -1,116 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 调试脚本:为指定账号铸造 JWT 并调用系统接口完成收货。
|
||||
* 用法:
|
||||
* node script/debug-complete-receiving.cjs --receiving-id=1512 --account-id=1
|
||||
* node script/debug-complete-receiving.cjs --receiving-id=1512 --account-id=1 --host=127.0.0.1 --port=6060
|
||||
*/
|
||||
|
||||
const http = require('node:http');
|
||||
const jwt = require('jsonwebtoken');
|
||||
|
||||
const JWT_SECRET = 'E5#ex.g@,GfL_8?';
|
||||
const JWT_EXPIRES_IN = 14400;
|
||||
|
||||
function parseArgs(argv) {
|
||||
const options = {
|
||||
receivingId: 0,
|
||||
accountId: 1,
|
||||
host: '127.0.0.1',
|
||||
port: 6060,
|
||||
remark: '',
|
||||
};
|
||||
|
||||
for (const arg of argv) {
|
||||
if (!arg.startsWith('--')) {
|
||||
continue;
|
||||
}
|
||||
const [ rawKey, ...rest ] = arg.slice(2).split('=');
|
||||
const value = rest.join('=');
|
||||
switch (rawKey) {
|
||||
case 'receiving-id':
|
||||
options.receivingId = Number(value || options.receivingId);
|
||||
break;
|
||||
case 'account-id':
|
||||
options.accountId = Number(value || options.accountId);
|
||||
break;
|
||||
case 'host':
|
||||
options.host = value || options.host;
|
||||
break;
|
||||
case 'port':
|
||||
options.port = Number(value || options.port);
|
||||
break;
|
||||
case 'remark':
|
||||
options.remark = value || '';
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return options;
|
||||
}
|
||||
|
||||
function postSystemMethod(options, token, method, body) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const bodyJson = JSON.stringify(body);
|
||||
const path = `/system?method=${encodeURIComponent(method)}&v=1×tamp=${Math.floor(Date.now() / 1000)}`;
|
||||
const req = http.request({
|
||||
hostname: options.host,
|
||||
port: options.port,
|
||||
path,
|
||||
method: 'POST',
|
||||
headers: {
|
||||
platform: 'web',
|
||||
project: 'wms',
|
||||
Authorization: `Bearer ${token}`,
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Length': Buffer.byteLength(bodyJson),
|
||||
},
|
||||
}, res => {
|
||||
let data = '';
|
||||
res.on('data', chunk => {
|
||||
data += chunk;
|
||||
});
|
||||
res.on('end', () => {
|
||||
resolve({ status: res.statusCode, body: data });
|
||||
});
|
||||
});
|
||||
req.on('error', reject);
|
||||
req.write(bodyJson);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const options = parseArgs(process.argv.slice(2));
|
||||
if (!options.receivingId) {
|
||||
console.error('缺少 --receiving-id');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const token = jwt.sign({
|
||||
id: options.accountId,
|
||||
platform_code: 'web',
|
||||
current_store_id: 100000,
|
||||
}, JWT_SECRET, { expiresIn: JWT_EXPIRES_IN });
|
||||
|
||||
console.log(`[debug-complete-receiving] accountId=${options.accountId} receivingId=${options.receivingId}`);
|
||||
const result = await postSystemMethod(options, token, 'storage.receiving.completeReceiving', {
|
||||
id: options.receivingId,
|
||||
remark: options.remark || undefined,
|
||||
});
|
||||
|
||||
console.log(`HTTP ${result.status}`);
|
||||
try {
|
||||
console.log(JSON.stringify(JSON.parse(result.body), null, 2).substring(0, 3000));
|
||||
} catch (_) {
|
||||
console.log(result.body.substring(0, 1000));
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
console.error('[debug-complete-receiving] failed:', error.message);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,245 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 站内信消息推送调试脚本(模拟 IM 桥向仓库推送入站消息,走真实验签链路)。
|
||||
*
|
||||
* 用法:
|
||||
* node script/debug-inbox-push.cjs
|
||||
* 默认: 向 test-stock-group 推送「查退回 <随机不存在运单号>」
|
||||
* node script/debug-inbox-push.cjs --content "查退回 888888888888888"
|
||||
* node script/debug-inbox-push.cjs --waybill 888888888888888 --groupId test-stock-group --userName 测试用户
|
||||
*
|
||||
* 行为:
|
||||
* 1. 按 app/lib/api_sign.js 规则签名,POST /warehouse?method=inbox.push
|
||||
* 2. 等待 AI 异步处理(默认 15s)
|
||||
* 3. 回查本地库: 入站消息 / AI 思考过程 / 回信内容 / wms_return_query_log 登记
|
||||
*/
|
||||
|
||||
const crypto = require('crypto');
|
||||
const http = require('http');
|
||||
const mysql = require('mysql2/promise');
|
||||
|
||||
// ========================== 稳定序列化(与 app/lib/api_sign.js 一致) ==========================
|
||||
|
||||
function isPlainObject(value) {
|
||||
return Object.prototype.toString.call(value) === '[object Object]';
|
||||
}
|
||||
|
||||
function stableStringify(value) {
|
||||
if (value === undefined) return '';
|
||||
if (value === null || typeof value !== 'object') return JSON.stringify(value);
|
||||
if (Array.isArray(value)) {
|
||||
return `[${value.map(item => stableStringify(item)).join(',')}]`;
|
||||
}
|
||||
if (!isPlainObject(value)) return JSON.stringify(value);
|
||||
const keys = Object.keys(value).sort();
|
||||
return `{${keys.map(key => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(',')}}`;
|
||||
}
|
||||
|
||||
function md5(str) {
|
||||
return crypto.createHash('md5').update(str, 'utf8').digest('hex')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function buildSign(query, body, secret) {
|
||||
const ignoreSet = new Set([ 'sign', 'signature' ]);
|
||||
const keys = Object.keys(query)
|
||||
.filter(key => !ignoreSet.has(String(key).toLowerCase()))
|
||||
.filter(key => query[key] !== undefined)
|
||||
.sort();
|
||||
const canonicalQuery = keys.map(key => {
|
||||
const v = query[key];
|
||||
if (v === undefined || v === null) return `${key}=`;
|
||||
if (typeof v === 'object') return `${key}=${stableStringify(v)}`;
|
||||
return `${key}=${String(v)}`;
|
||||
}).join('&');
|
||||
const bodySign = md5(stableStringify(body));
|
||||
const signText = `${canonicalQuery}${secret}${bodySign}`;
|
||||
return { canonicalQuery, bodySign, sign: md5(signText) };
|
||||
}
|
||||
|
||||
// ========================== 参数解析 ==========================
|
||||
|
||||
const ARGS = {};
|
||||
for (let i = 2; i < process.argv.length; i++) {
|
||||
const arg = process.argv[i];
|
||||
const match = arg.match(/^--([^=]+)=(.*)$/);
|
||||
if (match) {
|
||||
ARGS[match[1]] = match[2];
|
||||
} else if (arg.startsWith('--')) {
|
||||
ARGS[arg.slice(2)] = process.argv[i + 1];
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
const CONFIG = {
|
||||
baseUrl: ARGS.baseUrl || 'http://127.0.0.1:6060',
|
||||
appKey: ARGS.appKey || 'APP2025011514315678',
|
||||
appSecret: ARGS.appSecret || 'sec_xyz789uvw012abc345def678ghi901jkl234mno567pqr890',
|
||||
groupId: ARGS.groupId || 'test-stock-group',
|
||||
groupName: ARGS.groupName || '库存查询测试群',
|
||||
userId: ARGS.userId || 'debug_user',
|
||||
userName: ARGS.userName || '测试用户',
|
||||
waitMs: Number(ARGS.waitMs || 15000),
|
||||
waybill: ARGS.waybill || `${Date.now()}99`,
|
||||
};
|
||||
|
||||
if (ARGS.content) {
|
||||
CONFIG.content = ARGS.content;
|
||||
} else {
|
||||
CONFIG.content = `查退回 ${CONFIG.waybill}`;
|
||||
}
|
||||
|
||||
// ========================== HTTP 推送 ==========================
|
||||
|
||||
function postWarehouse(method, body) {
|
||||
const query = {
|
||||
method,
|
||||
v: '1.0',
|
||||
timestamp: Math.floor(Date.now() / 1000),
|
||||
app_key: CONFIG.appKey,
|
||||
};
|
||||
const { sign } = buildSign(query, body, CONFIG.appSecret);
|
||||
query.sign = sign;
|
||||
|
||||
const qs = Object.entries(query)
|
||||
.map(([ k, v ]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
|
||||
.join('&');
|
||||
const bodyStr = JSON.stringify(body);
|
||||
const url = `${CONFIG.baseUrl}/warehouse?${qs}`;
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = http.request(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Length': Buffer.byteLength(bodyStr),
|
||||
},
|
||||
timeout: 20000,
|
||||
}, res => {
|
||||
let data = '';
|
||||
res.on('data', chunk => (data += chunk));
|
||||
res.on('end', () => {
|
||||
try { resolve({ status: res.statusCode, body: JSON.parse(data) }); } catch (e) { resolve({ status: res.statusCode, body: data }); }
|
||||
});
|
||||
});
|
||||
req.on('error', reject);
|
||||
req.on('timeout', () => { req.destroy(); reject(new Error('Request timeout')); });
|
||||
req.write(bodyStr);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
// ========================== 本地库回查 ==========================
|
||||
|
||||
async function queryDb(sql) {
|
||||
const conn = await mysql.createConnection({
|
||||
host: '127.0.0.1',
|
||||
port: 3307,
|
||||
user: 'wms',
|
||||
password: 'dspxmRwRdRbWtbm7',
|
||||
database: 'wms',
|
||||
});
|
||||
try {
|
||||
const [ rows ] = await conn.query(sql);
|
||||
return rows;
|
||||
} finally {
|
||||
await conn.end();
|
||||
}
|
||||
}
|
||||
|
||||
// ========================== 主流程 ==========================
|
||||
|
||||
(async () => {
|
||||
const requestId = `debug-return-${Date.now()}`;
|
||||
console.log('========== 站内信模拟推送 ==========');
|
||||
console.log(` 群: ${CONFIG.groupId} (${CONFIG.groupName})`);
|
||||
console.log(` 用户: ${CONFIG.userName}`);
|
||||
console.log(` 内容: ${CONFIG.content}`);
|
||||
console.log(` requestId: ${requestId}`);
|
||||
|
||||
const r = await postWarehouse('inbox.push', {
|
||||
requestId,
|
||||
content: CONFIG.content,
|
||||
groupId: CONFIG.groupId,
|
||||
groupName: CONFIG.groupName,
|
||||
userId: CONFIG.userId,
|
||||
userName: CONFIG.userName,
|
||||
targetType: 'im',
|
||||
});
|
||||
|
||||
console.log(` HTTP ${r.status}: ${JSON.stringify(r.body).slice(0, 300)}`);
|
||||
if (r.status !== 200 || (r.body && r.body.ok === false)) {
|
||||
console.error('推送失败,请检查签名与仓库应用配置');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log(`\n等待 AI 异步处理 ${CONFIG.waitMs / 1000}s ...`);
|
||||
await sleep(CONFIG.waitMs);
|
||||
|
||||
const extId = `api:${CONFIG.appKey}:${requestId}`;
|
||||
|
||||
// 1. 入站消息 + AI 思考
|
||||
const inbound = await queryDb(
|
||||
`SELECT id, direction, content, ai_thoughts, push_status, created_at
|
||||
FROM wms_inbox_message WHERE ext_id='${extId}' ORDER BY id DESC LIMIT 1`
|
||||
);
|
||||
console.log('\n[入站消息]');
|
||||
if (inbound.length === 0) {
|
||||
console.log(' 未找到(消息可能尚未入库)');
|
||||
} else {
|
||||
console.log(` id=${inbound[0].id} push_status=${inbound[0].push_status}`);
|
||||
console.log(` content: ${inbound[0].content}`);
|
||||
const thoughts = inbound[0].ai_thoughts;
|
||||
if (thoughts && typeof thoughts === 'string') {
|
||||
try {
|
||||
const parsed = JSON.parse(thoughts);
|
||||
console.log(` ai_thoughts: ${JSON.stringify(parsed).slice(0, 400)}`);
|
||||
} catch (e) {
|
||||
console.log(` ai_thoughts(raw): ${String(thoughts).slice(0, 400)}`);
|
||||
}
|
||||
} else {
|
||||
console.log(' ai_thoughts: 无');
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 回信内容
|
||||
const outbound = await queryDb(
|
||||
`SELECT id, direction, content, created_at
|
||||
FROM wms_inbox_message
|
||||
WHERE direction='outbound' AND group_id='${CONFIG.groupId}'
|
||||
ORDER BY id DESC LIMIT 1`
|
||||
);
|
||||
console.log('\n[最新回信]');
|
||||
if (outbound.length === 0) {
|
||||
console.log(' 无回信');
|
||||
} else {
|
||||
console.log(` id=${outbound[0].id} created_at=${outbound[0].created_at}`);
|
||||
console.log(` content:\n${outbound[0].content}`);
|
||||
}
|
||||
|
||||
// 3. 退回查询登记
|
||||
const waybill = CONFIG.waybill;
|
||||
const queryLog = await queryDb(
|
||||
`SELECT id, warehouse_id, store_id, waybill_code, remark, is_notified, is_back, created_at
|
||||
FROM wms_return_query_log WHERE waybill_code='${waybill}' ORDER BY id DESC LIMIT 3`
|
||||
);
|
||||
console.log('\n[wms_return_query_log 登记]');
|
||||
if (queryLog.length === 0) {
|
||||
console.log(' 无登记');
|
||||
} else {
|
||||
queryLog.forEach(row => {
|
||||
console.log(` id=${row.id} store_id=${row.store_id} is_back=${row.is_back} is_notified=${row.is_notified} remark=${row.remark} ${row.created_at}`);
|
||||
});
|
||||
}
|
||||
|
||||
console.log('\n完成。测试记录按需保留,无需删除。');
|
||||
process.exit(0);
|
||||
})().catch(e => {
|
||||
console.error('异常:', e.message);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,252 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const path = require('node:path');
|
||||
const urllib = require('urllib');
|
||||
|
||||
const DEFAULT_FILE_URL = 'https://ye4s.file.gzxunren.com/exports/receiving/completed/100000/20260405/%E6%94%B6%E8%B4%A7%E5%AE%8C%E6%88%90_R20547058.xlsx';
|
||||
const DEFAULT_FILE_NAME = '收货完成_R20547058.xlsx';
|
||||
|
||||
function parseArgs(argv) {
|
||||
const options = {
|
||||
url: process.env.WEBHOOK_DEBUG_URL || '',
|
||||
textUrl: process.env.WEBHOOK_DEBUG_TEXT_URL || '',
|
||||
fileUrl: process.env.WEBHOOK_DEBUG_FILE_URL || '',
|
||||
mode: process.env.WEBHOOK_DEBUG_MODE || 'both',
|
||||
warehouseId: Number(process.env.WEBHOOK_DEBUG_WAREHOUSE_ID || 100000),
|
||||
storeId: Number(process.env.WEBHOOK_DEBUG_STORE_ID || 1000016),
|
||||
receivingId: Number(process.env.WEBHOOK_DEBUG_RECEIVING_ID || 202604050001),
|
||||
receivingNumber: process.env.WEBHOOK_DEBUG_RECEIVING_NUMBER || 'SIM202604050001',
|
||||
fileResourceUrl: process.env.WEBHOOK_DEBUG_REPORT_URL || DEFAULT_FILE_URL,
|
||||
fileName: process.env.WEBHOOK_DEBUG_REPORT_FILE || DEFAULT_FILE_NAME,
|
||||
timeout: Number(process.env.WEBHOOK_DEBUG_TIMEOUT || 10000),
|
||||
};
|
||||
|
||||
for (const arg of argv) {
|
||||
if (!arg.startsWith('--')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const [rawKey, ...rest] = arg.slice(2).split('=');
|
||||
const value = rest.join('=');
|
||||
switch (rawKey) {
|
||||
case 'url':
|
||||
options.url = value || options.url;
|
||||
break;
|
||||
case 'text-url':
|
||||
options.textUrl = value || options.textUrl;
|
||||
break;
|
||||
case 'file-url':
|
||||
options.fileUrl = value || options.fileUrl;
|
||||
break;
|
||||
case 'mode':
|
||||
options.mode = value || options.mode;
|
||||
break;
|
||||
case 'warehouse-id':
|
||||
options.warehouseId = Number(value || options.warehouseId);
|
||||
break;
|
||||
case 'store-id':
|
||||
options.storeId = Number(value || options.storeId);
|
||||
break;
|
||||
case 'receiving-id':
|
||||
options.receivingId = Number(value || options.receivingId);
|
||||
break;
|
||||
case 'receiving-number':
|
||||
options.receivingNumber = value || options.receivingNumber;
|
||||
break;
|
||||
case 'report-url':
|
||||
options.fileResourceUrl = value || options.fileResourceUrl;
|
||||
break;
|
||||
case 'report-file':
|
||||
options.fileName = value || options.fileName;
|
||||
break;
|
||||
case 'timeout':
|
||||
options.timeout = Number(value || options.timeout);
|
||||
break;
|
||||
case 'help':
|
||||
options.help = true;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!options.textUrl) {
|
||||
options.textUrl = options.url;
|
||||
}
|
||||
if (!options.fileUrl) {
|
||||
options.fileUrl = options.url;
|
||||
}
|
||||
|
||||
return options;
|
||||
}
|
||||
|
||||
function printHelp() {
|
||||
console.log(`用法:\n npm run debug:webhook:receiving -- --url=http://127.0.0.1:7071/notic\n npm run debug:webhook:receiving -- --text-url=http://127.0.0.1:7071/notic --file-url=http://127.0.0.1:7071/notic2\n\n说明:\n - 默认发送两次请求:text + file\n - 默认模拟 warehouseId=100000, storeId=1000016 的收货完成通知\n - 可通过 --mode=text 或 --mode=file 只发送一种\n`);
|
||||
}
|
||||
|
||||
function buildBasePayload(options) {
|
||||
return {
|
||||
traceId: `debug_${Date.now()}_${Math.random().toString(16).slice(2, 8)}`,
|
||||
event: 'receiving_completed',
|
||||
businessName: 'receiving',
|
||||
warehouseId: Number(options.warehouseId),
|
||||
storeId: Number(options.storeId),
|
||||
businessId: Number(options.receivingId),
|
||||
occurredAt: new Date().toISOString(),
|
||||
subject: {
|
||||
id: Number(options.warehouseId),
|
||||
type: 'warehouse',
|
||||
name: `测试仓${options.warehouseId}`,
|
||||
code: '',
|
||||
config: {
|
||||
max_notice_webhook_count: 5,
|
||||
},
|
||||
},
|
||||
store: {
|
||||
id: Number(options.storeId),
|
||||
name: `测试货主${options.storeId}`,
|
||||
businessLicense: `BL-${options.storeId}`,
|
||||
storeRemask: `货主${options.storeId}备注`,
|
||||
},
|
||||
sender: {
|
||||
id: 90001,
|
||||
name: '调试脚本',
|
||||
},
|
||||
receivers: [],
|
||||
metadata: {
|
||||
debug: true,
|
||||
sourceScript: path.basename(__filename),
|
||||
receivingId: Number(options.receivingId),
|
||||
receivingNumber: options.receivingNumber,
|
||||
warehouseId: Number(options.warehouseId),
|
||||
storeId: Number(options.storeId),
|
||||
stats: {
|
||||
total_details: 10,
|
||||
matched_details: 10,
|
||||
unmatched_details: 0,
|
||||
total_quantity: 120,
|
||||
},
|
||||
completionReport: null,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function buildTextPayload(options) {
|
||||
const payload = buildBasePayload(options);
|
||||
const title = `收货单${options.receivingNumber}已完成`;
|
||||
const content = `收货单${options.receivingNumber}已完成,匹配商品10件,未匹配商品0件,总数量120,完成人调试脚本。`;
|
||||
payload.message = {
|
||||
type: 'text',
|
||||
title,
|
||||
content,
|
||||
url: '',
|
||||
fileName: '',
|
||||
mimeType: '',
|
||||
body: content,
|
||||
};
|
||||
return payload;
|
||||
}
|
||||
|
||||
function buildFilePayload(options) {
|
||||
const payload = buildBasePayload(options);
|
||||
const title = `收货单${options.receivingNumber}已完成`;
|
||||
const content = `收货单${options.receivingNumber}已完成,匹配商品10件,未匹配商品0件,总数量120,完成人调试脚本。`;
|
||||
payload.message = {
|
||||
type: 'file',
|
||||
title,
|
||||
content,
|
||||
url: options.fileResourceUrl,
|
||||
fileName: options.fileName,
|
||||
mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
body: content,
|
||||
};
|
||||
payload.metadata.completionReport = {
|
||||
fileKey: options.fileName,
|
||||
url: options.fileResourceUrl,
|
||||
};
|
||||
return payload;
|
||||
}
|
||||
|
||||
async function postJson(url, data, timeout) {
|
||||
const response = await urllib.request(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
},
|
||||
data: JSON.stringify(data),
|
||||
timeout: Number(timeout) || 10000,
|
||||
dataType: 'text',
|
||||
});
|
||||
|
||||
return {
|
||||
status: response.status,
|
||||
body: String(response.data || ''),
|
||||
};
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const options = parseArgs(process.argv.slice(2));
|
||||
if (options.help) {
|
||||
printHelp();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!options.textUrl && !options.fileUrl) {
|
||||
throw new Error('请通过 --url 或 --text-url/--file-url 指定接收端地址');
|
||||
}
|
||||
|
||||
const tasks = [];
|
||||
if ([ 'both', 'text' ].includes(options.mode) && options.textUrl) {
|
||||
tasks.push({
|
||||
label: 'text',
|
||||
url: options.textUrl,
|
||||
payload: buildTextPayload(options),
|
||||
});
|
||||
}
|
||||
if ([ 'both', 'file' ].includes(options.mode) && options.fileUrl) {
|
||||
tasks.push({
|
||||
label: 'file',
|
||||
url: options.fileUrl,
|
||||
payload: buildFilePayload(options),
|
||||
});
|
||||
}
|
||||
|
||||
if (tasks.length === 0) {
|
||||
throw new Error(`mode=${options.mode} 下没有可发送的 webhook 请求`);
|
||||
}
|
||||
|
||||
const results = [];
|
||||
for (const task of tasks) {
|
||||
console.log(`\n[send] ${task.label.toUpperCase()} -> ${task.url}`);
|
||||
const response = await postJson(task.url, task.payload, options.timeout);
|
||||
console.log(`[response] status=${response.status} body=${response.body}`);
|
||||
results.push({
|
||||
label: task.label,
|
||||
url: task.url,
|
||||
status: response.status,
|
||||
body: response.body,
|
||||
traceId: task.payload.traceId,
|
||||
event: task.payload.event,
|
||||
});
|
||||
}
|
||||
|
||||
const failedCount = results.filter(item => Number(item.status) < 200 || Number(item.status) >= 300).length;
|
||||
console.log('\n[summary]');
|
||||
console.log(JSON.stringify({
|
||||
options: {
|
||||
...options,
|
||||
timeout: Number(options.timeout),
|
||||
},
|
||||
results,
|
||||
failedCount,
|
||||
}, null, 2));
|
||||
|
||||
if (failedCount > 0) {
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
console.error('[debug-send-receiving-webhooks] failed:', error.message);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,206 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 仓库接口消息推送 — 本地调试接收服务。
|
||||
* 模拟外部适配器:接收 WMS 出站推送(notify.reply / notify.event 等),
|
||||
* 打印完整回信(query 签名参数 + headers + body)到控制台与日志文件,方便调试。
|
||||
*
|
||||
* 默认配置匹配线上仓库「仓库管理系统oms」:
|
||||
* app_key=APP2025011514315678
|
||||
* app_secret=sec_xyz789uvw012abc345def678ghi901jkl234mno567pqr890
|
||||
* callback_url=http://localhost:6061/push
|
||||
*
|
||||
* 用法:
|
||||
* npm run debug:warehouse:push-receiver
|
||||
* node script/debug-warehouse-push-receiver.cjs --port=6061 --path=/push --log-file=run/push.log
|
||||
* node script/debug-warehouse-push-receiver.cjs --no-verify # 跳过 MD5 验签
|
||||
*/
|
||||
|
||||
const http = require('node:http');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const crypto = require('node:crypto');
|
||||
const { URL } = require('node:url');
|
||||
|
||||
const DEFAULT_HOST = '127.0.0.1';
|
||||
const DEFAULT_PORT = 6061;
|
||||
const DEFAULT_PATH = '/push';
|
||||
const DEFAULT_APP_KEY = 'APP2025011514315678';
|
||||
const DEFAULT_APP_SECRET = 'sec_xyz789uvw012abc345def678ghi901jkl234mno567pqr890';
|
||||
const DEFAULT_LOG_FILE = path.join(process.cwd(), 'run', 'warehouse-push-receiver.log');
|
||||
|
||||
function parseArgs(argv) {
|
||||
const options = {
|
||||
host: process.env.PUSH_RECEIVER_HOST || DEFAULT_HOST,
|
||||
port: Number(process.env.PUSH_RECEIVER_PORT || DEFAULT_PORT),
|
||||
path: process.env.PUSH_RECEIVER_PATH || DEFAULT_PATH,
|
||||
appKey: process.env.PUSH_RECEIVER_APP_KEY || DEFAULT_APP_KEY,
|
||||
appSecret: process.env.PUSH_RECEIVER_APP_SECRET || DEFAULT_APP_SECRET,
|
||||
logFile: process.env.PUSH_RECEIVER_LOG_FILE || DEFAULT_LOG_FILE,
|
||||
verifySign: ![ '0', 'false' ].includes(String(process.env.PUSH_RECEIVER_VERIFY_SIGN || '1').toLowerCase()),
|
||||
help: false,
|
||||
};
|
||||
|
||||
for (const arg of argv) {
|
||||
if (!arg.startsWith('--')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const [ rawKey, ...rest ] = arg.slice(2).split('=');
|
||||
const value = rest.join('=');
|
||||
switch (rawKey) {
|
||||
case 'host':
|
||||
options.host = value || options.host;
|
||||
break;
|
||||
case 'port':
|
||||
options.port = Number(value || options.port);
|
||||
break;
|
||||
case 'path':
|
||||
options.path = value.startsWith('/') ? value : `/${value}`;
|
||||
break;
|
||||
case 'app-key':
|
||||
options.appKey = value || options.appKey;
|
||||
break;
|
||||
case 'app-secret':
|
||||
options.appSecret = value || options.appSecret;
|
||||
break;
|
||||
case 'log-file':
|
||||
options.logFile = value || options.logFile;
|
||||
break;
|
||||
case 'no-verify':
|
||||
options.verifySign = false;
|
||||
break;
|
||||
case 'help':
|
||||
options.help = true;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return options;
|
||||
}
|
||||
|
||||
function printHelp() {
|
||||
console.log(`用法:
|
||||
npm run debug:warehouse:push-receiver
|
||||
node script/debug-warehouse-push-receiver.cjs --port=6061 --path=/push --log-file=run/push.log
|
||||
node script/debug-warehouse-push-receiver.cjs --no-verify
|
||||
|
||||
参数:
|
||||
--host=127.0.0.1 监听地址
|
||||
--port=6061 监听端口
|
||||
--path=/push 接收路径
|
||||
--app-key=... 期望的 app_key(仅用于展示)
|
||||
--app-secret=... 验签密钥(MD5(appSecret + timestamp + bodyJson))
|
||||
--log-file=... 日志文件(默认 run/warehouse-push-receiver.log)
|
||||
--no-verify 跳过 MD5 验签
|
||||
|
||||
环境变量:
|
||||
PUSH_RECEIVER_HOST / PUSH_RECEIVER_PORT / PUSH_RECEIVER_PATH
|
||||
PUSH_RECEIVER_APP_KEY / PUSH_RECEIVER_APP_SECRET / PUSH_RECEIVER_LOG_FILE
|
||||
PUSH_RECEIVER_VERIFY_SIGN=0 关闭验签`);
|
||||
}
|
||||
|
||||
function readRequestBody(req) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const chunks = [];
|
||||
req.on('data', chunk => chunks.push(chunk));
|
||||
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
|
||||
req.on('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
function writeLog(logFile, text) {
|
||||
const line = text.endsWith('\n') ? text : text + '\n';
|
||||
try {
|
||||
fs.appendFileSync(logFile, line, 'utf8');
|
||||
console.log(`[push-receiver] 已写入日志文件: ${logFile}`);
|
||||
} catch (error) {
|
||||
console.error('[push-receiver] 写日志文件失败:', error.message);
|
||||
}
|
||||
}
|
||||
|
||||
function md5(value) {
|
||||
return crypto.createHash('md5').update(value).digest('hex');
|
||||
}
|
||||
|
||||
async function start() {
|
||||
const options = parseArgs(process.argv.slice(2));
|
||||
if (options.help) {
|
||||
printHelp();
|
||||
return;
|
||||
}
|
||||
|
||||
const logFile = path.resolve(options.logFile);
|
||||
const logDir = path.dirname(logFile);
|
||||
fs.mkdirSync(logDir, { recursive: true });
|
||||
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const url = new URL(req.url, `http://${req.headers.host || `${options.host}:${options.port}`}`);
|
||||
const startedAt = new Date().toISOString();
|
||||
const rawBody = await readRequestBody(req);
|
||||
const query = Object.fromEntries(url.searchParams.entries());
|
||||
|
||||
if (url.pathname === '/health') {
|
||||
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' });
|
||||
res.end(JSON.stringify({ ok: true, service: 'warehouse-push-receiver' }));
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.method !== 'POST' || url.pathname !== options.path) {
|
||||
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });
|
||||
res.end(`404 Not Found(接收路径为 ${options.path})`);
|
||||
return;
|
||||
}
|
||||
|
||||
// MD5 验签:sign = MD5(appSecret + timestamp + bodyJson)
|
||||
const timestamp = String(query.timestamp || '');
|
||||
const providedSign = String(query.sign || '');
|
||||
const expectedSign = options.appSecret ? md5(options.appSecret + timestamp + rawBody) : '';
|
||||
const signOk = !options.verifySign || (timestamp && providedSign === expectedSign);
|
||||
|
||||
let parsedBody = rawBody;
|
||||
try {
|
||||
parsedBody = rawBody ? JSON.parse(rawBody) : null;
|
||||
} catch (_) {
|
||||
// keep raw text
|
||||
}
|
||||
|
||||
const logText = [
|
||||
'================ 收到仓库接口推送 ================',
|
||||
`[time] ${startedAt}`,
|
||||
`[route] POST ${url.pathname}`,
|
||||
`[query] ${JSON.stringify(query, null, 2)}`,
|
||||
options.verifySign
|
||||
? `[sign] ${signOk ? '验签通过' : `验签失败(期望 ${expectedSign})`}`
|
||||
: '[sign] 已关闭验签',
|
||||
`[header] ${JSON.stringify(req.headers, null, 2)}`,
|
||||
`[body] ${JSON.stringify(parsedBody, null, 2)}`,
|
||||
'==================================================',
|
||||
].join('\n');
|
||||
|
||||
console.log('\n' + logText);
|
||||
writeLog(logFile, `${logText}\n`);
|
||||
|
||||
// 始终返回 HTTP 200 + code=200,便于 WMS 判定推送成功
|
||||
const responseBody = JSON.stringify({ code: 200, message: 'ok', received_at: startedAt });
|
||||
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' });
|
||||
res.end(responseBody);
|
||||
});
|
||||
|
||||
server.listen(options.port, options.host, () => {
|
||||
console.log('[warehouse-push-receiver] listening on http://' + options.host + ':' + options.port + options.path);
|
||||
console.log(`[warehouse-push-receiver] app_key=${options.appKey}`);
|
||||
console.log(`[warehouse-push-receiver] app_secret=${options.appSecret ? options.appSecret.slice(0, 8) + '…' : '(空)'}`);
|
||||
console.log(`[warehouse-push-receiver] 验签=${options.verifySign ? '开启' : '关闭'}`);
|
||||
console.log(`[warehouse-push-receiver] 日志文件=${logFile}`);
|
||||
console.log(`[warehouse-push-receiver] 健康检查: GET http://${options.host}:${options.port}/health`);
|
||||
console.log('[warehouse-push-receiver] 按 Ctrl+C 停止');
|
||||
});
|
||||
}
|
||||
|
||||
start().catch(error => {
|
||||
console.error('[warehouse-push-receiver] failed:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,134 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const http = require('node:http');
|
||||
const { URL } = require('node:url');
|
||||
|
||||
function parseArgs(argv) {
|
||||
const options = {
|
||||
host: process.env.WEBHOOK_DEBUG_HOST || '127.0.0.1',
|
||||
port: Number(process.env.WEBHOOK_DEBUG_PORT || 7071),
|
||||
defaultResponse: process.env.WEBHOOK_DEBUG_RESPONSE || '1',
|
||||
noticResponse: process.env.WEBHOOK_DEBUG_NOTIC_RESPONSE || '',
|
||||
notic2Response: process.env.WEBHOOK_DEBUG_NOTIC2_RESPONSE || '',
|
||||
};
|
||||
|
||||
for (const arg of argv) {
|
||||
if (!arg.startsWith('--')) {
|
||||
continue;
|
||||
}
|
||||
const [rawKey, ...rest] = arg.slice(2).split('=');
|
||||
const value = rest.join('=');
|
||||
switch (rawKey) {
|
||||
case 'host':
|
||||
options.host = value || options.host;
|
||||
break;
|
||||
case 'port':
|
||||
options.port = Number(value || options.port);
|
||||
break;
|
||||
case 'response':
|
||||
options.defaultResponse = value || options.defaultResponse;
|
||||
break;
|
||||
case 'notic-response':
|
||||
options.noticResponse = value || options.noticResponse;
|
||||
break;
|
||||
case 'notic2-response':
|
||||
options.notic2Response = value || options.notic2Response;
|
||||
break;
|
||||
case 'help':
|
||||
options.help = true;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return options;
|
||||
}
|
||||
|
||||
function printHelp() {
|
||||
console.log(`用法:\n npm run debug:webhook:receiver\n npm run debug:webhook:receiver -- --port=7071 --notic-response=1 --notic2-response=0\n\n环境变量:\n WEBHOOK_DEBUG_PORT=7071\n WEBHOOK_DEBUG_RESPONSE=1\n WEBHOOK_DEBUG_NOTIC_RESPONSE=1\n WEBHOOK_DEBUG_NOTIC2_RESPONSE=0\n`);
|
||||
}
|
||||
|
||||
function readRequestBody(req) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const chunks = [];
|
||||
req.on('data', chunk => chunks.push(chunk));
|
||||
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
|
||||
req.on('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
function buildResponseBody(pathname, options) {
|
||||
if (pathname === '/notic2' && options.notic2Response) {
|
||||
return options.notic2Response;
|
||||
}
|
||||
if (pathname === '/notic' && options.noticResponse) {
|
||||
return options.noticResponse;
|
||||
}
|
||||
return options.defaultResponse;
|
||||
}
|
||||
|
||||
async function start() {
|
||||
const options = parseArgs(process.argv.slice(2));
|
||||
if (options.help) {
|
||||
printHelp();
|
||||
return;
|
||||
}
|
||||
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const url = new URL(req.url, `http://${req.headers.host || `${options.host}:${options.port}`}`);
|
||||
const startedAt = new Date().toISOString();
|
||||
const rawBody = await readRequestBody(req);
|
||||
let parsedBody = rawBody;
|
||||
|
||||
try {
|
||||
parsedBody = rawBody ? JSON.parse(rawBody) : null;
|
||||
} catch (_) {
|
||||
// keep raw text
|
||||
}
|
||||
|
||||
console.log('\n================ WEBHOOK DEBUG RECEIVER ================');
|
||||
console.log(`[time] ${startedAt}`);
|
||||
console.log(`[route] ${req.method} ${url.pathname}`);
|
||||
console.log('[query] ', Object.fromEntries(url.searchParams.entries()));
|
||||
console.log('[header]', req.headers);
|
||||
console.log('[body] ', JSON.stringify(parsedBody, null, 2));
|
||||
|
||||
if (![ '/notic', '/notic2', '/health' ].includes(url.pathname)) {
|
||||
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });
|
||||
res.end('404 Not Found');
|
||||
return;
|
||||
}
|
||||
|
||||
if (url.pathname === '/health') {
|
||||
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' });
|
||||
res.end(JSON.stringify({ ok: true, service: 'webhook-debug-receiver' }));
|
||||
return;
|
||||
}
|
||||
|
||||
const responseBody = buildResponseBody(url.pathname, options);
|
||||
const statusCode = String(responseBody).startsWith('{') || String(responseBody).startsWith('[') ? 200 : 200;
|
||||
const contentType = String(responseBody).startsWith('{') || String(responseBody).startsWith('[')
|
||||
? 'application/json; charset=utf-8'
|
||||
: 'text/plain; charset=utf-8';
|
||||
|
||||
res.writeHead(statusCode, { 'content-type': contentType });
|
||||
res.end(responseBody);
|
||||
|
||||
console.log(`[reply] ${url.pathname} -> ${responseBody}`);
|
||||
console.log('========================================================\n');
|
||||
});
|
||||
|
||||
server.listen(options.port, options.host, () => {
|
||||
console.log(`[webhook-debug-receiver] listening on http://${options.host}:${options.port}`);
|
||||
console.log(`[webhook-debug-receiver] endpoints:`);
|
||||
console.log(` - POST http://${options.host}:${options.port}/notic`);
|
||||
console.log(` - POST http://${options.host}:${options.port}/notic2`);
|
||||
console.log(` - GET http://${options.host}:${options.port}/health`);
|
||||
});
|
||||
}
|
||||
|
||||
start().catch(error => {
|
||||
console.error('[webhook-debug-receiver] failed:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -265,6 +265,7 @@ function createHarness(options = {}) {
|
||||
Storage: {
|
||||
async findAll(options = {}) {
|
||||
captures.storageFindAllWhere = options.where;
|
||||
captures.storageFindAllInclude = options.include;
|
||||
return storageRows.filter(row => matchesWhere(row, options.where)).map(row => ({ ...row }));
|
||||
},
|
||||
},
|
||||
@ -540,6 +541,118 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
|
||||
assert.equal(orders[1].storage_status, 'fin');
|
||||
});
|
||||
|
||||
it('should ignore location type restriction when allow_storage_location is true', async () => {
|
||||
const { service, captures } = createHarness({
|
||||
orders: [
|
||||
{ id: 901, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 },
|
||||
],
|
||||
orderItems: [
|
||||
{ id: 9011, order_id: 901, stock_id: 9011, plan_qty: 1, order_line_no: '1' },
|
||||
],
|
||||
stockRows: [
|
||||
{ id: 9011, item_code: 'SKU-9011', item_name: '测试商品9011', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 },
|
||||
],
|
||||
storageRows: [
|
||||
{
|
||||
id: 90101,
|
||||
warehouse_id: 100000,
|
||||
stock_id: 9011,
|
||||
is_enabled: 1,
|
||||
delete_at: null,
|
||||
available_quantity: 1,
|
||||
quantity: 1,
|
||||
locked_quantity: 0,
|
||||
production_date: null,
|
||||
inbound_time: '2026-04-15 08:00:00',
|
||||
space_id: 90501,
|
||||
space: {
|
||||
id: 90501,
|
||||
space_code: 'ST-901',
|
||||
custom_name: '受限存储位',
|
||||
is_preferred_pick: false,
|
||||
locationType: {
|
||||
id: 9,
|
||||
allow_allocation: 0,
|
||||
is_active: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const result = await service.allocateStorage({
|
||||
allow_storage_location: true,
|
||||
order_ids: [ 901 ],
|
||||
});
|
||||
|
||||
assert.equal(result.code, 200);
|
||||
assert.equal(result.data.allocated_order_ids.length, 1);
|
||||
|
||||
const locationTypeInclude = captures.storageFindAllInclude
|
||||
&& captures.storageFindAllInclude[0]
|
||||
&& captures.storageFindAllInclude[0].include
|
||||
&& captures.storageFindAllInclude[0].include[0];
|
||||
assert.ok(locationTypeInclude, 'locationType include 应存在');
|
||||
assert.equal(Object.prototype.hasOwnProperty.call(locationTypeInclude, 'where'), false);
|
||||
});
|
||||
|
||||
it('should keep location type restriction when allow_storage_location is false', async () => {
|
||||
const { service, captures } = createHarness({
|
||||
orders: [
|
||||
{ id: 902, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 },
|
||||
],
|
||||
orderItems: [
|
||||
{ id: 9021, order_id: 902, stock_id: 9021, plan_qty: 1, order_line_no: '1' },
|
||||
],
|
||||
stockRows: [
|
||||
{ id: 9021, item_code: 'SKU-9021', item_name: '测试商品9021', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 },
|
||||
],
|
||||
storageRows: [
|
||||
{
|
||||
id: 90201,
|
||||
warehouse_id: 100000,
|
||||
stock_id: 9021,
|
||||
is_enabled: 1,
|
||||
delete_at: null,
|
||||
available_quantity: 1,
|
||||
quantity: 1,
|
||||
locked_quantity: 0,
|
||||
production_date: null,
|
||||
inbound_time: '2026-04-15 08:00:00',
|
||||
space_id: 90502,
|
||||
space: {
|
||||
id: 90502,
|
||||
space_code: 'ST-902',
|
||||
custom_name: '存储位902',
|
||||
is_preferred_pick: false,
|
||||
locationType: {
|
||||
id: 1,
|
||||
allow_allocation: 1,
|
||||
is_active: 1,
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const result = await service.allocateStorage({
|
||||
allow_storage_location: false,
|
||||
order_ids: [ 902 ],
|
||||
});
|
||||
|
||||
assert.equal(result.code, 200);
|
||||
|
||||
const locationTypeInclude = captures.storageFindAllInclude
|
||||
&& captures.storageFindAllInclude[0]
|
||||
&& captures.storageFindAllInclude[0].include
|
||||
&& captures.storageFindAllInclude[0].include[0];
|
||||
assert.ok(locationTypeInclude, 'locationType include 应存在');
|
||||
assert.deepEqual(locationTypeInclude.where, {
|
||||
allow_allocation: 1,
|
||||
is_active: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it('should skip cancelled orders when allocating storage', async () => {
|
||||
const { service, captures, orders } = createHarness({
|
||||
orders: [
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user