新增功能: - AI智能助手: DeepSeek多轮推理、函数调用(searchStock/createOrder等) - silent动作: AI识别无需回复的消息(好的/谢谢/再见)自动跳过回执 - ai_enabled灰度开关: 群级别控制AI启停,支持逐群放量 - 消息列表增强: storeId/groupId/groupName/userName/content/sourceType多条件筛选,时间格式化 代码优化: - processWithAI: 多轮推理循环(MAX_ROUNDS=5)、对话历史不含[#N]前缀防AI污染 - 回执记录补齐group_id/user_id/group_name/user_name上下文 - 移除未使用的target_channel字段及迁移 - bindCode文档修正: store_warehouse → store 接口文档: - system.json v0.3.18→0.3.19: 新增aiEnabled参数、消息列表响应扩充 - changes/system.json: 新增bindCode变更记录 杂项: - store_warehouse.js JSDoc补全 - wave.js waveBatchSource修复
1061 lines
39 KiB
JavaScript
1061 lines
39 KiB
JavaScript
'use strict';
|
||
|
||
const Service = require('egg').Service;
|
||
|
||
/**
|
||
* ## 函数分组常量
|
||
*
|
||
* 层级格式:`{主分组}` 或 `{主分组}:{子分组}`
|
||
*
|
||
* ### 分组匹配规则(注册 / 查询)
|
||
*
|
||
* 1. **精确匹配**:`['common']` 只匹配当前活跃分组包含 `common` 的上下文。
|
||
* 2. **主分组通配**:`['bound:store:*']` 匹配 `bound:store` 及其所有子分组
|
||
* (`bound:store:after_sales` / `bound:store:finance` / `bound:store:receiving`),
|
||
* 适用于同一主分组下所有子分组都需要的函数。
|
||
* 3. **显式子分组**:`['bound:store:after_sales']` 只在该子分组活跃时可用,
|
||
* 适用于某子分组专属的函数。
|
||
* 4. **组合使用**:`['common', 'bound:store:*']` 表示通用 + 所有货主子分组均可用。
|
||
*
|
||
* ### 如何注册新函数
|
||
*
|
||
* ```js
|
||
* // 仅通用分组
|
||
* this.register('myFunc', { groups: [GROUP.COMMON], ... });
|
||
*
|
||
* // 所有货主子分组(推荐)
|
||
* this.register('myFunc', { groups: [GROUP.BOUND_STORE_WILDCARD], ... });
|
||
*
|
||
* // 仅售后子分组
|
||
* this.register('myFunc', { groups: [GROUP.BOUND_STORE_AFTER_SALES], ... });
|
||
*
|
||
* // 售后 + 财务(但非收货)
|
||
* this.register('myFunc', {
|
||
* groups: [GROUP.BOUND_STORE_AFTER_SALES, GROUP.BOUND_STORE_FINANCE],
|
||
* ...
|
||
* });
|
||
* ```
|
||
*
|
||
* @constant
|
||
*/
|
||
const GROUP = {
|
||
/** 通用分组 — 所有上下文均可用 */
|
||
COMMON: 'common',
|
||
/** 已绑定货主群主分组 */
|
||
BOUND_STORE: 'bound:store',
|
||
/** 货主群通配 — 匹配 bound:store 及其全部子分组 */
|
||
BOUND_STORE_WILDCARD: 'bound:store:*',
|
||
/** 货主-售后子分组 */
|
||
BOUND_STORE_AFTER_SALES: 'bound:store:after_sales',
|
||
/** 货主-财务子分组 */
|
||
BOUND_STORE_FINANCE: 'bound:store:finance',
|
||
/** 货主-收货子分组 */
|
||
BOUND_STORE_RECEIVING: 'bound:store:receiving',
|
||
/** 已绑定仓库群(预留) */
|
||
BOUND_WAREHOUSE: 'bound:warehouse',
|
||
/** 已绑定快递群(预留) */
|
||
BOUND_EXPRESS: 'bound:express',
|
||
};
|
||
|
||
/**
|
||
* 子分组 → 主分组映射,用于 `resolveActiveGroups` 展开。
|
||
* 新增子分组时必须同步追加。
|
||
* @constant {Record<string, string>}
|
||
*/
|
||
const SUB_TO_MAIN = {
|
||
[GROUP.BOUND_STORE_AFTER_SALES]: GROUP.BOUND_STORE,
|
||
[GROUP.BOUND_STORE_FINANCE]: GROUP.BOUND_STORE,
|
||
[GROUP.BOUND_STORE_RECEIVING]: GROUP.BOUND_STORE,
|
||
};
|
||
|
||
/**
|
||
* 注册时声明的主分组通配 → 所有已知子分组展开列表。
|
||
* 用于 `isFunctionAvailable` 中展开 `bound:store:*` → 实际子分组集合。
|
||
* @constant {Record<string, string[]>}
|
||
*/
|
||
const WILDCARD_EXPAND = {
|
||
[GROUP.BOUND_STORE_WILDCARD]: [
|
||
GROUP.BOUND_STORE,
|
||
GROUP.BOUND_STORE_AFTER_SALES,
|
||
GROUP.BOUND_STORE_FINANCE,
|
||
GROUP.BOUND_STORE_RECEIVING,
|
||
],
|
||
};
|
||
|
||
/**
|
||
* 站内信函数库。
|
||
* 注册可被 AI 调用的内部方法,支持按分组筛选,
|
||
* 根据当前上下文(群类型、绑定状态)自动选择可用函数集合。
|
||
*/
|
||
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 ],
|
||
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 ],
|
||
handler: async (params = {}) => {
|
||
const { ctx } = this;
|
||
void params;
|
||
const storeId = Number(
|
||
ctx.inboxContext?.store_id
|
||
|| ctx.user?.store_id
|
||
|| 0
|
||
);
|
||
const warehouseId = Number(
|
||
ctx.inboxContext?.warehouse_id
|
||
|| ctx.user?.store_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 ],
|
||
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: '搜索仓库商品。按关键词查询当前仓库+货主的商品,返回 stock_store.id、编码、名称、条码、库存总量/锁定/可用 供建单参考',
|
||
params: {
|
||
keyword: { type: 'string', required: true, description: '搜索关键词:商品编码(item_code)、条码(barcode)、商品名称(item_name)' },
|
||
},
|
||
groups: [ GROUP.BOUND_STORE_WILDCARD ],
|
||
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 {
|
||
const items = await ctx.model.StockStore.findAll({
|
||
attributes: [ 'id', 'stock_id', 'item_code', 'item_name', 'barcode', 'brand_name', 'stock_unit' ],
|
||
where: {
|
||
warehouse_id: warehouseId,
|
||
store_id: storeId,
|
||
[Op.or]: [
|
||
{ item_code: { [Op.like]: `%${keyword}%` } },
|
||
{ item_name: { [Op.like]: `%${keyword}%` } },
|
||
{ barcode: { [Op.like]: `%${keyword}%` } },
|
||
],
|
||
},
|
||
limit: 10,
|
||
raw: true,
|
||
});
|
||
|
||
if (items.length === 0) {
|
||
return { success: true, data: { total: 0, items: [], hint: '未找到匹配商品,请尝试其他关键词' } };
|
||
}
|
||
|
||
// 批量查库存数量
|
||
const stockIds = [ ...new Set(items.map(i => i.stock_id).filter(Boolean)) ];
|
||
const stockQtyMap = {};
|
||
if (stockIds.length > 0) {
|
||
const stocks = await ctx.model.StockWarehouse.findAll({
|
||
attributes: [ 'id', 'quantity', 'locked_quantity' ],
|
||
where: { id: { [Op.in]: stockIds } },
|
||
raw: true,
|
||
});
|
||
for (const s of stocks) {
|
||
stockQtyMap[s.id] = {
|
||
quantity: s.quantity || 0,
|
||
locked_quantity: s.locked_quantity || 0,
|
||
available: Math.max(0, (s.quantity || 0) - (s.locked_quantity || 0)),
|
||
};
|
||
}
|
||
}
|
||
|
||
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: i.barcode,
|
||
brand_name: i.brand_name || '',
|
||
unit: i.stock_unit || '',
|
||
stock_qty: stockQtyMap[i.stock_id]?.quantity || 0,
|
||
stock_locked: stockQtyMap[i.stock_id]?.locked_quantity || 0,
|
||
stock_available: stockQtyMap[i.stock_id]?.available || 0,
|
||
})),
|
||
},
|
||
};
|
||
} 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 ],
|
||
handler: async (params = {}) => {
|
||
const limit = Math.min(10, Math.max(1, Number(params.limit) || 5));
|
||
const history = await this.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 => ({
|
||
seq: h.seq,
|
||
role: h.role === 'user' ? '用户' : 'AI',
|
||
content: h.content || '',
|
||
})),
|
||
},
|
||
};
|
||
},
|
||
});
|
||
|
||
this.register('createOrder', {
|
||
description: '创建发货订单。传入商品 stock_id(来自 searchStock)及数量、收件人信息,使用手工建单流程创建发货单',
|
||
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 ],
|
||
handler: async (params = {}) => {
|
||
const { ctx } = this;
|
||
void params;
|
||
const groupName = String(ctx.inboxContext?.group_name || '').trim();
|
||
const userName = String(ctx.inboxContext?.user_name || '').trim();
|
||
|
||
if (!groupName && !userName) {
|
||
return {
|
||
success: false,
|
||
error: '无法获取群名称或用户名称,屏蔽操作需要明确的群或用户身份',
|
||
};
|
||
}
|
||
|
||
try {
|
||
const { InboxBlock } = ctx.model;
|
||
await InboxBlock.create({
|
||
group_name: groupName || null,
|
||
user_name: userName || null,
|
||
});
|
||
|
||
// 失效屏蔽缓存
|
||
const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0);
|
||
await ctx.service.inbox.processor.invalidateBlockCache(warehouseId);
|
||
|
||
const scope = [];
|
||
if (groupName) scope.push(`群「${groupName}」`);
|
||
if (userName) scope.push(`用户「${userName}」`);
|
||
|
||
return {
|
||
success: true,
|
||
data: {
|
||
blocked: groupName || userName,
|
||
message: `已屏蔽${scope.join('的')},后续将不再处理你的消息。如需解除屏蔽,请联系客服到WMS解除。`,
|
||
},
|
||
};
|
||
} catch (error) {
|
||
// 唯一键冲突 = 已屏蔽
|
||
if (error.name === 'SequelizeUniqueConstraintError') {
|
||
return {
|
||
success: true,
|
||
data: {
|
||
message: '该群或用户已在屏蔽列表中,无需重复操作。如需解除屏蔽,请联系客服到WMS解除。',
|
||
},
|
||
};
|
||
}
|
||
return {
|
||
success: false,
|
||
error: `屏蔽操作失败: ${error.message}`,
|
||
};
|
||
}
|
||
},
|
||
});
|
||
|
||
this.register('listGroups', {
|
||
description: '查询当前仓库的群列表,包含屏蔽状态',
|
||
params: {},
|
||
groups: [ GROUP.COMMON ],
|
||
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 {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 ],
|
||
handler: def.handler,
|
||
});
|
||
this.ctx.logger.info(`[inbox functions] 注册函数: ${name} groups=${this.registry.get(name).groups.join(',')}`);
|
||
}
|
||
|
||
/**
|
||
* 根据当前上下文解析可用分组集合。
|
||
*
|
||
* ### 分组解析逻辑
|
||
*
|
||
* - 始终包含 `common`(通用分组)。
|
||
* - 若群已绑定货主(`store_id > 0` 且 `groupType === 'store'`):
|
||
* - 追加 `bound:store`(主分组)。
|
||
* - 若有 `subType`(如 `after_sales`),追加 `bound:store:{subType}`。
|
||
* - 若群已绑定仓库(`groupType === 'warehouse'`):追加 `bound:warehouse`。
|
||
* - 若群已绑定快递(`groupType === 'express'`):追加 `bound:express`。
|
||
*
|
||
* ### 使用方式
|
||
*
|
||
* - AI 处理消息时自动调用,无需手动传参。
|
||
* - 也可显式传入 `opts.groupType` / `opts.subType` 覆盖上下文。
|
||
*
|
||
* @param {Object} [opts] 可选覆盖参数。
|
||
* @param {string} [opts.groupType] 群类型(store / warehouse / express)。
|
||
* @param {string} [opts.subType] 子类型(after_sales / finance / receiving)。
|
||
* @return {string[]} 当前上下文中可用的分组列表。
|
||
*/
|
||
resolveActiveGroups(opts = {}) {
|
||
const { ctx } = this;
|
||
const groups = [ GROUP.COMMON ];
|
||
|
||
const groupType = String(
|
||
opts.groupType || ctx.inboxContext?.group_type || ''
|
||
).trim();
|
||
const subType = String(
|
||
opts.subType || ctx.inboxContext?.sub_type || ''
|
||
).trim();
|
||
const storeId = Number(ctx.inboxContext?.store_id || 0);
|
||
|
||
// 已绑定货主 → 加入 bound:store 及相关子分组
|
||
if (storeId > 0 && groupType === 'store') {
|
||
groups.push(GROUP.BOUND_STORE);
|
||
const subGroup = `bound:store:${subType}`;
|
||
if (SUB_TO_MAIN[subGroup]) {
|
||
groups.push(subGroup);
|
||
}
|
||
}
|
||
|
||
// 其他绑定类型预留
|
||
if (storeId > 0 && groupType === 'warehouse') {
|
||
groups.push(GROUP.BOUND_WAREHOUSE);
|
||
}
|
||
if (storeId > 0 && groupType === 'express') {
|
||
groups.push(GROUP.BOUND_EXPRESS);
|
||
}
|
||
|
||
return groups;
|
||
}
|
||
|
||
/**
|
||
* 判断某个函数在当前活跃分组集合中是否可用。
|
||
*
|
||
* ### 匹配规则
|
||
*
|
||
* 1. 函数未声明 `groups` 或为空数组 → 视为 `['common']`,始终可用。
|
||
* 2. 函数 `groups` 中包含 `common` → 始终可用。
|
||
* 3. 函数 `groups` 中包含 `{主分组}:*` 通配(如 `bound:store:*`) →
|
||
* 展开为 `WILDCARD_EXPAND` 中定义的所有子分组,逐一与活跃分组求交集。
|
||
* 4. 精确匹配:函数 `groups` 中的每一个精确分组名与活跃分组集合取交集。
|
||
*
|
||
* @param {Object} def 函数定义对象(含 `groups` 字段)。
|
||
* @param {string[]} activeGroups 当前上下文的活跃分组列表。
|
||
* @return {boolean} 该函数在当前分组中是否可用。
|
||
*/
|
||
isFunctionAvailable(def, activeGroups) {
|
||
if (!Array.isArray(def.groups) || def.groups.length === 0) return true;
|
||
|
||
const expanded = [];
|
||
for (const g of def.groups) {
|
||
// 通配展开:bound:store:* → [bound:store, bound:store:after_sales, ...]
|
||
if (WILDCARD_EXPAND[g]) {
|
||
expanded.push(...WILDCARD_EXPAND[g]);
|
||
} else {
|
||
expanded.push(g);
|
||
}
|
||
}
|
||
|
||
// common 分组或任一展开后的分组命中活跃集合即视为可用
|
||
return expanded.some(g => g === GROUP.COMMON || activeGroups.includes(g));
|
||
}
|
||
|
||
/**
|
||
* 获取指定分组下的函数列表。
|
||
*
|
||
* @param {string[]} [activeGroups] 活跃分组列表,不传则返回全部已注册函数。
|
||
* @return {Array<{name: string, description: string, params: Object}>} 函数列表。
|
||
*/
|
||
getFunctionList(activeGroups) {
|
||
const list = [];
|
||
for (const [ name, def ] of this.registry) {
|
||
if (activeGroups && !this.isFunctionAvailable(def, activeGroups)) continue;
|
||
list.push({
|
||
name,
|
||
description: def.description,
|
||
params: def.params,
|
||
});
|
||
}
|
||
return list;
|
||
}
|
||
|
||
/**
|
||
* 构建函数列表的文本描述,供 AI prompt 使用。
|
||
*
|
||
* @param {string[]} [activeGroups] 活跃分组列表,不传则返回全部。
|
||
* @return {string} 函数列表文本。
|
||
*/
|
||
buildFunctionListText(activeGroups) {
|
||
const lines = [];
|
||
for (const [ name, def ] of this.registry) {
|
||
if (activeGroups && !this.isFunctionAvailable(def, activeGroups)) continue;
|
||
const paramEntries = Object.entries(def.params);
|
||
const paramStr = paramEntries.length > 0
|
||
? paramEntries.map(([ k, v ]) => `${k}(${v.type || 'string'}, ${v.required ? '必填' : '可选'}): ${v.description}`).join(', ')
|
||
: '无参数';
|
||
lines.push(`- ${name}: ${def.description}。参数: ${paramStr}`);
|
||
}
|
||
return lines.join('\n');
|
||
}
|
||
|
||
/**
|
||
* 执行已注册的函数。
|
||
*
|
||
* @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}`,
|
||
};
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 调用 DeepSeek API。
|
||
*
|
||
* @param {Array<{role: string, content: string}>} messages 消息列表。
|
||
* @param {Object} [options] 额外选项。
|
||
* @return {Promise<string>} AI 返回的文本内容。
|
||
*/
|
||
async callDeepSeek(messages, options = {}) {
|
||
const { ctx } = this;
|
||
const apiKey = ctx.app.config.deepseek.apiKey;
|
||
const baseUrl = ctx.app.config.deepseek.baseUrl || 'https://api.deepseek.com';
|
||
|
||
if (!apiKey) {
|
||
throw new Error('DeepSeek API Key 未配置');
|
||
}
|
||
|
||
const result = await ctx.curl(`${baseUrl}/v1/chat/completions`, {
|
||
method: 'POST',
|
||
contentType: 'json',
|
||
dataType: 'json',
|
||
headers: { Authorization: `Bearer ${apiKey}` },
|
||
data: {
|
||
model: 'deepseek-v4-pro',
|
||
messages,
|
||
temperature: options.temperature ?? 0,
|
||
max_tokens: options.maxTokens ?? 1000,
|
||
},
|
||
timeout: options.timeout || 30000,
|
||
});
|
||
|
||
if (result.status !== 200 || !result.data) {
|
||
throw new Error(`DeepSeek 请求失败, HTTP ${result.status}`);
|
||
}
|
||
|
||
let content = result.data.choices?.[0]?.message?.content || '';
|
||
// 清理 markdown 代码块
|
||
content = content.replace(/^```json\s*/i, '').replace(/\s*```$/i, '');
|
||
content = content.replace(/^```\s*/i, '').replace(/\s*```$/i, '');
|
||
return content.trim();
|
||
}
|
||
|
||
/**
|
||
* 获取智能对话历史上下文。
|
||
* 同一群 + 同一用户 → 最近 N 条消息(含 AI 回复),用于多轮对话短期记忆。
|
||
* 按创建时间升序排列,并为每条消息附加序号供 AI 追踪。
|
||
*
|
||
* @param {Object} opts 查询选项。
|
||
* @param {number} [opts.parentId] 当前消息的 parent_id(兼容旧参数)。
|
||
* @param {number} [opts.maxMessages=5] 最大历史消息数。
|
||
* @return {Promise<Array<{role: string, content: string, seq?: number}>>} 历史消息列表。
|
||
*/
|
||
async getConversationHistory(opts = {}) {
|
||
const parentId = Number(opts.parentId) || 0;
|
||
const maxMessages = Math.min(10, Math.max(1, Number(opts.maxMessages) || 5));
|
||
|
||
const { ctx } = this;
|
||
const { InboxMessage } = ctx.model;
|
||
const { Op } = ctx.app.Sequelize;
|
||
|
||
const groupId = String(ctx.inboxContext?.group_id || '').trim();
|
||
const userId = String(ctx.inboxContext?.user_id || '').trim();
|
||
const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0);
|
||
|
||
// 无群/用户上下文时,退回旧逻辑:沿 parent_id 追溯
|
||
if (!groupId || !userId || !warehouseId) {
|
||
if (!parentId) return [];
|
||
try {
|
||
const history = [];
|
||
let currentId = parentId;
|
||
const visited = new Set();
|
||
while (currentId && history.length < maxMessages) {
|
||
if (visited.has(currentId)) break;
|
||
visited.add(currentId);
|
||
const msg = await InboxMessage.findOne({
|
||
attributes: [ 'id', 'parent_id', 'direction', 'content' ],
|
||
where: { id: currentId },
|
||
raw: true,
|
||
});
|
||
if (!msg) break;
|
||
history.unshift({ role: msg.direction === 'inbound' ? 'user' : 'assistant', content: msg.content || '' });
|
||
currentId = msg.parent_id;
|
||
}
|
||
return history;
|
||
} catch (error) {
|
||
ctx.logger.warn(`[inbox functions] 对话历史回退查询失败: ${error.message}`);
|
||
return [];
|
||
}
|
||
}
|
||
|
||
// 智能查询:同一群+用户,最近 maxMessages 条(入站+出站混合)
|
||
try {
|
||
const messages = await InboxMessage.findAll({
|
||
attributes: [ 'id', 'parent_id', 'direction', 'content', 'created_at' ],
|
||
where: {
|
||
warehouse_id: warehouseId,
|
||
group_id: groupId,
|
||
user_id: userId,
|
||
direction: { [Op.in]: [ 'inbound', 'outbound' ] },
|
||
},
|
||
order: [[ 'created_at', 'DESC' ]],
|
||
limit: maxMessages,
|
||
raw: true,
|
||
});
|
||
|
||
if (messages.length === 0) return [];
|
||
|
||
// 升序排列(不再附加序号前缀,防止 AI 输出污染)
|
||
return messages.reverse().map(msg => ({
|
||
role: msg.direction === 'inbound' ? 'user' : 'assistant',
|
||
content: msg.content || '',
|
||
}));
|
||
} catch (error) {
|
||
ctx.logger.warn(`[inbox functions] 智能对话历史查询失败: ${error.message}`);
|
||
return [];
|
||
}
|
||
}
|
||
|
||
/**
|
||
* DeepSeek 多轮推理:思考→调函数→评估→(重复或输出)。
|
||
*
|
||
* 每轮 AI 返回 JSON,通过 action 字段决定行为:
|
||
* { "action": "call", "function": "函数名", "params": {...}, "reason": "..." }
|
||
* { "action": "reply", "reply": "最终回复内容" }
|
||
*
|
||
* 最多 MAX_ROUNDS 轮,防止无限循环。
|
||
*
|
||
* @param {Object} data 消息数据。
|
||
* @param {string} data.content 消息正文。
|
||
* @param {Object} [data.ext_data] 透传数据。
|
||
* @param {number} [data.parentId] 父消息ID。
|
||
* @return {Promise<{reply: string, functionName: string|null, functionResult: Object|null}>} AI 回复。
|
||
*/
|
||
async processWithAI(data = {}) {
|
||
const { ctx } = this;
|
||
const content = String(data.content || '').trim();
|
||
if (!content) {
|
||
return { reply: '消息正文为空,无法处理', functionName: null, functionResult: null };
|
||
}
|
||
|
||
const activeGroups = this.resolveActiveGroups();
|
||
ctx.logger.info(`[inbox functions] 当前活跃分组: ${activeGroups.join(', ')}`);
|
||
|
||
const functionListText = this.buildFunctionListText(activeGroups);
|
||
if (!functionListText) {
|
||
ctx.logger.info('[inbox functions] 当前上下文无可用的 AI 函数');
|
||
return { reply: null, functionName: null, functionResult: null };
|
||
}
|
||
|
||
const history = await this.getConversationHistory({
|
||
parentId: data.parentId,
|
||
maxMessages: 5,
|
||
});
|
||
|
||
const MAX_ROUNDS = 5;
|
||
const executedFunctions = [];
|
||
const thoughts = [];
|
||
let finalReply = null;
|
||
let lastFunctionName = null;
|
||
let lastFunctionResult = null;
|
||
|
||
const systemPrompt = `你是一个 WMS 仓库管理系统的智能助手,支持多步推理。
|
||
已注册函数:\n${functionListText}\n
|
||
你需要通过多轮调用来完成用户的复杂请求。每轮返回纯 JSON:
|
||
|
||
如果还需要调用函数获取信息:
|
||
{
|
||
"action": "call",
|
||
"function": "函数名",
|
||
"params": { "参数名": "参数值" },
|
||
"reason": "为什么需要这个函数"
|
||
}
|
||
|
||
如果信息充足可以回复用户了:
|
||
{
|
||
"action": "reply",
|
||
"reply": "最终回复(中文纯文本,禁止Markdown,200字以内,可适当使用\\n换行分隔信息)"
|
||
}
|
||
|
||
如果消息无需回复(用户只是确认、道谢、告别或表示自己处理):
|
||
{
|
||
"action": "silent"
|
||
}
|
||
|
||
约束:
|
||
- 最多 ${MAX_ROUNDS} 轮函数调用,第 ${MAX_ROUNDS} 轮必须给出最终回复
|
||
- 同一函数不要重复调用(除非参数不同)
|
||
- 如果函数执行失败,换其他方式或直接告知用户
|
||
- 回复使用中文纯文本,禁止 Markdown 语法,可用 \\n 换行提升可读性
|
||
- silent 仅用于以下纯社交/确认性语句(用户无提问、无请求):"好的""收到""OK""谢谢""再见""等会再说""手工处理""知道了"
|
||
- 以下情况严禁 silent,必须 reply:用户提出疑问、请求查询/建单/操作、函数执行完毕需告知结果、库存为0需说明原因
|
||
- 已调用函数获取了用户请求的数据后,必须 reply 告知结果,绝对不能 silent
|
||
- 无法判断是否需要回复时,宁可回复也不要 silent
|
||
- searchStock 返回多条结果时,必须列举让用户选择(告知 id/编码/名称/可用库存),不要擅自决定
|
||
- createOrder 失败时告知失败原因(库存不足/商品不存在等),不要重试同一商品
|
||
- searchStock 返回的 stock_available 为 0 时,提醒用户该商品无库存,建议选择其他商品
|
||
- 用户说"第1个""第2个"时,按 searchStock 返回的顺序对应选择
|
||
- 需要上下文但记忆不足时,主动调用 recallHistory 回顾对话历史`;
|
||
|
||
// 多轮推理循环
|
||
for (let round = 1; round <= MAX_ROUNDS; round++) {
|
||
const contextLines = [];
|
||
if (executedFunctions.length > 0) {
|
||
contextLines.push('已执行的函数及结果:');
|
||
executedFunctions.forEach((f, i) => {
|
||
contextLines.push(
|
||
` ${i + 1}. ${f.name}(${JSON.stringify(f.params)}) → ${JSON.stringify(f.result)}`
|
||
);
|
||
});
|
||
}
|
||
|
||
const messages = [
|
||
{ role: 'system', content: systemPrompt },
|
||
...history,
|
||
...(contextLines.length > 0 ? [{ role: 'system', content: contextLines.join('\n') }] : []),
|
||
{ role: 'user', content: round === 1
|
||
? content
|
||
: (executedFunctions.length > 0
|
||
? `已获取到函数执行结果,请根据结果 reply 告知用户(禁止 silent)。第 ${round}/${MAX_ROUNDS} 轮`
|
||
: `请根据已获取的信息,决定下一步:继续调用函数还是给出最终回复。第 ${round}/${MAX_ROUNDS} 轮`),
|
||
},
|
||
];
|
||
|
||
let raw = '';
|
||
try {
|
||
raw = await this.callDeepSeek(messages, { maxTokens: 600 });
|
||
ctx.logger.info(`[inbox functions] 第 ${round}/${MAX_ROUNDS} 轮: ${raw}`);
|
||
|
||
const result = JSON.parse(raw);
|
||
|
||
// 记录思考过程
|
||
thoughts.push({
|
||
round,
|
||
action: result.action || 'unknown',
|
||
function: result.function || null,
|
||
params: result.params || null,
|
||
reason: result.reason || null,
|
||
});
|
||
|
||
if (result.action === 'reply') {
|
||
finalReply = String(result.reply || '').trim();
|
||
if (!finalReply) finalReply = '已处理完成';
|
||
break;
|
||
}
|
||
|
||
if (result.action === 'silent') {
|
||
// 已调用过函数 → 必须回复结果,不能 silent
|
||
if (executedFunctions.length > 0) {
|
||
ctx.logger.info('[inbox functions] 已有函数调用,忽略 silent 继续要求回复');
|
||
continue;
|
||
}
|
||
ctx.logger.info('[inbox functions] AI 判定无需回复,跳过回执');
|
||
return { reply: null, functionName: null, functionResult: null, thoughts, skip: true };
|
||
}
|
||
|
||
if (result.action === 'call' && result.function) {
|
||
const fnName = String(result.function).trim();
|
||
const params = result.params || {};
|
||
|
||
if (fnName === 'none' || fnName === 'stop') {
|
||
finalReply = result.reply || '已处理完成';
|
||
break;
|
||
}
|
||
|
||
lastFunctionName = fnName;
|
||
lastFunctionResult = await this.callFunction(fnName, params);
|
||
executedFunctions.push({ name: fnName, params, result: lastFunctionResult });
|
||
|
||
// 补充函数执行结果到思考记录
|
||
const lastThought = thoughts[thoughts.length - 1];
|
||
if (lastThought) lastThought.functionResult = lastFunctionResult;
|
||
ctx.logger.info(`[inbox functions] 执行 ${fnName}: ${JSON.stringify(lastFunctionResult)}`);
|
||
|
||
// 最后一轮强制输出
|
||
if (round === MAX_ROUNDS) {
|
||
finalReply = lastFunctionResult?.data?.message
|
||
|| lastFunctionResult?.data?.greeting
|
||
|| JSON.stringify(lastFunctionResult?.data || lastFunctionResult);
|
||
}
|
||
continue;
|
||
}
|
||
|
||
// 无法解析 → 尝试提取 reply
|
||
finalReply = result.reply || result.message || '抱歉,暂时无法处理您的请求';
|
||
break;
|
||
} catch (error) {
|
||
ctx.logger.warn(`[inbox functions] 第 ${round} 轮异常: ${error.message}, raw: ${raw}`);
|
||
|
||
// 不是 JSON → 当作文本回复
|
||
if (error instanceof SyntaxError && raw) {
|
||
finalReply = raw;
|
||
break;
|
||
}
|
||
|
||
// 最后一轮兜底
|
||
if (round === MAX_ROUNDS) {
|
||
finalReply = '抱歉,暂时无法处理您的请求,请稍后重试';
|
||
}
|
||
continue;
|
||
}
|
||
}
|
||
|
||
// 无回复的兜底
|
||
if (!finalReply && lastFunctionResult) {
|
||
finalReply = lastFunctionResult?.data?.message
|
||
|| lastFunctionResult?.data?.greeting
|
||
|| (lastFunctionResult?.success !== false ? '操作已完成' : lastFunctionResult?.error || '处理完成');
|
||
}
|
||
if (!finalReply) {
|
||
finalReply = '抱歉,暂时无法处理您的请求';
|
||
}
|
||
|
||
ctx.logger.info(`[inbox functions] 最终回复: ${finalReply}`);
|
||
return {
|
||
reply: finalReply,
|
||
functionName: lastFunctionName,
|
||
functionResult: lastFunctionResult,
|
||
thoughts,
|
||
};
|
||
}
|
||
}
|
||
|
||
module.exports = InboxFunctionsService;
|