feat: inbox 新增打包视频查询/查重/分配快递号函数,快递反馈回信优化

This commit is contained in:
liufumingren 2026-08-14 23:06:05 +08:00
parent 98bc088929
commit f3cf941721
15 changed files with 1283 additions and 37 deletions

View File

@ -35,6 +35,7 @@ module.exports = app => {
{ name: '多发', value: 'extra_item' },
{ name: '改地址', value: 'change_address' },
{ name: '换快递', value: 'change_carrier' },
{ name: '揽收', value: 'pickup' },
{ name: '重量异常', value: 'weight_issue' },
{ name: '运费争议', value: 'freight_issue' },
{ name: '其他', value: 'other' },

View File

@ -83,6 +83,10 @@ class InboxAIService extends Service {
const userId = String(ctx.inboxContext?.user_id || '').trim();
const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0);
// 排除当前消息本身(parentId=当前消息id;recallHistory 时取上下文注入的入站消息id),
// 避免"当前请求"混入历史导致 AI 重复处理
const excludeId = parentId || Number(ctx.inboxContext?.inbound_message_id) || 0;
// 无群/用户上下文时,退回旧逻辑:沿 parent_id 追溯
if (!groupId || !userId || !warehouseId) {
if (!parentId) return [];
@ -117,6 +121,7 @@ class InboxAIService extends Service {
warehouse_id: warehouseId,
group_id: groupId,
direction: { [Op.in]: [ 'inbound', 'outbound' ] },
...(excludeId ? { id: { [Op.ne]: excludeId } } : {}),
},
order: [[ 'created_at', 'DESC' ]],
limit: maxMessages,
@ -186,7 +191,7 @@ class InboxAIService extends Service {
const historyContext = history.length > 0
? history.map(h => {
const tag = h.blocked ? '[已屏蔽]' : '';
return `[${h.role === 'user' ? h.user_name || h.user_id || '未知' : 'AI'}]${tag}: ${h.content}`;
return `[历史]${h.role === 'user' ? h.user_name || h.user_id || '未知' : 'AI'}${tag}: ${h.content}`;
}).join('\n')
: '(无历史)';
@ -207,6 +212,12 @@ ${historyContext}
对话历史中 [已屏蔽] 标记表示该用户已主动要求屏蔽(不想被 AI 打扰)。
如果 [已屏蔽] 用户发送了表示接手或正在处理的内容(如"我来处理""不用回复""稍等""我看看"),说明真人已接管 → 直接 silent。
【历史消息边界 - 最高优先级】
- 以上带 [历史] 前缀的记录均为群历史消息,**全部已处理完毕**,仅作背景参考(判断是否有人已接管等),不是待处理请求
- 严禁把历史记录中的运单号/订单号/地址/售后诉求等当作当前用户的新请求;严禁对历史记录中的请求重复调用函数或重复创建工单
- 只有最后一条不带 [历史] 前缀的用户消息才是本次待处理请求,所有函数参数只能从这条当前消息中提取
- 当前消息未提供运单号/订单号等必填参数时,必须先向用户确认,严禁从历史记录中拼凑参数
你需要通过多轮调用来完成用户的复杂请求。每轮返回纯 JSON:
如果还需要调用函数获取信息:
@ -241,6 +252,7 @@ ${historyContext}
- 回复使用中文纯文本,禁止 Markdown 语法,可用 \\n 换行提升可读性
- silent 仅用于:用户已确认收到消息且无新问题("好的""收到""OK""谢谢""知道了""好"),或用户表示告别/离场("再见""拜拜""88")
- 以下情况严禁 silent,必须 reply:任何形式的提问(含"在吗""有人吗""在不在")、操作请求、函数执行完毕、自定义欢迎语"你好""嗨""hello"等首次问候
- 【快递群专项】快递客服发出的进度/结果反馈("已通知网点""网点正在处理""已拦截""已联系收件人""改地址失败/无法改""已签收"等)严禁 silent,必须先调用 handleExpressFeedback 记录反馈再回复
- 无法判断时,宁可回复也不要 silent
- searchStock 返回多条结果时,必须列举让用户选择(告知 id/编码/名称/可用库存),不要擅自决定
- createOrder 失败时告知失败原因(库存不足/商品不存在等),不要重试同一商品
@ -253,11 +265,17 @@ ${historyContext}
- 用户说"第1个""第2个"时,按 searchStock 返回的顺序对应选择
- 需要上下文但记忆不足时,主动调用 recallHistory 回顾对话历史
- 【防误判规则 - interceptWaybill】讨论已有售后工单(AS开头编号)、询问物流进度、问"快递到哪了"、转发售后截图等均不是拦截请求,严禁调用 interceptWaybill。只有用户明确说"拦截/退回/召回/追回/取消"运单时才可调用
- 【规则 - requestPickup】货主售后群/仓库客服群中客户要求上门揽收/取件(如"揽收""上门取件""退货取件""寄回""让快递来拿"等)且提供了运单号时,调用 requestPickup(keyword=运单号,多个用逗号分隔)。函数会创建揽收售后工单,并优先转发到对应快递的揽收群(未配置揽收群时回退到售后群);返回的 data.message 是模板消息必须原样回复;若消息中无运单号,先向客户确认运单号再调用
- 【措辞规则 - interceptWaybill】拦截结果回复严禁使用"已拦截""拦截成功"等确定口吻,必须使用"拦截信息已登记""已提交拦截申请"等措辞。因为快递拦截可能失败,实际结果以快递公司反馈为准。回复时需列出工单号供用户跟进
- 【规则 - handleStoreFeedback】货主售后群中客户反馈"错发/发错""破损/坏了""多发/发多""少发/漏发"且提供了运单号时,调用 handleStoreFeedback 创建售后工单(初始状态未开始处理,不通知快递群);若消息中无运单号,先向客户确认运单号再调用
- 【规则 - handleExpressFeedback】快递售后群中,快递客服反馈处理进度/结果(如"已通知网点""网点正在处理""已拦截""已联系收件人""改地址失败/无法改""已签收""加急处理"等)且消息含运单号时,必须调用 handleExpressFeedback(keyword=运单号,多个用逗号分隔)。该函数会自动查找已有售后工单追加反馈并回信到相关群,无工单则自动创建。严禁把快递客服的进度/结果反馈判定为无需处理而 silent;若消息无运单号,先用 recallHistory 或询问确认运单号,严禁跳过
- 【规则 - handleExpressFeedback 证据核实】快递售后群中快递方发消息要求"提供交易记录截图/未收到依据/核实签收/带日期单号"等证据类诉求且消息含运单号时,同样必须调用 handleExpressFeedback(as_sub_type=verify_delivery),由函数创建售后工单并回信到货主售后群;严禁仅回复"收到/已记录"等确认话术而不调用函数
- 【规则 - changeAddr】货主售后群中客户消息含"改地址/改电话/改联系人/改收件人/地址更改/改手机/催退回/尽快安排派送/催促退回"等诉求且提供了运单号时,调用 changeAddr(issue_type:addr=改地址类诉求,return=催退回类诉求);函数会创建售后工单并把客户原文转发到对应快递群,返回的 data.message 是模板消息必须原样回复;若消息中无运单号,先向客户确认运单号再调用
- 【规则 - weishoudao】货主售后群中客户消息含"核实签收/未收到/是否发出/是否已经发货/核实/没有找到快递"等诉求且提供了运单号时,调用 weishoudao 创建核实签收售后工单,并把"运单号+核实签收"转发到对应快递群;返回的 data.message 是模板消息必须原样回复;若消息中无运单号,先向客户确认运单号再调用
- 【规则 - changeExpress】货主售后群中客户要求"改快递/换快递/改圆通/改中通/改顺丰"等且提供了订单号时,调用 changeExpress(keyword=订单号,express=目标快递名称或编码);仅待处理表中未分配快递的订单可以修改,已分配快递或不在待处理表的订单不能修改;返回的 data.message 是模板消息必须原样回复;若消息中缺订单号或目标快递,先向客户确认再调用
- 【规则 - queryPackVideo】用户询问"打包视频/打包录像/装箱视频"且提供了运单号时,调用 queryPackVideo 查询(散单按订单、团购单按波次找打包记录);仅查询不建工单;返回的 data.message 是模板消息必须原样回复;若消息中无运单号,先向客户确认运单号再调用
- 【规则 - queryWeight】用户询问"查重/重量/核实重量/核重/称重"且提供了运单号时,调用 queryWeight 查询运单称重;重量为0时模板输出"未称重";仅查询不建工单;返回的 data.message 是模板消息必须原样回复;若消息中无运单号,先向客户确认运单号再调用
- 【规则 - createPostnum】货主售后群中客户要求"出单/打单/打印单/催发货/分配快递号"且提供了订单号时,调用 createPostnum(keyword=订单号,多个用逗号分隔);仅待处理表已审核且未分配快递号的订单可分配,函数会走分配流程并按结果返回"已分配+已回传"或"分配失败,等待客服人工处理"模板;返回的 data.message 是模板消息必须原样回复;若消息中无订单号,先向客户确认订单号再调用
- 【模板消息 - queryReturn】queryReturn 返回的 data.message 是已排版好的模板消息,必须原样作为最终回复输出,禁止改写、删减、增补内容,禁止添加 Markdown 或额外说明
- 【规则 - queryWarehouseAddress】用户询问"仓库地址/收货地址/退货地址/退件地址/寄回地址"时,调用 queryWarehouseAddress 查询仓库配置中的 receiver_address;返回的 data.message 是模板消息必须原样回复
- 【模板消息 - handleStoreFeedback】handleStoreFeedback 返回的 data.message 是已排版好的模板消息(运单号+问题类型+工单号+"稍后客服将人工核实跟进"),必须原样作为最终回复输出,禁止改写、删减或增补内容
@ -279,7 +297,6 @@ ${historyContext}
const messages = [
{ role: 'system', content: systemPrompt },
...history,
...(contextLines.length > 0 ? [{ role: 'system', content: contextLines.join('\n') }] : []),
{ role: 'user', content: round === 1
? content

View File

@ -631,7 +631,7 @@ class InboxFunctionsService extends Service {
});
this.register('recallHistory', {
description: '回顾当前群+用户的最近对话历史。当需要上下文但信息不足时调用,获取最近N条消息记录(含AI回复),每条带序号',
description: '回顾当前群的最近对话历史(均为已处理完毕的历史记录,仅作背景参考,严禁把其中的运单号/诉求当成新请求)。当需要上下文但信息不足时调用,获取最近N条消息记录(含AI回复),每条带序号',
params: {
limit: { type: 'number', required: false, description: '获取最近几条,默认5,最大10' },
},
@ -649,6 +649,7 @@ class InboxFunctionsService extends Service {
success: true,
data: {
total: history.length,
hint: '以下均为已处理完毕的历史记录,仅作背景参考,严禁把其中的运单号/诉求当作新请求处理',
messages: history.map(h => ({
role: h.role === 'user' ? '用户' : 'AI',
user: h.user_name || h.user_id || null,
@ -1193,6 +1194,297 @@ class InboxFunctionsService extends Service {
},
});
this.register('requestPickup', {
description: '揽收处理(退货/寄件上门取件)。客户要求上门揽收/取件且提供了运单号时调用:创建揽收售后工单,并把客户原文转发到对应快递的揽收群;该快递未配置揽收群时回退发送到售后群。仅写工单与通知群,不修改订单表和快递表数据',
weight: 88,
keywords: [ '揽收', '上门取件', '取件', '退货取件', '寄回', '上门揽收', '让快递来拿' ],
params: {
keyword: { type: 'string', required: true, description: '运单号,多个用逗号或空格分隔,如 SF111,SF222' },
reason: { type: 'string', required: false, description: '揽收备注/原因' },
},
groups: [ GROUP.BOUND_WAREHOUSE_CUSTOMER_SERVICE, GROUP.BOUND_STORE_AFTER_SALES ],
handler: async (params = {}) => {
const { ctx } = this;
const raw = String(params.keyword || '').trim();
const reason = String(params.reason || '').trim();
const storeId = Number(ctx.inboxContext?.store_id || 0);
const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0);
const groupType = String(ctx.inboxContext?.group_type || '').trim();
const groupName = String(ctx.inboxContext?.group_name || '').trim();
const userName = String(ctx.inboxContext?.user_name || '').trim();
if (!raw) return { success: false, error: '请提供运单号' };
if (!warehouseId) return { success: false, error: '无法获取仓库信息' };
// 解析多个运单号(逗号/空格/换行分隔)
const keywords = raw.split(/[,,\s\n]+/).map(s => s.trim()).filter(Boolean);
if (keywords.length === 0) return { success: false, error: '未解析到有效运单号' };
// 前置拦截:拒绝看起来像售后单号(AS...)的输入
const asLikeList = keywords.filter(k => /^AS/i.test(k));
if (asLikeList.length > 0) {
return {
success: false,
error: `${asLikeList.join('、')} 看起来是售后工单号而非运单号,请提供运单号`,
};
}
try {
// 第一步:批量查询运单(仅读取,不做任何修改)
const expressList = await ctx.model.OrderExpress.findAll({
attributes: [
'id', 'waybill_code', 'logistics_name', 'store_id',
'logistics_interface_id', 'logistics_code', 'order_id',
],
where: {
waybill_code: { [ctx.app.Sequelize.Op.in]: keywords },
warehouse_id: warehouseId,
},
raw: true,
});
if (expressList.length === 0) {
return { success: false, error: `未找到运单号「${raw}」,请核实单号后重试` };
}
// 第二步:鉴权 + 过滤(与拦截一致:货主群需验 store_id)
const validList = [];
const skipped = [];
for (const e of expressList) {
if (groupType === 'store') {
if (!storeId || Number(e.store_id) !== storeId) {
skipped.push(e.waybill_code);
continue;
}
}
validList.push(e);
}
if (validList.length === 0) {
return {
success: false,
error: `运单${skipped.join('、')}不属于当前货主,无法操作`,
};
}
// 第三步:幂等检查(同子类型未完结工单不重复建单)
const validIds = validList.map(e => e.id);
const existingASList = await ctx.model.AfterSale.findAll({
attributes: [ 'waybill_id', 'after_sale_no' ],
where: {
waybill_id: { [ctx.app.Sequelize.Op.in]: validIds },
type: 'order',
sub_type: 'pickup',
status: { [ctx.app.Sequelize.Op.notIn]: [ 'completed', 'closed', 'cancelled' ] },
},
raw: true,
});
const existingWaybillIds = new Set(existingASList.map(r => r.waybill_id));
const toCreate = validList.filter(e => !existingWaybillIds.has(e.id));
const alreadyExist = existingASList.map(r => r.after_sale_no);
if (toCreate.length === 0) {
const replyLines = [];
const existedWbs = validList
.filter(e => existingWaybillIds.has(e.id))
.map(e => e.waybill_code);
if (existedWbs.length > 0) {
replyLines.push(existedWbs.join('\n'));
replyLines.push('已登记过,无需重复');
}
if (skipped.length > 0) replyLines.push(`无权操作:${skipped.join('\n')}`);
return {
success: true,
data: {
existed: true,
message: replyLines.join('\n'),
direct_reply: true,
after_sale_nos: alreadyExist,
},
};
}
// 第四步:创建工单(初始状态 pending,后续根据通知结果升级)
const creatorLabel = [ groupName, userName ].filter(Boolean).join('-') || 'AI系统';
// 获取原消息内容,写入工单明细与转发文本
let originalText = '';
try {
const mid = ctx.inboxContext?.inbound_message_id;
if (mid) {
const m = await ctx.model.InboxMessage.findByPk(mid, { attributes: [ 'content' ], raw: true });
if (m && m.content) originalText = String(m.content);
}
} catch (e) { /* ignore */ }
const createdNos = [];
const waybillToAsNo = {}; // waybill_id → after_sale_no 映射
for (const e of toCreate) {
const afterSaleNo = await ctx.service.systemMethods.afterSale.generateAfterSaleNo(warehouseId);
const descParts = [
`发起人: ${creatorLabel}`,
`运单号: ${e.waybill_code}`,
`快递公司: ${e.logistics_name || '未知'}`,
reason ? `揽收备注: ${reason}` : '',
originalText ? `原文: ${originalText}` : '',
].filter(Boolean).join('\n');
await ctx.service.systems.afterSale.create({
warehouse_id: warehouseId,
after_sale_no: afterSaleNo,
type: 'order',
sub_type: 'pickup',
title: `[AI工单] 揽收请求 - ${e.waybill_code}`,
description: descParts,
priority: 10,
creator_id: 0,
inbox_message_id: ctx.inboxContext?.inbound_message_id || null,
role_group: 'customer_service',
status: 'pending',
waybill_id: e.id,
waybill_no: e.waybill_code,
store_id: e.store_id || storeId || null,
order_id: e.order_id || null,
});
createdNos.push(afterSaleNo);
waybillToAsNo[e.id] = afterSaleNo;
}
ctx.logger.info(
`[inbox functions] 批量揽收: total=${keywords.length} found=${expressList.length} ` +
`valid=${validList.length} created=${createdNos.length} skipped=${skipped.length}`
);
// 第五步:合并通知快递群(按快递分组)——优先揽收群,无揽收群回退售后群
const expressByCode = {};
for (const e of toCreate) {
const code = e.logistics_code || '__unknown__';
if (!expressByCode[code]) {
expressByCode[code] = { interfaceId: e.logistics_interface_id, waybills: [] };
}
expressByCode[code].waybills.push(e.waybill_code);
}
let notifiedTotal = 0;
const notifiedWaybillIds = new Set(); // 记录哪些运单成功通知了至少一个群
for (const [ code, info ] of Object.entries(expressByCode)) {
if (code === '__unknown__' || !info.interfaceId) continue;
try {
const { afterSalesGroups, pickupGroups } = await ctx.service.systems.inbox.group.findGroupsByExpress({
expressInterfaceId: info.interfaceId,
expressCode: code,
warehouseId,
});
// 优先揽收群;未配置揽收群时回退售后群
const targetGroups = pickupGroups.length > 0 ? pickupGroups : afterSalesGroups;
if (targetGroups.length === 0) {
ctx.logger.info(`[inbox functions] 快递 ${code} 未配置揽收群与售后群,跳过通知`);
continue;
}
// 发给快递的模板:运单号(每个一行)+ 揽收
const forwardMsg = info.waybills.join('\n') + '\n揽收';
for (const g of targetGroups) {
ctx.service.inbox.processor.pushSystemNotification({
warehouse_id: warehouseId,
group_id: g.group_id,
group_name: g.group_name,
content: forwardMsg,
ext_data: g.ext_data || null,
});
notifiedTotal += 1;
}
// 有目标群即标记为已通知(推送是异步的,不计成败)
const codeWaybills = toCreate.filter(e => (e.logistics_code || '__unknown__') === code);
codeWaybills.forEach(e => notifiedWaybillIds.add(e.id));
} catch (e) {
ctx.logger.warn(`[inbox functions] 查快递群失败 code=${code}: ${e.message}`);
}
}
// 第六步:有通知的工单升级为 pending_feedback
const notifiedAsNos = [];
const notNotifiedAsNos = [];
for (const e of toCreate) {
const asNo = waybillToAsNo[e.id];
if (notifiedWaybillIds.has(e.id)) {
notifiedAsNos.push(asNo);
} else {
notNotifiedAsNos.push(asNo);
}
}
if (notifiedAsNos.length > 0) {
const hours = await ctx.service.systems.afterSale._resolveFollowupHours(
warehouseId, 'order', 'pickup'
);
await ctx.model.AfterSale.update(
{
status: 'pending_feedback',
followup_at: ctx.app.Sequelize.literal(`DATE_ADD(NOW(), INTERVAL ${hours} HOUR)`),
role_group: 'customer_service',
},
{ where: { after_sale_no: { [ctx.app.Sequelize.Op.in]: notifiedAsNos } } }
);
ctx.logger.info(
`[inbox functions] ${notifiedAsNos.length} 个揽收工单已通知快递群,` +
`升级为 pending_feedback,${hours}h 后追踪`
);
}
// 构造客户回信模板:多个快递号换行分隔,同类状态共用一行说明
const replyLines = [];
const notifiedWbs = [];
const existedWbs = [];
const notNotifiedWbs = [];
for (const e of validList) {
if (notifiedWaybillIds.has(e.id)) {
notifiedWbs.push(e.waybill_code);
} else if (existingWaybillIds.has(e.id)) {
existedWbs.push(e.waybill_code);
} else {
notNotifiedWbs.push(e.waybill_code);
}
}
if (notifiedWbs.length > 0) {
replyLines.push(notifiedWbs.join('\n'));
replyLines.push('已通知运方,待处理后刷新轨迹');
}
if (notNotifiedWbs.length > 0) {
replyLines.push(notNotifiedWbs.join('\n'));
replyLines.push('已登记(未配置快递群,需人工跟进)');
}
if (existedWbs.length > 0) {
replyLines.push(existedWbs.join('\n'));
replyLines.push('已登记过,无需重复');
}
if (skipped.length > 0) {
replyLines.push(`无权操作:${skipped.join('\n')}`);
}
return {
success: true,
data: {
created: createdNos.length,
existed: alreadyExist.length,
skipped: skipped.length,
after_sale_nos: [ ...createdNos, ...alreadyExist ],
notified_as_nos: notifiedAsNos,
not_notified_as_nos: notNotifiedAsNos,
notified_groups: notifiedTotal,
waybills: validList.map(e => e.waybill_code),
message: replyLines.join('\n'),
direct_reply: true,
},
};
} catch (error) {
ctx.logger.error(`[inbox functions] 批量揽收失败: ${error.message}`);
return { success: false, error: `揽收操作失败: ${error.message}` };
}
},
});
this.register('queryReturn', {
description: '查询退回包裹明细(查退回)。用户发送"查退回+运单号"时调用。传入运单号,查询退回收到/退回拆包/未退回登记状态:已拆包返回拆包明细与录像地址模板消息,未退回则自动登记到退回查询表。注意:仅查询退回状态使用,与 interceptWaybill 拦截、queryOrder 订单查询不同',
weight: 90,
@ -2457,6 +2749,528 @@ class InboxFunctionsService extends Service {
},
});
this.register('createPostnum', {
description: '分配快递号/出单(打单/催发货)。客户要求"出单/打单/打印单/催发货/分配快递号"且提供了订单号时调用。仅待处理表中已审核且未分配快递号的订单可分配;分配成功后同步回传平台并通知单号,失败则提示等待客服人工处理。仅创建运单,不创建售后工单',
weight: 86,
keywords: [ '出单', '打单', '打印单', '催发货', '分配快递号', '要单号' ],
params: {
keyword: { type: 'string', required: true, description: '订单号(发货单号或平台单号),多个用逗号或空格分隔' },
},
groups: [ GROUP.BOUND_STORE_AFTER_SALES ],
handler: async (params = {}) => {
const { ctx } = this;
const raw = String(params.keyword || '').trim();
const storeId = Number(ctx.inboxContext?.store_id || 0);
const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0);
const groupName = String(ctx.inboxContext?.group_name || '').trim();
const userName = String(ctx.inboxContext?.user_name || '').trim();
if (!raw) return { success: false, error: '请提供订单号' };
if (!warehouseId) return { success: false, error: '无法获取仓库信息' };
if (!storeId) return { success: false, error: '无法获取货主信息,请确认已在货主售后群上下文中操作' };
const keywords = raw.split(/[,,\s\n]+/).map(s => s.trim()).filter(Boolean);
if (keywords.length === 0) return { success: false, error: '未解析到有效订单号' };
// 前置拦截:AS 开头为售后工单号,不是订单号
const asLikeList = keywords.filter(k => /^AS/i.test(k));
if (asLikeList.length > 0) {
return { success: false, error: `${asLikeList.join('、')} 是售后工单号而非订单号,请提供发货单号或平台单号` };
}
try {
const { Op } = ctx.app.Sequelize;
const factory = ctx.model.OrderDeliveryFactory;
// 第一步:查待处理表(仅当前货主)
const currentModel = await factory.getCurrentModel(warehouseId);
if (!currentModel) {
return { success: false, error: `仓库 ${warehouseId} 的待处理表不可用` };
}
const foundOrders = await currentModel.findAll({
attributes: [
'id', 'delivery_order_code', 'source_platform_code', 'source_order_codes',
'step', 'post_status', 'logistics_name',
],
where: {
store_id: storeId,
[Op.or]: [
{ delivery_order_code: { [Op.in]: keywords } },
{ source_platform_code: { [Op.in]: keywords } },
...keywords.map(k => ({ source_order_codes: { [Op.like]: `%${k}%` } })),
],
},
raw: true,
});
const foundCodes = new Set();
for (const o of foundOrders) {
foundCodes.add(o.delivery_order_code);
foundCodes.add(o.source_platform_code);
for (const sc of String(o.source_order_codes || '').split(',')) {
if (sc.trim()) foundCodes.add(sc.trim());
}
}
const missing = keywords.filter(k => !foundCodes.has(k));
// 第二步:未在待处理表找到的 → 查配送表/历史表区分"不在待处理表"与"未找到"
const notInPending = [];
const notFound = [];
if (missing.length > 0) {
const tableConfigs = [
{ getModel: (f, wid) => f.getDispatchModel(wid) },
{ getModel: (f, wid) => f.getHistoryModel(wid) },
];
const missingSet = new Set(missing);
for (const cfg of tableConfigs) {
if (missingSet.size === 0) break;
const model = await cfg.getModel(factory, warehouseId);
if (!model) continue;
const rows = await model.findAll({
attributes: [ 'delivery_order_code', 'source_platform_code', 'source_order_codes' ],
where: {
store_id: storeId,
[Op.or]: [
{ delivery_order_code: { [Op.in]: [ ...missingSet ] } },
{ source_platform_code: { [Op.in]: [ ...missingSet ] } },
...[ ...missingSet ].map(k => ({ source_order_codes: { [Op.like]: `%${k}%` } })),
],
},
raw: true,
});
for (const r of rows) {
const codes = [
r.delivery_order_code,
r.source_platform_code,
...String(r.source_order_codes || '').split(','),
].map(s => String(s || '').trim()).filter(Boolean);
for (const k of [ ...missingSet ]) {
if (codes.includes(k)) {
missingSet.delete(k);
notInPending.push(k);
}
}
}
}
for (const k of missingSet) notFound.push(k);
}
// 第三步:区分可分配(已审核 step>=1 且未分配快递号 post_status=none)
const eligible = foundOrders.filter(
o => Number(o.step) >= 1 && String(o.post_status || '').trim() === 'none'
);
const notReviewed = foundOrders.filter(
o => Number(o.step) < 1 && String(o.post_status || '').trim() === 'none'
);
const allocated = foundOrders.filter(o => String(o.post_status || '').trim() !== 'none');
// 第四步:提交分配任务并轮询结果(复用已有分配运单号流程)
const successLines = [];
const failLines = [];
if (eligible.length > 0) {
const eligibleIds = eligible.map(o => o.id);
const originalUser = ctx.user;
ctx.user = {
...(originalUser || {}),
store_id: warehouseId,
employees_id: 0,
employees_name: [ groupName, userName ].filter(Boolean).join('-') || 'AI系统',
};
let taskId = '';
try {
const submitResult = await ctx.service.systemMethods.order.pendingOrder.allocateExpressCode({
ids: eligibleIds,
});
taskId = String((submitResult && submitResult.task_id) || '').trim();
} catch (submitErr) {
ctx.logger.warn(`[inbox functions] 分配快递号提交失败: ${submitErr.message}`);
taskId = '';
}
if (taskId) {
// 轮询任务进度(最多 40 次 × 1.5s = 60s)
let taskStatus = 'running';
for (let attempt = 0; attempt < 40; attempt++) {
await new Promise(resolve => setTimeout(resolve, 1500));
try {
const progressResult = await ctx.service.systemMethods.order.pendingOrder.allocateExpressCodeTaskProgress({
task_id: taskId,
});
taskStatus = String(progressResult && progressResult.status || '').trim();
if ([ 'success', 'failed', 'not_found' ].includes(taskStatus)) break;
} catch (pollErr) {
ctx.logger.warn(`[inbox functions] 查询分配进度失败: ${pollErr.message}`);
taskStatus = 'failed';
break;
}
}
if (taskStatus === 'success') {
// 第五步:回查运单号(business_key=1 且 status=1)
const expressRows = await ctx.model.OrderExpress.findAll({
attributes: [ 'order_id', 'waybill_code' ],
where: {
order_id: { [Op.in]: eligibleIds },
warehouse_id: warehouseId,
business_key: 1,
status: 1,
},
raw: true,
});
const waybillByOrder = new Map();
for (const er of expressRows) {
if (er.waybill_code) waybillByOrder.set(Number(er.order_id), String(er.waybill_code));
}
for (const o of eligible) {
const wb = waybillByOrder.get(Number(o.id));
if (wb) {
successLines.push(`订单${o.delivery_order_code} 已分配:${wb}\n已回传`);
} else {
failLines.push(`订单${o.delivery_order_code} 分配失败,等待客服人工处理`);
}
}
} else {
for (const o of eligible) {
failLines.push(`订单${o.delivery_order_code} 分配失败,等待客服人工处理`);
}
}
} else {
for (const o of eligible) {
failLines.push(`订单${o.delivery_order_code} 分配失败,等待客服人工处理`);
}
}
ctx.user = originalUser;
}
// 第六步:组装模板消息
const lines = [];
if (successLines.length > 0) lines.push(successLines.join('\n'));
if (failLines.length > 0) lines.push(failLines.join('\n'));
if (notReviewed.length > 0) {
lines.push(`未审核,不能分配:${notReviewed.map(o => o.delivery_order_code).join('、')}`);
}
if (allocated.length > 0) {
lines.push(`已分配快递号:${allocated.map(o => `${o.delivery_order_code}(${o.logistics_name || '已取号'})`).join('、')}`);
}
if (notInPending.length > 0) {
lines.push(`不在待处理表,不能分配:${notInPending.join('、')}`);
}
if (notFound.length > 0) {
lines.push(`未找到订单:${notFound.join('、')}`);
}
ctx.logger.info(
`[inbox functions] 分配快递号: total=${keywords.length} eligible=${eligible.length} ` +
`success=${successLines.length} fail=${failLines.length} notReviewed=${notReviewed.length}`
);
return {
success: true,
data: {
success_count: successLines.length,
fail_count: failLines.length,
message: lines.join('\n'),
direct_reply: true,
},
};
} catch (error) {
ctx.logger.error(`[inbox functions] 分配快递号失败: ${error.message}`);
return { success: false, error: `操作失败: ${error.message}` };
}
},
});
this.register('queryPackVideo', {
description: '打包视频查询。传入运单号,查询该运单对应的打包视频:散单按订单查打包记录,团购单按波次查打包记录。有视频返回视频地址;有打包记录无视频提示稍后再试;无打包记录提示无打包记录。仅查询,不创建工单',
weight: 86,
keywords: [ '打包视频', '打包录像', '装箱视频', '打包监控', '录像' ],
params: {
keyword: { type: 'string', required: true, description: '运单号,多个用逗号或空格分隔,如 SF111,SF222' },
},
groups: [ GROUP.BOUND_STORE_AFTER_SALES, GROUP.BOUND_WAREHOUSE_CUSTOMER_SERVICE ],
handler: async (params = {}) => {
const { ctx } = this;
const raw = String(params.keyword || '').trim();
const storeId = Number(ctx.inboxContext?.store_id || 0);
const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0);
const groupType = String(ctx.inboxContext?.group_type || '').trim();
if (!raw) return { success: false, error: '请提供运单号' };
if (!warehouseId) return { success: false, error: '无法获取仓库信息' };
const keywords = raw.split(/[,,\s\n]+/).map(s => s.trim()).filter(Boolean);
if (keywords.length === 0) return { success: false, error: '未解析到有效运单号' };
// 前置拦截:AS 开头为售后工单号,不是运单号
const asLikeList = keywords.filter(k => /^AS/i.test(k));
if (asLikeList.length > 0) {
return { success: false, error: `${asLikeList.join('、')} 是售后工单号而非运单号,请提供运单号` };
}
try {
const { Op } = ctx.app.Sequelize;
// 第一步:批量查询运单
const expressList = await ctx.model.OrderExpress.findAll({
attributes: [ 'id', 'waybill_code', 'store_id', 'order_id', 'logistics_name' ],
where: {
waybill_code: { [Op.in]: keywords },
warehouse_id: warehouseId,
},
raw: true,
});
const foundCodes = new Set(expressList.map(e => e.waybill_code));
const notFound = keywords.filter(k => !foundCodes.has(k));
// 鉴权:货主群需验 store_id
const validList = [];
const skipped = [];
for (const e of expressList) {
if (groupType === 'store') {
if (!storeId || Number(e.store_id) !== storeId) {
skipped.push(e.waybill_code);
continue;
}
}
validList.push(e);
}
if (validList.length === 0) {
const parts = [];
if (notFound.length > 0) parts.push(`未找到运单:${notFound.join('、')}`);
if (skipped.length > 0) parts.push(`无权操作:${skipped.join('、')}`);
return {
success: false,
error: parts.join(';') || `未找到运单号「${raw}」,请核实单号后重试`,
};
}
const videoLines = [];
const noVideoWbs = [];
const noRecordWbs = [];
const orderMissingWbs = [];
for (const e of validList) {
// 第二步:查订单行(当前表 → 历史表 → 配送表),取波次信息
let orderRow = null;
const tableGetters = [
(f, wid) => f.getCurrentModel(wid),
(f, wid) => f.getHistoryModel(wid),
(f, wid) => f.getDispatchModel(wid),
];
for (const getModel of tableGetters) {
try {
const model = await getModel(ctx.model.OrderDeliveryFactory, warehouseId);
if (!model) continue;
orderRow = await model.findOne({
attributes: [ 'id', 'wave_id', 'wave_no', 'pack_status' ],
where: { id: e.order_id },
raw: true,
});
} catch (err) { /* ignore */ }
if (orderRow) break;
}
if (!orderRow) {
orderMissingWbs.push(e.waybill_code);
continue;
}
// 第三步:判断团购/散单(wave_type=1 为团购波次)
let isGroupBuy = false;
if (Number(orderRow.wave_id) > 0) {
try {
const wave = await ctx.model.WaveBatch.findOne({
attributes: [ 'wave_id', 'wave_type' ],
where: { wave_id: orderRow.wave_id },
raw: true,
});
if (wave && Number(wave.wave_type) === 1) isGroupBuy = true;
} catch (err) { /* ignore */ }
}
// 第四步:团购按波次、散单按订单找打包记录
const packWhere = isGroupBuy
? { wave_id: orderRow.wave_id, deleted_at: null }
: { order_id: e.order_id, deleted_at: null };
const packTasks = await ctx.model.PackTask.findAll({
attributes: [ 'id', 'wave_id', 'wave_no', 'pack_mode', 'status' ],
where: packWhere,
raw: true,
});
if (packTasks.length === 0) {
noRecordWbs.push(e.waybill_code);
continue;
}
// 第五步:查打包视频
const taskIds = packTasks.map(t => t.id);
const videos = await ctx.model.PackTaskVideo.findAll({
attributes: [ 'id', 'video_url', 'status' ],
where: {
pack_task_id: { [Op.in]: taskIds },
deleted_at: null,
},
raw: true,
});
const urls = videos
.filter(v => String(v.status || '') !== 'failed')
.map(v => String(v.video_url || '').trim())
.filter(Boolean);
if (urls.length === 0) {
noVideoWbs.push(e.waybill_code);
} else {
videoLines.push(`${e.waybill_code}\n${urls.join('\n')}`);
}
}
// 第六步:组装模板消息(仅查询,不建工单)
const lines = [];
if (videoLines.length > 0) {
lines.push(videoLines.join('\n'));
}
if (noVideoWbs.length > 0) {
lines.push(noVideoWbs.join('\n'));
lines.push('打包视频可能还未保存,请稍后再试');
}
if (noRecordWbs.length > 0) {
lines.push(noRecordWbs.join('\n'));
lines.push('无打包记录');
}
if (orderMissingWbs.length > 0) {
lines.push(`未找到订单:${orderMissingWbs.join('、')}`);
}
if (notFound.length > 0) {
lines.push(`未找到运单:${notFound.join('、')}`);
}
if (skipped.length > 0) {
lines.push(`无权操作:${skipped.join('、')}`);
}
ctx.logger.info(
`[inbox functions] 打包视频查询: total=${keywords.length} found=${validList.length} ` +
`video=${videoLines.length} noVideo=${noVideoWbs.length} noRecord=${noRecordWbs.length}`
);
return {
success: true,
data: {
has_video: videoLines.length,
no_video: noVideoWbs.length,
no_record: noRecordWbs.length,
message: lines.join('\n'),
direct_reply: true,
},
};
} catch (error) {
ctx.logger.error(`[inbox functions] 打包视频查询失败: ${error.message}`);
return { success: false, error: `打包视频查询失败: ${error.message}` };
}
},
});
this.register('queryWeight', {
description: '查重(重量查询)。传入运单号,返回该运单的快递称重重量;重量为0或未称重时提示未称重。仅查询,不创建工单',
weight: 85,
keywords: [ '查重', '重量', '核实重量', '核重', '称重', '多重' ],
params: {
keyword: { type: 'string', required: true, description: '运单号,多个用逗号或空格分隔,如 SF111,SF222' },
},
groups: [ GROUP.BOUND_STORE_AFTER_SALES, GROUP.BOUND_WAREHOUSE_CUSTOMER_SERVICE ],
handler: async (params = {}) => {
const { ctx } = this;
const raw = String(params.keyword || '').trim();
const storeId = Number(ctx.inboxContext?.store_id || 0);
const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0);
const groupType = String(ctx.inboxContext?.group_type || '').trim();
if (!raw) return { success: false, error: '请提供运单号' };
if (!warehouseId) return { success: false, error: '无法获取仓库信息' };
const keywords = raw.split(/[,,\s\n]+/).map(s => s.trim()).filter(Boolean);
if (keywords.length === 0) return { success: false, error: '未解析到有效运单号' };
// 前置拦截:AS 开头为售后工单号,不是运单号
const asLikeList = keywords.filter(k => /^AS/i.test(k));
if (asLikeList.length > 0) {
return { success: false, error: `${asLikeList.join('、')} 是售后工单号而非运单号,请提供运单号` };
}
try {
const { Op } = ctx.app.Sequelize;
const expressList = await ctx.model.OrderExpress.findAll({
attributes: [ 'id', 'waybill_code', 'store_id', 'weighing_weight' ],
where: {
waybill_code: { [Op.in]: keywords },
warehouse_id: warehouseId,
},
raw: true,
});
const foundCodes = new Set(expressList.map(e => e.waybill_code));
const notFound = keywords.filter(k => !foundCodes.has(k));
// 鉴权:货主群需验 store_id
const validList = [];
const skipped = [];
for (const e of expressList) {
if (groupType === 'store') {
if (!storeId || Number(e.store_id) !== storeId) {
skipped.push(e.waybill_code);
continue;
}
}
validList.push(e);
}
if (validList.length === 0) {
const parts = [];
if (notFound.length > 0) parts.push(`未找到运单:${notFound.join('、')}`);
if (skipped.length > 0) parts.push(`无权操作:${skipped.join('、')}`);
return {
success: false,
error: parts.join(';') || `未找到运单号「${raw}」,请核实单号后重试`,
};
}
// 组装模板:每个运单一行,只输出重量;重量为0 → 未称重
const lines = [];
for (const e of validList) {
const weight = Number(e.weighing_weight) || 0;
lines.push(weight > 0 ? `${e.waybill_code}:${weight}g` : `${e.waybill_code}:未称重`);
}
if (notFound.length > 0) {
lines.push(`未找到运单:${notFound.join('、')}`);
}
if (skipped.length > 0) {
lines.push(`无权操作:${skipped.join('、')}`);
}
ctx.logger.info(
`[inbox functions] 查重: total=${keywords.length} found=${validList.length} ` +
`notFound=${notFound.length} skipped=${skipped.length}`
);
return {
success: true,
data: {
waybills: validList.map(e => e.waybill_code),
message: lines.join('\n'),
direct_reply: true,
},
};
} catch (error) {
ctx.logger.error(`[inbox functions] 查重失败: ${error.message}`);
return { success: false, error: `查重失败: ${error.message}` };
}
},
});
this.register('handleExpressFeedback', {
description: '快递群售后通用反馈。传入运单号,优先找已有售后工单追加记录,无工单则按运单查订单并自动创建售后工单。AI 可根据快递反馈内容传入售后类型和子类型',
weight: 90,
@ -2564,7 +3378,8 @@ class InboxFunctionsService extends Service {
`快递公司: ${e.logistics_name || '未知'}`,
`售后类型: ${asType}.${asSubType}`,
'来源: 快递群反馈',
].join('\n');
feedbackMsgContent ? `原文: ${feedbackMsgContent}` : '',
].filter(Boolean).join('\n');
await ctx.service.systems.afterSale.create({
warehouse_id: warehouseId,
@ -2644,7 +3459,36 @@ class InboxFunctionsService extends Service {
// - 已有工单且带 inbox_message_id → 查原始消息获取群信息 → 回信到原群
// - 无工单或无 inbox_message_id → 回信到货主售后群
replyTargets = new Map(); // group_id → { group_id, group_name, user_id, ext_data }
const replyMsg = parts.join(';') || '处理完成';
// 未命中排除关键词 → 直接反馈原文(按目标货主过滤掉其他货主的运单号)
const baseContent = feedbackMsgContent || (parts.join(';') || '处理完成');
// 运单号 → 货主ID 映射(用于按货主过滤原文中的运单号)
const waybillStoreMap = new Map();
for (const e of expressList) {
if (e.waybill_code) waybillStoreMap.set(e.waybill_code, e.store_id ? Number(e.store_id) : null);
}
for (const as of existingAS) {
if (as.waybill_no && !waybillStoreMap.has(as.waybill_no) && as.store_id) {
waybillStoreMap.set(as.waybill_no, Number(as.store_id));
}
}
/**
* 从反馈原文中移除属于其他货主的运单号。
* @param {string} content 原始文本。
* @param {number|null} targetStoreId 目标货主ID,为空则不过滤。
* @return {string} 过滤后的文本。
*/
const filterOtherStoreWaybills = (content, targetStoreId) => {
if (!content || !targetStoreId) return content || '';
let text = String(content);
for (const [ wb, sid ] of waybillStoreMap) {
if (sid && sid !== targetStoreId) {
text = text.split(wb).join('');
}
}
return text.replace(/[ \t]+/g, ' ').replace(/\n{3,}/g, '\n\n').trim();
};
// 4a. 已有工单带 inbox_message_id:回信到原消息所在群(排除快递群)
const asWithMsgId = existingAS.filter(as => as.inbox_message_id);
@ -2659,17 +3503,22 @@ class InboxFunctionsService extends Service {
});
// 过滤快递群:原消息来自快递群的,不回信到快递群,走 4b 货主售后群
const candidateGroupIds = [ ...new Set(messages.map(m => m.group_id).filter(Boolean)) ];
let groupStoreMap = {};
if (candidateGroupIds.length > 0) {
const expressGroups = await ctx.model.InboxGroup.findAll({
attributes: [ 'group_id' ],
const groupRows = await ctx.model.InboxGroup.findAll({
attributes: [ 'group_id', 'group_type', 'store_id' ],
where: {
group_id: { [ctx.app.Sequelize.Op.in]: candidateGroupIds },
warehouse_id: warehouseId,
group_type: 'express',
},
raw: true,
});
expressGroupIds = new Set(expressGroups.map(g => g.group_id));
expressGroupIds = new Set(
groupRows.filter(g => g.group_type === 'express').map(g => g.group_id)
);
groupStoreMap = Object.fromEntries(
groupRows.filter(g => g.store_id).map(g => [ g.group_id, Number(g.store_id) ])
);
}
for (const msg of messages) {
if (msg.group_id && !replyTargets.has(msg.group_id) && !expressGroupIds.has(msg.group_id)) {
@ -2679,6 +3528,7 @@ class InboxFunctionsService extends Service {
user_id: msg.user_id || '',
user_name: msg.user_name || '',
ext_data: null,
store_id: groupStoreMap[msg.group_id] || null,
});
}
}
@ -2722,6 +3572,7 @@ class InboxFunctionsService extends Service {
user_id: '',
user_name: '',
ext_data: g.ext_data || null,
store_id: g.store_id || null,
});
}
}
@ -2730,14 +3581,17 @@ class InboxFunctionsService extends Service {
}
}
// 3c. 发送回信
// 3c. 发送回信(直接反馈原文,按目标货主过滤其他货主的运单号)
for (const [ , target ] of replyTargets) {
const content = filterOtherStoreWaybills(baseContent, target.store_id);
if (!content) continue;
ctx.service.inbox.processor.pushSystemNotification({
warehouse_id: warehouseId,
group_id: target.group_id,
group_name: target.group_name,
content: `快递反馈: ${replyMsg}`,
content,
ext_data: target.ext_data,
store_id: target.store_id || null,
});
}

View File

@ -4,6 +4,9 @@ const Service = require('egg').Service;
const WAREHOUSE_INTERFACE_TYPE_ID = 3;
/** 历史消息过滤默认阈值:发送时间距今超过 10 分钟视为历史/补推消息,跳过 AI(可用 config.inbox.historyMessageMaxAgeMs 覆盖) */
const DEFAULT_HISTORY_MESSAGE_MAX_AGE_MS = 10 * 60 * 1000;
/**
* 站内信内容处理器。
* 负责解析入站消息正文,按 source_type 分流处理,
@ -73,6 +76,29 @@ class InboxProcessorService extends Service {
this._groupCache.set(cacheKey, info);
return info;
}
/**
* 判断消息是否为历史消息(发送时间距今超过阈值)。
* - flags.skipAi === true:外部显式要求跳过 AI。
* - flags.send_time 距今超过 config.inbox.historyMessageMaxAgeMs:视为历史/补推消息。
* - 未携带发送时间:按实时消息处理(向后兼容)。
* @param {Object} data 入站消息数据。
* @return {boolean} 是否应跳过 AI 处理。
*/
isStaleMessage(data = {}) {
const flags = data.flags || {};
if (flags.skipAi === true) return true;
const sendTime = Number(flags.send_time || 0);
if (!Number.isFinite(sendTime) || sendTime <= 0) return false;
const maxAgeMs = Number(this.app.config.inbox?.historyMessageMaxAgeMs);
const threshold = Number.isFinite(maxAgeMs) && maxAgeMs > 0
? maxAgeMs
: DEFAULT_HISTORY_MESSAGE_MAX_AGE_MS;
return Date.now() - sendTime > threshold;
}
/**
* 处理入站消息内容。
* 解析 content 后将 warehouse_id 和 store_id 写入 ctx 上下文。
@ -162,6 +188,12 @@ class InboxProcessorService extends Service {
return;
}
// 2.5 历史消息过滤:发送时间距今超过阈值的历史/补推消息不触发绑群与 AI,防止误建工单
if (this.isStaleMessage(data)) {
ctx.logger.info(`[inbox processor] 历史消息,跳过 AI 处理 ext_id=${extId}`);
return;
}
// 3. 绑群码识别:消息匹配"授权:CODE"时执行绑群
const bindHandled = await this.tryBindGroup(data);
if (bindHandled) return;
@ -419,7 +451,7 @@ class InboxProcessorService extends Service {
} else {
const created = await InboxMessage.create({
ext_id: ackExtId, warehouse_id: warehouseId,
store_id: ctx.inboxContext?.store_id || null,
store_id: Number(data.store_id) || ctx.inboxContext?.store_id || null,
direction: 'outbound', parent_id: parentId || null,
source_type: 'system', source_extra: null,
target_type: 'api',
@ -687,6 +719,8 @@ class InboxProcessorService extends Service {
* @param {string} data.group_name 目标群名称。
* @param {string} data.content 通知内容。
* @param {Object} [data.ext_data] 群扩展数据(渠道信息)。
* @param {number} [data.store_id] 目标货主ID(用于写入回信记录的 store_id)。
* @return {void} 无返回值,异步写入与推送。
*/
pushSystemNotification(data = {}) {
const { ctx } = this;
@ -695,6 +729,7 @@ class InboxProcessorService extends Service {
const groupName = String(data.group_name || '').trim();
const content = String(data.content || '').trim();
const extData = data.ext_data || null;
const storeId = Number(data.store_id) || null;
if (!warehouseId || !groupId || !content) return;
@ -708,6 +743,7 @@ class InboxProcessorService extends Service {
user_id: '',
group_name: groupName,
user_name: '',
store_id: storeId,
};
// 写库 + POST,异步不阻塞

View File

@ -28,6 +28,7 @@ class InboxReceiverService extends Service {
* @param {string} [data.content] 消息正文/摘要。
* @param {Object} [data.ext_data] 透传数据。
* @param {Object} [data.flags] 处理标记。
* @param {number} [data.send_time] 消息原始发送时间(毫秒时间戳,可选,用于历史消息过滤)。
* @return {Promise<{ok: boolean, id: number, ext_id: string}>} 接收结果。
*/
async receive(data = {}) {
@ -96,6 +97,15 @@ class InboxReceiverService extends Service {
throw new Error(`消息体超过 64KB 限制(当前 ${Math.round(bodySize / 1024)}KB)`);
}
// flags 合并:消息发送时间统一存入 flags.send_time(毫秒),供 AI 历史消息过滤
const flags = { ...(data.flags || {}) };
if (!flags.send_time && data.send_time != null) {
const sendTime = Number(data.send_time);
if (Number.isFinite(sendTime) && sendTime > 0) {
flags.send_time = Math.floor(sendTime);
}
}
// 从群绑定查询货主ID(外部不再直接传入 store_id)
let storeId = null;
const extGroupId = String(data.group_id || '').trim();
@ -130,7 +140,7 @@ class InboxReceiverService extends Service {
user_id: data.user_id || null,
content: data.content || null,
ext_data: data.ext_data || null,
flags: data.flags || {},
flags,
});
ctx.logger.info(`[inbox] 消息入库成功 ext_id=${extId} id=${record.id}`);
@ -168,6 +178,7 @@ class InboxReceiverService extends Service {
user_name: data.user_name || null,
group_id: data.group_id || null,
user_id: data.user_id || null,
flags,
}).catch(err => {
ctx.logger.error(`[inbox] API 异步回执异常 ext_id=${extId}: ${err.message}`);
});

View File

@ -81,6 +81,8 @@ class AfterSaleMethodService extends MainService {
const result = await service.systems.afterSale.list(enforcedWhere, pagination, sort, {
order: [[ 'priority', 'DESC' ], [ 'updated_at', 'DESC' ]],
excludeFutureFollowup: true,
// 列表行补充货主名称 store_name(合约表 store_remask 货主备注,无备注时回退货主公司全称)
enrichStoreName: true,
});
return this.success('ok', result);
}

View File

@ -36,6 +36,7 @@ class AfterSaleService extends Service {
* @param {Object} [opts] 额外选项
* @param {Array<Array>} [opts.order] 自定义 Sequelize order(优先于 sort)
* @param {boolean} [opts.excludeFutureFollowup] 是否排除 followup_at 未到的 pending_feedback 工单
* @param {boolean} [opts.enrichStoreName] 是否补充每行 store_name 货主名称(合约表货主备注 store_remask,无备注时回退货主公司全称)
* @return {Promise<Object>} { list: Array, pagination: Object }
*/
async list(where = {}, pagination = {}, sort = {}, opts = {}) {
@ -87,6 +88,11 @@ class AfterSaleService extends Service {
const list = rows.map(row => this._formatAfterSaleRow(row, app));
// 工作列表:批量补充货主名称(合约表 store_remask 货主备注,无备注时回退货主公司全称)
if (opts.enrichStoreName && list.length > 0) {
await this._enrichListStoreNames(list);
}
return {
list,
pagination: {
@ -282,6 +288,8 @@ class AfterSaleService extends Service {
/**
* 售后单明细查询,包含主表信息、步骤列表及附件。
* 售后主表 description(详细描述)非空时,默认作为第一条 step 输出
* (虚拟步骤:id=null、is_virtual=true、action=售后描述、remark=description,不落库)。
* 若关联了订单(order_delivery_id),自动补充收件人/发件人/订单明细/打包视频。
* 若关联了货主(store_id),自动补充货主合约备注。
*
@ -318,13 +326,32 @@ class AfterSaleService extends Service {
// 补充关联单据详情
const related = await this._enrichAfterSaleDetail(afterSale);
// 开始处理时间:取首条步骤记录的创建时间
const firstStep = stepsWithAttachments[0];
// 默认详细描述作为第一条 step 输出(虚拟步骤,不落库)
let finalSteps = stepsWithAttachments;
if (afterSale.description && String(afterSale.description).trim()) {
finalSteps = [{
id: null,
after_sale_id: afterSale.id,
step_status: 'pending',
operator_id: null,
operator_snapshot: null,
action: '售后描述',
remark: afterSale.description,
started_at: null,
completed_at: null,
created_at: afterSale.created_at,
attachments: [],
is_virtual: true,
}, ...stepsWithAttachments ];
}
// 开始处理时间:取首条真实步骤记录的创建时间(不含默认描述虚拟步骤)
const firstStep = steps[0];
const startedAt = firstStep ? (firstStep.created_at ? app.formatDate(firstStep.created_at) : null) : null;
return {
after_sale: { ...formatRow(afterSale), started_at: startedAt },
steps: stepsWithAttachments.map(formatRow),
steps: finalSteps.map(formatRow),
related,
};
}
@ -782,6 +809,63 @@ class AfterSaleService extends Service {
return this._formatAfterSaleRow(json, app);
}
/**
* 批量补充列表行的货主名称 store_name。
* 货主名称优先取合约表 wms_store_warehouse.store_remask(货主备注名称),
* 无合约或备注为空时回退 wms_store.company_name(公司全称)。
*
* @param {Object[]} list 售后单列表行(原地补充 store_name 字段)
* @return {Promise<void>}
*/
async _enrichListStoreNames(list) {
const { ctx } = this;
const { Op } = ctx.app.Sequelize;
const storeIds = [ ...new Set(list.map(row => row.store_id).filter(Boolean)) ];
const warehouseIds = [ ...new Set(list.map(row => row.warehouse_id).filter(Boolean)) ];
if (storeIds.length === 0) {
list.forEach(row => {
row.store_name = '';
});
return;
}
// 1. 合约表货主备注名称(store_id + warehouse_id 维度)
let contractMap = {};
if (warehouseIds.length > 0) {
const swRows = await ctx.model.StoreWarehouse.findAll({
where: {
store_id: { [Op.in]: storeIds },
warehouse_id: { [Op.in]: warehouseIds },
},
attributes: [ 'store_id', 'warehouse_id', 'store_remask' ],
raw: true,
});
contractMap = swRows.reduce((acc, sw) => {
acc[`${sw.store_id}_${sw.warehouse_id}`] = sw.store_remask || '';
return acc;
}, {});
}
// 2. 货主公司全称兜底
let storeMap = {};
const storeRows = await ctx.model.Store.findAll({
where: { id: { [Op.in]: storeIds } },
attributes: [ 'id', 'company_name' ],
raw: true,
});
storeMap = storeRows.reduce((acc, store) => {
acc[store.id] = store.company_name || '';
return acc;
}, {});
list.forEach(row => {
const contractRemask = contractMap[`${row.store_id}_${row.warehouse_id}`] || '';
row.store_name = contractRemask || storeMap[row.store_id] || '';
});
}
// ===========================
// 更新售后单
// ===========================

View File

@ -64,7 +64,66 @@ class ReturnUnpackService extends Service {
.filter(id => Number.isInteger(id) && id > 0);
}
// 1. 原单反查:命中则回填原单关联字段
// 1. 幂等复用:同一仓库同一运单号 3 个月内已开过拆包单时,不重复创建,直接返回已有明细
const threeMonthsAgo = new Date();
threeMonthsAgo.setMonth(threeMonthsAgo.getMonth() - 3);
try {
const existingList = await ctx.model.ReturnUnpack.findAll({
where: {
warehouse_id: warehouseId,
waybill_code: waybillCode,
created_at: { [Op.gte]: threeMonthsAgo },
status: { [Op.ne]: 'cancelled' },
},
attributes: [ 'id', 'order_express_id', 'created_at' ],
order: [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]],
raw: true,
});
let existing = null;
if (existingList.length > 0) {
existing = existingList[0];
// 同运单号可能有多张拆包单(并发/重复点击产生的空单):优先复用已录明细的最新单,
// 避免命中最新空单导致"返回明细为空"(按明细表真实计数判断,不依赖主表冗余汇总)
const countRows = await ctx.model.ReturnUnpackDetail.findAll({
where: { unpack_id: { [Op.in]: existingList.map(row => row.id) } },
attributes: [
'unpack_id',
[ ctx.model.fn('COUNT', ctx.model.col('id')), 'detail_count' ],
],
group: [ 'unpack_id' ],
raw: true,
});
const detailCountMap = new Map(
countRows.map(row => [ Number(row.unpack_id), Number(row.detail_count) || 0 ])
);
const withDetails = existingList.find(row => (detailCountMap.get(Number(row.id)) || 0) > 0);
if (withDetails) {
existing = withDetails;
}
}
if (existing) {
// 复用已有拆包单:返回主表 + 明细 + 视频 + 原订单详情(复用 detail 查询逻辑)
const existingDetail = await this.detail(existing.id);
ctx.logger.info(
`[returnUnpack.create] 运单号 ${waybillCode} 3 个月内已有拆包单 id=${existing.id},直接复用返回明细`
);
return {
id: existing.id,
record: existingDetail.record,
is_original_return: Boolean(existing.order_express_id),
store_remark: String(existingDetail.record && existingDetail.record.shop_name || ''),
order: (existingDetail.related && existingDetail.related.order) || null,
reused: true,
};
}
} catch (err) {
// 查重失败不阻断开单主流程
ctx.logger.warn(`[returnUnpack.create] 查重已有拆包单失败: ${err.message}`);
}
// 2. 原单反查:命中则回填原单关联字段
let orderExpressId = null;
let orderId = null;
let storeId = null;
@ -85,11 +144,9 @@ class ReturnUnpackService extends Service {
ctx.logger.warn(`[returnUnpack.create] 反查原运单失败: ${err.message}`);
}
// 2. 未命中原单:从退回查询记录表反查货主(限最近 3 个月内登记,运单号可能被复用)
// 3. 未命中原单:从退回查询记录表反查货主(限最近 3 个月内登记,运单号可能被复用)
if (!orderExpressId) {
try {
const threeMonthsAgo = new Date();
threeMonthsAgo.setMonth(threeMonthsAgo.getMonth() - 3);
const queryLog = await ctx.model.ReturnQueryLog.findOne({
where: {
warehouse_id: warehouseId,
@ -110,14 +167,14 @@ class ReturnUnpackService extends Service {
const isOriginalReturn = Boolean(orderExpressId);
// 3. 货主备注(原单退回 / 反查命中货主时)
// 4. 货主备注(原单退回 / 反查命中货主时)
const storeRemark = await this._resolveStoreRemark(storeId, warehouseId);
// 4. 拆包日期/开始时间(单号在下方重试循环内生成)
// 5. 拆包日期/开始时间(单号在下方重试循环内生成)
const now = new Date();
const unpackDate = app.formatDate(now, 'YYYY-MM-DD');
// 5. 插入主表(并发下撞 uk_unpack_no 唯一索引时重新取号重试,最多 5 次,指数退避+随机抖动)
// 6. 插入主表(并发下撞 uk_unpack_no 唯一索引时重新取号重试,最多 5 次,指数退避+随机抖动)
const baseFields = {
warehouse_id: warehouseId,
return_received_id: return_received_id ? Number(return_received_id) || null : null,
@ -167,7 +224,7 @@ class ReturnUnpackService extends Service {
const createdRow = created && typeof created.toJSON === 'function' ? created.toJSON() : created;
// 6. 原订单详情(仅原单退回时拉取,参考 afterSale.detail._resolveOrderDetail)
// 7. 原订单详情(仅原单退回时拉取,参考 afterSale.detail._resolveOrderDetail)
let order = null;
if (isOriginalReturn && orderId) {
try {
@ -280,6 +337,7 @@ class ReturnUnpackService extends Service {
const summary = await this._recalcMain(unpack.id, unpack.warehouse_id);
const createdRow = created && typeof created.toJSON === 'function' ? created.toJSON() : created;
await this._enrichDetailsWithStock([ createdRow ], Number(unpack.warehouse_id || 0));
return {
detail_id: createdRow.id,
detail: createdRow,
@ -320,6 +378,7 @@ class ReturnUnpackService extends Service {
}
if (Object.keys(updateFields).length === 0) {
await this._enrichDetailsWithStock([ detail ], Number(unpack.warehouse_id || 0));
return {
detail,
total_items: unpack.total_items,
@ -346,6 +405,7 @@ class ReturnUnpackService extends Service {
summary = await this._recalcMain(unpack.id, unpack.warehouse_id);
}
await this._enrichDetailsWithStock([ updated ], Number(unpack.warehouse_id || 0));
return {
detail: updated,
...summary,
@ -529,6 +589,10 @@ class ReturnUnpackService extends Service {
const list = rows.map(row => (row && typeof row.toJSON === 'function' ? row.toJSON() : row));
// 明细批量附加库存详情(条码/图片等,统一走 stockWarehouse.getStockDetails 通用方法)
const listWarehouseId = list.length > 0 ? Number(list[0].warehouse_id || 0) : 0;
await this._enrichDetailsWithStock(list, listWarehouseId);
return {
list,
pagination: {
@ -592,6 +656,14 @@ class ReturnUnpackService extends Service {
const recordJson = record && typeof record.toJSON === 'function' ? record.toJSON() : record;
// 明细批量附加库存详情(条码/图片等,统一走 stockWarehouse.getStockDetails 通用方法)
if (recordJson && Array.isArray(recordJson.details)) {
recordJson.details = await this._enrichDetailsWithStock(
recordJson.details,
Number(recordJson.warehouse_id || 0)
);
}
// 原订单详情(仅原单退回时返回)
let relatedOrder = null;
if (recordJson && recordJson.order_id) {
@ -1132,6 +1204,50 @@ class ReturnUnpackService extends Service {
return record;
}
/**
* 批量附加库存详情(条码/图片等)到明细行。
* 统一走 stockWarehouse.getStockDetails 通用方法(带缓存,含 barcodes/image_url/
* packing_requirements/stock_unit 等字段),为每条有 stock_id 的明细补充 stock 字段;
* 商品失效或查询失败时 stock 为 null(不影响主流程)。
*
* @param {Array<Object>} details 明细行数组(含 stock_id,就地补充 stock 字段)。
* @param {number} warehouseId 仓库ID(用于库存详情查询的仓库过滤)。
* @return {Promise<Array<Object>>} 补充 stock 字段后的明细行数组。
*/
async _enrichDetailsWithStock(details, warehouseId) {
const { ctx } = this;
if (!Array.isArray(details) || details.length === 0) {
return details || [];
}
const stockIds = [ ...new Set(
details
.map(row => Number(row.stock_id))
.filter(sid => Number.isInteger(sid) && sid > 0)
) ];
/** @type {Map<number, Object>} */
const stockMap = new Map();
if (stockIds.length > 0) {
try {
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { warehouseId });
for (const detail of stockDetails) {
if (detail && detail.id != null) {
stockMap.set(Number(detail.id), detail);
}
}
} catch (err) {
ctx.logger.warn(`[returnUnpack._enrichDetailsWithStock] 批量获取库存详情失败: ${err.message}`);
}
}
for (const row of details) {
const stockId = Number(row.stock_id);
row.stock = stockId > 0 ? (stockMap.get(stockId) || null) : null;
}
return details;
}
/**
* 查询货主合约备注名称(wms_store_warehouse.store_remask)。
*

View File

@ -32,6 +32,9 @@ class WarehouseInboxService extends MainService {
// 构造 ext_id
const extId = `api:${String(appKey || 'unknown')}:${String(body.requestId).trim()}`;
// 解析消息原始发送时间(可选,用于历史消息过滤)
const sendTime = this.parseSendTime(body.sendTime);
// 构造入站数据并委托给 inbox receiver
const result = await ctx.service.inbox.receiver.receive({
ext_id: extId,
@ -48,10 +51,28 @@ class WarehouseInboxService extends MainService {
content: body.content || null,
ext_data: body.extData || null,
flags: body.flags || {},
send_time: sendTime,
});
return result;
}
/**
* 解析外部传入的消息发送时间。
* 支持毫秒时间戳、秒时间戳、ISO 时间字符串;解析失败返回 null。
* @param {number|string|null} value 外部传入的 sendTime。
* @return {number|null} 毫秒时间戳,解析失败返回 null。
*/
parseSendTime(value) {
if (value == null || value === '') return null;
if (typeof value === 'number' && Number.isFinite(value)) {
if (value > 1e12) return Math.floor(value); // 毫秒
if (value > 1e8) return Math.floor(value * 1000); // 秒
return null;
}
const ms = Date.parse(String(value));
return Number.isFinite(ms) ? ms : null;
}
}
module.exports = WarehouseInboxService;

View File

@ -56,6 +56,8 @@ module.exports = appInfo => {
// 站内信模块配置
config.inbox = {
imageBaseUrl: '', // 商品图片域名,为空时用请求 ctx.host
// 历史消息过滤:消息原始发送时间距今超过该阈值(毫秒)则跳过 AI 处理,防止补推历史消息被当成新工单
historyMessageMaxAgeMs: 10 * 60 * 1000,
};
config.tencentCloud = {

View File

@ -1,4 +1,74 @@
[
{
"version": "2026.08.14-afterSale.detail-desc-first-step",
"date": "2026-08-14",
"type": "enhanced",
"summary": "enhance: afterSale.detail 步骤列表默认将售后详细描述作为第一条 step 输出(虚拟步骤不落库),保证详情页首条即可看到售后问题描述。",
"methods": [
"afterSale.detail"
],
"notes": [
"售后主表 description 非空时,steps 列表头部前置一条虚拟步骤:action=售后描述、remark=description、step_status=pending、created_at=主表创建时间、attachments=[]、is_virtual=true、id=null",
"虚拟步骤不写入 wms_after_sale_detail,仅在 detail 响应中动态拼接",
"after_sale.started_at 仍取首条真实步骤记录的创建时间,不受虚拟步骤影响",
"description 为空时不生成虚拟步骤,行为与之前一致",
"同步更新 methods/system.json 中 afterSale.detail 的 steps 字段说明"
],
"module": "afterSale"
},
{
"version": "2026.08.14-afterSale.workList-storeName",
"date": "2026-08-14",
"type": "changed",
"summary": "afterSale.workList 返回列表行新增 store_name 货主名称字段:取合约表 wms_store_warehouse.store_remask 货主备注名称,无合约或备注为空时回退 wms_store.company_name 公司全称,无货主时为空字符串",
"methods": [
"afterSale.workList"
],
"notes": [
"systems/afterSale.js list() 新增 opts.enrichStoreName 开关,开启后调用新增私有方法 _enrichListStoreNames 批量补充:按行收集 store_id/warehouse_id,一次查询 StoreWarehouse(store_remask)与 Store(company_name),映射后写入每行 store_name",
"systemMethods/afterSale.js workList 调用 list 时传 enrichStoreName: true;auditList 不受影响",
"向后兼容:仅在列表行新增 store_name 字段,不影响既有字段",
"同步更新 methods/system.json 中 afterSale.workList 的 response.list 字段说明"
],
"module": "afterSale"
},
{
"version": "2026.08.14-returnUnpack.stockDetails",
"date": "2026-08-14",
"type": "changed",
"summary": "returnUnpack 明细补充库存详情:detail/detailList/addDetail/updateDetail 返回的明细行统一走 stockWarehouse.getStockDetails 通用方法附加 stock 字段(item_code/item_name/sku_property/barcodes 条码数组/image_url 图片数组/packing_requirements/stock_unit/quantity/locked_quantity 等,带缓存),补齐条码与照片信息;create 幂等复用返回的 record.details 同步受益",
"methods": [
"returnUnpack.detail",
"returnUnpack.detailList",
"returnUnpack.addDetail",
"returnUnpack.updateDetail",
"returnUnpack.create"
],
"notes": [
"systems/return_unpack.js 新增私有方法 _enrichDetailsWithStock:收集明细 stock_id 批量调用 stockWarehouse.getStockDetails(缓存 key cache:stock_detail:{warehouseId}:{stockId}),按 stock_id 映射为明细行 stock 字段;未识别明细(stock_id 为空)/商品失效/拉取失败时 stock=null,不影响主流程",
"detail:record.details 逐条附加 stock;detailList:list 逐条附加 stock(取首行 warehouse_id 作为查询仓库);addDetail/updateDetail:返回 detail 附加 stock(用主表 warehouse_id)",
"向后兼容:明细行原有字段与 stockWarehouse 关联保持不变,仅新增 stock 字段",
"同步更新 methods/system.json 中 create/detail/detailList/addDetail/updateDetail 的响应字段说明"
],
"module": "returnUnpack"
},
{
"version": "2026.08.14-returnUnpack.createReuse",
"date": "2026-08-14",
"type": "changed",
"summary": "returnUnpack.create 增加幂等复用:同一仓库同一运单号 3 个月内已存在非 cancelled 拆包单时不重复创建,直接返回已有拆包单的主表+明细(record.details)+视频+原订单详情,并携带 reused=true 标识;同运单号多张拆包单时优先复用已录明细的最新单;超过 3 个月视为运单号复用,按新单正常创建",
"methods": [
"returnUnpack.create"
],
"notes": [
"开单前先按 warehouse_id+waybill_code+created_at>=3个月前 查全部非 cancelled 拆包单(created_at DESC, id DESC)",
"同运单号存在多张拆包单时优先复用已录明细的最新单(按 wms_return_unpack_detail 真实计数判定,不依赖主表冗余 total_items),避免命中并发/重复点击产生的空单导致返回明细为空;全部无明细时复用最新单",
"命中时复用 detail 查询逻辑组装 record(含 details 明细+stockWarehouse 关联、videos、returnReceived)与 related.order,返回字段新增 reused=true",
"查重失败仅记日志不阻断开单主流程;3 个月时间基准与退回查询记录反查货主窗口一致",
"同步更新 methods/system.json 中 returnUnpack.create 的 description 与 response(record/reused 字段说明)"
],
"module": "returnUnpack"
},
{
"version": "2026.08.14-warehouse-receive-address",
"date": "2026-08-14",

View File

@ -64,5 +64,22 @@
"source_type 从 body.sourceType || 'api' 改为硬编码 'api'",
"文档移除 sourceType 参数,description 补注 source_type 固定为 api"
]
},
{
"version": "2026-08-14-warehouse-01",
"date": "2026-08-14",
"type": "changed",
"summary": "inbox.push 新增 sendTime 参数与历史消息过滤:外部补推的历史消息不再触发 AI 自动处理(防止误建工单)",
"methods": [
"inbox.push"
],
"notes": [
"inbox.push 新增可选参数 sendTime:消息原始发送时间(毫秒/秒时间戳或 ISO 字符串),由 warehouseMethods/inbox.js parseSendTime 统一规范化为毫秒",
"send_time 统一存入 wms_inbox_message.flags.send_time(毫秒),flags.send_time 与 sendTime 参数等价",
"processor.handleApiMessage 新增历史消息过滤:flags.skipAi=true 或 send_time 距今超过 config.inbox.historyMessageMaxAgeMs(默认 10 分钟)→ 跳过绑群与 AI 处理,不自动回复、不创建工单",
"未传 sendTime 的消息按实时消息处理,保持向后兼容",
"过滤点位于屏蔽检查之后、绑群码识别之前,仅拦截自动处理链路"
],
"module": "inbox"
}
]

View File

@ -34119,7 +34119,7 @@
"name": "list",
"type": "array",
"required": true,
"description": "售后单列表,每条含主表字段 + detail_count"
"description": "售后单列表,每条含主表字段 + detail_count + store_name(货主名称:取合约表 wms_store_warehouse.store_remask 货主备注名称,无合约或备注为空时回退 wms_store.company_name 公司全称,无货主时为空字符串)"
},
{
"name": "pagination",
@ -34198,11 +34198,11 @@
"name": "steps",
"type": "array",
"required": true,
"description": "售后进度步骤列表(含附件 attachments),按创建时间升序",
"description": "售后进度步骤列表(含附件 attachments),按创建时间升序。售后主表 description(详细描述)非空时,列表第一条为默认描述虚拟步骤(action=售后描述、remark=详细描述、step_status=pending、created_at=主表创建时间、id=null、is_virtual=true、attachments=[],不落库)",
"list": [
{
"value": "object",
"label": "{ id, after_sale_id, step_status, operator_id, action, remark, attachments: [{id,file_url,file_name}] }"
"label": "{ id, after_sale_id, step_status, operator_id, action, remark, is_virtual, attachments: [{id,file_url,file_name}] }"
}
]
},
@ -35044,7 +35044,7 @@
"list": [
{
"method": "returnUnpack.create",
"description": "开拆包单(明细不在此提交,由 returnUnpack.addDetail 逐件录入)。用 waybill_code 反查 wms_order_express 判定是否原单退回,命中则回填 order_express_id/order_id/store_id 及订单信息快照(source_order_codes 平台交易单号 / shop_name 店铺名称=货主自定义店铺名称 store_remask)并返回原订单详情;未命中原单时按 warehouse_id+waybill_code 从 wms_return_query_log 反查货主(限最近 3 个月内登记)。拆包单号规则 RP+YYYYMMDD+6位序号。仓库隔离:warehouse_id 由服务端注入 ctx.user.store_id,禁止前端传入。",
"description": "开拆包单(明细不在此提交,由 returnUnpack.addDetail 逐件录入)。用 waybill_code 反查 wms_order_express 判定是否原单退回,命中则回填 order_express_id/order_id/store_id 及订单信息快照(source_order_codes 平台交易单号 / shop_name 店铺名称=货主自定义店铺名称 store_remask)并返回原订单详情;未命中原单时按 warehouse_id+waybill_code 从 wms_return_query_log 反查货主(限最近 3 个月内登记)。幂等复用:同一仓库同一运单号 3 个月内已存在非 cancelled 拆包单时,不重复创建,直接返回已有拆包单的主表+明细(record.details)+视频(record.videos)+原订单详情(order),并携带 reused=true 标识;同运单号存在多张拆包单时优先复用已录明细的最新单(按明细表真实计数判定),超过 3 个月视为运单号已复用,按新单正常创建。拆包单号规则 RP+YYYYMMDD+6位序号。仓库隔离:warehouse_id 由服务端注入 ctx.user.store_id,禁止前端传入。",
"isNeedAuth": true,
"isNeedLogin": true,
"headers": [],
@ -35089,7 +35089,7 @@
"name": "record",
"type": "object",
"required": true,
"description": "拆包单主表记录(含 unpack_no、waybill_code、unpack_date、start_time、unpacker_id/unpacker_name、status、detail_status、camera_ids 数组、回填的 order_express_id/order_id/store_id/source_order_codes/shop_name 快照及 is_original_return 派生字段)"
"description": "拆包单主表记录(含 unpack_no、waybill_code、unpack_date、start_time、unpacker_id/unpacker_name、status、detail_status、camera_ids 数组、回填的 order_express_id/order_id/store_id/source_order_codes/shop_name 快照及 is_original_return 派生字段);幂等复用命中已有拆包单时,record 为已有单的详情记录并携带 details 明细数组(含 stockWarehouse 关联,识别明细另附加 stock 库存详情对象:barcodes 条码数组/image_url 图片数组等)、videos 视频数组与 returnReceived 关联"
},
{
"name": "is_original_return",
@ -35108,6 +35108,12 @@
"type": "object",
"required": false,
"description": "原订单详情(含 items 明细,仅原单退回时返回,非原单为 null)"
},
{
"name": "reused",
"type": "boolean",
"required": false,
"description": "是否幂等复用已有拆包单(true 表示 3 个月内同仓库同运单号已有非 cancelled 拆包单,本次未新建,record.details 即已有明细;新建时为 false 或不返回)"
}
],
"errors": [
@ -35198,7 +35204,7 @@
"name": "detail",
"type": "object",
"required": true,
"description": "新增的明细行(含 barcode/is_recognized/item_code/item_name(未知商品)/spec/product_snapshot 等)"
"description": "新增的明细行(含 barcode/is_recognized/item_code/item_name(未知商品)/spec/product_snapshot 等;识别到系统商品时附加 stock 库存详情对象,含 item_code/item_name/sku_property/barcodes 条码数组/image_url 图片数组/packing_requirements/stock_unit 等,由 getStockDetails 通用方法拉取)"
},
{
"name": "total_items",
@ -35299,7 +35305,7 @@
"name": "detail",
"type": "object",
"required": true,
"description": "更新后的明细行"
"description": "更新后的明细行(识别到系统商品时附加 stock 库存详情对象,含 barcodes 条码数组/image_url 图片数组等,由 getStockDetails 通用方法拉取)"
},
{
"name": "total_items",
@ -35698,7 +35704,7 @@
},
{
"method": "returnUnpack.detailList",
"description": "拆包明细分页列表,命中识别商品时含 stockWarehouse 关联。仓库隔离:warehouse_id 由服务端自动注入 ctx.user.store_id,禁止前端传入。支持按拆包单ID、系统商品、条码、识别标记、产品状态筛选。",
"description": "拆包明细分页列表,命中识别商品时含 stockWarehouse 关联,并统一走 stockWarehouse.getStockDetails 通用方法为每条识别明细附加 stock 库存详情对象(item_code/item_name/sku_property/barcodes 条码数组/image_url 图片数组/packing_requirements/stock_unit/quantity/locked_quantity 等,带缓存)。仓库隔离:warehouse_id 由服务端自动注入 ctx.user.store_id,禁止前端传入。支持按拆包单ID、系统商品、条码、识别标记、产品状态筛选。",
"isNeedAuth": true,
"isNeedLogin": true,
"headers": [],
@ -35765,7 +35771,7 @@
"name": "list",
"type": "array",
"required": true,
"description": "明细行列表(含 is_recognized/item_code/item_name/spec/product_snapshot,识别命中时含 stockWarehouse 关联)"
"description": "明细行列表(含 is_recognized/item_code/item_name/spec/product_snapshot,识别命中时含 stockWarehouse 关联与 stock 库存详情对象:barcodes 条码数组/image_url 图片数组/sku_property/packing_requirements/stock_unit 等)"
},
{
"name": "pagination",
@ -35791,7 +35797,7 @@
},
{
"method": "returnUnpack.detail",
"description": "拆包单详情:主表 + 明细(含 stockWarehouse 关联,命中时)+ 视频副表(含 camera 关联,命中时)+ 退回收到单(命中时);原单退回时(order_id 有值)返回 related.order 原订单详情。需 548 权限(客服员工及以上),仓库隔离校验(仅本仓库拆包单)。",
"description": "拆包单详情:主表 + 明细(含 stockWarehouse 关联,命中时;每条识别明细另附加 stock 库存详情对象,含 barcodes 条码数组/image_url 图片数组等,由 getStockDetails 通用方法拉取)+ 视频副表(含 camera 关联,命中时)+ 退回收到单(命中时);原单退回时(order_id 有值)返回 related.order 原订单详情。需 548 权限(客服员工及以上),仓库隔离校验(仅本仓库拆包单)。",
"isNeedAuth": true,
"isNeedLogin": true,
"headers": [],

View File

@ -272,12 +272,19 @@
"source": "body",
"description": "外部透传数据,任意 JSON,WMS 不解析,回信时原样返回"
},
{
"name": "sendTime",
"type": "number",
"required": false,
"source": "body",
"description": "消息原始发送时间(可选):毫秒时间戳、秒时间戳或 ISO 时间字符串。WMS 据此判断历史消息:发送时间距今超过阈值(默认 10 分钟,config.inbox.historyMessageMaxAgeMs 可调)的历史/补推消息将跳过 AI 处理,不自动回复、不创建工单;不传则按实时消息处理"
},
{
"name": "flags",
"type": "object",
"required": false,
"source": "body",
"description": "处理标记(预留,当前未消费)"
"description": "处理标记。支持:skipAi=true 显式跳过 AI 处理;send_time=毫秒时间戳(消息原始发送时间,用于历史消息过滤,与 sendTime 参数等价)"
}
],
"response": [

View File

@ -37,7 +37,8 @@ function stableStringify(value) {
}
function md5(str) {
return crypto.createHash('md5').update(str, 'utf8').digest('hex').toLowerCase();
return crypto.createHash('md5').update(str, 'utf8').digest('hex')
.toLowerCase();
}
function buildSign(query, body, secret) {
@ -77,6 +78,7 @@ const CONFIG = {
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`,
@ -165,7 +167,7 @@ async function queryDb(sql) {
content: CONFIG.content,
groupId: CONFIG.groupId,
groupName: CONFIG.groupName,
userId: 'debug_user',
userId: CONFIG.userId,
userName: CONFIG.userName,
targetType: 'im',
});