feat(inbox): 规则引擎成为主回复路径,退回收件登记按仓库+货主聚合通知货主群
This commit is contained in:
parent
f2fe5311aa
commit
fd565fda7b
@ -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: '退回收到登记表',
|
||||
|
||||
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;
|
||||
@ -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}`);
|
||||
|
||||
@ -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,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');
|
||||
}
|
||||
},
|
||||
};
|
||||
Loading…
x
Reference in New Issue
Block a user