WMS_MAIN/app/service/inbox/functions.js
liufumingren 806e739267 feat(inbox): v2 规则引擎完善(help 指令/建单开关/系统回复)并修复拦截日志误写仓库 ID
- functions.js: 拦截/取消拦截波次感知写订单日志 businessId 误用仓库 ID,改为订单 ID
  (生产订单 JY2026091813795 已发起拦截但订单详情查不到拦截日志的根因)
- rules/v2/processor/config/functionSync: 新增 help 指令、create_work_order=0 时跳过
  工单登记、系统级回复与无单号提示、白名单范围修正
- after_sale_reply 模型 + 6 个迁移: create_work_order 字段与相关配置种子
- return_unpack: 列表 count 统计修复、分页排序追加主键防重漏行、视频附加 camera_name
- methods/system.json + changes + sync 脚本: 接口文档与权限同步
2026-09-18 22:38:57 +08:00

4535 lines
202 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const Service = require('egg').Service;
// 群类型常量定义统一收口到 inbox/groups.js
const { GROUP } = require('./groups');
const { pickNoticeTimeOrderIds } = require('../../lib/intercept_time');
/**
* 提取车牌号(与 wms_inbox_number_rule 车牌取号规则同版:支持蓝/黄牌、新能源绿牌、
* 挂车、警/学/港澳牌及 ·/· 分隔符)。
* 省份简称兼容简体与异体写法(如 粤/粵)。
* 只取第一个匹配,无匹配返回空字符串。
* @param {string} text 消息正文。
* @return {string} 车牌号。
*/
function extractLicensePlate(text) {
const raw = String(text || '');
const m = raw.match(/[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤粵青藏川宁琼使领][A-HJ-NP-Z][·.]?(?:[DF][A-HJ-NP-Z0-9]{5}|[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳])/);
return m ? m[0] : '';
}
/**
* 回复配置 create_work_order=0 时,v2 引擎注入 ctx.inboxContext.skip_work_order,
* 函数照常执行但建单前应跳过工单登记。
* @param {Object} ctx Egg 上下文。
* @return {boolean} 是否跳过工单登记。
*/
function shouldSkipWorkOrder(ctx) {
return !!(ctx && ctx.inboxContext && ctx.inboxContext.skip_work_order === true);
}
/**
* 站内信函数注册表。
* 负责注册 AI 可调用的函数(含 handler),支持按分组声明可见性。
* 分组匹配与筛选逻辑在 {@link InboxGroupsService} 中。
*/
class InboxFunctionsService extends Service {
/**
* 初始化函数注册表。
* @param {Object} ctx Egg.js 上下文。
*/
constructor(ctx) {
super(ctx);
/** @type {Map<string, {name:string, description:string, params:Object, handler:Function, groups:string[]}>} */
this.registry = new Map();
this.registerBuiltinFunctions();
}
/**
* 注册内置函数。
*/
registerBuiltinFunctions() {
this.register('help', {
description: '帮助指令:枚举当前仓库可见的售后类型与子类型(含关键词),返回可用指令清单(back_text),供回复模板 {back_text} 占位符渲染',
params: {},
groups: [ GROUP.COMMON ],
weight: 0,
keywords: [ '指令', '帮助' ],
handler: async (params = {}) => {
const { ctx } = this;
void params;
const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0);
let cfg = null;
try {
cfg = await ctx.service.inbox.v2.config.load(warehouseId);
} catch (e) {
ctx.logger.warn(`[inbox functions] help 加载 v2 配置失败: ${e.message}`);
}
// 类型名映射
let typeNameMap = {};
try {
const types = await ctx.model.AfterSaleType.findAll({ attributes: [ 'type', 'name' ], raw: true });
typeNameMap = {};
for (const t of types) typeNameMap[t.type] = t.name;
} catch (e) { /* ignore */ }
// 关键词按子类型聚合(可见配置)
const kwBySubType = {};
if (cfg && Array.isArray(cfg.keywords)) {
for (const k of cfg.keywords) {
if (!kwBySubType[k.sub_type_id]) kwBySubType[k.sub_type_id] = [];
kwBySubType[k.sub_type_id].push(k.keyword);
}
}
const lines = [];
const subTypes = (cfg && cfg.subTypes) ? Object.values(cfg.subTypes) : [];
for (const st of subTypes) {
const tName = typeNameMap[st.type] || st.type;
const kws = kwBySubType[st.id] || [];
lines.push(`${tName}:`);
lines.push(` ${st.name}:关键词:${kws.length > 0 ? kws.join(',') : '(未配置)'}`);
}
const backText = lines.length > 0 ? lines.join('\n') : '(当前仓库未配置可用指令)';
return {
success: true,
data: { back_text: backText },
};
},
});
this.register('hello', {
description: '问候接口,返回欢迎信息。传入 name 参数可个性化问候',
params: {
name: { type: 'string', required: false, description: '用户名称' },
},
groups: [ GROUP.COMMON ],
weight: 0,
keywords: [ '你好', 'hi', 'hello', '在吗' ],
handler: async (params = {}) => {
const name = String(params.name || '').trim();
const greeting = name ? `你好,${name}!欢迎使用 WMS 站内信服务` : '你好!欢迎使用 WMS 站内信服务';
return {
success: true,
data: { greeting },
};
},
});
this.register('queryPrintBalance', {
description: '查询当前货主的面单余额。根据上下文中的货主ID和仓库ID查询合约中的面单剩余量和锁定量',
params: {},
groups: [ GROUP.BOUND_STORE_WILDCARD ],
weight: 80,
keywords: [ '面单余额', '打印余额', '快递单余额', '还剩多少单', '面单' ],
handler: async (params = {}) => {
const { ctx } = this;
void params;
const storeId = Number(ctx.inboxContext?.store_id || 0);
const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0);
if (!Number.isFinite(storeId) || storeId <= 0) {
return {
success: false,
error: '无法获取货主信息,请确认已在已签约的货主上下文中操作',
};
}
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
return {
success: false,
error: '无法获取仓库信息,请确认上下文已正确设置',
};
}
try {
const contract = await ctx.model.StoreWarehouse.findOne({
attributes: [
'id', 'store_id', 'warehouse_id',
'print_quantity', 'print_quantity_locked',
],
where: {
store_id: storeId,
warehouse_id: warehouseId,
auth_status: 2,
warehouse_use_status: 1,
},
raw: true,
});
if (!contract) {
return {
success: false,
error: `货主 ${storeId} 在仓库 ${warehouseId} 中无有效合约,请检查货主ID是否正确`,
};
}
const available = Math.max(0, contract.print_quantity - contract.print_quantity_locked);
return {
success: true,
data: {
store_id: contract.store_id,
warehouse_id: contract.warehouse_id,
print_quantity: contract.print_quantity,
print_quantity_locked: contract.print_quantity_locked,
available,
},
};
} catch (error) {
return {
success: false,
error: `查询面单余额失败: ${error.message}`,
};
}
},
});
this.register('createWaybill', {
description: '为指定平台单号创建快递单号。根据平台订单号查找发货单并分配快递单号',
params: {
order_code: { type: 'string', required: true, description: '平台订单号' },
},
groups: [ GROUP.BOUND_STORE_WILDCARD ],
weight: 90,
keywords: [ '创建快递单', '取号', '分配快递', '生成运单', '快递单号' ],
handler: async (params = {}) => {
const { ctx } = this;
const orderCode = String(params.order_code || '').trim();
const storeId = Number(ctx.inboxContext?.store_id || 0);
const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0);
if (!orderCode) {
return {
success: false,
error: '未提供有效的平台单号,请提供订单编号',
};
}
if (!warehouseId || !storeId) {
return {
success: false,
error: '无法获取仓库或货主信息,请确认上下文已正确设置',
};
}
try {
const OrderDelivery = await ctx.service.systems.express.getWaybillAsyncOrderDeliveryModel(warehouseId);
if (!OrderDelivery) {
return { success: false, error: `仓库 ${warehouseId} 的发货单表不可用` };
}
const orderDelivery = await OrderDelivery.findOne({
attributes: [ 'id', 'delivery_order_code', 'source_order_codes', 'store_id', 'warehouse_id', 'post_status' ],
where: {
source_order_codes: { [ctx.app.Sequelize.Op.like]: `%${orderCode}%` },
warehouse_id: warehouseId,
store_id: storeId,
},
raw: true,
});
if (!orderDelivery) {
return {
success: false,
error: `未找到平台单号 ${orderCode} 对应的发货单,请核实单号是否正确`,
};
}
// 查已有快递单号(强制同仓校验:同时匹配订单ID与仓库ID)
const existingExpress = await ctx.model.OrderExpress.findOne({
attributes: [ 'waybill_code', 'logistics_name', 'status' ],
where: { order_id: orderDelivery.id, business_key: 1, warehouse_id: warehouseId },
raw: true,
});
if (existingExpress && existingExpress.waybill_code) {
return {
success: true,
data: {
order_id: orderDelivery.id,
delivery_order_code: orderDelivery.delivery_order_code,
waybill_code: existingExpress.waybill_code,
logistics_name: existingExpress.logistics_name,
existed: true,
},
};
}
// 触发取号
await ctx.service.systemMethods.order.pendingOrder.allocateExpressCode({
ids: [ orderDelivery.id ],
});
return {
success: true,
data: {
order_id: orderDelivery.id,
delivery_order_code: orderDelivery.delivery_order_code,
message: `已为订单 ${orderCode} 提交快递取号任务,请稍后查询`,
},
};
} catch (error) {
return {
success: false,
error: `创建快递单号失败: ${error.message}`,
};
}
},
});
this.register('searchStock', {
description: '搜索仓库商品(货主级)。返回商品ID/编码/名称/品牌/单位/毛重/管理标识/库存/图片/关联条码/箱规/违禁品/打包要求',
params: {
keyword: { type: 'string', required: true, description: '搜索关键词:商品编码(item_code)、条码(barcode)、商品名称(item_name)' },
},
groups: [ GROUP.BOUND_STORE_WILDCARD ],
weight: 70,
keywords: [ '查商品', '搜商品', '找商品', '商品信息', '库存', '商品' ],
handler: async (params = {}) => {
const { ctx } = this;
const storeId = Number(ctx.inboxContext?.store_id || 0);
const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0);
const keyword = String(params.keyword || '').trim();
const { Op } = ctx.app.Sequelize;
if (!keyword) return { success: false, error: '请提供搜索关键词' };
if (!warehouseId || !storeId) return { success: false, error: '无法获取仓库或货主信息' };
try {
// 从 stock_barcodes 找匹配条码的 stock_id
const barcodeMatchIds = await ctx.model.StockBarcode.findAll({
attributes: [ 'stock_id' ],
where: { barcode: { [Op.like]: `%${keyword}%` } },
raw: true,
});
const barcodeStockIds = [ ...new Set(barcodeMatchIds.map(b => b.stock_id)) ];
// 直接查 stock_warehouse(按货主过滤,不查 stock_store)
const orConditions = [
{ item_code: { [Op.like]: `%${keyword}%` } },
{ item_name: { [Op.like]: `%${keyword}%` } },
];
if (barcodeStockIds.length > 0) {
orConditions.push({ id: { [Op.in]: barcodeStockIds } });
}
const items = await ctx.model.StockWarehouse.findAll({
attributes: [ 'id', 'item_code', 'item_name', 'brand_name', 'stock_unit', 'gross_weight', 'quantity', 'locked_quantity', 'is_images', 'is_sn_mgmt', 'is_shelf_life_mgmt', 'is_batch_mgmt', 'prohibited_id', 'enable_box_spec', 'box_gross_weight', 'box_net_weight', 'box_length', 'box_width', 'box_height', 'quantity_per_box', 'box_volume', 'packing_requirements' ],
where: {
store_id: storeId,
[Op.or]: orConditions,
},
limit: 10,
raw: true,
});
if (items.length === 0) {
return { success: true, data: { total: 0, items: [], hint: '未找到匹配商品,请尝试其他关键词' } };
}
// 批查条码
const itemIds = items.map(i => i.id);
const barcodeMap = {};
if (itemIds.length > 0) {
const barcodes = await ctx.model.StockBarcode.findAll({
attributes: [ 'stock_id', 'barcode' ],
where: { stock_id: { [Op.in]: itemIds } },
raw: true,
});
for (const b of barcodes) {
if (!barcodeMap[b.stock_id]) barcodeMap[b.stock_id] = [];
barcodeMap[b.stock_id].push(b.barcode);
}
}
// 批查违禁品
const prohibitedIds = [ ...new Set(items.map(i => i.prohibited_id).filter(Boolean)) ];
const prohibitedMap = {};
if (prohibitedIds.length > 0) {
const pts = await ctx.model.ProhibitedType.findAll({
attributes: [ 'id', 'type_name' ],
where: { id: { [Op.in]: prohibitedIds } },
raw: true,
});
for (const p of pts) prohibitedMap[p.id] = p.type_name || '';
}
// 批查商品图片(wms_file_reference + wms_file,与 stock.warehouse.list 一致)
const imageUrlMap = {};
if (itemIds.length > 0) {
const refs = await ctx.model.FileReference.findAll({
attributes: [ 'business_id' ],
include: [{
model: ctx.model.File,
as: 'file',
attributes: [ 'file_url' ],
required: false,
}],
where: {
business_type: 'stock',
business_id: { [Op.in]: itemIds.map(String) },
},
order: [[ 'display_order', 'ASC' ]],
raw: true,
});
for (const r of refs) {
const sid = Number(r.business_id);
if (!imageUrlMap[sid]) imageUrlMap[sid] = [];
const url = (r['file.file_url'] && String(r['file.file_url']).trim()) || '';
if (url) imageUrlMap[sid].push(url);
}
}
return {
success: true,
data: {
total: items.length,
items: items.map(i => ({
id: i.id,
item_code: i.item_code,
item_name: i.item_name,
barcode: barcodeMap[i.id]?.[0] || '',
brand_name: i.brand_name || '',
unit: i.stock_unit || '',
gross_weight: i.gross_weight || 0,
is_sn_mgmt: i.is_sn_mgmt === 'Y',
is_shelf_life_mgmt: i.is_shelf_life_mgmt === 'Y',
is_batch_mgmt: i.is_batch_mgmt === 'Y',
stock_qty: i.quantity || 0,
stock_locked: i.locked_quantity || 0,
stock_available: Math.max(0, (i.quantity || 0) - (i.locked_quantity || 0)),
has_images: i.is_images === 'Y',
image_url: imageUrlMap[i.id] || [],
barcodes: barcodeMap[i.id] || [],
box_spec: i.enable_box_spec ? {
length: i.box_length || 0, width: i.box_width || 0, height: i.box_height || 0,
volume: i.box_volume || 0, gross_weight: i.box_gross_weight || 0,
net_weight: i.box_net_weight || 0, quantity_per_box: i.quantity_per_box || 0,
} : null,
packing_requirements: i.packing_requirements || '',
prohibited_type: prohibitedMap[i.prohibited_id] || '',
})),
},
};
} catch (error) {
return { success: false, error: `商品搜索失败: ${error.message}` };
}
},
});
this.register('searchWarehouseStock', {
description: '搜索仓库商品(仓库级,不限货主)。返回商品ID/货主/编码/名称/条码/品牌/单位/毛重/管理标识/库存/图片/关联条码/箱规/违禁品/打包要求',
params: {
keyword: { type: 'string', required: true, description: '搜索关键词:商品编码(item_code)、条码(barcode)、商品名称(item_name)' },
},
groups: [ GROUP.COMMON ],
weight: 60,
keywords: [ '仓库商品', '所有商品' ],
handler: async (params = {}) => {
const { ctx } = this;
const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0);
const keyword = String(params.keyword || '').trim();
const { Op } = ctx.app.Sequelize;
if (!keyword) return { success: false, error: '请提供搜索关键词' };
if (!warehouseId) return { success: false, error: '无法获取仓库信息' };
try {
// 从 stock_barcodes 找匹配条码的 stock_id
const barcodeMatchIds = await ctx.model.StockBarcode.findAll({
attributes: [ 'stock_id' ],
where: { barcode: { [Op.like]: `%${keyword}%` } },
raw: true,
});
const barcodeStockIds = [ ...new Set(barcodeMatchIds.map(b => b.stock_id)) ];
// 直接查 stock_warehouse
const orConditions = [
{ item_code: { [Op.like]: `%${keyword}%` } },
{ item_name: { [Op.like]: `%${keyword}%` } },
];
if (barcodeStockIds.length > 0) {
orConditions.push({ id: { [Op.in]: barcodeStockIds } });
}
const items = await ctx.model.StockWarehouse.findAll({
attributes: [ 'id', 'store_id', 'item_code', 'item_name', 'brand_name', 'stock_unit', 'gross_weight', 'quantity', 'locked_quantity', 'is_images', 'is_sn_mgmt', 'is_shelf_life_mgmt', 'is_batch_mgmt', 'prohibited_id', 'enable_box_spec', 'box_gross_weight', 'box_net_weight', 'box_length', 'box_width', 'box_height', 'quantity_per_box', 'box_volume', 'packing_requirements' ],
where: {
[Op.or]: orConditions,
},
limit: 10,
raw: true,
});
if (items.length === 0) {
return { success: true, data: { total: 0, items: [], hint: '未找到匹配商品,请尝试其他关键词' } };
}
// 批查条码
const itemIds = items.map(i => i.id);
const barcodeMap = {};
const barcodes = await ctx.model.StockBarcode.findAll({
attributes: [ 'stock_id', 'barcode' ],
where: { stock_id: { [Op.in]: itemIds } },
raw: true,
});
for (const b of barcodes) {
if (!barcodeMap[b.stock_id]) barcodeMap[b.stock_id] = [];
barcodeMap[b.stock_id].push(b.barcode);
}
// 批查违禁品
const prohibitedIds = [ ...new Set(items.map(i => i.prohibited_id).filter(Boolean)) ];
const prohibitedMap = {};
if (prohibitedIds.length > 0) {
const pts = await ctx.model.ProhibitedType.findAll({
attributes: [ 'id', 'type_name' ],
where: { id: { [Op.in]: prohibitedIds } },
raw: true,
});
for (const p of pts) prohibitedMap[p.id] = p.type_name || '';
}
// 批查商品图片(与 stock.warehouse.list 一致)
const itemIds2 = items.map(i => i.id);
const imageUrlMap2 = {};
if (itemIds2.length > 0) {
const refs2 = await ctx.model.FileReference.findAll({
attributes: [ 'business_id' ],
include: [{
model: ctx.model.File,
as: 'file',
attributes: [ 'file_url' ],
required: false,
}],
where: {
business_type: 'stock',
business_id: { [Op.in]: itemIds2.map(String) },
},
order: [[ 'display_order', 'ASC' ]],
raw: true,
});
for (const r of refs2) {
const sid = Number(r.business_id);
if (!imageUrlMap2[sid]) imageUrlMap2[sid] = [];
const url = (r['file.file_url'] && String(r['file.file_url']).trim()) || '';
if (url) imageUrlMap2[sid].push(url);
}
}
return {
success: true,
data: {
total: items.length,
items: items.map(i => ({
id: i.id,
store_id: i.store_id,
item_code: i.item_code,
item_name: i.item_name,
barcode: barcodeMap[i.id]?.[0] || '',
brand_name: i.brand_name || '',
unit: i.stock_unit || '',
gross_weight: i.gross_weight || 0,
is_sn_mgmt: i.is_sn_mgmt === 'Y',
is_shelf_life_mgmt: i.is_shelf_life_mgmt === 'Y',
is_batch_mgmt: i.is_batch_mgmt === 'Y',
stock_qty: i.quantity || 0,
stock_locked: i.locked_quantity || 0,
stock_available: Math.max(0, (i.quantity || 0) - (i.locked_quantity || 0)),
has_images: i.is_images === 'Y',
image_url: imageUrlMap2[i.id] || [],
barcodes: barcodeMap[i.id] || [],
box_spec: i.enable_box_spec ? {
length: i.box_length || 0, width: i.box_width || 0, height: i.box_height || 0,
volume: i.box_volume || 0, gross_weight: i.box_gross_weight || 0,
net_weight: i.box_net_weight || 0, quantity_per_box: i.quantity_per_box || 0,
} : null,
packing_requirements: i.packing_requirements || '',
prohibited_type: prohibitedMap[i.prohibited_id] || '',
})),
},
};
} catch (error) {
return { success: false, error: `仓库商品搜索失败: ${error.message}` };
}
},
});
this.register('queryOrder', {
description: '查询订单。先精确匹配运单号,未命中则模糊搜索发货单号/平台单号。自动定位订单在待处理表/配送表/历史表中的位置,返回订单关键信息和重量。重量字段说明:items_weight 为订单商品总重量(g),waybills[].weighing_weight 为快递实际称重重量(g),仅已分配运单号时才有称重值',
params: {
keyword: { type: 'string', required: true, description: '搜索关键词:运单号(waybill_code,精确匹配)、发货单号(delivery_order_code,模糊)、平台单号(source_platform_code,模糊)' },
},
groups: [ GROUP.BOUND_STORE_AFTER_SALES ],
weight: 85,
keywords: [ '查订单', '搜订单', '订单详情', '运单号', '快递单号', '发货单' ],
handler: async (params = {}) => {
const { ctx } = this;
const storeId = Number(ctx.inboxContext?.store_id || 0);
const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0);
const keyword = String(params.keyword || '').trim();
const { Op } = ctx.app.Sequelize;
if (!keyword) return { success: false, error: '请提供搜索关键词' };
if (!warehouseId || !storeId) return { success: false, error: '无法获取仓库或货主信息' };
// 公共:三张订单表配置
const attributes = [
'id', 'delivery_order_code', 'source_platform_code', 'source_order_codes',
'store_id', 'warehouse_id', 'status', 'step',
'name', 'mobile', 'province', 'city', 'area', 'detail_address',
'items_count', 'items_total', 'items_weight',
'express_code', 'logistics_name', 'logistics_code',
'total_amount', 'freight',
'create_at', 'updated_at', 'delivery_time',
];
const tableConfigs = [
{ key: 'current', label: '待处理表', getModel: (f, wid) => f.getCurrentModel(wid) },
{ key: 'dispatch', label: '配送表', getModel: (f, wid) => f.getDispatchModel(wid) },
{ key: 'history', label: '历史表', getModel: (f, wid) => f.getHistoryModel(wid) },
];
const factory = ctx.model.OrderDeliveryFactory;
/**
* 在三张订单表中查找匹配行
* @param {Object} where WHERE 条件
* @return {Object|null} 找到的行(含 table/key),或 null
*/
const findInDeliveryTables = async where => {
for (const cfg of tableConfigs) {
const model = await cfg.getModel(factory, warehouseId);
if (!model) continue;
const row = await model.findOne({ attributes, where, raw: true });
if (row) return { table: cfg.key, table_label: cfg.label, ...row };
}
return null;
};
try {
let found = null;
// ========== 第一步:运单号精确匹配 ==========
const exactExpress = await ctx.model.OrderExpress.findOne({
attributes: [ 'delivery_order_code', 'order_id' ],
where: {
waybill_code: keyword,
store_id: storeId,
warehouse_id: warehouseId,
},
raw: true,
});
if (exactExpress && exactExpress.delivery_order_code) {
// 运单精确匹配:先通过序列表定位订单所在分表,命中只查一张表;
// 未命中(存量订单无指针)回退三表按单号遍历
const exactOrderId = Number(exactExpress.order_id || 0);
if (exactOrderId > 0 && factory && typeof factory.getOrderLocation === 'function') {
try {
const locatedAt = await factory.getOrderLocation(exactOrderId, warehouseId);
if (locatedAt) {
const locatedCfg = tableConfigs.find(cfg => cfg.key === locatedAt);
if (locatedCfg) {
const locatedModel = await locatedCfg.getModel(factory, warehouseId);
if (locatedModel) {
const locatedRow = await locatedModel.findOne({
attributes,
where: { id: exactOrderId, store_id: storeId },
raw: true,
});
if (locatedRow) {
found = { table: locatedCfg.key, table_label: locatedCfg.label, ...locatedRow };
}
}
}
}
} catch (_err) { /* 定位失败,降级三表遍历 */ }
}
if (!found) {
// 用运单关联的发货单号精确查找订单
found = await findInDeliveryTables({
store_id: storeId,
delivery_order_code: exactExpress.delivery_order_code,
});
}
}
// ========== 第二步:运单未命中 → 模糊搜索发货单号 / 平台单号 ==========
if (!found) {
found = await findInDeliveryTables({
store_id: storeId,
[Op.or]: [
{ delivery_order_code: { [Op.like]: `%${keyword}%` } },
{ source_platform_code: { [Op.like]: `%${keyword}%` } },
],
});
}
if (!found) {
return {
success: false,
error: `未找到与「${keyword}」匹配的订单,请核实单号后重试(支持运单号精确匹配 / 发货单号模糊 / 平台单号模糊查询)`,
};
}
// ========== 第三步:查关联运单信息 ==========
const linkedExpress = await ctx.model.OrderExpress.findAll({
attributes: [ 'waybill_code', 'logistics_name', 'weighing_weight', 'status', 'is_galaxy_receive' ],
where: {
delivery_order_code: found.delivery_order_code,
store_id: storeId,
},
raw: true,
});
const hasWaybill = linkedExpress.length > 0;
return {
success: true,
data: {
table: found.table,
table_label: found.table_label,
order_id: found.id,
delivery_order_code: found.delivery_order_code || '',
source_platform_code: found.source_platform_code || '',
source_order_codes: found.source_order_codes || '',
status: found.status,
step: found.step,
receiver_name: found.name || '',
receiver_mobile: found.mobile || '',
receiver_address: [ found.province, found.city, found.area, found.detail_address ]
.filter(Boolean).join(''),
items_count: found.items_count || 0,
items_total: found.items_total || 0,
// 重量信息(必须区分说明)
items_weight: found.items_weight || 0,
items_weight_note: '商品总重量(克),订单中所有商品SKU的合计重量',
has_waybill: hasWaybill,
has_waybill_note: hasWaybill ? '' : '该订单尚未分配运单号,无实际称重重量',
waybills: linkedExpress.map(e => ({
waybill_code: e.waybill_code || '',
logistics_name: e.logistics_name || '',
weighing_weight: e.weighing_weight || 0,
weighing_weight_note: '快递实际称重重量(克),仅已分配运单号并完成称重时才有值',
status: e.status,
is_received: e.is_galaxy_receive === 'Y',
})),
express_code: found.express_code || '',
logistics_name: found.logistics_name || '',
total_amount: found.total_amount,
freight: found.freight,
created_at: found.create_at,
updated_at: found.updated_at,
delivery_time: found.delivery_time || null,
},
};
} catch (error) {
return { success: false, error: `订单查询失败: ${error.message}` };
}
},
});
this.register('recallHistory', {
description: '回顾当前群的最近对话历史(均为已处理完毕的历史记录,仅作背景参考,严禁把其中的运单号/诉求当成新请求)。当需要上下文但信息不足时调用,获取最近N条消息记录(含AI回复),每条带序号',
params: {
limit: { type: 'number', required: false, description: '获取最近几条,默认5,最大10' },
},
groups: [ GROUP.COMMON ],
weight: 0,
keywords: [],
handler: async (params = {}) => {
const { ctx } = this;
const limit = Math.min(10, Math.max(1, Number(params.limit) || 5));
const history = await ctx.service.inbox.ai.getConversationHistory({ maxMessages: limit });
if (history.length === 0) {
return { success: true, data: { total: 0, messages: [], hint: '暂无对话历史' } };
}
return {
success: true,
data: {
total: history.length,
hint: '以下均为已处理完毕的历史记录,仅作背景参考,严禁把其中的运单号/诉求当作新请求处理',
messages: history.map(h => ({
role: h.role === 'user' ? '用户' : 'AI',
user: h.user_name || h.user_id || null,
blocked: h.blocked || false,
content: h.content || '',
})),
},
};
},
});
this.register('createOrder', {
description: '创建发货订单。传入商品 stock_id(来自 searchStock)及数量、收件人信息,使用手工建单流程创建发货单',
weight: 90,
keywords: [ '建单', '创建订单', '下单', '发货', '新建订单' ],
params: {
items: { type: 'array', required: true, description: '商品列表 [{item_id: stock_id, plan_qty: 数量}]' },
receiverName: { type: 'string', required: true, description: '收件人姓名' },
receiverPhone: { type: 'string', required: true, description: '收件人电话' },
receiverProvince: { type: 'string', required: false, description: '省份' },
receiverCity: { type: 'string', required: false, description: '城市' },
receiverDistrict: { type: 'string', required: false, description: '区县' },
receiverAddress: { type: 'string', required: true, description: '详细地址' },
},
groups: [ GROUP.BOUND_STORE_AFTER_SALES ],
handler: async (params = {}) => {
const { ctx } = this;
const storeId = Number(ctx.inboxContext?.store_id || 0);
const items = Array.isArray(params.items) ? params.items : [];
const name = String(params.receiverName || '').trim();
const mobile = String(params.receiverPhone || '').trim();
const province = String(params.receiverProvince || '').trim();
const city = String(params.receiverCity || '').trim();
const area = String(params.receiverDistrict || '').trim();
const detailAddress = String(params.receiverAddress || '').trim();
if (!storeId) return { success: false, error: '无法获取货主信息' };
if (!name) return { success: false, error: '收件人姓名不能为空' };
if (!mobile) return { success: false, error: '收件人电话不能为空' };
if (!detailAddress) return { success: false, error: '详细地址不能为空' };
if (!province) return { success: false, error: '省份不能为空' };
if (items.length === 0) return { success: false, error: '请提供至少一个商品' };
try {
// 适配手工建单格式
const orderItems = items.map((item, i) => ({
item_id: Number(item.item_id),
plan_qty: Number(item.plan_qty) || 1,
item_code: String(item.item_code || '').trim(),
item_name: String(item.item_name || '').trim(),
order_line_no: String(i + 1),
}));
const invalidItems = orderItems.filter(i => !i.item_id || i.item_id <= 0);
if (invalidItems.length > 0) {
return { success: false, error: '商品 item_id 必须为正整数(请先使用 searchStock 获取正确的商品ID)' };
}
const result = await ctx.service.systemMethods.order.pendingOrder.createOrder({
store_id: storeId,
name,
mobile,
tel: '',
province,
city,
area,
detail_address: detailAddress,
items: orderItems,
});
return {
success: true,
data: {
deliveryOrderCode: result?.delivery_order_code || result?.deliveryOrderCode || '',
message: result?.message || '发货单创建成功',
},
};
} catch (error) {
return { success: false, error: `建单失败: ${error.message}` };
}
},
});
this.register('blockUser', {
description: '屏蔽用户消息。将当前群和用户加入屏蔽列表,后续不再回复',
params: {},
groups: [ GROUP.COMMON ],
weight: 0,
keywords: [ '屏蔽', '不回复', '拉黑' ],
handler: async (params = {}) => {
const { ctx } = this;
void params;
const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0);
const groupId = String(ctx.inboxContext?.group_id || '').trim();
const userId = String(ctx.inboxContext?.user_id || '').trim();
const groupName = String(ctx.inboxContext?.group_name || '').trim();
const userName = String(ctx.inboxContext?.user_name || '').trim();
if (!warehouseId) {
return { success: false, error: '无法获取仓库信息,屏蔽操作失败' };
}
if (!groupId && !userId) {
return {
success: false,
error: '无法获取群ID或用户ID,屏蔽操作需要明确的群或用户身份',
};
}
try {
const { InboxBlock } = ctx.model;
await InboxBlock.create({
warehouse_id: warehouseId,
group_id: groupId || null,
user_id: userId || null,
});
// 失效屏蔽缓存
await ctx.service.inbox.processor.invalidateBlockCache(warehouseId);
const scope = [];
if (groupName) scope.push(`群「${groupName}」`);
if (userName) scope.push(`用户「${userName}」`);
return {
success: true,
data: {
message: `已屏蔽${scope.join('的')},后续将不再处理你的消息。如需解除屏蔽,请联系客服到WMS解除。`,
},
};
} catch (error) {
// 唯一键冲突 = 已屏蔽
if (error.name === 'SequelizeUniqueConstraintError') {
return {
success: true,
data: {
message: '该群或用户已在屏蔽列表中,无需重复操作。如需解除屏蔽,请联系客服到WMS解除。',
},
};
}
return {
success: false,
error: `屏蔽操作失败: ${error.message}`,
};
}
},
});
this.register('interceptWaybill', {
description: '拦截运单(支持批量)。仅当用户明确要求"拦截/退回/召回/追回"快递运单时才调用。传入运单号(如SF123456),校验权限后批量创建售后工单,并合并通知对应快递的售后群。货主群需验store_id,仓库群无需。严禁:讨论已有售后工单(AS开头)不是拦截请求、询问物流进度不是拦截请求',
weight: 95,
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 ],
/**
* 拦截运单处理器:批量创建售后工单,并按波次规则写入订单拦截状态
* intercept_status='requested' 与拦截时间 intercept_time。
* @param {Object} params 入参,包含 keyword(运单号)与 reason(拦截原因)。
* @return {Promise<Object>} 处理结果,包含 success 与 data/error。
*/
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('、')} 看起来是售后工单号而非运单号,如需查询工单请用 queryOrder,如需拦截请提供运单号`,
};
}
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}」,请核实单号后重试` };
}
// 第二步:鉴权 + 过滤
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: 'intercept',
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);
// 已存在工单对应的运单号(去重):客户回信只给运单号,不暴露售后单号
const alreadyExistWbs = [ ...new Set(existingASList.map(r => {
const hit = validList.find(v => Number(v.id) === Number(r.waybill_id));
return hit ? hit.waybill_code : '';
}).filter(Boolean)) ];
if (toCreate.length === 0) {
return {
success: true,
data: {
existed: true,
message: alreadyExistWbs.length > 0
? `运单${alreadyExistWbs.join('、')} 已有处理中的拦截申请`
: '拦截信息已登记过,无需重复提交',
after_sale_nos: alreadyExist,
},
};
}
// 第四步:批量创建工单(初始状态 pending,后续根据通知结果升级)
const creatorLabel = [ groupName, userName ].filter(Boolean).join('-') || 'AI系统';
// 获取原消息内容,写入工单明细
let interceptMsgContent = '';
try {
const iid = ctx.inboxContext?.inbound_message_id;
if (iid) {
const imsg = await ctx.model.InboxMessage.findByPk(iid, { attributes: [ 'content' ], raw: true });
if (imsg && imsg.content) interceptMsgContent = String(imsg.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}` : '',
interceptMsgContent ? `原消息: ${interceptMsgContent}` : '',
].filter(Boolean).join('\n');
if (shouldSkipWorkOrder(ctx)) {
ctx.logger.info(`[inbox functions] 拦截: skip_work_order,跳过工单登记 ${e.waybill_code}`);
return { success: true, data: { message: '已记录拦截诉求(本次不登记工单)', skipped_work_order: true } };
}
await ctx.service.systems.afterSale.create({
warehouse_id: warehouseId,
after_sale_no: afterSaleNo,
type: 'order',
sub_type: 'intercept',
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}`
);
// 第4.5步:波次感知拦截处理(仅操作待处理表中的订单)
const orderIds = toCreate.map(e => e.order_id).filter(id => id);
if (orderIds.length > 0) {
try {
const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
if (orderModel) {
const orders = await orderModel.findAll({
attributes: [ 'id', 'step', 'wave_id', 'inspection_status', 'intercept_time' ],
where: {
id: { [ctx.app.Sequelize.Op.in]: orderIds },
step: { [ctx.app.Sequelize.Op.in]: [ 1, 2, 3 ] },
},
raw: true,
});
if (orders.length > 0) {
// 按 wave_id 分组查波次信息
const waveIds = [ ...new Set(orders.map(o => o.wave_id).filter(id => id > 0)) ];
let waveMap = {};
if (waveIds.length > 0) {
const waves = await ctx.model.WaveBatch.findAll({
attributes: [ 'wave_id', 'wave_type', 'wave_status', 'total_orders' ],
where: { wave_id: { [ctx.app.Sequelize.Op.in]: waveIds } },
raw: true,
});
waveMap = Object.fromEntries(waves.map(w => [ w.wave_id, w ]));
}
const interceptOrderIds = [];
const kickOutOrderIds = [];
// 批量查询散单的称重状态(wms_order_express.weighing_weight)
let weighingMap = {};
const scatterOrderIds = orders
.filter(o => o.wave_id > 0 && waveMap[o.wave_id] && waveMap[o.wave_id].wave_type === 2)
.map(o => o.id);
if (scatterOrderIds.length > 0) {
const expressRows = await ctx.model.OrderExpress.findAll({
attributes: [ 'order_id', 'weighing_weight' ],
where: { order_id: { [ctx.app.Sequelize.Op.in]: scatterOrderIds }, warehouse_id: warehouseId },
raw: true,
});
weighingMap = Object.fromEntries(
(Array.isArray(expressRows) ? expressRows : [])
.map(r => [ r.order_id, Number(r.weighing_weight || 0) ])
);
}
for (const order of orders) {
const wave = waveMap[order.wave_id];
const orderId = order.id;
// 规则1:团购未复核 / 散单未称重 → 设置拦截
let needIntercept = false;
if (order.wave_id > 0 && wave) {
if (wave.wave_type === 1) {
// 团购波次:未复核 → 拦截
needIntercept = order.inspection_status !== 'fin';
} else if (wave.wave_type === 2) {
// 散单波次:未称重 → 拦截(weighing_weight = 0 表示未称重)
const weight = weighingMap[orderId] ?? 0;
needIntercept = weight <= 0;
}
} else {
// 无波次订单:直接拦截
needIntercept = true;
}
if (needIntercept) {
interceptOrderIds.push(orderId);
}
// 规则2:有波次且未打印
if (order.wave_id > 0 && wave && wave.wave_status < 2) {
const minGroupQty = 13; // 默认大团购阈值
if (wave.wave_type === 1 && wave.total_orders >= minGroupQty) {
// 大团购:踢出波次
kickOutOrderIds.push(orderId);
}
// 小团购/散单:仅拦截,不踢出(已在 interceptOrderIds 中处理)
}
}
// 执行拦截状态设置(订单表 + 运单表;通知拦截时间只在首次发起时写入,不覆盖已有值)
if (interceptOrderIds.length > 0) {
const noticeNow = new Date();
const interceptIdSet = new Set(interceptOrderIds.map(id => Number(id)));
const fillNoticeOrderIds = pickNoticeTimeOrderIds(
orders.filter(order => interceptIdSet.has(Number(order.id)))
);
await orderModel.update(
{ intercept_status: 'requested' },
{ where: { id: { [ctx.app.Sequelize.Op.in]: interceptOrderIds } } }
);
if (fillNoticeOrderIds.length > 0) {
await orderModel.update(
{ intercept_time: noticeNow },
{ where: { id: { [ctx.app.Sequelize.Op.in]: fillNoticeOrderIds } } }
);
}
// 同步更新运单表拦截标记
await ctx.model.OrderExpress.update(
{ is_intercept: 'Y' },
{ where: { order_id: { [ctx.app.Sequelize.Op.in]: interceptOrderIds }, warehouse_id: warehouseId } }
);
// 写入操作日志(失败不影响主流程)
try {
const logService = ctx.service?.systems?.operationLog;
if (logService && typeof logService.createOperationLogs === 'function') {
await logService.createOperationLogs(
interceptOrderIds.map(oid => ({
businessType: 'order',
businessId: String(oid),
operationCode: 'ORDER_INTERCEPT_REQUEST',
operator: { id: '0', name: groupName || 'AI系统' },
extras: { warehouseId, orderId: oid, newInterceptStatus: 'requested' },
}))
);
}
} catch (logErr) {
ctx.logger.warn(`[inbox functions] 写入拦截操作日志失败: ${logErr.message}`);
}
ctx.logger.info(
`[inbox functions] 设置拦截状态: ${interceptOrderIds.length} 个订单`
);
}
// 执行踢出波次
if (kickOutOrderIds.length > 0) {
await ctx.service.systemMethods.order.wave.batchRemoveOrders({
ids: kickOutOrderIds,
});
ctx.logger.info(
`[inbox functions] 踢出大团购波次: ${kickOutOrderIds.length} 个订单`
);
}
}
}
} catch (e) {
ctx.logger.warn(`[inbox functions] 波次感知拦截处理失败: ${e.message}`);
}
}
// 第五步:合并通知对应快递的售后群(按快递分组,每条消息包含该快递的所有运单)
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 notifyMsg = 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: notifyMsg,
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 = [];
const notifiedWbs = [];
const notNotifiedWbs = [];
for (const e of toCreate) {
const asNo = waybillToAsNo[e.id];
if (notifiedWaybillIds.has(e.id)) {
notifiedAsNos.push(asNo);
notifiedWbs.push(e.waybill_code);
} else {
notNotifiedAsNos.push(asNo);
notNotifiedWbs.push(e.waybill_code);
}
}
if (notifiedAsNos.length > 0) {
// 与 handleWorkOrder 一致:设置追踪时间 + 分配客服组
const hours = await ctx.service.systems.afterSale._resolveFollowupHours(
warehouseId, 'order', 'intercept'
);
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 parts = [];
if (notifiedWbs.length > 0) {
parts.push(`运单${notifiedWbs.join('、')} 拦截信息已登记,已通知快递群`);
}
if (notNotifiedWbs.length > 0) {
parts.push(`运单${notNotifiedWbs.join('、')} 拦截信息已登记(未配置快递群,需人工跟进)`);
}
if (alreadyExistWbs.length > 0) {
parts.push(`运单${alreadyExistWbs.join('、')} 拦截信息已登记过`);
}
if (skipped.length > 0) {
parts.push(`无权操作: ${skipped.join('、')}`);
}
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: parts.join(';'),
},
};
} catch (error) {
ctx.logger.error(`[inbox functions] 批量拦截失败: ${error.message}`);
return { success: false, error: `拦截操作失败: ${error.message}` };
}
},
});
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');
if (shouldSkipWorkOrder(ctx)) {
ctx.logger.info(`[inbox functions] 揽收: skip_work_order,跳过工单登记 ${e.waybill_code}`);
return { success: true, data: { message: '已记录揽收诉求(本次不登记工单)', skipped_work_order: true } };
}
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,
keywords: [ '查退回', '查退件', '退回查询', '退回明细', '查拆包', '退件查询', '退回进度' ],
params: {
waybill_code: { type: 'string', required: true, description: '退回包裹运单号,支持多个(换行/逗号/空格分隔),如"查退回 465570943491370\nSF123456"' },
},
groups: [ GROUP.COMMON ],
handler: async (params = {}) => {
const { ctx } = this;
const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0);
const storeId = Number(ctx.inboxContext?.store_id || 0);
let raw = String(params.waybill_code || '').trim();
if (!raw) return { success: false, error: '请提供退回包裹运单号' };
// 兼容把"查退回 123456"整体传入的情况
const match = raw.match(/查退[回件]\s*[::]?\s*(.+)$/);
if (match) raw = String(match[1]).trim();
// 解析多个单号:换行/逗号/空格/常见中文标点分隔,去重保序
const waybills = [ ...new Set(
raw.split(/[\s,,。;;]+/)
.map(s => s.trim())
.filter(Boolean)
) ];
if (waybills.length === 0) return { success: false, error: '未解析到有效运单号' };
if (!warehouseId) return { success: false, error: '无法获取仓库信息' };
try {
const messages = [];
const statuses = [];
for (const waybill of waybills) {
try {
const result = await ctx.service.systems.returnUnpack.queryByWaybill({
waybill_code: waybill,
warehouse_id: warehouseId,
store_id: storeId,
});
const warehouseLabel = result.warehouse_name || '仓库';
let message = '';
if (result.status === 'unpacked') {
const unpack = result.unpack || {};
const details = result.details || [];
const videos = result.videos || [];
const orderInfo = result.order_info || {};
const lines = [];
lines.push(`${waybill}已在已退件中登记,登记信息为:`);
lines.push('');
lines.push(`运单号:${waybill}`);
lines.push(`是否原单:${unpack.order_express_id ? '是' : '否'}`);
lines.push(`交易单号:${orderInfo.trade_no || ''}`);
lines.push(`快递:${orderInfo.express || ''}`);
lines.push(`店铺名称:${orderInfo.shop_name || ''}`);
lines.push(`${warehouseLabel}收到且已拆包,拆包明细为:`);
if (details.length > 0) {
for (const detail of details) {
lines.push(`商品名称:${detail.item_name || ''}`);
lines.push(`条码:${detail.barcode || ''}`);
lines.push(`数量:${detail.quantity || 0}`);
lines.push(`是否破损:${detail.product_status === 'damaged' ? '是' : '否'}`);
}
} else {
lines.push('暂无拆包明细,拆包完成后可再次查询');
}
lines.push('');
lines.push('退件录像地址为:');
const unpackId = Number(unpack.id || 0);
if (videos.length > 0) {
for (const video of videos) {
if (!video.video_url) continue;
const cameraName = String(video.camera_name || '').trim();
lines.push(cameraName ? `${cameraName}:${video.video_url}` : String(video.video_url));
}
lines.push('拆包视频保存会有延迟,可以在稍后发送:查退回+运单号,查询');
// 视频已可用:推进补录请求状态为 completed(回写视频地址)
if (unpackId > 0) {
try {
await ctx.service.systems.videoRecordRequest.syncByVideos({
biz_type: 'unpack',
biz_id: unpackId,
videos,
});
} catch (err) {
ctx.logger.warn(`[inbox functions] 拆包视频补录状态同步失败 unpack=${unpackId}: ${err.message}`);
}
}
} else if (unpackId > 0) {
// 视频不可用:登记补录请求并推送录制服务重新录制(录制服务不可用时仅登记,不阻断查询)
let inFlight = false;
try {
const req = await ctx.service.systems.videoRecordRequest.requestUnpackVideo({
warehouse_id: warehouseId,
unpack_id: unpackId,
waybill_code: waybill,
store_id: Number(unpack.store_id || 0),
group_id: String(ctx.inboxContext?.group_id || '').trim(),
group_name: String(ctx.inboxContext?.group_name || '').trim(),
user_id: String(ctx.inboxContext?.user_id || '').trim(),
user_name: String(ctx.inboxContext?.user_name || '').trim(),
source: 'inbox',
});
inFlight = Boolean(req && (req.pushed || (req.reused && req.status !== 'failed')));
} catch (err) {
ctx.logger.warn(`[inbox functions] 拆包视频补录推送失败 unpack=${unpackId}: ${err.message}`);
}
lines.push(inFlight
? '视频暂不可用,已推送重新录制,请稍等通知录制结果'
: '视频暂不可用,已登记补录,请稍后重试');
} else {
lines.push('暂无');
}
message = lines.join('\n');
} else if (result.status === 'received') {
message = `包裹${waybill}已收到未拆包,拆包登记后,将自动发送通知拆包信息`;
} else if (result.status === 'not_returned') {
message = `${waybill}尚未退回仓库,已在未退回表中登记成功,等待包裹退件登记后,将自动发送通知包裹信息`;
} else {
message = `未查询到运单号${waybill}的退回信息,请核实单号后重试`;
}
messages.push(message);
statuses.push(result.status);
} catch (error) {
ctx.logger.warn(`[inbox functions] 退回查询单号失败 ${waybill}: ${error.message}`);
messages.push(`${waybill}退回查询失败:${error.message}`);
statuses.push('error');
}
}
return {
success: true,
data: {
status: statuses[0],
waybill_code: waybills[0],
total: waybills.length,
message: messages[0], // 兼容单条回复(AI 兜底路径取首条)
messages, // 规则引擎多行回复:每个单号一条消息
direct_reply: true,
},
};
} catch (error) {
ctx.logger.error(`[inbox functions] 退回查询失败: ${error.message}`);
return { success: false, error: `退回查询失败: ${error.message}` };
}
},
});
this.register('cancelIntercept', {
description: '取消拦截运单(支持批量)。当用户要求"取消拦截/撤销拦截/不拦截了"时调用。先查已有售后工单,有则追加取消记录,无则按拦截规则创建工单。同时设置订单和运单拦截状态并通知快递群',
weight: 94,
keywords: [ '取消拦截', '撤销拦截', '解除拦截', '不拦截了', '不用拦截' ],
params: {
keyword: { type: 'string', required: true, description: '运单号,多个用逗号或空格分隔' },
reason: { type: 'string', required: false, description: '取消拦截原因' },
},
groups: [ GROUP.BOUND_WAREHOUSE_CUSTOMER_SERVICE, GROUP.BOUND_STORE_AFTER_SALES ],
/**
* 取消拦截处理器:为运单创建/追加取消拦截工单,并按波次规则重新写入
* 订单拦截状态 intercept_status='requested' 与拦截时间 intercept_time。
* @param {Object} params 入参,包含 keyword(运单号)与 reason(取消拦截原因)。
* @return {Promise<Object>} 处理结果,包含 success 与 data/error。
*/
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: '未解析到有效运单号' };
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}」,请核实单号后重试` };
}
// 第二步:鉴权
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: [ 'id', 'waybill_id', 'waybill_no', 'after_sale_no', 'status', 'store_id' ],
where: {
waybill_id: { [ctx.app.Sequelize.Op.in]: validIds },
type: 'order',
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));
// 获取原消息内容用于反馈记录
let cancelMsgContent = '';
try {
const cid = ctx.inboxContext?.inbound_message_id;
if (cid) {
const cm = await ctx.model.InboxMessage.findByPk(cid, { attributes: [ 'content' ], raw: true });
if (cm && cm.content) cancelMsgContent = String(cm.content);
}
} catch (e) { /* ignore */ }
let feedbackCount = 0;
const feedbackWbs = [];
const cancelGroup = ctx.inboxContext?.group_name || '未知群';
const cancelUser = ctx.inboxContext?.user_name || '未知用户';
const cancelTime = new Date().toISOString().slice(0, 19)
.replace('T', ' ');
// 已有工单:追加取消拦截记录
for (const as of existingASList) {
try {
const remarkLines = [
`群: ${cancelGroup}`, `用户: ${cancelUser}`, `时间: ${cancelTime}`,
];
if (cancelMsgContent) remarkLines.push(`原消息: ${cancelMsgContent}`);
if (reason) remarkLines.push(`取消原因: ${reason}`);
await ctx.service.systems.afterSale.addStep(as.id, {
step_status: 'processing',
action: '取消拦截',
remark: remarkLines.join('\n'),
});
feedbackCount += 1;
if (as.waybill_no) feedbackWbs.push(as.waybill_no);
} catch (e) {
ctx.logger.warn(`[inbox functions] 取消拦截反馈失败 as_no=${as.after_sale_no}: ${e.message}`);
}
}
const parts = [];
if (feedbackCount > 0) {
const wbs = [ ...new Set(feedbackWbs) ];
parts.push(wbs.length > 0
? `运单${wbs.join('、')} 取消拦截信息已登记(已追加到处理中的工单)`
: `取消拦截信息已登记 ${feedbackCount} 个`);
}
// 第四步:无工单的按拦截规则创建
const createdNos = [];
if (toCreate.length > 0) {
if (shouldSkipWorkOrder(ctx)) {
ctx.logger.info('[inbox functions] 取消拦截: skip_work_order,跳过创建工单');
return { success: true, data: { message: '取消拦截信息已登记(本次不创建工单)', skipped_work_order: true } };
}
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 || '未知'}`,
reason ? `取消原因: ${reason}` : '',
'来源: 取消拦截',
].filter(Boolean).join('\n');
await ctx.service.systems.afterSale.create({
warehouse_id: warehouseId, after_sale_no: afterSaleNo,
type: 'order', sub_type: 'intercept',
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);
}
}
if (createdNos.length > 0) {
const wbs = toCreate.map(e => e.waybill_code).filter(Boolean);
parts.push(wbs.length > 0
? `运单${wbs.join('、')} 取消拦截信息已登记(已创建处理工单)`
: `取消拦截信息已登记 ${createdNos.length} 个`);
}
ctx.logger.info(
`[inbox functions] 取消拦截: total=${keywords.length} ` +
`feedback=${feedbackCount} created=${createdNos.length} skipped=${skipped.length}`
);
// 第4.5步:波次感知拦截(与 interceptWaybill 相同)
const orderIds = toCreate.map(e => e.order_id).filter(id => id);
if (orderIds.length > 0) {
try {
const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
if (orderModel) {
const orders = await orderModel.findAll({
attributes: [ 'id', 'step', 'wave_id', 'inspection_status', 'intercept_time' ],
where: { id: { [ctx.app.Sequelize.Op.in]: orderIds }, step: { [ctx.app.Sequelize.Op.in]: [ 1, 2, 3 ] } },
raw: true,
});
if (orders.length > 0) {
const waveIds = [ ...new Set(orders.map(o => o.wave_id).filter(id => id > 0)) ];
let waveMap = {};
if (waveIds.length > 0) {
const waves = await ctx.model.WaveBatch.findAll({
attributes: [ 'wave_id', 'wave_type', 'wave_status', 'total_orders' ],
where: { wave_id: { [ctx.app.Sequelize.Op.in]: waveIds } }, raw: true,
});
waveMap = Object.fromEntries(waves.map(w => [ w.wave_id, w ]));
}
const interceptOrderIds = [];
// 批量查询散单的称重状态
const scatterIds = orders
.filter(o => o.wave_id > 0 && waveMap[o.wave_id] && waveMap[o.wave_id].wave_type === 2)
.map(o => o.id);
const wMap = {};
if (scatterIds.length > 0) {
const er = await ctx.model.OrderExpress.findAll({
attributes: [ 'order_id', 'weighing_weight' ],
where: { order_id: { [ctx.app.Sequelize.Op.in]: scatterIds }, warehouse_id: warehouseId },
raw: true,
});
for (const r of (Array.isArray(er) ? er : [])) {
wMap[r.order_id] = Number(r.weighing_weight || 0);
}
}
for (const order of orders) {
const wave = waveMap[order.wave_id];
let needIntercept = false;
if (order.wave_id > 0 && wave) {
if (wave.wave_type === 1) {
needIntercept = order.inspection_status !== 'fin';
} else {
needIntercept = (wMap[order.id] ?? 0) <= 0;
}
} else {
needIntercept = true;
}
if (needIntercept) interceptOrderIds.push(order.id);
}
if (interceptOrderIds.length > 0) {
const noticeNow = new Date();
const interceptIdSet = new Set(interceptOrderIds.map(id => Number(id)));
const fillNoticeOrderIds = pickNoticeTimeOrderIds(
orders.filter(order => interceptIdSet.has(Number(order.id)))
);
await orderModel.update(
{ intercept_status: 'requested' },
{ where: { id: { [ctx.app.Sequelize.Op.in]: interceptOrderIds } } }
);
if (fillNoticeOrderIds.length > 0) {
await orderModel.update(
{ intercept_time: noticeNow },
{ where: { id: { [ctx.app.Sequelize.Op.in]: fillNoticeOrderIds } } }
);
}
await ctx.model.OrderExpress.update(
{ is_intercept: 'Y' },
{ where: { order_id: { [ctx.app.Sequelize.Op.in]: interceptOrderIds }, warehouse_id: warehouseId } }
);
// 写入操作日志(失败不影响主流程)
try {
const logSvc = ctx.service?.systems?.operationLog;
if (logSvc && typeof logSvc.createOperationLogs === 'function') {
await logSvc.createOperationLogs(
interceptOrderIds.map(oid => ({
businessType: 'order',
businessId: String(oid),
operationCode: 'ORDER_INTERCEPT_REQUEST',
operator: { id: '0', name: groupName || 'AI系统' },
extras: { warehouseId, orderId: oid, newInterceptStatus: 'requested' },
}))
);
}
} catch (logErr) {
ctx.logger.warn(`[inbox functions] 取消拦截-写入操作日志失败: ${logErr.message}`);
}
ctx.logger.info(`[inbox functions] 取消拦截-设置拦截状态: ${interceptOrderIds.length} 个订单`);
}
}
}
} catch (e) {
ctx.logger.warn(`[inbox functions] 取消拦截-波次处理失败: ${e.message}`);
}
}
// 第五步:通知快递群
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 notifiedNos = [];
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) continue;
const notifyMsg = 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: notifyMsg, ext_data: g.ext_data || null,
});
notifiedTotal += 1;
}
} catch (e) {
ctx.logger.warn(`[inbox functions] 取消拦截查快递群失败 code=${code}: ${e.message}`);
}
}
if (notifiedTotal > 0) parts.push(`已通知 ${notifiedTotal} 个快递群`);
// 有通知的工单升级 pending_feedback
if (notifiedNos.length > 0) {
const hours = await ctx.service.systems.afterSale._resolveFollowupHours(warehouseId, 'order', 'intercept');
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]: notifiedNos }, warehouse_id: warehouseId } }
);
}
return { success: true, data: { feedback: feedbackCount, created: createdNos.length, skipped: skipped.length, notified_groups: notifiedTotal, message: parts.join(';') || '处理完成' } };
} catch (error) {
ctx.logger.error(`[inbox functions] 取消拦截失败: ${error.message}`);
return { success: false, error: `操作失败: ${error.message}` };
}
},
});
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 运单号→工单号列表(as_no 仅内部使用)。
* @return {string} 模板消息。
*/
const buildReply = pairs => {
const lines = pairs.map(p => `运单${p.waybill} ${issue.label}问题已登记`);
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');
if (shouldSkipWorkOrder(ctx)) {
ctx.logger.info(`[inbox functions] 问题反馈: skip_work_order,跳过工单登记 ${e.waybill_code}`);
return { success: true, data: { message: '已记录问题反馈(本次不登记工单)', skipped_work_order: true } };
}
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(催退回类诉求)/urge(催件/催派送类诉求),注意区分:催退回用 return,催件/催派送用 urge' },
},
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: '催退回' },
urge: { sub_type: 'urge', label: '催件' },
催件: { sub_type: 'urge', 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);
// 第三步:创建工单(含原文)并映射 waybill_id → 工单号
const createdNos = [];
const waybillToAsNo = {}; // waybill_id → after_sale_no 映射(新建 + 已存在)
for (const r of existingASList) {
waybillToAsNo[r.waybill_id] = r.after_sale_no;
}
if (shouldSkipWorkOrder(ctx)) {
ctx.logger.info('[inbox functions] 改地址/催件: skip_work_order,跳过工单登记');
return { success: true, data: { message: '已记录诉求(本次不登记工单)', skipped_work_order: true } };
}
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 expressList) {
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 = 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;
}
expressList
.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 + 跟踪时限(新建与已有工单,仅 pending 状态升级)
const notifiedAsNos = expressList
.filter(e => notifiedWaybillIds.has(e.id))
.map(e => waybillToAsNo[e.id])
.filter(Boolean);
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 },
status: 'pending',
},
}
);
} catch (e) {
ctx.logger.warn(`[inbox functions] 改地址/催退回更新工单状态失败: ${e.message}`);
}
}
// 第六步:客户回信模板(单号+诉求,区分是否已通知快递)
// key 必须与 issue.sub_type 对齐(change_address/rejected/urge),
// 此前误用 addr/return 导致永远回退到改地址文案
const REPLY_TEXT = {
change_address: { done: '修改地址已经登记', notify: '并已通知快递修改' },
rejected: { done: '催退回已经登记', notify: '并已通知快递处理' },
urge: { done: '催件已经登记', notify: '并已通知快递处理' },
};
const replyText = REPLY_TEXT[issue.sub_type] || REPLY_TEXT.change_address;
const lines = expressList.map(e => {
const head = `运单${e.waybill_code}${replyText.done}`;
return notifiedWaybillIds.has(e.id)
? `${head}·${replyText.notify}`
: `${head},稍后客服将人工跟进`;
});
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 (shouldSkipWorkOrder(ctx)) {
ctx.logger.info('[inbox functions] 核实签收: skip_work_order,跳过工单登记');
return { success: true, data: { message: '已记录核实签收诉求(本次不登记工单)', skipped_work_order: true } };
}
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}问题已登记`);
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('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();
// 触发查询的群/人员:写入补录请求,供后续录制结果回发原群、@原用户
const inboxGroupId = String(ctx.inboxContext?.group_id || '').trim();
const inboxGroupName = String(ctx.inboxContext?.group_name || '').trim();
const inboxUserId = String(ctx.inboxContext?.user_id || '').trim();
const inboxUserName = 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 { 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 noRecordWbs = [];
const orderMissingWbs = [];
// 视频不可用已推送重新录制 / 仅登记补录(推送失败)
const reRecordWbs = [];
const reRecordFailedWbs = [];
for (const e of validList) {
// 第二步:查订单行(优先序列表定位,未命中回退 当前→历史→配送 遍历)
let orderRow = null;
const factory = ctx.model.OrderDeliveryFactory;
const tableGetters = [
{ location: 'current', getModel: (f, wid) => f.getCurrentModel(wid) },
{ location: 'history', getModel: (f, wid) => f.getHistoryModel(wid) },
{ location: 'dispatch', getModel: (f, wid) => f.getDispatchModel(wid) },
];
let location = null;
try {
if (factory && typeof factory.getOrderLocation === 'function') {
location = await factory.getOrderLocation(e.order_id, warehouseId);
}
} catch (err) { /* ignore */ }
const orderedGetters = location
? [
...tableGetters.filter(entry => entry.location === location),
...tableGetters.filter(entry => entry.location !== location),
]
: tableGetters;
for (const entry of orderedGetters) {
try {
const model = await entry.getModel(factory, 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', 'camera_id', 'status' ],
where: {
pack_task_id: { [Op.in]: taskIds },
deleted_at: null,
},
raw: true,
});
// 视频地址拼接 CDN 域名(与 order.packing.list、queryReturn 对齐)
const inboxTools = ctx.service.inbox.tools;
const recordingComputerId = await inboxTools.getRecordingComputerId(warehouseId);
const urls = videos
.filter(v => String(v.status || '') !== 'failed')
.map(v => inboxTools.buildVideoUrl(warehouseId, recordingComputerId, v.video_url))
.filter(Boolean);
if (urls.length === 0) {
// 视频不可用:登记补录请求并推送录制服务重新录制(录制服务不可用时仅登记,不阻断查询)
let inFlight = 0;
for (const task of packTasks) {
try {
const req = await ctx.service.systems.videoRecordRequest.requestPackVideo({
warehouse_id: warehouseId,
pack_task_id: task.id,
waybill_code: e.waybill_code,
store_id: Number(e.store_id || 0),
group_id: inboxGroupId,
group_name: inboxGroupName,
user_id: inboxUserId,
user_name: inboxUserName,
source: 'inbox',
});
if (req && (req.pushed || (req.reused && req.status !== 'failed'))) inFlight += 1;
} catch (err) {
ctx.logger.warn(`[inbox functions] 打包视频补录推送失败 task=${task.id}: ${err.message}`);
}
}
if (inFlight > 0) {
reRecordWbs.push(e.waybill_code);
} else {
reRecordFailedWbs.push(e.waybill_code);
}
} else {
// 摄像头名称放链接前(系统设置的自定义名称优先,通道原始名称兜底)
const packCameraIds = [ ...new Set(videos.filter(v => v.camera_id).map(v => v.camera_id)) ];
const packCameraNameMap = new Map();
if (packCameraIds.length > 0) {
const packCameras = await ctx.model.Camera.findAll({
attributes: [ 'id', 'custom_name', 'channel_name' ],
where: { id: { [Op.in]: packCameraIds } },
raw: true,
});
for (const c of packCameras) {
packCameraNameMap.set(Number(c.id), String(c.custom_name || c.channel_name || '').trim());
}
}
const displayLines = videos
.filter(v => String(v.status || '') !== 'failed')
.map(v => {
const url = inboxTools.buildVideoUrl(warehouseId, recordingComputerId, v.video_url);
if (!url) return '';
const cameraName = v.camera_id ? (packCameraNameMap.get(Number(v.camera_id)) || '') : '';
return cameraName ? `${cameraName}:${url}` : url;
})
.filter(Boolean);
videoLines.push(`${e.waybill_code}\n${displayLines.join('\n')}`);
// 视频已可用:推进补录请求状态为 completed(回写视频地址)
for (const task of packTasks) {
try {
await ctx.service.systems.videoRecordRequest.syncByVideos({
biz_type: 'pack',
biz_id: task.id,
videos,
});
} catch (err) {
ctx.logger.warn(`[inbox functions] 打包视频补录状态同步失败 task=${task.id}: ${err.message}`);
}
}
}
}
// 第六步:组装模板消息(仅查询,不建工单)
const lines = [];
if (videoLines.length > 0) {
lines.push(videoLines.join('\n'));
}
if (reRecordWbs.length > 0) {
lines.push(reRecordWbs.join('\n'));
lines.push('视频暂不可用,已推送重新录制,请稍等通知录制结果');
}
if (reRecordFailedWbs.length > 0) {
lines.push(reRecordFailedWbs.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} reRecord=${reRecordWbs.length} reRecordFailed=${reRecordFailedWbs.length} ` +
`noRecord=${noRecordWbs.length}`
);
return {
success: true,
data: {
has_video: videoLines.length,
no_video: reRecordWbs.length + reRecordFailedWbs.length,
re_record: reRecordWbs.length,
re_record_failed: reRecordFailedWbs.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,
keywords: [ '已处理', '已联系', '已通知', '核实', '反馈' ],
params: {
keyword: { type: 'string', required: true, description: '运单号,多个用逗号或空格分隔' },
as_type: { type: 'string', required: false, description: '新建工单时的售后类型(order/receiving),默认 order' },
as_sub_type: { type: 'string', required: false, description: '新建工单时的售后子类型,默认 logistics_issue。可选: logistics_issue(物流异常)/damage(破损)/missing_item(少发)/delivery_delay(发货延迟)/urge(催件)/verify_delivery(核实签收)/change_carrier(换快递)/rejected(拒收)/other(其他)' },
},
groups: [ GROUP.BOUND_EXPRESS_AFTER_SALES ],
handler: async (params = {}) => {
const { ctx } = this;
const raw = String(params.keyword || '').trim();
const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0);
const asType = String(params.as_type || 'order').trim() || 'order';
const asSubType = String(params.as_sub_type || 'logistics_issue').trim() || 'logistics_issue';
// 工单详细描述中的售后类型/子类型显示中文名称(存储仍用英文编码)
const asTypesMeta = (ctx.model.AfterSale && ctx.model.AfterSale.AFTER_SALE_TYPES) || [];
const asTypeMeta = asTypesMeta.find(t => t.type === asType);
const asTypeName = (asTypeMeta && asTypeMeta.name) || asType;
const asSubTypeMeta = asTypeMeta && Array.isArray(asTypeMeta.subType)
? asTypeMeta.subType.find(s => s.value === asSubType)
: null;
const asSubTypeName = (asSubTypeMeta && asSubTypeMeta.name) || asSubType;
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: '未解析到有效运单号' };
try {
// 第一步:查已有售后工单
const existingAS = await ctx.model.AfterSale.findAll({
attributes: [ 'id', 'after_sale_no', 'waybill_no', 'status', 'warehouse_id', 'inbox_message_id', 'store_id' ],
where: {
waybill_no: { [ctx.app.Sequelize.Op.in]: keywords },
warehouse_id: warehouseId,
},
raw: true,
});
const hasAS = new Set(existingAS.map(r => r.waybill_no));
let feedbackCount = 0;
let createdCount = 0;
const parts = [];
// 已有工单:追加反馈
// 获取原始消息内容用于反馈记录
let feedbackMsgContent = '';
try {
const fbMsgId = ctx.inboxContext?.inbound_message_id;
if (fbMsgId) {
const fbMsg = await ctx.model.InboxMessage.findByPk(fbMsgId, {
attributes: [ 'content' ],
raw: true,
});
if (fbMsg && fbMsg.content) feedbackMsgContent = String(fbMsg.content);
}
} catch (e) {
ctx.logger.warn(`[inbox functions] 获取原消息内容失败: ${e.message}`);
}
const feedbackGroup = ctx.inboxContext?.group_name || '未知群';
const feedbackUser = ctx.inboxContext?.user_name || '未知用户';
for (const as of existingAS) {
try {
const remarkLines = [
`群: ${feedbackGroup}`,
`用户: ${feedbackUser}`,
`时间: ${new Date().toISOString().slice(0, 19)
.replace('T', ' ')}`,
];
if (feedbackMsgContent) {
remarkLines.push(`原消息: ${feedbackMsgContent}`);
}
await ctx.service.systems.afterSale.addStep(as.id, {
step_status: 'processing',
action: '快递反馈',
remark: remarkLines.join('\n'),
});
feedbackCount += 1;
} catch (e) {
ctx.logger.warn(`[inbox functions] 快递反馈失败 as_no=${as.after_sale_no}: ${e.message}`);
}
}
if (feedbackCount > 0) {
parts.push(`已有工单追加反馈: ${feedbackCount}个`);
}
// 第二步:无工单的运单,查订单并创建售后工单
const needCreate = keywords.filter(k => !hasAS.has(k));
let expressList = [];
const createdAsNos = [];
if (needCreate.length > 0) {
expressList = await ctx.model.OrderExpress.findAll({
attributes: [ 'id', 'waybill_code', 'logistics_name', 'store_id', 'warehouse_id', 'order_id' ],
where: {
waybill_code: { [ctx.app.Sequelize.Op.in]: needCreate },
warehouse_id: warehouseId,
},
raw: true,
});
const foundCodes = new Set(expressList.map(e => e.waybill_code));
const notFound = needCreate.filter(k => !foundCodes.has(k));
for (const e of expressList) {
try {
const afterSaleNo = await ctx.service.systemMethods.afterSale.generateAfterSaleNo(warehouseId);
const title = `[AI工单] 快递反馈 - ${e.waybill_code}`;
const description = [
`运单号: ${e.waybill_code}`,
`快递公司: ${e.logistics_name || '未知'}`,
`售后类型: ${asTypeName}.${asSubTypeName}`,
'来源: 快递群反馈',
feedbackMsgContent ? `原文: ${feedbackMsgContent}` : '',
].filter(Boolean).join('\n');
if (shouldSkipWorkOrder(ctx)) {
ctx.logger.info(`[inbox functions] 快递反馈: skip_work_order,跳过工单登记 ${e.waybill_code}`);
return { success: true, data: { message: '已记录快递反馈(本次不登记工单)', skipped_work_order: true } };
}
await ctx.service.systems.afterSale.create({
warehouse_id: warehouseId,
after_sale_no: afterSaleNo,
type: asType,
sub_type: asSubType,
title,
description,
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 || null,
order_id: e.order_id || null,
});
createdAsNos.push(afterSaleNo);
createdCount += 1;
} catch (e) {
ctx.logger.warn(`[inbox functions] 快递反馈建单失败 wb=${e.waybill_code}: ${e.message}`);
}
}
if (createdCount > 0) {
parts.push(`已创建工单: ${createdCount}个`);
}
if (notFound.length > 0) {
parts.push(`未找到运单: ${notFound.join('、')}`);
}
}
ctx.logger.info(
`[inbox functions] 快递反馈: total=${keywords.length} ` +
`feedback=${feedbackCount} created=${createdCount}`
);
// 第三步:排除回复检查(仓库配置 inbox_reply_exclude_keywords)
let skipReply = false;
try {
const inboundMsgId = ctx.inboxContext?.inbound_message_id;
if (inboundMsgId) {
const [ inboundMsg, store ] = await Promise.all([
ctx.model.InboxMessage.findByPk(inboundMsgId, {
attributes: [ 'id', 'content' ],
raw: true,
}),
ctx.model.Store.findByPk(warehouseId, {
attributes: [ 'subject_config' ],
raw: true,
}),
]);
const excludeKeywords = (store && store.subject_config
&& Array.isArray(store.subject_config.inbox_reply_exclude_keywords))
? store.subject_config.inbox_reply_exclude_keywords.filter(k => typeof k === 'string' && k.trim())
: [];
if (excludeKeywords.length > 0 && inboundMsg && inboundMsg.content) {
const msgContent = String(inboundMsg.content);
const matched = excludeKeywords.find(kw => msgContent.includes(kw));
if (matched) {
skipReply = true;
ctx.logger.info(
`[inbox functions] 消息命中排除关键词「${matched}」,仅记录不通知`
);
}
}
}
} catch (e) {
ctx.logger.warn(`[inbox functions] 排除回复检查失败: ${e.message}`);
}
let replyTargets = new Map();
if (!skipReply) {
// 第四步:回信路由
// - 已有工单且带 inbox_message_id → 查原始消息获取群信息 → 回信到原群
// - 无工单或无 inbox_message_id → 回信到货主售后群
replyTargets = new Map(); // group_id → { group_id, group_name, user_id, ext_data }
// 未命中排除关键词 → 直接反馈原文(按目标货主过滤掉其他货主的运单号)
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);
let expressGroupIds = new Set();
if (asWithMsgId.length > 0) {
const msgIds = [ ...new Set(asWithMsgId.map(as => as.inbox_message_id)) ];
try {
const messages = await ctx.model.InboxMessage.findAll({
attributes: [ 'id', 'group_id', 'user_id', 'group_name', 'user_name' ],
where: { id: { [ctx.app.Sequelize.Op.in]: msgIds } },
raw: true,
});
// 过滤快递群:原消息来自快递群的,不回信到快递群,走 4b 货主售后群
const candidateGroupIds = [ ...new Set(messages.map(m => m.group_id).filter(Boolean)) ];
let groupStoreMap = {};
if (candidateGroupIds.length > 0) {
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,
is_blocked: 0,
},
raw: true,
});
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)) {
replyTargets.set(msg.group_id, {
group_id: msg.group_id,
group_name: msg.group_name || '',
user_id: msg.user_id || '',
user_name: msg.user_name || '',
ext_data: null,
store_id: groupStoreMap[msg.group_id] || null,
});
}
}
} catch (e) {
ctx.logger.warn(`[inbox functions] 查原消息群信息失败: ${e.message}`);
}
}
// 4b. 已有工单无 inbox_message_id + 新建工单 + 原消息来自快递群:回信到货主售后群
const storeIdsForReply = new Set();
// 已有工单无 inbox_message_id 的 store_id
for (const as of existingAS) {
if (!as.inbox_message_id && as.store_id) {
storeIdsForReply.add(as.store_id);
}
}
// 已有工单 inbox_message_id 指向快递群的(4a 已排除),也走货主售后群
if (expressGroupIds && expressGroupIds.size > 0) {
for (const as of asWithMsgId) {
if (as.store_id) storeIdsForReply.add(as.store_id);
}
}
// 新建工单的 store_id(来自 OrderExpress 记录)
for (const e of expressList) {
if (!hasAS.has(e.waybill_code) && e.store_id) {
storeIdsForReply.add(e.store_id);
}
}
if (storeIdsForReply.size > 0) {
try {
const storeGroups = await ctx.service.systems.inbox.group.findStoreAfterSalesGroups({
storeIds: [ ...storeIdsForReply ],
warehouseId,
});
for (const g of storeGroups) {
if (g.group_id && !replyTargets.has(g.group_id)) {
replyTargets.set(g.group_id, {
group_id: g.group_id,
group_name: g.group_name || '',
user_id: '',
user_name: '',
ext_data: g.ext_data || null,
store_id: g.store_id || null,
});
}
}
} catch (e) {
ctx.logger.warn(`[inbox functions] 查货主售后群失败: ${e.message}`);
}
}
// 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,
ext_data: target.ext_data,
store_id: target.store_id || null,
});
}
if (replyTargets.size > 0) {
parts.push(`已回信到 ${replyTargets.size} 个群`);
}
} // if (!skipReply)
if (skipReply) {
parts.push('消息命中排除关键词,仅记录不通知');
}
// 第五步:更新新建工单状态
// - 已回信 → pending_feedback(等待外部通知)+ 跟踪时间
// - 未回信/排除关键词 → processing(处理中)
// 注意:已有工单仅追加反馈,不改变原有状态
if (createdAsNos.length > 0) {
try {
if (!skipReply && replyTargets && replyTargets.size > 0) {
const hours = await ctx.service.systems.afterSale._resolveFollowupHours(
warehouseId, asType, asSubType
);
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]: createdAsNos },
warehouse_id: warehouseId,
},
}
);
ctx.logger.info(
`[inbox functions] ${createdAsNos.length} 个工单已通知客户群,升级 pending_feedback,${hours}h 后追踪`
);
} else {
await ctx.model.AfterSale.update(
{ status: 'processing', role_group: 'customer_service' },
{
where: {
after_sale_no: { [ctx.app.Sequelize.Op.in]: createdAsNos },
warehouse_id: warehouseId,
},
}
);
ctx.logger.info(
`[inbox functions] ${createdAsNos.length} 个工单未通知客户群,状态设为 processing`
);
}
} catch (e) {
ctx.logger.warn(`[inbox functions] 更新工单状态失败: ${e.message}`);
}
}
return {
success: true,
data: {
feedback: feedbackCount,
created: createdCount,
message: parts.join(';') || '处理完成',
},
};
} catch (error) {
ctx.logger.error(`[inbox functions] 快递反馈处理失败: ${error.message}`);
return { success: false, error: `操作失败: ${error.message}` };
}
},
});
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: {},
groups: [ GROUP.BOUND_WAREHOUSE ],
weight: 0,
keywords: [ '群列表', '有哪些群', '群组' ],
handler: async (params = {}) => {
const { ctx } = this;
void params;
const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0);
if (!warehouseId) {
return { success: false, error: '无法获取仓库信息' };
}
try {
const groups = await ctx.model.InboxGroup.findAll({
attributes: [ 'id', 'group_name', 'is_blocked', 'created_at' ],
where: { warehouse_id: warehouseId },
order: [[ 'created_at', 'DESC' ]],
limit: 20,
raw: true,
});
return {
success: true,
data: {
warehouse_id: warehouseId,
total: groups.length,
groups: groups.map(g => ({
name: g.group_name,
blocked: g.is_blocked === 1,
created_at: g.created_at,
})),
},
};
} catch (error) {
return { success: false, error: `查询群列表失败: ${error.message}` };
}
},
});
this.register('openDoor', {
description: '开门:仓库群收到"开门"指令时调用,触发大门开启动作。回复内容为空,由 extend_props 指令驱动开门',
params: {},
groups: [ GROUP.BOUND_WAREHOUSE ],
weight: 90,
keywords: [ '开门' ],
handler: async (params = {}) => {
const { ctx } = this;
void params;
ctx.logger.info('[inbox functions] 执行开门指令');
return {
success: true,
data: {
message: '',
direct_reply: true,
extend_props: { do: 'openDoor' },
},
};
},
});
this.register('registerLicensePlate', {
description: '到货登记:从当前消息中提取车牌号并登记。货主/仓库群发送"到货+车牌号"时调用',
params: {},
groups: [ GROUP.BOUND_STORE, GROUP.BOUND_WAREHOUSE ],
weight: 90,
keywords: [ '到货' ],
handler: async (params = {}) => {
const { ctx } = this;
void params;
// 读取原消息内容提取车牌号
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 carnum = extractLicensePlate(originalText);
if (!carnum) {
return {
success: false,
error: '未识别到车牌号,请发送:到货+车牌号\n例:到货 粤A12345',
};
}
// 写库登记(失败不阻塞回执,仅告警)
try {
await ctx.model.InboxArrivalRegister.create({
warehouse_id: Number(ctx.inboxContext?.warehouse_id) || 0,
store_id: Number(ctx.inboxContext?.store_id) || null,
license_plate: carnum,
});
} catch (e) {
ctx.logger.warn(`[inbox functions] 到货登记写库失败: ${e.message}`);
}
ctx.logger.info(`[inbox functions] 到货登记车牌: ${carnum}`);
return {
success: true,
data: {
message: `车牌${carnum}已登记,请在6小时内入场,超时请重新登记`,
direct_reply: true,
carnum,
extend_props: { do: 'registerLicensePlate', value: carnum },
},
};
},
});
this.register('departure', {
description: '离场登记:消息含"离场"时调用,提取车牌号,查6小时内未消费的到货登记,标记消费并通知对应货主(优先收货群,其次售后群,发送失败换下一个群);当前消息不回执',
params: {},
groups: [ GROUP.BOUND_WAREHOUSE ],
weight: 90,
keywords: [ '离场' ],
handler: async (params = {}) => {
const { ctx } = this;
void params;
// 读取原消息内容提取车牌号
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 carnum = extractLicensePlate(originalText);
if (!carnum) {
return {
success: false,
error: '未识别到车牌号,请发送:车牌号+离场\n例:粤A12345离场',
};
}
const warehouseId = Number(ctx.inboxContext?.warehouse_id) || 0;
if (!warehouseId) {
return { success: false, error: '无法获取仓库信息' };
}
const { Op } = ctx.app.Sequelize;
// 第一步:查6小时内未消费的到货登记
const record = await ctx.model.InboxArrivalRegister.findOne({
attributes: [ 'id', 'store_id', 'license_plate' ],
where: {
warehouse_id: warehouseId,
license_plate: carnum,
consumed: 0,
created_at: { [Op.gte]: ctx.app.Sequelize.literal('DATE_SUB(NOW(), INTERVAL 6 HOUR)') },
},
order: [[ 'created_at', 'DESC' ]],
raw: true,
});
if (!record) {
// 区分提示:6小时内已消费过 → 重复离场;否则无有效登记
const consumedRecord = await ctx.model.InboxArrivalRegister.findOne({
attributes: [ 'id' ],
where: {
warehouse_id: warehouseId,
license_plate: carnum,
consumed: 1,
created_at: { [Op.gte]: ctx.app.Sequelize.literal('DATE_SUB(NOW(), INTERVAL 6 HOUR)') },
},
raw: true,
});
if (consumedRecord) {
// 已离过场:静默处理,不回执不通知
ctx.logger.info(`[inbox functions] 离场登记: 车牌=${carnum} 已离过场,静默忽略`);
return {
success: true,
data: { carnum, consumed: false, duplicate: true },
};
}
return {
success: false,
error: `未查询到车牌 ${carnum} 6小时内的有效登记,离场失败`,
};
}
// 第二步:乐观标记消费(防并发重复离场)
const [ affected ] = await ctx.model.InboxArrivalRegister.update(
{ consumed: 1, consumed_at: ctx.app.Sequelize.literal('CURRENT_TIMESTAMP') },
{ where: { id: record.id, consumed: 0 } }
);
if (affected !== 1) {
// 并发重复离场:静默处理,不回执不通知
ctx.logger.info(`[inbox functions] 离场登记: 车牌=${carnum} 并发重复离场,静默忽略`);
return {
success: true,
data: { carnum, consumed: false, duplicate: true },
};
}
// 第三步:通知对应货主(优先收货群,其次售后群,发送失败换下一个群)
const notifyResult = await this.notifyStoreReceiving(
warehouseId, record.store_id,
`${carnum}已卸货离场,本次收货完成,在清点中,请耐心等待清点结果,天豹云仓竭诚为您服务。`
);
const pushed = notifyResult.pushed;
const pushedGroup = notifyResult.pushedGroup;
ctx.logger.info(
`[inbox functions] 离场登记: 车牌=${carnum} 消费成功 ` +
`store_id=${record.store_id || '-'} pushed=${pushed} group=${pushedGroup || '-'}`
);
// 当前消息不回执(data 不含 message/extend_props → 规则引擎无回复)
return {
success: true,
data: { carnum, consumed: true, pushed, pushed_group: pushedGroup },
};
},
});
this.register('enter', {
description: '进场登记:消息含"进场"时调用,提取车牌号,查6小时内未消费的到货登记,通知对应货主收货群"车辆已入场,等待卸货"(优先收货群,其次售后群,发送失败换下一个群);当前消息不回执',
params: {},
groups: [ GROUP.BOUND_WAREHOUSE ],
weight: 90,
keywords: [ '进场' ],
handler: async (params = {}) => {
const { ctx } = this;
void params;
// 读取原消息内容提取车牌号
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 carnum = extractLicensePlate(originalText);
if (!carnum) {
return {
success: false,
error: '未识别到车牌号,请发送:车牌号+进场\n例:粤A12345进场',
};
}
const warehouseId = Number(ctx.inboxContext?.warehouse_id) || 0;
if (!warehouseId) {
return { success: false, error: '无法获取仓库信息' };
}
const { Op } = ctx.app.Sequelize;
// 查6小时内未消费的到货登记(进场不改消费状态,离场时才消费)
const record = await ctx.model.InboxArrivalRegister.findOne({
attributes: [ 'id', 'store_id', 'license_plate' ],
where: {
warehouse_id: warehouseId,
license_plate: carnum,
consumed: 0,
created_at: { [Op.gte]: ctx.app.Sequelize.literal('DATE_SUB(NOW(), INTERVAL 6 HOUR)') },
},
order: [[ 'created_at', 'DESC' ]],
raw: true,
});
if (!record) {
return {
success: false,
error: `未查询到车牌 ${carnum} 6小时内的有效登记,请先登记到货`,
};
}
// 通知对应货主(优先收货群,其次售后群,发送失败换下一个群)
const notifyResult = await this.notifyStoreReceiving(
warehouseId, record.store_id,
`车辆${carnum}已入场,等待卸货`
);
const pushed = notifyResult.pushed;
const pushedGroup = notifyResult.pushedGroup;
ctx.logger.info(
`[inbox functions] 进场登记: 车牌=${carnum} ` +
`store_id=${record.store_id || '-'} pushed=${pushed} group=${pushedGroup || '-'}`
);
// 当前消息不回执(data 不含 message/extend_props → 规则引擎无回复)
return {
success: true,
data: { carnum, entered: true, pushed, pushed_group: pushedGroup },
};
},
});
}
/**
* 通知货主(优先收货群 receiving,其次售后群 after_sales,发送失败换下一个群)。
* @param {number} warehouseId 仓库ID。
* @param {number|null} storeId 货主ID(为空时直接返回未推送)。
* @param {string} content 通知内容。
* @return {Promise<{pushed: boolean, pushedGroup: string}>} 推送结果。
*/
async notifyStoreReceiving(warehouseId, storeId, content) {
const { ctx } = this;
let pushed = false;
let pushedGroup = '';
if (!storeId) return { pushed, pushedGroup };
try {
const groupSvc = ctx.service.systems.inbox.group;
const [ receivingGroups, afterSalesGroups ] = await Promise.all([
groupSvc.findStoreGroups({ storeIds: [ storeId ], warehouseId, subTypes: [ 'receiving' ] }),
groupSvc.findStoreGroups({ storeIds: [ storeId ], warehouseId, subTypes: [ 'after_sales' ] }),
]);
const candidates = [ ...receivingGroups, ...afterSalesGroups ];
for (const g of candidates) {
if (!g.group_id) continue;
const ok = await ctx.service.inbox.processor.writeOutboundReply({
warehouse_id: warehouseId,
ext_id: `sys:store-notify:${warehouseId}:${Date.now()}:${Math.random().toString(36).slice(2, 8)}`,
parent_id: null,
ext_data: g.ext_data || null,
group_id: g.group_id,
user_id: '',
group_name: g.group_name || '',
user_name: '',
store_id: g.store_id || null,
}, content, 'system');
if (ok) {
pushed = true;
pushedGroup = g.group_name || g.group_id;
break;
}
ctx.logger.warn(`[inbox functions] 通知货主群 ${g.group_name || g.group_id} 推送失败,尝试下一个`);
}
} catch (e) {
ctx.logger.warn(`[inbox functions] 通知货主失败: ${e.message}`);
}
return { pushed, pushedGroup };
}
/**
* 注册一个函数。
*
* @param {string} name 函数名称。
* @param {Object} def 函数定义。
* @param {string} def.description 函数描述(供 AI 理解用途)。
* @param {Object} def.params 参数定义。
* @param {string[]} def.groups 所属分组列表,按 {主分组}:{子分组} 格式。
* 例如 ['common'] 或 ['bound:store', 'bound:store:after_sales']。
* @param {number} [def.weight=0] 权重,值越大优先级越高,用于 AI 多函数匹配时排序。
* @param {string[]} [def.keywords] 触发关键词,用于 AI 快速匹配用户意图。
* @param {Function} def.handler 函数实现,接收 params 对象,返回结果。
*/
register(name, def) {
if (!name || typeof name !== 'string') {
throw new Error('函数名称必须是非空字符串');
}
if (!def || typeof def.handler !== 'function') {
throw new Error(`函数 ${name} 必须提供 handler 实现`);
}
this.registry.set(name, {
name,
description: String(def.description || ''),
params: def.params || {},
groups: Array.isArray(def.groups) && def.groups.length > 0
? def.groups
: [ GROUP.COMMON ],
weight: Number.isFinite(def.weight) ? def.weight : 0,
keywords: Array.isArray(def.keywords) ? def.keywords : [],
handler: def.handler,
});
this.ctx.logger.info(`[inbox functions] 注册函数: ${name} groups=${this.registry.get(name).groups.join(',')}`);
}
/**
* 执行已注册的函数。
*
* @param {string} name 函数名称。
* @param {Object} [params={}] 函数参数。
* @return {Promise<Object>} 函数执行结果。
*/
async callFunction(name, params = {}) {
const def = this.registry.get(name);
if (!def) {
return {
success: false,
error: `未注册的函数: ${name},可用函数: ${Array.from(this.registry.keys()).join(', ')}`,
};
}
// 群类型权限过滤:按当前群的活跃分组校验函数可用性,
// 防止货主群调用快递群专属函数(如 handleExpressFeedback)等越权调用。
// 无 groups 服务的场景(单元测试直接实例化)跳过校验,由调用方保证上下文。
const groupsSvc = this.ctx.service && this.ctx.service.inbox && this.ctx.service.inbox.groups;
if (groupsSvc && typeof groupsSvc.isFunctionAvailable === 'function') {
const activeGroups = groupsSvc.resolveActiveGroups();
if (!groupsSvc.isFunctionAvailable(def, activeGroups)) {
this.ctx.logger.warn(
`[inbox functions] 越权调用被拦截: ${name} ` +
`groups=${(def.groups || []).join(',')} active=${activeGroups.join(',')}`
);
return {
success: false,
error: `函数 ${name} 在当前群类型下不可用,请通过对应类型的群发起`,
};
}
}
try {
const result = await def.handler(params);
return result && typeof result === 'object' ? result : { success: true, data: result };
} catch (error) {
return {
success: false,
error: `函数 ${name} 执行异常: ${error.message}`,
};
}
}
}
module.exports = InboxFunctionsService;