feat: 仓库配置新增收货地址 receiver_address,inbox 售后群新增工单登记/改地址/核实签收/改快递/查询仓库地址函数

This commit is contained in:
liufumingren 2026-08-14 15:29:59 +08:00
parent bcf6a5b384
commit 98bc088929
8 changed files with 1047 additions and 2 deletions

View File

@ -56,6 +56,7 @@ module.exports = app => {
district_name: '',
town_name: '',
address: '',
receiver_address: '',
group_wave_prefix: 'B',
delete_order_wave_prefix: 'A',
inventory_warning_rules: DEFAULT_INVENTORY_WARNING_RULES,

View File

@ -254,9 +254,16 @@ ${historyContext}
- 需要上下文但记忆不足时,主动调用 recallHistory 回顾对话历史
- 【防误判规则 - interceptWaybill】讨论已有售后工单(AS开头编号)、询问物流进度、问"快递到哪了"、转发售后截图等均不是拦截请求,严禁调用 interceptWaybill。只有用户明确说"拦截/退回/召回/追回/取消"运单时才可调用
- 【措辞规则 - interceptWaybill】拦截结果回复严禁使用"已拦截""拦截成功"等确定口吻,必须使用"拦截信息已登记""已提交拦截申请"等措辞。因为快递拦截可能失败,实际结果以快递公司反馈为准。回复时需列出工单号供用户跟进
- 【规则 - handleStoreFeedback】货主售后群中客户反馈"错发/发错""破损/坏了""多发/发多""少发/漏发"且提供了运单号时,调用 handleStoreFeedback 创建售后工单(初始状态未开始处理,不通知快递群);若消息中无运单号,先向客户确认运单号再调用
- 【规则 - changeAddr】货主售后群中客户消息含"改地址/改电话/改联系人/改收件人/地址更改/改手机/催退回/尽快安排派送/催促退回"等诉求且提供了运单号时,调用 changeAddr(issue_type:addr=改地址类诉求,return=催退回类诉求);函数会创建售后工单并把客户原文转发到对应快递群,返回的 data.message 是模板消息必须原样回复;若消息中无运单号,先向客户确认运单号再调用
- 【规则 - weishoudao】货主售后群中客户消息含"核实签收/未收到/是否发出/是否已经发货/核实/没有找到快递"等诉求且提供了运单号时,调用 weishoudao 创建核实签收售后工单,并把"运单号+核实签收"转发到对应快递群;返回的 data.message 是模板消息必须原样回复;若消息中无运单号,先向客户确认运单号再调用
- 【规则 - changeExpress】货主售后群中客户要求"改快递/换快递/改圆通/改中通/改顺丰"等且提供了订单号时,调用 changeExpress(keyword=订单号,express=目标快递名称或编码);仅待处理表中未分配快递的订单可以修改,已分配快递或不在待处理表的订单不能修改;返回的 data.message 是模板消息必须原样回复;若消息中缺订单号或目标快递,先向客户确认再调用
- 【模板消息 - queryReturn】queryReturn 返回的 data.message 是已排版好的模板消息,必须原样作为最终回复输出,禁止改写、删减、增补内容,禁止添加 Markdown 或额外说明
- 【规则 - queryWarehouseAddress】用户询问"仓库地址/收货地址/退货地址/退件地址/寄回地址"时,调用 queryWarehouseAddress 查询仓库配置中的 receiver_address;返回的 data.message 是模板消息必须原样回复
- 【模板消息 - handleStoreFeedback】handleStoreFeedback 返回的 data.message 是已排版好的模板消息(运单号+问题类型+工单号+"稍后客服将人工核实跟进"),必须原样作为最终回复输出,禁止改写、删减或增补内容
- 用户发送"查退回+运单号"时,调用 queryReturn 查询退回明细,不要误调 queryOrder 或 interceptWaybill
- 【查询类请求强制调函数】查订单/查退回/查库存等查询类请求必须实际调用对应函数获取结果后再回复,严禁仅凭历史对话或猜测臆测"服务不可用/无法处理"而跳过函数调用`;
- 【查询类请求强制调函数】查订单/查退回/查库存等查询类请求必须实际调用对应函数获取结果后再回复,严禁仅凭历史对话或猜测臆测"服务不可用/无法处理"而跳过函数调用
- 【历史失败回复免疫】群历史中 AI 的历史回复(尤其含"失败""异常""无法处理"等字样的兜底回复)只是历史记录,不代表当前功能不可用;严禁模仿、引用这类历史回复,也严禁据此判断函数不可用而拒绝调用;登记/操作/查询类请求必须实际调用对应函数获取最新结果`;
// 多轮推理循环
for (let round = 1; round <= MAX_ROUNDS; round++) {

View File

@ -1562,6 +1562,901 @@ class InboxFunctionsService extends Service {
},
});
this.register('handleStoreFeedback', {
description: '货主售后群问题反馈建工单。客户反馈"错发/发错""破损/坏了""多发/发多""少发/漏发"等问题并提供了运单号时调用。校验货主权限后创建售后工单,初始状态为未开始处理(pending),不转发通知快递群',
weight: 88,
keywords: [ '错发', '发错', '破损', '坏了', '多发', '发多', '少发', '漏发', '发少' ],
params: {
keyword: { type: 'string', required: true, description: '运单号,多个用逗号或空格分隔,如 SF111,SF222' },
issue_type: { type: 'string', required: true, description: '问题类型:wrong(错发)/damaged(破损)/multiple(多发)/missing(少发)' },
},
groups: [ GROUP.BOUND_STORE_AFTER_SALES ],
handler: async (params = {}) => {
const { ctx } = this;
const raw = String(params.keyword || '').trim();
const issueTypeRaw = String(params.issue_type || '').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 ISSUE_TYPE_MAP = {
wrong: { sub_type: 'mis_shipment', label: '错发' },
错发: { sub_type: 'mis_shipment', label: '错发' },
damaged: { sub_type: 'damage', label: '破损' },
破损: { sub_type: 'damage', label: '破损' },
multiple: { sub_type: 'extra_item', label: '多发' },
多发: { sub_type: 'extra_item', label: '多发' },
missing: { sub_type: 'missing_item', label: '少发' },
少发: { sub_type: 'missing_item', label: '少发' },
};
const issue = ISSUE_TYPE_MAP[issueTypeRaw];
if (!issue) {
return {
success: false,
error: `不支持的问题类型「${issueTypeRaw || '空'}」,仅支持 wrong(错发)/damaged(破损)/multiple(多发)/missing(少发)`,
};
}
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', 'order_id' ],
where: {
waybill_code: { [ctx.app.Sequelize.Op.in]: keywords },
warehouse_id: warehouseId,
store_id: storeId,
},
raw: true,
});
const foundCodes = new Set(expressList.map(e => e.waybill_code));
const notFound = keywords.filter(k => !foundCodes.has(k));
if (expressList.length === 0) {
return { success: false, error: `未找到当前货主在仓库中的运单「${raw}」,请核实单号后重试` };
}
// 第二步:幂等检查(同子类型未完结工单不重复建单)
const expressIds = expressList.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]: expressIds },
type: 'order',
sub_type: issue.sub_type,
status: { [ctx.app.Sequelize.Op.notIn]: [ 'completed', 'closed', 'cancelled' ] },
},
raw: true,
});
const existingWaybillIds = new Set(existingASList.map(r => r.waybill_id));
const toCreate = expressList.filter(e => !existingWaybillIds.has(e.id));
const alreadyExist = existingASList.map(r => r.after_sale_no);
/**
* 组装客户回信模板:单号 + 问题信息 + 工单号。
* @param {Array<{waybill: string, as_no: string}>} pairs 运单号→工单号列表。
* @return {string} 模板消息。
*/
const buildReply = pairs => {
const lines = pairs.map(p => `运单${p.waybill} ${issue.label}问题已登记,工单:${p.as_no}`);
if (notFound.length > 0) {
lines.push(`未找到运单:${notFound.join('、')},请核实单号`);
}
return `${lines.join('\n')},稍后客服将人工核实跟进`;
};
if (toCreate.length === 0) {
const existedPairs = expressList
.filter(e => existingWaybillIds.has(e.id))
.map(e => {
const row = existingASList.find(r => Number(r.waybill_id) === Number(e.id));
return { waybill: e.waybill_code, as_no: (row && row.after_sale_no) || '' };
})
.filter(p => p.as_no);
return {
success: true,
data: {
existed: true,
message: buildReply(existedPairs),
direct_reply: true,
after_sale_nos: alreadyExist,
},
};
}
// 第三步:创建工单(初始状态 pending=未开始处理,不转发通知快递群)
const creatorLabel = [ groupName, userName ].filter(Boolean).join('-') || 'AI系统';
let msgContent = '';
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) msgContent = 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 || '未知'}`,
`问题类型: ${issue.label}`,
msgContent ? `原消息: ${msgContent}` : '',
].filter(Boolean).join('\n');
await ctx.service.systems.afterSale.create({
warehouse_id: warehouseId,
after_sale_no: afterSaleNo,
type: 'order',
sub_type: issue.sub_type,
title: `[AI工单] ${issue.label} - ${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,
order_id: e.order_id || null,
});
createdNos.push(afterSaleNo);
waybillToAsNo[e.id] = afterSaleNo;
}
ctx.logger.info(
`[inbox functions] 货主问题反馈建工单: sub_type=${issue.sub_type} ` +
`total=${keywords.length} found=${expressList.length} created=${createdNos.length} notFound=${notFound.length}`
);
// 构造返回数据(客户回信模板:单号+问题+工单,细节字段仅作内部记录)
const createdPairs = toCreate.map(e => ({
waybill: e.waybill_code,
as_no: waybillToAsNo[e.id] || '',
}));
const existedPairs = expressList
.filter(e => existingWaybillIds.has(e.id))
.map(e => {
const row = existingASList.find(r => Number(r.waybill_id) === Number(e.id));
return { waybill: e.waybill_code, as_no: (row && row.after_sale_no) || '' };
})
.filter(p => p.as_no);
return {
success: true,
data: {
created: createdNos.length,
existed: alreadyExist.length,
after_sale_nos: [ ...createdNos, ...alreadyExist ],
not_found: notFound,
message: buildReply([ ...createdPairs, ...existedPairs ]),
direct_reply: true,
},
};
} catch (error) {
ctx.logger.error(`[inbox functions] 货主问题反馈建工单失败: ${error.message}`);
return { success: false, error: `操作失败: ${error.message}` };
}
},
});
this.register('changeAddr', {
description: '货主售后群改地址/催退回处理。客户消息含"改地址/改电话/改联系人/改收件人/地址更改/改手机/催退回/尽快安排派送/催促退回"等诉求且提供了运单号时调用:创建售后工单(改地址/催退回),并将客户原文转发到对应快递的售后群通知快递处理',
weight: 89,
keywords: [ '改地址', '改电话', '改联系人', '改收件人', '地址更改', '改手机', '催退回', '尽快安排派送', '催促退回' ],
params: {
keyword: { type: 'string', required: true, description: '运单号,多个用逗号或空格分隔,如 SF111,SF222' },
issue_type: { type: 'string', required: true, description: '诉求类型:addr(改地址类诉求)/return(催退回类诉求)' },
},
groups: [ GROUP.BOUND_STORE_AFTER_SALES ],
handler: async (params = {}) => {
const { ctx } = this;
const raw = String(params.keyword || '').trim();
const issueTypeRaw = String(params.issue_type || '').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 ISSUE_TYPE_MAP = {
addr: { sub_type: 'change_address', label: '改地址' },
改地址: { sub_type: 'change_address', label: '改地址' },
return: { sub_type: 'rejected', label: '催退回' },
催退回: { sub_type: 'rejected', label: '催退回' },
};
const issue = ISSUE_TYPE_MAP[issueTypeRaw] || ISSUE_TYPE_MAP.addr;
const keywords = raw.split(/[,,\s\n]+/).map(s => s.trim()).filter(Boolean);
if (keywords.length === 0) return { success: false, error: '未解析到有效运单号' };
const asLikeList = keywords.filter(k => /^AS/i.test(k));
if (asLikeList.length > 0) {
return { success: false, error: `${asLikeList.join('、')} 是售后工单号而非运单号,请提供运单号` };
}
try {
// 原文(客户原始消息,用于转发快递群 + 工单明细)
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 expressList = await ctx.model.OrderExpress.findAll({
attributes: [ 'id', 'waybill_code', 'logistics_name', 'store_id', 'order_id',
'logistics_interface_id', 'logistics_code' ],
where: {
waybill_code: { [ctx.app.Sequelize.Op.in]: keywords },
warehouse_id: warehouseId,
store_id: storeId,
},
raw: true,
});
const foundCodes = new Set(expressList.map(e => e.waybill_code));
const notFound = keywords.filter(k => !foundCodes.has(k));
if (expressList.length === 0) {
return { success: false, error: `未找到当前货主在仓库中的运单「${raw}」,请核实单号后重试` };
}
// 第二步:幂等检查(同子类型未完结工单不重复建单)
const expressIds = expressList.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]: expressIds },
type: 'order',
sub_type: issue.sub_type,
status: { [ctx.app.Sequelize.Op.notIn]: [ 'completed', 'closed', 'cancelled' ] },
},
raw: true,
});
const existingWaybillIds = new Set(existingASList.map(r => r.waybill_id));
const toCreate = expressList.filter(e => !existingWaybillIds.has(e.id));
const alreadyExist = existingASList.map(r => r.after_sale_no);
const existedPairs = expressList
.filter(e => existingWaybillIds.has(e.id))
.map(e => {
const row = existingASList.find(r => Number(r.waybill_id) === Number(e.id));
return { waybill: e.waybill_code, as_no: (row && row.after_sale_no) || '' };
})
.filter(p => p.as_no);
// 第三步:创建工单(含原文)并映射 waybill_id → 工单号
const createdNos = [];
const waybillToAsNo = {}; // waybill_id → after_sale_no 映射
if (toCreate.length > 0) {
const creatorLabel = [ groupName, userName ].filter(Boolean).join('-') || 'AI系统';
for (const e of toCreate) {
const afterSaleNo = await ctx.service.systemMethods.afterSale.generateAfterSaleNo(warehouseId);
const descParts = [
`发起人: ${creatorLabel}`,
`运单号: ${e.waybill_code}`,
`快递公司: ${e.logistics_name || '未知'}`,
`诉求类型: ${issue.label}`,
originalText ? `原文: ${originalText}` : '',
].filter(Boolean).join('\n');
await ctx.service.systems.afterSale.create({
warehouse_id: warehouseId,
after_sale_no: afterSaleNo,
type: 'order',
sub_type: issue.sub_type,
title: `[AI工单] ${issue.label} - ${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,
order_id: e.order_id || null,
});
createdNos.push(afterSaleNo);
waybillToAsNo[e.id] = afterSaleNo;
}
}
// 第四步:原文转发到对应快递的售后群(按快递分组)
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 } = await ctx.service.systems.inbox.group.findGroupsByExpress({
expressInterfaceId: info.interfaceId,
expressCode: code,
warehouseId,
});
if (afterSalesGroups.length === 0) {
ctx.logger.info(`[inbox functions] 快递 ${code} 未配置售后群,跳过转发`);
continue;
}
// 原文转发:运单号 + 客户原始消息
const forwardMsg = `运单: ${info.waybills.join('、')}\n原文: ${originalText || raw}`;
for (const g of afterSalesGroups) {
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;
}
toCreate
.filter(e => (e.logistics_code || '__unknown__') === code)
.forEach(e => notifiedWaybillIds.add(e.id));
} catch (e) {
ctx.logger.warn(`[inbox functions] 改地址/催退回查快递群失败 code=${code}: ${e.message}`);
}
}
// 第五步:有转发通知的工单升级 pending_feedback + 跟踪时限
const notifiedAsNos = createdNos.filter((asNo, idx) => notifiedWaybillIds.has(toCreate[idx].id));
if (notifiedAsNos.length > 0) {
try {
const hours = await ctx.service.systems.afterSale._resolveFollowupHours(
warehouseId, 'order', issue.sub_type
);
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 } } }
);
} catch (e) {
ctx.logger.warn(`[inbox functions] 改地址/催退回更新工单状态失败: ${e.message}`);
}
}
// 第六步:客户回信模板(单号+诉求+工单)
const createdPairs = toCreate.map(e => ({
waybill: e.waybill_code,
as_no: waybillToAsNo[e.id] || '',
}));
const lines = [ ...createdPairs, ...existedPairs ].map(p => `运单${p.waybill} ${issue.label}问题已登记,工单:${p.as_no}`);
if (notFound.length > 0) {
lines.push(`未找到运单:${notFound.join('、')},请核实单号`);
}
ctx.logger.info(
`[inbox functions] 改地址/催退回: sub_type=${issue.sub_type} ` +
`total=${keywords.length} found=${expressList.length} created=${createdNos.length} notified=${notifiedTotal}`
);
return {
success: true,
data: {
created: createdNos.length,
existed: alreadyExist.length,
after_sale_nos: [ ...createdNos, ...alreadyExist ],
notified_groups: notifiedTotal,
not_found: notFound,
message: `${lines.join('\n')},稍后客服将人工核实跟进`,
direct_reply: true,
},
};
} catch (error) {
ctx.logger.error(`[inbox functions] 改地址/催退回处理失败: ${error.message}`);
return { success: false, error: `操作失败: ${error.message}` };
}
},
});
this.register('weishoudao', {
description: '货主售后群核实签收处理。客户消息含"核实签收/未收到/是否发出/是否已经发货/核实/没有找到快递"等诉求且提供了运单号时调用:创建核实签收售后工单(verify_delivery),并把"运单号+核实签收"转发到对应快递的售后群通知快递核实',
weight: 89,
keywords: [ '核实签收', '未收到', '是否发出', '是否已经发货', '没有找到快递' ],
params: {
keyword: { type: 'string', required: true, description: '运单号,多个用逗号或空格分隔,如 SF111,SF222' },
},
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();
const issue = { sub_type: 'verify_delivery', label: '核实签收' };
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: '未解析到有效运单号' };
const asLikeList = keywords.filter(k => /^AS/i.test(k));
if (asLikeList.length > 0) {
return { success: false, error: `${asLikeList.join('、')} 是售后工单号而非运单号,请提供运单号` };
}
try {
// 原文(客户原始消息,写入工单明细)
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 expressList = await ctx.model.OrderExpress.findAll({
attributes: [ 'id', 'waybill_code', 'logistics_name', 'store_id', 'order_id',
'logistics_interface_id', 'logistics_code' ],
where: {
waybill_code: { [ctx.app.Sequelize.Op.in]: keywords },
warehouse_id: warehouseId,
store_id: storeId,
},
raw: true,
});
const foundCodes = new Set(expressList.map(e => e.waybill_code));
const notFound = keywords.filter(k => !foundCodes.has(k));
if (expressList.length === 0) {
return { success: false, error: `未找到当前货主在仓库中的运单「${raw}」,请核实单号后重试` };
}
// 第二步:幂等检查(同子类型未完结工单不重复建单)
const expressIds = expressList.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]: expressIds },
type: 'order',
sub_type: issue.sub_type,
status: { [ctx.app.Sequelize.Op.notIn]: [ 'completed', 'closed', 'cancelled' ] },
},
raw: true,
});
const existingWaybillIds = new Set(existingASList.map(r => r.waybill_id));
const toCreate = expressList.filter(e => !existingWaybillIds.has(e.id));
const alreadyExist = existingASList.map(r => r.after_sale_no);
const existedPairs = expressList
.filter(e => existingWaybillIds.has(e.id))
.map(e => {
const row = existingASList.find(r => Number(r.waybill_id) === Number(e.id));
return { waybill: e.waybill_code, as_no: (row && row.after_sale_no) || '' };
})
.filter(p => p.as_no);
// 第三步:创建工单(含原文)并映射 waybill_id → 工单号
const createdNos = [];
const waybillToAsNo = {};
if (toCreate.length > 0) {
const creatorLabel = [ groupName, userName ].filter(Boolean).join('-') || 'AI系统';
for (const e of toCreate) {
const afterSaleNo = await ctx.service.systemMethods.afterSale.generateAfterSaleNo(warehouseId);
const descParts = [
`发起人: ${creatorLabel}`,
`运单号: ${e.waybill_code}`,
`快递公司: ${e.logistics_name || '未知'}`,
`诉求类型: ${issue.label}`,
originalText ? `原文: ${originalText}` : '',
].filter(Boolean).join('\n');
await ctx.service.systems.afterSale.create({
warehouse_id: warehouseId,
after_sale_no: afterSaleNo,
type: 'order',
sub_type: issue.sub_type,
title: `[AI工单] ${issue.label} - ${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,
order_id: e.order_id || null,
});
createdNos.push(afterSaleNo);
waybillToAsNo[e.id] = afterSaleNo;
}
}
// 第四步:转发快递群(格式:运单号 + \n + 核实签收)
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 } = await ctx.service.systems.inbox.group.findGroupsByExpress({
expressInterfaceId: info.interfaceId,
expressCode: code,
warehouseId,
});
if (afterSalesGroups.length === 0) {
ctx.logger.info(`[inbox functions] 快递 ${code} 未配置售后群,跳过转发`);
continue;
}
const forwardMsg = `${info.waybills.join('\n')}\n核实签收`;
for (const g of afterSalesGroups) {
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;
}
toCreate
.filter(e => (e.logistics_code || '__unknown__') === code)
.forEach(e => notifiedWaybillIds.add(e.id));
} catch (e) {
ctx.logger.warn(`[inbox functions] 核实签收查快递群失败 code=${code}: ${e.message}`);
}
}
// 第五步:有转发通知的工单升级 pending_feedback + 跟踪时限
const notifiedAsNos = createdNos.filter((asNo, idx) => notifiedWaybillIds.has(toCreate[idx].id));
if (notifiedAsNos.length > 0) {
try {
const hours = await ctx.service.systems.afterSale._resolveFollowupHours(
warehouseId, 'order', issue.sub_type
);
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 } } }
);
} catch (e) {
ctx.logger.warn(`[inbox functions] 核实签收更新工单状态失败: ${e.message}`);
}
}
// 第六步:客户回信模板(单号+诉求+工单)
const createdPairs = toCreate.map(e => ({
waybill: e.waybill_code,
as_no: waybillToAsNo[e.id] || '',
}));
const lines = [ ...createdPairs, ...existedPairs ].map(p => `运单${p.waybill} ${issue.label}问题已登记,工单:${p.as_no}`);
if (notFound.length > 0) {
lines.push(`未找到运单:${notFound.join('、')},请核实单号`);
}
ctx.logger.info(
`[inbox functions] 核实签收: total=${keywords.length} found=${expressList.length} created=${createdNos.length} notified=${notifiedTotal}`
);
return {
success: true,
data: {
created: createdNos.length,
existed: alreadyExist.length,
after_sale_nos: [ ...createdNos, ...alreadyExist ],
notified_groups: notifiedTotal,
not_found: notFound,
message: `${lines.join('\n')},稍后客服将人工核实跟进`,
direct_reply: true,
},
};
} catch (error) {
ctx.logger.error(`[inbox functions] 核实签收处理失败: ${error.message}`);
return { success: false, error: `操作失败: ${error.message}` };
}
},
});
this.register('changeExpress', {
description: '货主售后群改快递。客户要求"改快递/换快递/改圆通/改中通/改顺丰"等且提供了订单号时调用。仅待处理表中未分配快递(post_status=none)的订单可以修改快递;已分配快递或不在待处理表的订单不能修改',
weight: 87,
keywords: [ '改快递', '换快递', '改圆通', '改中通', '改申通', '改顺丰', '改极兔', '改韵达', '改京东', '改德邦' ],
params: {
keyword: { type: 'string', required: true, description: '订单号(发货单号或平台单号),多个用逗号或空格分隔' },
express: { type: 'string', required: true, description: '目标快递名称或编码,如 圆通/中通/顺丰,或系统编码如 YTO/STO/SF' },
},
groups: [ GROUP.BOUND_STORE_AFTER_SALES ],
handler: async (params = {}) => {
const { ctx } = this;
const raw = String(params.keyword || '').trim();
const expressRaw = String(params.express || '').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 (!expressRaw) 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;
// 第一步:解析目标快递(兼容名称/别名/编码)。
// 快递列表服务依赖 ctx.user.store_id 作为仓库上下文,临时注入后恢复。
const originalUser = ctx.user;
ctx.user = {
...(originalUser || {}),
store_id: warehouseId,
employees_id: 0,
employees_name: [ groupName, userName ].filter(Boolean).join('-') || 'AI系统',
};
let expressList = [];
try {
expressList = await ctx.service.systems.express.getExpressList();
} finally {
ctx.user = originalUser;
}
const expressKey = expressRaw.toUpperCase();
const list = Array.isArray(expressList) ? expressList : [];
// 第一轮:精确匹配(编码/名称/别名/系统编码)
let expressItem = list.find(item => {
const code = String(item.code || item.value || '').trim().toUpperCase();
const name = String(item.name || '').trim().toUpperCase();
const alias = String(item.alias || '').trim().toUpperCase();
const sysCode = String(item.express_code || '').trim().toUpperCase();
return code === expressKey || name === expressKey || alias === expressKey || sysCode === expressKey;
});
// 第二轮:模糊匹配(如客户说"圆通",列表名为"圆通快递")
if (!expressItem && expressKey.length >= 2) {
const fuzzy = list.filter(item => {
const code = String(item.code || item.value || '').trim().toUpperCase();
const name = String(item.name || '').trim().toUpperCase();
const alias = String(item.alias || '').trim().toUpperCase();
const fields = [ name, alias, code ].filter(Boolean);
return fields.some(f => f.includes(expressKey) || expressKey.includes(f));
});
if (fuzzy.length === 1) {
expressItem = fuzzy[0];
} else if (fuzzy.length > 1) {
const names = fuzzy.slice(0, 10)
.map(item => `${item.name || item.code || ''}(${item.code || item.value || ''})`)
.join('、');
return {
success: false,
error: `快递「${expressRaw}」匹配到多个结果,请明确:${names}`,
};
}
}
if (!expressItem) {
const names = list.slice(0, 20)
.map(item => `${item.name || item.code || ''}(${item.code || item.value || ''})`)
.join('、');
return {
success: false,
error: `未找到快递「${expressRaw}」${names ? `,当前仓库可选快递:${names}` : ''}`,
};
}
// 第二步:查待处理表(仅当前货主)
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',
'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);
}
// 第四步:区分可改(post_status=none)与已分配快递
const eligible = foundOrders.filter(o => String(o.post_status || '').trim() === 'none');
const allocated = foundOrders.filter(o => String(o.post_status || '').trim() !== 'none');
// 第五步:逐个改快递(复用 updateOrderExpress,内部自带 post_status=none 保护)
const expressCode = String(expressItem.code || expressItem.value || '').trim();
const changed = [];
const unchanged = [];
for (const o of eligible) {
try {
const originalUser2 = ctx.user;
ctx.user = {
...(originalUser2 || {}),
store_id: warehouseId,
employees_id: 0,
employees_name: [ groupName, userName ].filter(Boolean).join('-') || 'AI系统',
};
let updateResult = null;
try {
updateResult = await ctx.service.systemMethods.order.pendingOrder.updateOrderExpress({
order_ids: [ o.id ],
express_code: expressCode,
});
} finally {
ctx.user = originalUser2;
}
const updated = Number(updateResult && updateResult.updated_count) || 0;
if (updated > 0) {
changed.push(o.delivery_order_code);
} else {
unchanged.push(o.delivery_order_code);
}
} catch (e) {
ctx.logger.warn(`[inbox functions] 改快递失败 order=${o.delivery_order_code}: ${e.message}`);
unchanged.push(o.delivery_order_code);
}
}
// 第六步:组装模板回复
const expressName = String(expressItem.name || expressItem.code || expressRaw).trim();
const lines = [];
if (changed.length > 0) {
lines.push(`已改快递为「${expressName}」:${changed.join('、')}`);
}
if (allocated.length > 0) {
lines.push(`已分配快递,不能修改:${allocated.map(o => `${o.delivery_order_code}(${o.logistics_name || '已取号'})`).join('、')}`);
}
if (unchanged.length > 0) {
lines.push(`改快递未生效(可能刚分配了快递),请核实:${unchanged.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} ` +
`changed=${changed.length} allocated=${allocated.length} notInPending=${notInPending.length} notFound=${notFound.length}`
);
return {
success: true,
data: {
changed: changed.length,
allocated: allocated.length,
not_in_pending: notInPending.length,
not_found: notFound.length,
express: expressName,
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,
@ -1915,6 +2810,80 @@ class InboxFunctionsService extends Service {
},
});
this.register('queryWarehouseAddress', {
description: '查询仓库收货地址(退货/退件寄回地址)。读取仓库配置中的 receiver_address。用户询问"仓库地址/收货地址/退货地址/退件地址/寄回地址"时调用。仅货主群和仓库群可用,快递群不可用',
weight: 80,
keywords: [ '仓库地址', '收货地址', '退货地址', '退件地址', '寄回地址', '寄件地址' ],
params: {},
groups: [ GROUP.BOUND_STORE_WILDCARD, GROUP.BOUND_WAREHOUSE_WILDCARD ],
handler: async (params = {}) => {
const { ctx } = this;
void params;
const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0);
if (!warehouseId) {
return { success: false, error: '无法获取仓库信息' };
}
try {
const store = await ctx.model.Store.findByPk(warehouseId, {
attributes: [ 'id', 'subject_config' ],
raw: true,
});
if (!store) {
return { success: false, error: `仓库 ${warehouseId} 不存在` };
}
// 读取仓库配置 subject_config.receiver_address(兼容 JSON 字符串形态)
let config = store.subject_config;
if (typeof config === 'string') {
try {
config = JSON.parse(config);
} catch (e) {
config = null;
}
}
if (!config || typeof config !== 'object' || Array.isArray(config)) {
config = {};
}
const receiverAddress = String(config.receiver_address || '').trim();
if (!receiverAddress) {
return {
success: true,
data: {
warehouse_id: warehouseId,
receiver_address: '',
message: '当前仓库未配置收货地址,请联系仓管在仓库设置中维护「仓库收货地址」',
direct_reply: true,
},
};
}
// 配置中可能存的是字面 \n,转成真实换行便于群消息阅读
const displayAddress = receiverAddress
.replace(/\\r\\n/g, '\n')
.replace(/\\n/g, '\n')
.replace(/\\r/g, '\n');
return {
success: true,
data: {
warehouse_id: warehouseId,
receiver_address: receiverAddress,
message: `仓库收货地址:\n${displayAddress}`,
direct_reply: true,
},
};
} catch (error) {
ctx.logger.error(`[inbox functions] 查询仓库收货地址失败: ${error.message}`);
return { success: false, error: `查询仓库地址失败: ${error.message}` };
}
},
});
this.register('listGroups', {
description: '查询当前仓库的群列表,包含屏蔽状态(仅内部仓库群可用)',
params: {},

View File

@ -26,7 +26,7 @@ const GROUP_TYPES = [
type: 'warehouse',
label: '仓库群',
mainGroup: 'bound:warehouse',
wildcardGroup: null,
wildcardGroup: 'bound:warehouse:*',
subTypes: [
{ key: 'receiving', label: '收货' },
{ key: 'production', label: '生产' },

View File

@ -148,6 +148,15 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([
description: '仓库默认发件详细地址',
maxLength: 200,
}),
Object.freeze({
key: 'receiver_address',
name: '仓库收货地址',
type: 'string',
default: '',
required: false,
description: '仓库收货地址(退货/退件收件地址),一行文本',
maxLength: 500,
}),
Object.freeze({
key: 'group_wave_prefix',
name: '团购波次前缀',

View File

@ -1,4 +1,22 @@
[
{
"version": "2026.08.14-warehouse-receive-address",
"date": "2026-08-14",
"type": "added",
"summary": "仓库设置 setting.warehouse 新增仓库收货地址配置字段 receiver_address(一行文本,退货/退件收件地址)",
"methods": [
"setting.warehouse.getSettings",
"setting.warehouse.getFieldMeta",
"setting.warehouse.saveSettings"
],
"notes": [
"在 WAREHOUSE_SETTING_FIELDS 中新增 receiver_address(string,非必填,默认空字符串,最大长度 500)",
"wms_store.subject_config 默认值同步补齐(app/model/store.js DEFAULT_SUBJECT_CONFIG)",
"methods/system.json 中 getSettings 响应与 saveSettings 入参补充对应字段文档",
"向后兼容:新增字段为可选,不影响既有仓库设置读写"
],
"module": "setting.warehouse"
},
{
"version": "2026.08.13-stockQueryWhere",
"date": "2026-08-13",

View File

@ -13663,6 +13663,12 @@
"type": "string",
"required": false,
"description": "仓库默认发件详细地址,默认空字符串"
},
{
"name": "subject_config.receiver_address",
"type": "string",
"required": false,
"description": "仓库收货地址(退货/退件收件地址),一行文本,默认空字符串"
}
],
"errors": [
@ -13906,6 +13912,13 @@
"required": false,
"source": "body.subject_config",
"description": "仓库默认发件详细地址,默认空字符串,最大长度 200"
},
{
"name": "subject_config.receiver_address",
"type": "string",
"required": false,
"source": "body.subject_config",
"description": "仓库收货地址(退货/退件收件地址),一行文本,默认空字符串,最大长度 500"
}
],
"response": [

View File

@ -252,4 +252,32 @@ describe('test/app/service/systems/setting/warehouse.test.js', () => {
);
assert.equal(inventoryWarningRulesField.required, false);
});
it('getFieldMeta should include warehouse receive address field', async () => {
const { ctx } = createHarness();
const service = new SettingWarehouseService(ctx);
const list = await service.getFieldMeta();
const field = list.find(item => item.key === 'receiver_address');
assert.ok(field, '字段信息应包含 receiver_address');
assert.equal(field.name, '仓库收货地址');
assert.equal(field.type, 'string');
assert.equal(field.required, false);
assert.equal(field.default, '');
assert.equal(field.maxLength, 500);
});
it('saveSettings should persist warehouse receive address field', async () => {
const { ctx, calls } = createHarness();
const service = new SettingWarehouseService(ctx);
await service.saveSettings({
subject_config: {
receiver_address: '浙江省杭州市余杭区文一西路 1000 号',
},
});
assert.equal(calls.updatePayload.subject_config.receiver_address, '浙江省杭州市余杭区文一西路 1000 号');
});
});