'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} */ 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} */ 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} */ 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 || 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 ], 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 ], 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 ], 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 ], 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 ], 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 => ({ 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)及数量、收件人信息,使用手工建单流程创建发货单', 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 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('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} 函数执行结果。 */ 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} 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>} 历史消息列表。 */ 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', 'user_id', 'user_name', 'created_at' ], where: { warehouse_id: warehouseId, group_id: groupId, direction: { [Op.in]: [ 'inbound', 'outbound' ] }, }, order: [[ 'created_at', 'DESC' ]], limit: maxMessages, raw: true, }); if (messages.length === 0) return []; // 升序排列,附加上下文信息供 AI 判断真人接管 const blockedUsers = ctx.inboxContext?._blockedUserIds || new Set(); return messages.reverse().map(msg => { const u = String(msg.user_id || '').trim(); const name = String(msg.user_name || '').trim(); const isBlocked = u && blockedUsers.has(u); return { role: msg.direction === 'inbound' ? 'user' : 'assistant', content: msg.content || '', user_id: u || null, user_name: name || null, blocked: isBlocked, }; }); } 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 }; } // 拉取群历史(最多 10 条),同时注入 system prompt 和对话上下文 const history = await this.getConversationHistory({ parentId: data.parentId, maxMessages: 10, }); const historyContext = history.length > 0 ? history.map(h => { const tag = h.blocked ? '[已屏蔽]' : ''; return `[${h.role === 'user' ? h.user_name || h.user_id || '未知' : 'AI'}]${tag}: ${h.content}`; }).join('\n') : '(无历史)'; const MAX_ROUNDS = 5; const executedFunctions = []; const thoughts = []; let finalReply = null; let lastFunctionName = null; let lastFunctionResult = null; const systemPrompt = `你是一个 WMS 仓库管理系统的智能助手,支持多步推理。 已注册函数:\n${functionListText}\n === 群最近对话历史 === ${historyContext} === 对话历史中 [已屏蔽] 标记表示该用户已主动要求屏蔽(不想被 AI 打扰)。 如果 [已屏蔽] 用户发送了表示接手或正在处理的内容(如"我来处理""不用回复""稍等""我看看"),说明真人已接管 → 直接 silent。 你需要通过多轮调用来完成用户的复杂请求。每轮返回纯 JSON: 如果还需要调用函数获取信息: { "action": "call", "function": "函数名", "params": { "参数名": "参数值" }, "reason": "为什么需要这个函数" } 如果信息充足可以回复用户了: { "action": "reply", "reply": "最终回复(中文纯文本,禁止Markdown,200字以内,可适当使用\\n换行分隔信息)" } 如果消息无需回复(用户只是确认、道谢、告别或表示自己处理): { "action": "silent" } 真人接管判断规则(优先级最高,先于所有其他规则): - 如果历史中某条消息 blocked=true 的用户发送了与当前问题相关的内容(如"我来处理""稍等""我看看"等表示接手的话术),说明真人客服已介入处理 → 直接 silent - 如果 blocked 用户发送的内容与问题无关(如闲聊、询问其他事情),且当前用户仍在提问 → 正常回复当前用户 - 如果历史中只有当前用户的连续消息,没有其他用户介入 → 正常回复 一般约束: - 最多 ${MAX_ROUNDS} 轮函数调用,第 ${MAX_ROUNDS} 轮必须给出最终回复 - 同一函数不要重复调用(除非参数不同) - 如果函数执行失败,换其他方式或直接告知用户 - 回复使用中文纯文本,禁止 Markdown 语法,可用 \\n 换行提升可读性 - silent 仅用于:用户已确认收到消息且无新问题("好的""收到""OK""谢谢""知道了""好"),或用户表示告别/离场("再见""拜拜""88") - 以下情况严禁 silent,必须 reply:任何形式的提问(含"在吗""有人吗""在不在")、操作请求、函数执行完毕、自定义欢迎语"你好""嗨""hello"等首次问候 - 无法判断时,宁可回复也不要 silent - searchStock 返回多条结果时,必须列举让用户选择(告知 id/编码/名称/可用库存),不要擅自决定 - createOrder 失败时告知失败原因(库存不足/商品不存在等),不要重试同一商品 - searchStock 返回的 stock_available 为 0 时,提醒用户该商品无库存,建议选择其他商品 - searchStock/searchWarehouseStock 返回的 image_url 为图片URL数组(可能多张),has_images 为 true 时给出链接 - searchStock/searchWarehouseStock 返回的 barcodes 为关联条码,回复时可列出帮助核对 - searchStock/searchWarehouseStock 返回的管理标识 is_sn_mgmt/is_shelf_life_mgmt/is_batch_mgmt 分别表示SN管理/效期管理/批次管理 - searchStock/searchWarehouseStock 返回的 box_spec 为箱规(长宽高体积毛净重装箱数),packing_requirements 为打包要求,用户问及时告知 - searchStock/searchWarehouseStock 返回的 prohibited_type 为违禁品类型,非空时告知用户 - 用户说"第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') { // 已调用过操作类函数(非 recallHistory)→ 必须回复结果,不能 silent const actionFunctions = executedFunctions.filter(f => f.name !== 'recallHistory'); if (actionFunctions.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;