confirmIntercept + interceptScan 确认拦截后: - step = 4(配送中) - outbound_status = 'fin'(出库完成) - intercept_status = intercepted_at_warehouse
1930 lines
84 KiB
JavaScript
1930 lines
84 KiB
JavaScript
'use strict';
|
||
|
||
const Service = require('egg').Service;
|
||
|
||
// 群类型常量定义统一收口到 inbox/groups.js
|
||
const { GROUP } = require('./groups');
|
||
|
||
/**
|
||
* 站内信函数注册表。
|
||
* 负责注册 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('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} 对应的发货单,请核实单号是否正确`,
|
||
};
|
||
}
|
||
|
||
// 查已有快递单号
|
||
const existingExpress = await ctx.model.OrderExpress.findOne({
|
||
attributes: [ 'waybill_code', 'logistics_name', 'status' ],
|
||
where: { order_id: orderDelivery.id, business_key: 1 },
|
||
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' ],
|
||
where: {
|
||
waybill_code: keyword,
|
||
store_id: storeId,
|
||
warehouse_id: warehouseId,
|
||
},
|
||
raw: true,
|
||
});
|
||
|
||
if (exactExpress && exactExpress.delivery_order_code) {
|
||
// 用运单关联的发货单号精确查找订单
|
||
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,
|
||
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 ],
|
||
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);
|
||
|
||
if (toCreate.length === 0) {
|
||
return {
|
||
success: true,
|
||
data: {
|
||
existed: true,
|
||
message: `运单已存在处理中的拦截工单: ${alreadyExist.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');
|
||
|
||
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' ],
|
||
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) {
|
||
await orderModel.update(
|
||
{ intercept_status: 'requested' },
|
||
{ where: { id: { [ctx.app.Sequelize.Op.in]: interceptOrderIds } } }
|
||
);
|
||
// 同步更新运单表拦截标记
|
||
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(warehouseId),
|
||
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 = [];
|
||
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) {
|
||
// 与 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 (notifiedAsNos.length > 0) {
|
||
parts.push(`拦截信息已登记并通知快递群,工单: ${notifiedAsNos.join('、')}`);
|
||
}
|
||
if (notNotifiedAsNos.length > 0) {
|
||
parts.push(`拦截信息已登记(未配置快递群,需人工跟进),工单: ${notNotifiedAsNos.join('、')}`);
|
||
}
|
||
if (alreadyExist.length > 0) {
|
||
parts.push(`已登记过,工单: ${alreadyExist.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('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 ],
|
||
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 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;
|
||
} catch (e) {
|
||
ctx.logger.warn(`[inbox functions] 取消拦截反馈失败 as_no=${as.after_sale_no}: ${e.message}`);
|
||
}
|
||
}
|
||
|
||
const parts = [];
|
||
if (feedbackCount > 0) parts.push(`已有工单追加取消拦截: ${feedbackCount}个`);
|
||
|
||
// 第四步:无工单的按拦截规则创建
|
||
const createdNos = [];
|
||
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 || '未知'}`,
|
||
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) parts.push(`已创建取消拦截工单: ${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' ],
|
||
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) {
|
||
await orderModel.update(
|
||
{ intercept_status: 'requested' },
|
||
{ where: { id: { [ctx.app.Sequelize.Op.in]: interceptOrderIds } } }
|
||
);
|
||
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(warehouseId),
|
||
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('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';
|
||
|
||
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 || '未知'}`,
|
||
`售后类型: ${asType}.${asSubType}`,
|
||
'来源: 快递群反馈',
|
||
].join('\n');
|
||
|
||
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 replyMsg = parts.join(';') || '处理完成';
|
||
|
||
// 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)) ];
|
||
if (candidateGroupIds.length > 0) {
|
||
const expressGroups = await ctx.model.InboxGroup.findAll({
|
||
attributes: [ 'group_id' ],
|
||
where: {
|
||
group_id: { [ctx.app.Sequelize.Op.in]: candidateGroupIds },
|
||
warehouse_id: warehouseId,
|
||
group_type: 'express',
|
||
},
|
||
raw: true,
|
||
});
|
||
expressGroupIds = new Set(expressGroups.map(g => g.group_id));
|
||
}
|
||
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,
|
||
});
|
||
}
|
||
}
|
||
} 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,
|
||
});
|
||
}
|
||
}
|
||
} catch (e) {
|
||
ctx.logger.warn(`[inbox functions] 查货主售后群失败: ${e.message}`);
|
||
}
|
||
}
|
||
|
||
// 3c. 发送回信
|
||
for (const [ , target ] of replyTargets) {
|
||
ctx.service.inbox.processor.pushSystemNotification({
|
||
warehouse_id: warehouseId,
|
||
group_id: target.group_id,
|
||
group_name: target.group_name,
|
||
content: `快递反馈: ${replyMsg}`,
|
||
ext_data: target.ext_data,
|
||
});
|
||
}
|
||
|
||
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('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}` };
|
||
}
|
||
},
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 注册一个函数。
|
||
*
|
||
* @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(', ')}`,
|
||
};
|
||
}
|
||
|
||
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;
|