diff --git a/app/controller/inbox.js b/app/controller/inbox.js deleted file mode 100644 index 239cdc8..0000000 --- a/app/controller/inbox.js +++ /dev/null @@ -1,127 +0,0 @@ -'use strict'; - -const { Controller } = require('egg'); -const { toSuccess, toFailure } = require('../lib/api_response'); - -/** - * 站内信内部管理接口控制器。 - * 提供消息列表、详情、对话链、回信、重推、统计等管理功能。 - */ -class InboxController extends Controller { - /** - * 获取当前仓库上下文。 - * @return {{ warehouseId: number }} 仓库上下文。 - */ - getWarehouseContext() { - const { ctx } = this; - const warehouseId = Number(ctx.user && ctx.user.store_id); - - if (!Number.isFinite(warehouseId) || warehouseId <= 0) { - throw new Error('缺少仓库信息'); - } - - return { warehouseId }; - } - - /** - * 内部管理统一入口,分发到对应 service 方法。 - * @return {Promise} 无返回值,结果写入 ctx.body。 - */ - async index() { - const { ctx } = this; - - try { - const method = String(ctx.request.body && ctx.request.body.method || '').trim(); - if (!method || !method.startsWith('inbox.')) { - ctx.status = 400; - ctx.body = toFailure({ message: 'method 参数无效' }); - ctx.type = 'application/json'; - return; - } - - const action = method.replace('inbox.', ''); - const data = (ctx.request.body && ctx.request.body.data) || {}; - - let result; - - switch (action) { - case 'list': { - const { warehouseId } = this.getWarehouseContext(); - result = await ctx.service.inbox.index.list({ - warehouseId, - ...data, - }); - break; - } - - case 'detail': { - const { warehouseId } = this.getWarehouseContext(); - result = await ctx.service.inbox.index.detail({ - warehouseId, - id: data.id, - }); - break; - } - - case 'thread': { - const { warehouseId } = this.getWarehouseContext(); - result = await ctx.service.inbox.index.thread({ - warehouseId, - id: data.id, - }); - break; - } - - case 'reply': { - const { warehouseId } = this.getWarehouseContext(); - result = await ctx.service.inbox.index.reply({ - warehouseId, - parentId: data.parentId, - targetChannel: data.targetChannel, - targetUrl: data.targetUrl, - targetType: data.targetType, - refCode: data.refCode, - extData: data.extData, - flags: data.flags, - }); - break; - } - - case 'retry': { - const { warehouseId } = this.getWarehouseContext(); - result = await ctx.service.inbox.index.retry({ - warehouseId, - id: data.id, - }); - break; - } - - case 'stats': { - const { warehouseId } = this.getWarehouseContext(); - result = await ctx.service.inbox.index.stats({ - warehouseId, - direction: data.direction, - }); - break; - } - - default: - ctx.status = 400; - ctx.body = toFailure({ message: `不支持的 inbox 方法: ${action}` }); - ctx.type = 'application/json'; - return; - } - - ctx.status = 200; - ctx.body = toSuccess(result, 'ok'); - ctx.type = 'application/json'; - } catch (error) { - const message = String(error && error.message || '请求失败'); - ctx.status = 500; - ctx.body = toFailure({ message: `站内信错误: ${message}` }); - ctx.type = 'application/json'; - } - } -} - -module.exports = InboxController; diff --git a/app/model/inbox_block.js b/app/model/inbox_block.js new file mode 100644 index 0000000..4baa2dd --- /dev/null +++ b/app/model/inbox_block.js @@ -0,0 +1,45 @@ +'use strict'; + +/** + * 站内信屏蔽表 Model。 + * 记录被屏蔽的群/用户,后续来自该群+用户的消息不再触发 AI 回信。 + * group_name 和 user_name 均为 NULL 时表示全局屏蔽(预留)。 + * + * @param {Object} app Egg.js Application 实例。 + * @return {Object} Sequelize Model 定义。 + */ +module.exports = app => { + const { BIGINT, STRING, DATE } = app.Sequelize; + + const InboxBlock = app.model.define('inbox_block', { + id: { + type: BIGINT.UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + group_name: { + type: STRING(100), + allowNull: true, + comment: '群名称', + }, + user_name: { + type: STRING(100), + allowNull: true, + comment: '用户名称', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + }, { + tableName: 'wms_inbox_block', + timestamps: false, + comment: '站内信屏蔽表', + }); + + return InboxBlock; +}; diff --git a/app/model/inbox_group.js b/app/model/inbox_group.js new file mode 100644 index 0000000..3b5dc47 --- /dev/null +++ b/app/model/inbox_group.js @@ -0,0 +1,106 @@ +'use strict'; + +/** + * 站内信群表 Model。 + * 记录与 WMS 交互的群信息,支持按仓库屏蔽。 + * + * @param {Object} app Egg.js Application 实例。 + * @return {Object} Sequelize Model 定义。 + */ +module.exports = app => { + const { BIGINT, STRING, TINYINT, DATE } = app.Sequelize; + + const InboxGroup = app.model.define('inbox_group', { + id: { + type: BIGINT.UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + group_name: { + type: STRING(100), + allowNull: false, + comment: '群名称', + }, + group_id: { + type: STRING(100), + allowNull: true, + comment: '外部群ID', + }, + warehouse_id: { + type: BIGINT.UNSIGNED, + allowNull: false, + comment: '所属仓库ID', + }, + store_id: { + type: BIGINT.UNSIGNED, + allowNull: true, + comment: '关联货主ID', + }, + group_type: { + type: app.Sequelize.ENUM('store', 'warehouse', 'express'), + allowNull: true, + comment: '群类型: store=货主 warehouse=仓库 express=快递', + }, + sub_type: { + type: STRING(20), + allowNull: true, + comment: '群子类型: 货主(售后/财务/收货) 仓库(收货/普通/生产) 快递(揽收/售后)', + }, + source_type: { + type: STRING(20), + allowNull: true, + comment: '来源类型:im / api / system', + }, + source_extra: { + type: STRING(100), + allowNull: true, + comment: '来源附加信息', + }, + is_blocked: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否屏蔽 0=否 1=是', + }, + ai_enabled: { + type: TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否启用AI自动回复: 0=关闭 1=开启', + }, + express_interfaces: { + type: STRING(500), + allowNull: true, + comment: '快递接口ID列表,逗号分隔(仅群类型为 express 时生效)', + }, + system_express_code: { + type: STRING(50), + allowNull: true, + comment: '系统快递编码(仅群类型为 express 时必填)', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }, { + tableName: 'wms_inbox_group', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + deletedAt: 'deleted_at', + paranoid: true, + comment: '站内信群表', + }); + + return InboxGroup; +}; diff --git a/app/model/inbox_message.js b/app/model/inbox_message.js index 6a43ce1..73873b5 100644 --- a/app/model/inbox_message.js +++ b/app/model/inbox_message.js @@ -77,34 +77,30 @@ module.exports = app => { }, comment: '目标类型:im / api / webhook', }, - target_channel: { - type: STRING(50), - allowNull: false, - validate: { - notEmpty: { - msg: 'target_channel 不能为空', - }, - }, - comment: '目标渠道:wecom / dingtalk / feishu / warehouse_api / webhook', - }, - target_url: { - type: STRING(500), - allowNull: false, - validate: { - notEmpty: { - msg: 'target_url 不能为空', - }, - len: { - args: [ 1, 500 ], - msg: 'target_url 长度应在1-500个字符之间', - }, - }, - comment: '推送目标URL(IM Bot webhook 地址 / API 回调地址)', - }, - ref_code: { + group_name: { type: STRING(100), allowNull: true, - comment: '外部引用编码,推送/回执时原样携带', + comment: '群名称(外部传入)', + }, + user_name: { + type: STRING(100), + allowNull: true, + comment: '用户名称(外部传入)', + }, + group_id: { + type: STRING(100), + allowNull: true, + comment: '外部群ID', + }, + user_id: { + type: STRING(100), + allowNull: true, + comment: '外部用户ID', + }, + content: { + type: app.Sequelize.TEXT, + allowNull: true, + comment: '消息正文/摘要,用于列表展示和关键词搜索', }, ext_data: { type: JSON_TYPE, @@ -116,6 +112,11 @@ module.exports = app => { allowNull: true, comment: '处理标记,外部传入控制WMS处理行为', }, + ai_thoughts: { + type: JSON_TYPE, + allowNull: true, + comment: 'AI 多轮推理思考过程 [{round,action,function,params,reason,functionResult}]', + }, push_status: { type: TINYINT(4), allowNull: false, diff --git a/app/model/store_warehouse.js b/app/model/store_warehouse.js index 52136f9..5e7a40c 100644 --- a/app/model/store_warehouse.js +++ b/app/model/store_warehouse.js @@ -734,7 +734,14 @@ module.exports = app => { return normalizePolicyConfig(value, options); }; - // 统一构造复合键语义的 where 条件,避免 service 侧重复散落。 + /** + * 统一构造复合键语义的 where 条件,避免 service 侧重复散落。 + * @param {Object} options 配置项 + * @param {number} [options.warehouseId] 仓库ID + * @param {number} [options.storeId] 货主ID + * @param {number} [options.warehouseUseStatus=1] 仓库侧使用状态过滤,默认仅查可用合约 + * @return {Object} 组装后的 where 条件对象 + */ StoreWarehouse.buildScopedWhere = function(options = {}) { const { warehouseId, @@ -757,7 +764,16 @@ module.exports = app => { return where; }; - // 统一构造 StockWarehouse -> StoreWarehouse(include as=store_stock) 的 include。 + /** + * 统一构造 StockWarehouse -> StoreWarehouse(include as=store_stock) 的 include。 + * @param {Object} options 配置项 + * @param {number} [options.warehouseId] 仓库ID + * @param {number} [options.storeId] 货主ID + * @param {boolean} [options.required=false] 是否使用 INNER JOIN + * @param {number} [options.warehouseUseStatus=1] 仓库侧使用状态过滤,默认仅查可用合约 + * @param {Array} [options.attributes] 需要查询的字段 + * @return {Object} Sequelize include 对象 + */ StoreWarehouse.buildStoreStockInclude = function(options = {}) { const { warehouseId, diff --git a/app/router.js b/app/router.js index cf6fb6b..b437fe3 100644 --- a/app/router.js +++ b/app/router.js @@ -67,7 +67,4 @@ module.exports = app => { router.get('/testSendData', controller.home.testSendData); // IM交互入口 router.post('/im', controller.im.index); - - // 站内信内部管理接口 - router.post('/inbox', controller.inbox.index); }; diff --git a/app/service/inbox/dispatch/base.js b/app/service/inbox/dispatch/base.js deleted file mode 100644 index eb6ff61..0000000 --- a/app/service/inbox/dispatch/base.js +++ /dev/null @@ -1,118 +0,0 @@ -'use strict'; - -const Service = require('egg').Service; -const apiSignLib = require('../../../lib/api_sign'); - -const WAREHOUSE_INTERFACE_TYPE_ID = 3; -const DISPATCH_TIMEOUT_MS = 10000; // 10s 超时 - -/** - * 统一出站基类,所有渠道 dispatch 继承此类。 - * 统一处理:查密钥、签名、发 HTTP。 - * 子类只需实现 push(record) 方法,关注消息格式转换。 - */ -class OutboundBase extends Service { - /** - * 获取仓库 ApiApp 密钥配置(IM 渠道无需签名,返回 null)。 - * @param {number} warehouseId 仓库ID。 - * @return {Promise} ApiApp 配置对象,含 appKey / selfAppSecret / warehouseId。 - */ - async getApiApp(warehouseId) { - const { ctx } = this; - try { - // 通过仓库ID查找该仓库的 warehouse 类型 ApiApp - const apiApp = await ctx.model.ApiApp.findOne({ - attributes: [ 'id', 'self_app_key', 'self_app_secret', 'is_enabled', 'interface_type_id', 'warehouse_id' ], - where: { - warehouse_id: warehouseId, - interface_type_id: WAREHOUSE_INTERFACE_TYPE_ID, - is_enabled: 1, - }, - raw: true, - }); - - if (!apiApp || !apiApp.self_app_secret) { - return null; - } - - return { - appKey: apiApp.self_app_key, - selfAppSecret: apiApp.self_app_secret, - warehouseId: Number(apiApp.warehouse_id), - }; - } catch (error) { - ctx.logger.warn(`[inbox dispatch] 获取仓库 ApiApp 失败: ${error.message}`); - return null; - } - } - - /** - * 生成 MD5 签名,返回带签名后的完整 URL。 - * @param {string} url 原始目标URL。 - * @param {*} body 请求体。 - * @param {Object} secret ApiApp 密钥对象,含 appKey / selfAppSecret。 - * @return {string} 带签名的完整URL。 - */ - signRequest(url, body, secret) { - const timestamp = Math.floor(Date.now() / 1000); - const query = { - app_key: secret.appKey, - timestamp, - }; - - const { sign } = apiSignLib.signRequest({ - query, - body, - selfAppSecret: secret.selfAppSecret, - }); - - const separator = url.includes('?') ? '&' : '?'; - return `${url}${separator}app_key=${encodeURIComponent(query.app_key)}×tamp=${timestamp}&sign=${encodeURIComponent(sign)}`; - } - - /** - * 统一 HTTP POST 发送。 - * @param {string} url 目标URL。 - * @param {*} body 请求体。 - * @param {Object} [options] 额外选项。 - * @param {Object} [options.headers] 自定义请求头。 - * @return {Promise<{status: number, data: *}>} 响应结果。 - */ - async post(url, body, options = {}) { - const { ctx } = this; - const headers = { - 'Content-Type': 'application/json', - ...(options.headers || {}), - }; - - try { - const response = await ctx.curl(url, { - method: 'POST', - dataType: 'json', - contentType: 'json', - data: body, - headers, - timeout: DISPATCH_TIMEOUT_MS, - }); - - return { - status: response.status, - data: response.data, - }; - } catch (error) { - throw new Error(`HTTP 推送失败: ${error.message}`); - } - } - - /** - * 子类必须实现的推送方法。 - * @param {Object} record 消息记录(Sequelize Model 实例),子类按需使用。 - * @throws {Error} 子类未实现时抛出。 - */ - async push(record) { - const id = record && record.id; - throw new Error(`子类必须实现 push(record) 方法,当前消息ID: ${id || '未知'}`); - } -} - -module.exports = OutboundBase; diff --git a/app/service/inbox/dispatch/dingtalk.js b/app/service/inbox/dispatch/dingtalk.js deleted file mode 100644 index aab3df4..0000000 --- a/app/service/inbox/dispatch/dingtalk.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -const OutboundBase = require('./base'); - -/** - * 钉钉 Bot 渠道出站实现。 - * 推送 Markdown 消息到钉钉机器人 webhook。 - */ -class DingtalkDispatch extends OutboundBase { - /** - * 通过钉钉 Bot 推送消息。 - * @param {Object} record 消息记录(Sequelize Model 实例)。 - * @return {Promise<{status: number, data: *}>} 推送响应。 - */ - async push(record) { - const { ctx } = this; - - const extData = record.ext_data || {}; - const title = extData.title || '新消息通知'; - const text = extData.content || extData.text || `消息:${record.ref_code || record.ext_id}`; - - const body = { - msgtype: 'markdown', - markdown: { - title, - text: typeof text === 'string' ? text : JSON.stringify(text), - }, - }; - - ctx.logger.info(`[inbox dingtalk] 推送消息 ext_id=${record.ext_id} url=${record.target_url}`); - return await this.post(record.target_url, body); - } -} - -module.exports = DingtalkDispatch; diff --git a/app/service/inbox/dispatch/feishu.js b/app/service/inbox/dispatch/feishu.js deleted file mode 100644 index 26b5358..0000000 --- a/app/service/inbox/dispatch/feishu.js +++ /dev/null @@ -1,60 +0,0 @@ -'use strict'; - -const OutboundBase = require('./base'); - -/** - * 飞书 Bot 渠道出站实现。 - * 推送交互式卡片消息到飞书机器人 webhook。 - */ -class FeishuDispatch extends OutboundBase { - /** - * 通过飞书 Bot 推送消息。 - * @param {Object} record 消息记录(Sequelize Model 实例)。 - * @return {Promise<{status: number, data: *}>} 推送响应。 - */ - async push(record) { - const { ctx } = this; - - const extData = record.ext_data || {}; - const title = extData.title || '新消息通知'; - const content = extData.content || extData.text || `消息:${record.ref_code || record.ext_id}`; - - const body = { - msg_type: 'interactive', - card: { - header: { - title: { - tag: 'plain_text', - content: title, - }, - }, - elements: [ - { - tag: 'div', - text: { - tag: 'lark_md', - content: typeof content === 'string' ? content : JSON.stringify(content), - }, - }, - { - tag: 'hr', - }, - { - tag: 'note', - elements: [ - { - tag: 'plain_text', - content: `编号: ${record.ref_code || record.ext_id}`, - }, - ], - }, - ], - }, - }; - - ctx.logger.info(`[inbox feishu] 推送消息 ext_id=${record.ext_id} url=${record.target_url}`); - return await this.post(record.target_url, body); - } -} - -module.exports = FeishuDispatch; diff --git a/app/service/inbox/dispatch/webhook.js b/app/service/inbox/dispatch/webhook.js deleted file mode 100644 index 4df3812..0000000 --- a/app/service/inbox/dispatch/webhook.js +++ /dev/null @@ -1,44 +0,0 @@ -'use strict'; - -const OutboundBase = require('./base'); - -/** - * Webhook 渠道出站实现。 - * 直接 HTTP POST 推送 JSON 到目标 webhook URL。 - */ -class WebhookDispatch extends OutboundBase { - /** - * 通过 webhook 渠道推送消息。 - * @param {Object} record 消息记录(Sequelize Model 实例)。 - * @return {Promise<{status: number, data: *}>} 推送响应。 - */ - async push(record) { - const { ctx } = this; - - const body = { - ref_code: record.ref_code, - ext_data: record.ext_data, - message_id: record.ext_id, - direction: record.direction, - source_type: record.source_type, - created_at: record.created_at, - }; - - let targetUrl = record.target_url; - - // API 类型需要签名 - if (record.target_type === 'api') { - const apiApp = await this.getApiApp(record.warehouse_id); - if (apiApp) { - targetUrl = this.signRequest(targetUrl, body, apiApp); - } else { - ctx.logger.warn(`[inbox webhook] 仓库 ${record.warehouse_id} 没有可用 ApiApp,跳过签名`); - } - } - - ctx.logger.info(`[inbox webhook] 推送消息 ext_id=${record.ext_id} url=${targetUrl}`); - return await this.post(targetUrl, body); - } -} - -module.exports = WebhookDispatch; diff --git a/app/service/inbox/dispatch/wecom.js b/app/service/inbox/dispatch/wecom.js deleted file mode 100644 index 09ff283..0000000 --- a/app/service/inbox/dispatch/wecom.js +++ /dev/null @@ -1,33 +0,0 @@ -'use strict'; - -const OutboundBase = require('./base'); - -/** - * 企微 Bot 渠道出站实现。 - * 推送 Markdown 消息到企业微信机器人 webhook。 - */ -class WecomDispatch extends OutboundBase { - /** - * 通过企微 Bot 推送消息。 - * @param {Object} record 消息记录(Sequelize Model 实例)。 - * @return {Promise<{status: number, data: *}>} 推送响应。 - */ - async push(record) { - const { ctx } = this; - - const extData = record.ext_data || {}; - const content = extData.content || extData.text || `新消息通知:${record.ref_code || record.ext_id}`; - - const body = { - msgtype: 'markdown', - markdown: { - content: typeof content === 'string' ? content : JSON.stringify(content), - }, - }; - - ctx.logger.info(`[inbox wecom] 推送消息 ext_id=${record.ext_id} url=${record.target_url}`); - return await this.post(record.target_url, body); - } -} - -module.exports = WecomDispatch; diff --git a/app/service/inbox/functions.js b/app/service/inbox/functions.js new file mode 100644 index 0000000..650d65a --- /dev/null +++ b/app/service/inbox/functions.js @@ -0,0 +1,1060 @@ +'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 + || 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} 函数执行结果。 + */ + 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', '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; diff --git a/app/service/inbox/index.js b/app/service/inbox/index.js index c20b065..e2cfd53 100644 --- a/app/service/inbox/index.js +++ b/app/service/inbox/index.js @@ -9,13 +9,14 @@ const crypto = require('crypto'); */ class InboxService extends Service { /** - * 消息列表(按仓库/状态/方向筛选,分页)。 + * 消息列表(按仓库/状态/方向/群筛选,分页)。 * @param {Object} params 查询参数。 * @param {number} params.warehouseId 仓库ID(必填,服务端上下文注入)。 + * @param {string} [params.groupId] 按群ID筛选(精确匹配,用于群消息列表)。 * @param {string} [params.direction] 消息方向筛选:inbound / outbound。 * @param {number} [params.pushStatus] 推送状态筛选:0/1/2/3。 * @param {string} [params.targetChannel] 目标渠道筛选。 - * @param {string} [params.keyword] 关键词搜索(ext_id / ref_code)。 + * @param {string} [params.keyword] 关键词搜索(ext_id / content)。 * @param {number} [params.page=1] 页码。 * @param {number} [params.pageSize=20] 每页数量。 * @return {Promise<{list: Array, pagination: Object}>} 分页结果。 @@ -38,6 +39,12 @@ class InboxService extends Service { deleted_at: null, }; + // 按群ID筛选 + if (params.groupId && typeof params.groupId === 'string') { + const gid = params.groupId.trim(); + if (gid) where.group_id = gid; + } + if (params.direction && [ 'inbound', 'outbound' ].includes(params.direction)) { where.direction = params.direction; } @@ -49,15 +56,11 @@ class InboxService extends Service { } } - if (params.targetChannel && typeof params.targetChannel === 'string') { - where.target_channel = params.targetChannel.trim(); - } - if (params.keyword && typeof params.keyword === 'string') { const keyword = `%${params.keyword.trim()}%`; where[Op.or] = [ { ext_id: { [Op.like]: keyword } }, - + { content: { [Op.like]: keyword } }, ]; } @@ -188,13 +191,11 @@ class InboxService extends Service { } /** - * 系统回信:写入 outbound 记录 + 异步推送。 + * 系统回信:写入 outbound 记录。 * @param {Object} data 回信数据。 * @param {number} data.warehouseId 仓库ID(必填,服务端上下文注入)。 * @param {number} data.parentId 原消息ID。 - * @param {string} data.targetChannel 目标渠道。 - * @param {string} data.targetUrl 推送目标URL。 - * @param {string} [data.refCode] 引用编码。 + * @param {string} [data.content] 消息正文。 * @param {Object} [data.extData] 透传数据。 * @param {Object} [data.flags] 处理标记。 * @return {Promise} 回信结果。 @@ -232,10 +233,7 @@ class InboxService extends Service { parent_id: parentId, source_type: 'system', source_extra: null, - target_type: data.targetType || parent.target_type, - target_channel: data.targetChannel, - target_url: data.targetUrl, - ref_code: data.refCode || parent.ref_code, + content: data.content || null, ext_data: data.extData || parent.ext_data, flags: data.flags || {}, }); @@ -244,61 +242,7 @@ class InboxService extends Service { } /** - * 手动重推。 - * @param {Object} params 重推参数。 - * @param {number} params.warehouseId 仓库ID(必填)。 - * @param {number} params.id 消息ID。 - * @return {Promise} 重推结果。 - */ - async retry(params = {}) { - const { ctx } = this; - const { InboxMessage } = ctx.model; - - const warehouseId = Number(params.warehouseId); - const id = Number(params.id); - - if (!Number.isFinite(warehouseId) || warehouseId <= 0) { - throw new Error('warehouseId 无效'); - } - if (!Number.isFinite(id) || id <= 0) { - throw new Error('消息ID无效'); - } - - const record = await InboxMessage.findOne({ - where: { id, warehouse_id: warehouseId }, - }); - - if (!record) { - throw new Error('消息不存在或无权访问'); - } - - if (![ 3 ].includes(record.push_status)) { - throw new Error('仅失败状态的消息可以手动重推'); - } - - // 重置为待推送状态,由异步推送接管 - await record.update({ - push_status: 0, - push_started_at: null, - }); - - // 触发异步推送 - setImmediate(() => { - ctx.service.inbox.receiver.asyncPush(record, 0).catch(err => { - ctx.logger.error(`[inbox] 手动重推异常 ext_id=${record.ext_id}: ${err.message}`); - }); - }); - - return { - ok: true, - id: record.id, - ext_id: record.ext_id, - message: '已触发重推', - }; - } - - /** - * 推送统计(按仓库 + 状态汇总)。 + * 推送统计(按仓库 + 方向汇总)。 * @param {Object} params 统计参数。 * @param {number} params.warehouseId 仓库ID(必填)。 * @param {string} [params.direction] 消息方向筛选。 diff --git a/app/service/inbox/message.js b/app/service/inbox/message.js new file mode 100644 index 0000000..f572f26 --- /dev/null +++ b/app/service/inbox/message.js @@ -0,0 +1,335 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * 站内信消息查询/管理服务。 + * 提供消息列表、详情、对话链、回复、统计等管理功能。 + */ +class InboxMessageService extends Service { + /** + * 消息列表(多条件筛选,分页)。 + * 时间字段使用 app.formatDate 统一格式化输出。 + * + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID(必填,服务端上下文注入)。 + * @param {string|string[]} [params.storeId] 货主ID筛选,支持逗号分隔字符串或数组。 + * @param {string|string[]} [params.groupId] 群ID筛选,支持逗号分隔字符串或数组。 + * @param {string} [params.groupName] 群名称模糊搜索。 + * @param {string} [params.userName] 用户名模糊搜索。 + * @param {string} [params.content] 正文模糊搜索。 + * @param {string} [params.sourceType] 来源类型:im / api / system。 + * @param {string} [params.direction] 消息方向筛选:inbound / outbound。 + * @param {number} [params.pushStatus] 推送状态筛选:0/1/2/3。 + * @param {number} [params.page=1] 页码。 + * @param {number} [params.pageSize=20] 每页数量。 + * @return {Promise<{list: Array, pagination: Object}>} 分页结果。 + */ + async list(params = {}) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + const { InboxMessage } = ctx.model; + + const warehouseId = Number(params.warehouseId); + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw new Error('warehouseId 无效'); + } + + const page = Math.max(1, Number(params.page) || 1); + const pageSize = Math.min(200, Math.max(1, Number(params.pageSize) || 20)); + + const where = { + warehouse_id: warehouseId, + deleted_at: null, + }; + + // 货主ID:支持多选(逗号分隔字符串或数组) + const storeIds = this._normalizeIds(params.storeId); + if (storeIds.length > 0) { + where.store_id = { [Op.in]: storeIds }; + } + + // 群ID:支持多选(逗号分隔字符串或数组) + const groupIds = this._normalizeStrings(params.groupId); + if (groupIds.length > 0) { + where.group_id = { [Op.in]: groupIds }; + } + + // 群名称模糊搜索 + const groupName = String(params.groupName || '').trim(); + if (groupName) { + where.group_name = { [Op.like]: `%${groupName}%` }; + } + + // 用户名模糊搜索 + const userName = String(params.userName || '').trim(); + if (userName) { + where.user_name = { [Op.like]: `%${userName}%` }; + } + + // 正文模糊搜索 + const content = String(params.content || '').trim(); + if (content) { + where.content = { [Op.like]: `%${content}%` }; + } + + // 来源类型筛选 + const VALID_SOURCE_TYPES = [ 'im', 'api', 'system' ]; + const sourceType = String(params.sourceType || '').trim(); + if (sourceType && VALID_SOURCE_TYPES.includes(sourceType)) { + where.source_type = sourceType; + } + + // 方向筛选 + if (params.direction && [ 'inbound', 'outbound' ].includes(params.direction)) { + where.direction = params.direction; + } + + // 推送状态筛选 + if (params.pushStatus !== undefined && params.pushStatus !== null && params.pushStatus !== '') { + const status = Number(params.pushStatus); + if ([ 0, 1, 2, 3 ].includes(status)) { + where.push_status = status; + } + } + + const { count: total, rows } = await InboxMessage.findAndCountAll({ + attributes: { + exclude: [ 'ext_data', 'push_response', 'target_channel' ], + }, + where, + order: [[ 'created_at', 'DESC' ]], + offset: (page - 1) * pageSize, + limit: pageSize, + }); + + // 批量查货主名称 + const storeIdsInResult = [ ...new Set(rows.map(r => r.store_id).filter(Boolean)) ]; + const storeNameMap = {}; + if (storeIdsInResult.length > 0) { + const stores = await ctx.model.Store.findAll({ + attributes: [ 'id', 'company_name' ], + where: { id: { [Op.in]: storeIdsInResult } }, + raw: true, + }); + for (const s of stores) { + storeNameMap[s.id] = s.company_name || ''; + } + } + + const formatDate = ctx.app.formatDate; + const list = rows.map(row => { + const obj = row && typeof row.toJSON === 'function' ? row.toJSON() : row; + return { + ...obj, + store_name: storeNameMap[obj.store_id] || '', + created_at: obj.created_at ? formatDate(obj.created_at) : '', + updated_at: obj.updated_at ? formatDate(obj.updated_at) : '', + pushed_at: obj.pushed_at ? formatDate(obj.pushed_at) : '', + }; + }); + + return { + list, + pagination: { + page, + pageSize, + total, + totalPages: Math.ceil(total / pageSize), + hasPrevious: page > 1, + hasNext: page * pageSize < total, + }, + }; + } + + /** + * 将入参统一为数字ID数组。 + * 支持逗号分隔字符串 "1,2,3" 或数组 [1,2,3]。 + * @param {string|string[]|number[]|undefined} val 入参。 + * @return {number[]} 去重后的数字数组。 + */ + _normalizeIds(val) { + if (val === undefined || val === null) return []; + const arr = Array.isArray(val) ? val : String(val).split(','); + return [ ...new Set(arr.map(Number).filter(v => Number.isFinite(v) && v > 0)) ]; + } + + /** + * 将入参统一为字符串数组(去重去空)。 + * @param {string|string[]|undefined} val 入参。 + * @return {string[]} 去重后的非空字符串数组。 + */ + _normalizeStrings(val) { + if (val === undefined || val === null) return []; + const arr = Array.isArray(val) ? val : String(val).split(','); + return [ ...new Set(arr.map(String).map(s => s.trim()).filter(Boolean)) ]; + } + + /** + * 消息详情(含 push_response)。 + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID(必填)。 + * @param {number} params.id 消息ID。 + * @return {Promise} 消息详情。 + */ + async detail(params = {}) { + const { ctx } = this; + const { InboxMessage } = ctx.model; + + const warehouseId = Number(params.warehouseId); + const id = Number(params.id); + + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw new Error('warehouseId 无效'); + } + if (!Number.isFinite(id) || id <= 0) { + throw new Error('消息ID无效'); + } + + const record = await InboxMessage.findOne({ + where: { id, warehouse_id: warehouseId, deleted_at: null }, + }); + + if (!record) { + throw new Error('消息不存在或无权访问'); + } + + return record; + } + + /** + * 对话链查询(原消息 + 所有回信),按 parent_id 递归。 + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID(必填)。 + * @param {number} params.id 消息ID。 + * @return {Promise} 对话链列表。 + */ + async thread(params = {}) { + const { ctx } = this; + const { InboxMessage } = ctx.model; + + const warehouseId = Number(params.warehouseId); + const id = Number(params.id); + + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw new Error('warehouseId 无效'); + } + if (!Number.isFinite(id) || id <= 0) { + throw new Error('消息ID无效'); + } + + // 查找根消息 + const root = await InboxMessage.findOne({ + where: { id, warehouse_id: warehouseId }, + }); + + if (!root) { + throw new Error('消息不存在或无权访问'); + } + + // 收集对话链:从根到叶 + const MAX_THREAD_DEPTH = 50; + const thread = [ root ]; + const visited = new Set([ root.id ]); + + // 查找所有回信(以 root.id 为 parent_id) + const replies = await InboxMessage.findAll({ + where: { + warehouse_id: warehouseId, + parent_id: root.id, + deleted_at: null, + }, + order: [[ 'created_at', 'ASC' ]], + }); + + for (const reply of replies) { + if (!visited.has(reply.id) && thread.length < MAX_THREAD_DEPTH) { + visited.add(reply.id); + thread.push(reply); + } + } + + // 如果当前消息不是根(有 parent_id),也向上查找原消息 + if (root.parent_id) { + const parent = await InboxMessage.findOne({ + where: { + id: root.parent_id, + warehouse_id: warehouseId, + deleted_at: null, + }, + }); + + if (parent && !visited.has(parent.id) && thread.length < MAX_THREAD_DEPTH) { + visited.add(parent.id); + thread.unshift(parent); + } + } + + return thread; + } + + /** + * 推送统计(按仓库 + 方向汇总)。 + * @param {Object} params 统计参数。 + * @param {number} params.warehouseId 仓库ID(必填)。 + * @return {Promise} 统计结果。 + */ + async stats(params = {}) { + const { ctx } = this; + const { InboxMessage } = ctx.model; + const { Op } = ctx.app.Sequelize; + + const warehouseId = Number(params.warehouseId); + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw new Error('warehouseId 无效'); + } + + const where = { + warehouse_id: warehouseId, + }; + + if (params.direction && [ 'inbound', 'outbound' ].includes(params.direction)) { + where.direction = params.direction; + } + + // 按方向统计 + const directionStats = await InboxMessage.findAll({ + attributes: [ + 'direction', + [ ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'count' ], + ], + where, + group: [ 'direction' ], + raw: true, + }); + + // 按推送状态统计 + const statusStats = await InboxMessage.findAll({ + attributes: [ + 'push_status', + [ ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'count' ], + ], + where, + group: [ 'push_status' ], + raw: true, + }); + + // 最近24小时统计 + const recentWhere = { + ...where, + created_at: { + [Op.gte]: new Date(Date.now() - 24 * 60 * 60 * 1000), + }, + }; + + const recentCount = await InboxMessage.count({ where: recentWhere }); + + return { + total_by_direction: directionStats, + total_by_status: statusStats, + recent_24h_count: recentCount, + }; + } +} + +module.exports = InboxMessageService; diff --git a/app/service/inbox/processor.js b/app/service/inbox/processor.js new file mode 100644 index 0000000..c256ea6 --- /dev/null +++ b/app/service/inbox/processor.js @@ -0,0 +1,570 @@ +'use strict'; + +const Service = require('egg').Service; + +const WAREHOUSE_INTERFACE_TYPE_ID = 3; +const CALLBACK_TIMEOUT_MS = 10000; // 回执超时 10s + +/** + * 站内信内容处理器。 + * 负责解析入站消息正文,按 source_type 分流处理, + * 将 warehouse_id 和 store_id 挂载到 ctx 上下文供下游使用。 + */ +class InboxProcessorService extends Service { + /** + * 处理入站消息内容。 + * 解析 content 后将 warehouse_id 和 store_id 写入 ctx 上下文。 + * + * @param {Object} data 入站消息数据。 + * @param {string} data.content 消息正文。 + * @param {number} [data.warehouse_id] 仓库ID(优先使用显式传入值)。 + * @param {number} [data.store_id] 货主ID(优先使用显式传入值)。 + * @return {Promise<{warehouse_id: number|null, store_id: number|null, content: string}>} 处理结果。 + */ + async process(data = {}) { + const { ctx } = this; + + const content = String(data.content || '').trim(); + if (!content) { + throw new Error('消息正文 content 不能为空'); + } + + // warehouse_id:优先取显式传入,否则尝试从 content 中解析 + let warehouseId = data.warehouse_id != null ? Number(data.warehouse_id) : null; + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + warehouseId = this.extractWarehouseId(content) || this.getWarehouseIdFromContext(); + } + + // store_id:优先取显式传入,否则尝试从 content 中解析 + let storeId = data.store_id != null ? Number(data.store_id) : null; + if (!Number.isFinite(storeId) || storeId <= 0) { + storeId = this.extractStoreId(content) || this.getStoreIdFromContext(); + } + + // 写入 ctx 上下文,供下游使用 + if (!ctx.inboxContext) { + ctx.inboxContext = {}; + } + ctx.inboxContext.warehouse_id = warehouseId || null; + ctx.inboxContext.store_id = storeId || null; + ctx.inboxContext.group_name = data.group_name || null; + ctx.inboxContext.user_name = data.user_name || null; + ctx.inboxContext.group_id = data.group_id || null; + ctx.inboxContext.user_id = data.user_id || null; + + ctx.logger.info( + '[inbox processor] 内容处理完成 ' + + `warehouse_id=${ctx.inboxContext.warehouse_id} ` + + `store_id=${ctx.inboxContext.store_id} ` + + `content_length=${content.length}` + ); + + return { + warehouse_id: ctx.inboxContext.warehouse_id, + store_id: ctx.inboxContext.store_id, + content, + }; + } + + /** + * API 来源消息异步回执。 + * 处理消息正文后,向仓库 ApiApp 回调地址 POST 确认回执。 + * 回执内容为"收到",ext_data 原路带回。 + * 异步执行,不阻塞入站响应。 + * + * @param {Object} data 入站消息数据。 + * @param {number} data.warehouse_id 仓库ID。 + * @param {number} [data.store_id] 货主ID。 + * @param {number} [data.parent_id] 入站消息记录ID(回执的 parent_id)。 + * @param {Object} [data.ext_data] 原始透传数据。 + * @param {string} [data.ext_id] 外部消息ID。 + * @param {string} [data.content] 消息正文。 + * @return {Promise} 无返回值,异常仅记日志不抛出。 + */ + async handleApiMessage(data = {}) { + const { ctx } = this; + const { InboxMessage } = ctx.model; + + const warehouseId = Number(data.warehouse_id) || 0; + const extId = String(data.ext_id || ''); + const parentId = Number(data.parent_id) || null; + + try { + // 1. 处理消息正文,挂载上下文 + await this.process(data); + + // 2. 屏蔽检查 + const isBlocked = await this.isBlocked(); + if (isBlocked) { + ctx.logger.info(`[inbox processor] 已屏蔽,跳过回执 ext_id=${extId}`); + return; + } + + // 3. 绑群码识别:消息匹配"授权:CODE"时执行绑群 + const bindHandled = await this.tryBindGroup(data); + if (bindHandled) return; + + // 4. 群未绑定货主则跳过 AI 解析 + const storeId = Number(ctx.inboxContext?.store_id || 0); + if (!storeId) { + ctx.logger.info(`[inbox processor] 群未绑定货主,跳过 AI ext_id=${extId}`); + return; + } + + // 4.1 注入群的 group_type / sub_type / ai_enabled 到上下文 + if (!ctx.inboxContext.group_type || !ctx.inboxContext.sub_type || ctx.inboxContext.ai_enabled === undefined) { + try { + const groupId = String(ctx.inboxContext.group_id || '').trim(); + if (groupId) { + const group = await ctx.model.InboxGroup.findOne({ + attributes: [ 'group_type', 'sub_type', 'ai_enabled' ], + where: { group_id: groupId, warehouse_id: warehouseId }, + raw: true, + }); + if (group) { + ctx.inboxContext.group_type = group.group_type || ''; + ctx.inboxContext.sub_type = group.sub_type || ''; + ctx.inboxContext.ai_enabled = group.ai_enabled; + ctx.logger.info( + `[inbox processor] 注入群分组信息 group_type=${ctx.inboxContext.group_type} sub_type=${ctx.inboxContext.sub_type} ai_enabled=${ctx.inboxContext.ai_enabled}` + ); + } + } + } catch (e) { + ctx.logger.warn(`[inbox processor] 查询群分组信息失败: ${e.message}`); + } + } + + // 4.2 群未启用AI → 跳过 AI 解析(灰度开关) + if (ctx.inboxContext.ai_enabled === 0) { + ctx.logger.info(`[inbox processor] 群未启用AI自动回复,跳过 AI ext_id=${extId}`); + return; + } + + // 5. DeepSeek 两步交互 + const aiResult = await ctx.service.inbox.functions.processWithAI({ + content: data.content || '', + ext_data: data.ext_data || null, + parentId: data.parent_id || null, + }); + + // 无回复且无函数调用 → 跳过,节约资源 + // AI 显式指示跳过(silent 动作)→ 同上 + if (aiResult.skip || (!aiResult.reply && (!aiResult.functionName || aiResult.functionName === 'none'))) { + ctx.logger.info(`[inbox processor] 无回复且未匹配函数,跳过回执 ext_id=${extId}`); + return; + } + + const replyContent = aiResult.reply || '已处理完成'; + ctx.logger.info( + `[inbox processor] AI 处理完成 ext_id=${extId} ` + + `function=${aiResult.functionName || 'direct'} reply_length=${replyContent.length}` + ); + + // 6. 写入 outbound 回执记录 + const ackExtId = `sys:ack:${extId}`; + + try { + const existAck = await InboxMessage.findOne({ + where: { ext_id: ackExtId }, + attributes: [ 'id' ], + paranoid: false, + }); + + if (!existAck) { + await InboxMessage.create({ + ext_id: ackExtId, + warehouse_id: warehouseId, + store_id: data.store_id || null, + direction: 'outbound', + parent_id: parentId, + source_type: 'system', + source_extra: null, + target_type: 'api', + group_id: ctx.inboxContext?.group_id || data.group_id || null, + user_id: ctx.inboxContext?.user_id || data.user_id || null, + group_name: ctx.inboxContext?.group_name || data.group_name || null, + user_name: ctx.inboxContext?.user_name || data.user_name || null, + content: replyContent, + ext_data: data.ext_data || null, + ai_thoughts: aiResult.thoughts || null, + flags: {}, + }); + + ctx.logger.info(`[inbox processor] 回执记录写入成功 parent_id=${parentId}`); + } + } catch (writeError) { + ctx.logger.warn(`[inbox processor] 回执记录写入失败: ${writeError.message}`); + } + + // 7. 查回调地址并发送 + const callbackUrl = await this.getApiAppCallbackUrl(warehouseId); + if (!callbackUrl) { + ctx.logger.info(`[inbox processor] 仓库 ${warehouseId} 未配置回调地址,跳过回执 ext_id=${extId}`); + return; + } + + const ackBody = { + content: replyContent, + ext_data: data.ext_data || null, + ext_id: extId || null, + }; + + ctx.logger.info(`[inbox processor] 发送 API 回执 ext_id=${extId} url=${callbackUrl}`); + + const response = await ctx.curl(callbackUrl, { + method: 'POST', + dataType: 'json', + contentType: 'json', + data: ackBody, + headers: { 'Content-Type': 'application/json' }, + timeout: CALLBACK_TIMEOUT_MS, + }); + + ctx.logger.info( + `[inbox processor] API 回执完成 ext_id=${extId} ` + + `http_status=${response.status}` + ); + } catch (error) { + ctx.logger.error( + `[inbox processor] API 回执失败 ext_id=${extId}: ${error.message}` + ); + } + } + + /** + * 尝试识别并执行绑群操作。 + * 匹配"授权:CODE",从缓存读取绑群信息并绑定货主到群。 + * + * @param {Object} data 消息数据。 + * @return {Promise} 是否已处理绑群。 + */ + async tryBindGroup(data = {}) { + const { ctx } = this; + const content = String(data.content || '').trim(); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const groupId = String(ctx.inboxContext?.group_id || '').trim(); + + const bindMatch = content.match(/授权[::]\s*([A-Z0-9]{6,20})/i); + if (!bindMatch || !groupId || !warehouseId) return false; + + const code = bindMatch[1].toUpperCase(); + + // 查群是否已绑定(直接查 DB,避免 ctx 上下文被仓库ID污染) + try { + const existingGroup = await ctx.model.InboxGroup.findOne({ + attributes: [ 'store_id' ], + where: { group_id: groupId, warehouse_id: warehouseId }, + raw: true, + }); + if (existingGroup && existingGroup.store_id) { + await this.writeOutboundReply(data, '已在绑定状态,无需重复操作'); + return true; + } + } catch (e) { + ctx.logger.warn(`[inbox processor] 查群绑定状态异常: ${e.message}`); + } + + const cacheKey = `chat:bind:${warehouseId}:${code}`; + + try { + const cacheValue = await ctx.app.getCacheAsync(cacheKey); + if (!cacheValue || !cacheValue.store_id) { + await this.writeOutboundReply(data, '绑群码无效或已过期,请重新生成'); + return true; + } + + let storeName = `货主${cacheValue.store_id}`; + try { + const store = await ctx.model.Store.findOne({ + attributes: [ 'store_name' ], + where: { id: cacheValue.store_id }, + raw: true, + }); + if (store && store.store_name) storeName = store.store_name; + } catch (e) { /* ignore */ } + + await ctx.model.InboxGroup.update( + { + store_id: cacheValue.store_id, + group_type: cacheValue.group_type || 'store', + sub_type: cacheValue.sub_type || null, + }, + { where: { group_id: groupId, warehouse_id: warehouseId } } + ); + + ctx.inboxContext.store_id = cacheValue.store_id; + ctx.inboxContext.group_type = cacheValue.group_type || 'store'; + ctx.inboxContext.sub_type = cacheValue.sub_type || null; + await ctx.app.setCacheAsync(cacheKey, null, 0); + + ctx.logger.info( + `[inbox processor] 绑群成功 group_id=${groupId} store=${storeName}` + ); + + await this.writeOutboundReply(data, `绑定「${storeName}」成功`); + + // 绑定成功后自动查询面单余额 + try { + const balanceResult = await ctx.service.inbox.functions.callFunction('queryPrintBalance', {}); + const balanceMsg = balanceResult?.success + ? `面单余额:总量 ${balanceResult.data.print_quantity},已锁定 ${balanceResult.data.print_quantity_locked},可用 ${balanceResult.data.available}` + : `面单余额查询失败:${balanceResult?.error || '未知错误'}`; + // 使用独立 ext_id 避免与绑定成功回执冲突 + await this.writeOutboundReply({ ...data, ext_id: `${data.ext_id}:balance` }, balanceMsg); + } catch (balanceErr) { + ctx.logger.warn(`[inbox processor] 绑群后面单余额查询异常: ${balanceErr.message}`); + } + + return true; + } catch (error) { + ctx.logger.error(`[inbox processor] 绑群异常: ${error.message}`); + return false; + } + } + + /** + * 写入 outbound 回执并发送 HTTP 回调。 + * group_id / user_id / group_name / user_name 为强制入参, + * 缺失任一将抛出异常。 + * + * @param {Object} data 消息数据。 + * @param {string} data.group_id 群ID(必填)。 + * @param {string} data.user_id 用户ID(必填)。 + * @param {string} data.group_name 群名称(必填)。 + * @param {string} data.user_name 用户名称(必填)。 + * @param {string} replyContent 回复内容。 + * @return {Promise} + */ + async writeOutboundReply(data, replyContent) { + const { ctx } = this; + const { InboxMessage } = ctx.model; + + const warehouseId = Number(data.warehouse_id || 0); + const extId = String(data.ext_id || ''); + const parentId = Number(data.parent_id || 0); + + // 强制入参校验 + const groupId = String(data.group_id || ctx.inboxContext?.group_id || '').trim(); + const userId = String(data.user_id || ctx.inboxContext?.user_id || '').trim(); + const groupName = String(data.group_name || ctx.inboxContext?.group_name || '').trim(); + const userName = String(data.user_name || ctx.inboxContext?.user_name || '').trim(); + + if (!groupId || !userId || !groupName || !userName) { + throw new Error( + `回执缺少必填字段: group_id=${groupId || '?'}, user_id=${userId || '?'}, ` + + `group_name=${groupName || '?'}, user_name=${userName || '?'}` + ); + } + + try { + const ackExtId = `sys:ack:${extId}`; + const existAck = await InboxMessage.findOne({ + where: { ext_id: ackExtId }, attributes: [ 'id' ], paranoid: false, + }); + if (!existAck) { + await InboxMessage.create({ + ext_id: ackExtId, warehouse_id: warehouseId, + store_id: ctx.inboxContext?.store_id || null, + direction: 'outbound', parent_id: parentId || null, + source_type: 'system', source_extra: null, + target_type: 'api', + group_id: groupId, + user_id: userId, + group_name: groupName, + user_name: userName, + content: replyContent, + ext_data: data.ext_data || null, flags: {}, + }); + } + + const callbackUrl = await this.getApiAppCallbackUrl(warehouseId); + if (callbackUrl) { + const curlResult = await ctx.curl(callbackUrl, { + method: 'POST', dataType: 'json', contentType: 'json', + data: { + content: replyContent, + ext_data: data.ext_data || null, + ext_id: extId, + group_id: groupId, + user_id: userId, + group_name: groupName, + user_name: userName, + }, + headers: { 'Content-Type': 'application/json' }, timeout: 10000, + }); + + // HTTP 200 → 更新回执消息推送状态为已送达 + if (curlResult && curlResult.status === 200) { + await InboxMessage.update( + { + push_status: 2, + push_response: { http_status: curlResult.status, body: curlResult.data || null }, + pushed_at: ctx.app.Sequelize.literal('CURRENT_TIMESTAMP'), + }, + { where: { ext_id: ackExtId } } + ); + + // 同步更新原入站消息的推送状态 + if (parentId) { + await InboxMessage.update( + { + push_status: 2, + pushed_at: ctx.app.Sequelize.literal('CURRENT_TIMESTAMP'), + }, + { where: { id: parentId } } + ); + } + } + } + } catch (error) { + ctx.logger.warn(`[inbox processor] 回执写入失败: ${error.message}`); + } + } + + /** + * 检查当前消息的群/用户是否在屏蔽列表中。 + * + * @return {Promise} 是否已屏蔽。 + */ + async isBlocked() { + const { ctx } = this; + const app = ctx.app; + const groupName = String(ctx.inboxContext?.group_name || '').trim(); + const userName = String(ctx.inboxContext?.user_name || '').trim(); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + + if (!groupName && !userName) return false; + + try { + // 1. 尝试从缓存读取屏蔽列表 + const cacheKey = `inbox:block:${warehouseId}`; + let blockedSet = await app.getCacheAsync(cacheKey); + + if (!blockedSet || !(blockedSet instanceof Set)) { + // 2. 缓存未命中,查库并填入缓存 + const { InboxBlock } = ctx.model; + const rows = await InboxBlock.findAll({ attributes: [ 'group_name', 'user_name' ], raw: true }); + + blockedSet = new Set(); + for (const row of rows) { + const g = String(row.group_name || '').trim(); + const u = String(row.user_name || '').trim(); + if (g && u) blockedSet.add(`${g}:${u}`); + if (g) blockedSet.add(`${g}:*`); + if (u) blockedSet.add(`*:${u}`); + } + + // TTL 5 分钟 + await app.setCacheAsync(cacheKey, blockedSet, 300); + } + + // 3. 检查当前消息是否命中屏蔽规则 + if (groupName && userName && blockedSet.has(`${groupName}:${userName}`)) return true; + if (groupName && blockedSet.has(`${groupName}:*`)) return true; + if (userName && blockedSet.has(`*:${userName}`)) return true; + + return false; + } catch (error) { + ctx.logger.warn(`[inbox processor] 屏蔽检查异常: ${error.message}`); + return false; + } + } + + /** + * 失效屏蔽缓存,在新增屏蔽记录后调用。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 无返回值。 + */ + async invalidateBlockCache(warehouseId) { + const { ctx } = this; + try { + await ctx.app.setCacheAsync(`inbox:block:${warehouseId}`, null, 0); + } catch (error) { + ctx.logger.warn(`[inbox processor] 失效屏蔽缓存失败: ${error.message}`); + } + } + + /** + * 获取仓库 ApiApp 回调地址。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 回调 URL,未配置时返回 null。 + */ + async getApiAppCallbackUrl(warehouseId) { + const { ctx } = this; + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + return null; + } + + try { + const apiApp = await ctx.model.ApiApp.findOne({ + attributes: [ 'callback_url' ], + where: { + warehouse_id: warehouseId, + interface_type_id: WAREHOUSE_INTERFACE_TYPE_ID, + is_enabled: 1, + }, + raw: true, + }); + + return (apiApp && apiApp.callback_url) || null; + } catch (error) { + ctx.logger.warn(`[inbox processor] 查询回调地址失败: ${error.message}`); + return null; + } + } + + /** + * 尝试从消息正文中提取仓库ID。 + * 子类或业务方可覆盖此方法以实现自定义解析逻辑。 + * + * @param {string} content 消息正文。 + * @return {number|null} 仓库ID,无法解析时返回 null。 + */ + extractWarehouseId(content) { + // 默认不解析,由业务方覆盖 + void content; + return null; + } + + /** + * 尝试从消息正文中提取货主ID。 + * 子类或业务方可覆盖此方法以实现自定义解析逻辑。 + * + * @param {string} content 消息正文。 + * @return {number|null} 货主ID,无法解析时返回 null。 + */ + extractStoreId(content) { + // 默认不解析,由业务方覆盖 + void content; + return null; + } + + /** + * 从 Egg.js 请求上下文中获取仓库ID。 + * + * @return {number|null} 仓库ID。 + */ + getWarehouseIdFromContext() { + const { ctx } = this; + const user = ctx.user || ctx.state?.user || {}; + const warehouseId = Number(user.store_id || user.warehouse_id) || null; + return Number.isFinite(warehouseId) && warehouseId > 0 ? warehouseId : null; + } + + /** + * 从 Egg.js 请求上下文中获取货主ID。 + * + * @return {number|null} 货主ID。 + */ + getStoreIdFromContext() { + const { ctx } = this; + const user = ctx.user || ctx.state?.user || {}; + const storeId = Number(user.store_id) || null; + return Number.isFinite(storeId) && storeId > 0 ? storeId : null; + } +} + +module.exports = InboxProcessorService; diff --git a/app/service/inbox/receiver.js b/app/service/inbox/receiver.js index b68014e..b54acc1 100644 --- a/app/service/inbox/receiver.js +++ b/app/service/inbox/receiver.js @@ -2,157 +2,45 @@ const Service = require('egg').Service; -const { URL } = require('url'); -const { networkInterfaces } = require('os'); - -/** 推�?body 大小上限�?4KB */ -const MAX_PUSH_BODY_SIZE = 64 * 1024; -/** 最大重试次�?*/ -const MAX_RETRY_COUNT = 3; -/** 僵尸恢复阈值:5分钟 */ -const ZOMBIE_RECOVERY_MINUTES = 5; +/** 消息体大小上限 64KB */ +const MAX_BODY_SIZE = 64 * 1024; /** - * 收集本机所有内�?IPv4 地址�? - * @return {string[]} 内网IP地址列表�? - */ -function getLocalInternalIps() { - const ips = new Set(); - const nets = networkInterfaces(); - for (const interfaces of Object.values(nets)) { - for (const iface of interfaces) { - if (iface.family === 'IPv4' && !iface.internal) { - ips.add(iface.address); - } - } - } - return Array.from(ips); -} - -/** 内网 IP 前缀集合 */ -const INTERNAL_IP_PREFIXES = [ - '127.', - '10.', - '192.168.', - '0.', -]; - -/** - * 判断给定 IP 是否属于本机内网IP�? - * @param {string} ip IP地址�? - * @return {boolean} 是否为内网IP�? - */ -function isInternalIp(ip) { - if (!ip || ip === 'localhost') return true; - - // 检查已知内网前缀 - for (const prefix of INTERNAL_IP_PREFIXES) { - if (ip.startsWith(prefix)) return true; - } - - // 检�?172.16.0.0 ~ 172.31.255.255 - const parts = ip.split('.').map(Number); - if (parts.length === 4 && parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) { - return true; - } - - // 检查本机实际内网IP - const localIps = getLocalInternalIps(); - if (localIps.includes(ip)) return true; - - return false; -} - -/** - * 校验 target_url 安全性:仅允�?https://,禁止内网IP�? - * @param {string} urlStr 目标URL�? - * @throws {Error} URL 不合法时抛出�? - */ -// eslint-disable-next-line no-unused-vars -function validateTargetUrl(urlStr) { - if (!urlStr || typeof urlStr !== 'string') { - throw new Error('target_url 不能为空'); - } - - let parsed; - try { - parsed = new URL(urlStr); - } catch (e) { - throw new Error(`target_url 格式不合�? ${urlStr}`); - } - - if (parsed.protocol !== 'https:') { - throw new Error('target_url 仅允�?https:// 协议'); - } - - const hostname = parsed.hostname || ''; - if (isInternalIp(hostname)) { - throw new Error('target_url 不允许指向内网地址'); - } -} - -/** - * 站内信接收服务�? - * 统一处理消息入站:幂等去重、写库、异步推送、指数退避重试、僵尸恢复�? + * 站内信接收服务。 + * 统一处理消息入站:幂等去重、写库。 + * 暂不包含出站转发逻辑,纯入库管理。 */ class InboxReceiverService extends Service { /** - * 获取支持的目标渠道集合�? - * @return {Set} 支持的目标渠道�? - */ - static get SUPPORTED_CHANNELS() { - return new Set([ - 'webhook', - 'wecom', - 'dingtalk', - 'feishu', - 'warehouse_api', - ]); - } - - /** - * 初始化时执行僵尸恢复�? - * @param {Object} ctx Egg.js 上下文�? - */ - constructor(ctx) { - super(ctx); - // 异步执行僵尸恢复,不阻塞服务启动 - setImmediate(() => { - this.recoverZombieMessages().catch(err => { - ctx.logger.error(`[inbox] 僵尸恢复失败: ${err.message}`); - }); - }); - } - - /** - * 统一接收入口:幂等去重、写库、异步推送�? - * @param {Object} data 消息数据�? - * @param {string} data.ext_id 外部唯一消息主键�? - * @param {number} data.warehouse_id 所属仓库ID(服务端上下文注入,禁止外部传入)�? - * @param {number} [data.store_id] 关联货主ID�? - * @param {string} [data.direction='inbound'] 消息方向�? - * @param {number} [data.parent_id] 关联消息ID(回信时指向原消息)�? - * @param {string} data.source_type 来源类型:im / api / system�? - * @param {string} [data.source_extra] 来源附加信息�? - * @param {string} data.target_type 目标类型:im / api / webhook�? - * @param {string} data.target_channel 目标渠道�? - * @param {string} data.target_url 推送目标URL�? - * @param {string} [data.ref_code] 引用编码�? - * @param {Object} [data.ext_data] 透传数据�? - * @param {Object} [data.flags] 处理标记�? - * @return {Promise<{ok: boolean, id: number, ext_id: string}>} 接收结果�? + * 统一接收入口:幂等去重、写库。 + * @param {Object} data 消息数据。 + * @param {string} data.ext_id 外部唯一消息主键。 + * @param {number} data.warehouse_id 所属仓库ID(服务端上下文注入,禁止外部传入)。 + * @param {string} [data.direction='inbound'] 消息方向。 + * @param {number} [data.parent_id] 关联消息ID(回信时指向原消息)。 + * @param {string} data.source_type 来源类型:im / api / system。 + * @param {string} [data.source_extra] 来源附加信息。 + * @param {string} data.target_type 目标类型:im / api / webhook。 + * @param {string} [data.group_name] 群名称(外部传入)。 + * @param {string} [data.user_name] 用户名称(外部传入)。 + * @param {string} [data.group_id] 外部群ID。 + * @param {string} [data.user_id] 外部用户ID。 + * @param {string} [data.content] 消息正文/摘要。 + * @param {Object} [data.ext_data] 透传数据。 + * @param {Object} [data.flags] 处理标记。 + * @return {Promise<{ok: boolean, id: number, ext_id: string}>} 接收结果。 */ async receive(data = {}) { const { ctx } = this; const { InboxMessage } = ctx.model; - // 安全边界:校�?ext_id 不能为空 + // 安全边界:校验 ext_id 不能为空 const extId = String(data.ext_id || '').trim(); if (!extId) { throw new Error('ext_id 不能为空'); } - // 安全边界:warehouse_id 必须由服务端上下文提�? + // 安全边界:warehouse_id 必须由服务端上下文提供 const warehouseId = Number(data.warehouse_id); if (!Number.isFinite(warehouseId) || warehouseId <= 0) { throw new Error('warehouse_id 无效'); @@ -182,19 +70,10 @@ class InboxReceiverService extends Service { } } - - // 校验 target_channel 是否存在 - const targetChannel = String(data.target_channel || '').trim(); - if (!targetChannel || !InboxReceiverService.SUPPORTED_CHANNELS.has(targetChannel)) { - throw new Error(`不支持的目标渠道: ${targetChannel},支持的渠道: ${Array.from(InboxReceiverService.SUPPORTED_CHANNELS).join(', ')}`); - } - - // 安全边界:校�?target_url - // 幂等检查:ext_id 已存在则直接返回 const exist = await InboxMessage.findOne({ where: { ext_id: extId }, - attributes: [ 'id', 'ext_id', 'push_status' ], + attributes: [ 'id', 'ext_id' ], paranoid: false, }); @@ -207,69 +86,92 @@ class InboxReceiverService extends Service { }; } - // 推�?body 大小限制(序列化后检查) - const pushBody = { + // 消息体大小限制 + const checkBody = { + content: data.content || null, ext_data: data.ext_data || null, }; - const bodySize = Buffer.byteLength(JSON.stringify(pushBody), 'utf8'); - if (bodySize > MAX_PUSH_BODY_SIZE) { - throw new Error(`推�?body 超过 64KB 限制(当�?${Math.round(bodySize / 1024)}KB)`); + const bodySize = Buffer.byteLength(JSON.stringify(checkBody), 'utf8'); + if (bodySize > MAX_BODY_SIZE) { + throw new Error(`消息体超过 64KB 限制(当前 ${Math.round(bodySize / 1024)}KB)`); } - // 写库 - - // store_id 签约校验,若传入 store_id,必须存在有效合约关系 - const storeId = data.store_id ? Number(data.store_id) : null; - if (storeId && Number.isFinite(storeId) && storeId > 0) { - const contract = await ctx.model.StoreWarehouse.findOne({ - where: { - store_id: storeId, - warehouse_id: warehouseId, - auth_status: 2, - warehouse_use_status: 1, - }, - attributes: [ 'id' ], - }); - if (!contract) { - throw new Error(`store_id=${storeId} 与仓库 ${warehouseId} 无有效签约关系`); + // 从群绑定查询货主ID(外部不再直接传入 store_id) + let storeId = null; + const extGroupId = String(data.group_id || '').trim(); + if (extGroupId && warehouseId) { + try { + const group = await ctx.model.InboxGroup.findOne({ + attributes: [ 'store_id' ], + where: { group_id: extGroupId, warehouse_id: warehouseId }, + raw: true, + }); + if (group && group.store_id) { + storeId = Number(group.store_id); + } + } catch (groupErr) { + ctx.logger.warn(`[inbox] 查找群货主失败: ${groupErr.message}`); } } + + // 写库(暂不触发异步转发) const record = await InboxMessage.create({ ext_id: extId, warehouse_id: warehouseId, - store_id: data.store_id || null, + store_id: storeId || null, direction, parent_id: parentId, source_type: sourceType, source_extra: data.source_extra || null, target_type: targetType, - target_channel: targetChannel, + group_name: data.group_name || null, + user_name: data.user_name || null, + group_id: data.group_id || null, + user_id: data.user_id || null, + content: data.content || null, ext_data: data.ext_data || null, flags: data.flags || {}, - push_status: 0, }); ctx.logger.info(`[inbox] 消息入库成功 ext_id=${extId} id=${record.id}`); - // 异步后台推送(不阻塞响应) - setImmediate(() => { - this.asyncPush(record).catch(err => { - ctx.logger.error(`[inbox] setImmediate 异步推送异�?ext_id=${extId}: ${err.message}`); - // 异常已由 asyncPush 内部 try/catch,这里作为兜�? - try { - InboxMessage.update( - { - push_status: 3, - push_response: { error: `setImmediate 异常: ${err.message}` }, - pushed_at: new Date(), - }, - { where: { id: record.id, push_status: { [this.ctx.app.Sequelize.Op.in]: [ 0, 1 ] } } } - ); - } catch (updateErr) { - ctx.logger.error(`[inbox] 兜底更新推送状态失�?ext_id=${extId}: ${updateErr.message}`); - } + // 自动登记群(幂等 upsert) + const groupName = String(data.group_name || '').trim(); + if (groupName) { + try { + await ctx.model.InboxGroup.findOrCreate({ + where: { group_name: groupName, warehouse_id: warehouseId }, + defaults: { + group_id: extGroupId, + store_id: storeId || null, + source_type: sourceType, + source_extra: data.source_extra || null, + }, + }); + } catch (groupErr) { + ctx.logger.warn(`[inbox] 群登记失败: ${groupErr.message}`); + } + } + + // source_type 分流:API 来源异步回执 + if (sourceType === 'api') { + setImmediate(() => { + ctx.service.inbox.processor.handleApiMessage({ + warehouse_id: warehouseId, + store_id: storeId, + parent_id: record.id, + ext_data: data.ext_data || null, + ext_id: extId, + content: data.content || '', + group_name: data.group_name || null, + user_name: data.user_name || null, + group_id: data.group_id || null, + user_id: data.user_id || null, + }).catch(err => { + ctx.logger.error(`[inbox] API 异步回执异常 ext_id=${extId}: ${err.message}`); + }); }); - }); + } return { ok: true, @@ -277,133 +179,6 @@ class InboxReceiverService extends Service { ext_id: extId, }; } - - /** - * 异步推�?+ 指数退避重试�? - * @param {Object} record 消息记录(Sequelize Model 实例)�? - * @param {number} [attempt=0] 当前重试次数�? - * @return {Promise} 推送结果�? - */ - async asyncPush(record, attempt = 0) { - const { ctx } = this; - const { InboxMessage } = ctx.model; - const { Op } = ctx.app.Sequelize; - - try { - // 乐观锁:�?push_status=0 或(重试�?push_status=3)时可取�? - const allowedStatuses = attempt === 0 ? [ 0 ] : [ 3 ]; - const [ updatedCount ] = await InboxMessage.update( - { - push_status: 1, - push_started_at: new Date(), - }, - { - where: { - id: record.id, - push_status: { [Op.in]: allowedStatuses }, - }, - } - ); - - if (updatedCount === 0) { - ctx.logger.info(`[inbox] 消息已被其他进程取走,跳过推�?ext_id=${record.ext_id} id=${record.id}`); - return; - } - - // 获取 dispatch 服务 - const channel = record.target_channel; - if (!InboxReceiverService.SUPPORTED_CHANNELS.has(channel)) { - throw new Error(`不支持的目标渠道: ${channel}`); - } - - // 统一渠道映射:warehouse_api �?webhook - const dispatchChannel = channel === 'warehouse_api' ? 'webhook' : channel; - const dispatchService = ctx.service.inbox.dispatch[dispatchChannel]; - - if (!dispatchService || typeof dispatchService.push !== 'function') { - throw new Error(`dispatch 渠道 ${dispatchChannel} 未实现`); - } - - // 执行推�? - const response = await dispatchService.push(record); - - // 推送成�? - await InboxMessage.update( - { - push_status: 2, - push_response: { - http_status: response.status, - body: response.data, - }, - pushed_at: new Date(), - }, - { where: { id: record.id, push_status: 1 } } - ); - - ctx.logger.info(`[inbox] 推送成�?ext_id=${record.ext_id} channel=${channel}`); - } catch (error) { - const next = attempt + 1; - ctx.logger.warn(`[inbox] 推送失�?ext_id=${record.ext_id} attempt=${next} error=${error.message}`); - - // 更新失败状�? - await InboxMessage.update( - { - push_status: next >= MAX_RETRY_COUNT ? 3 : 3, - retry_count: next, - push_response: { error: error.message }, - ...(next >= MAX_RETRY_COUNT ? { pushed_at: new Date() } : {}), - }, - { where: { id: record.id, push_status: 1 } } - ); - - // 指数退避重试:30s �?60s �?120s - if (next < MAX_RETRY_COUNT) { - const delay = 30000 * Math.pow(2, attempt); - ctx.logger.info(`[inbox] 将在 ${delay / 1000}s 后重�?ext_id=${record.ext_id} attempt=${next}`); - setTimeout(() => { - this.asyncPush(record, next).catch(err => { - ctx.logger.error(`[inbox] 重试推送异�?ext_id=${record.ext_id}: ${err.message}`); - }); - }, delay); - } else { - ctx.logger.error(`[inbox] 推送达到最大重试次数,标记为终态失�?ext_id=${record.ext_id}`); - } - } - } - - /** - * 僵尸恢复:重置卡�?推送中"超过5分钟的消息为"待推�?�? - * 在服务启动时及定时任务中调用�? - * @return {Promise} 恢复的消息数量�? - */ - async recoverZombieMessages() { - const { ctx } = this; - const { InboxMessage } = ctx.model; - const { Op } = ctx.app.Sequelize; - - const threshold = new Date(Date.now() - ZOMBIE_RECOVERY_MINUTES * 60 * 1000); - - const [ updatedCount ] = await InboxMessage.update( - { - push_status: 0, - push_started_at: null, - }, - { - where: { - push_status: 1, - push_started_at: { - [Op.lt]: threshold, - }, - }, - } - ); - - if (updatedCount > 0) { - ctx.logger.info(`[inbox] 僵尸恢复完成,重�?${updatedCount} 条消息为待推送`); - } - - return updatedCount; - } } module.exports = InboxReceiverService; diff --git a/app/service/systemMethods/inbox.js b/app/service/systemMethods/inbox.js new file mode 100644 index 0000000..f3314f5 --- /dev/null +++ b/app/service/systemMethods/inbox.js @@ -0,0 +1,189 @@ +'use strict'; + +const MainService = require('../main'); + +/** + * 站内信系统方法层。 + * 提供需要用户权限的内部管理接口。 + */ +class InboxSystemService extends MainService { + /** + * 群管理子入口,供 /system dispatcher 按 inbox.group.* 路径访问。 + * @return {{list: Function, disable: Function, update: Function, messages: Function, checkAuth: Function}} + */ + get group() { + return { + list: data => this.groupList(data), + disable: data => this.groupDisable(data), + update: data => this.groupUpdate(data), + messages: data => this.groupMessages(data), + checkAuth: (...args) => this.checkAuth(...args), + }; + } + + /** + * 消息管理子入口,供 /system dispatcher 按 inbox.message.* 路径访问。 + * @return {{list: Function, detail: Function, thread: Function, reply: Function, stats: Function, checkAuth: Function}} + */ + get message() { + const { ctx } = this; + return { + list: data => { + const warehouseId = Number(ctx.user?.store_id || 0); + return ctx.service.inbox.message.list({ warehouseId, ...data }); + }, + detail: data => { + const warehouseId = Number(ctx.user?.store_id || 0); + return ctx.service.inbox.message.detail({ warehouseId, id: data.id }); + }, + thread: data => { + const warehouseId = Number(ctx.user?.store_id || 0); + return ctx.service.inbox.message.thread({ warehouseId, id: data.id }); + }, + stats: data => { + const warehouseId = Number(ctx.user?.store_id || 0); + return ctx.service.inbox.message.stats({ warehouseId, direction: data.direction }); + }, + checkAuth: (...args) => this.checkAuth(...args), + }; + } + + /** + * 生成货主绑群码。 + * 委托给 systems.store.bindCode 执行:校验 StoreWarehouse 合约 → 生成12位随机码 → 缓存300秒。 + * warehouseId 从 ctx.user.store_id 自动注入,绑群码缓存 key 为 chat:bind:{warehouseId}:{code}。 + * + * @param {Object} data 请求数据。 + * @param {number} data.storeId 货主ID。 + * @param {string} [data.subType] 群子类型编码:after_sales(售后) / finance(财务) / receiving(收货)。 + * @return {Promise} { code: 绑群码 }。 + */ + async bindCode(data = {}) { + const { ctx } = this; + const { storeId, subType } = data; + const warehouseId = Number(ctx.user?.store_id || 0); + + return await ctx.service.systems.store.bindCode({ + storeId, + warehouseId, + subType, + }); + } + + /** + * 拉取当前仓库的群列表。 + * warehouseId 从 ctx.user.store_id 自动注入。 + * + * @param {Object} data 请求数据。 + * @param {string} [data.groupType] 按群类型筛选:store / warehouse / express。 + * @param {string} [data.keyword] 群名称模糊搜索。 + * @param {number} [data.page] 页码。 + * @param {number} [data.pageSize] 每页条数。 + * @return {Promise} { total, list }。 + */ + async groupList(data = {}) { + const { ctx } = this; + const { groupType, keyword, page, pageSize } = data; + const warehouseId = Number(ctx.user?.store_id || 0); + + return await ctx.service.systems.inbox.group.list({ + warehouseId, + groupType, + keyword, + page, + pageSize, + }); + } + + /** + * 禁用 / 解禁群。 + * warehouseId 从 ctx.user.store_id 自动注入。 + * + * @param {Object} data 请求数据。 + * @param {number} data.id 群记录主键ID(必填)。 + * @param {number} [data.isBlocked=1] 是否禁用 1=是 0=否。 + * @return {Promise} { message: 操作结果 }。 + */ + async groupDisable(data = {}) { + const { ctx } = this; + const { id, isBlocked } = data; + const warehouseId = Number(ctx.user?.store_id || 0); + + await ctx.service.systems.inbox.group.disable({ + id, + warehouseId, + isBlocked: isBlocked === 0 ? 0 : 1, + }); + + return { message: isBlocked === 0 ? '群已启用' : '群已禁用' }; + } + + /** + * 修改群信息。 + * 支持修改 group_type / sub_type / store_id / express_interfaces / system_express_code。 + * warehouseId 从 ctx.user.store_id 自动注入。 + * + * @param {Object} data 请求数据。 + * @param {number} data.id 群记录主键ID(必填)。 + * @param {string} [data.groupType] 群类型:store / warehouse / express。 + * @param {string} [data.subType] 群子类型。 + * @param {number} [data.storeId] 关联货主ID。 + * @param {number[]} [data.expressInterfaces] 快递接口ID数组(仅 express 生效)。 + * @param {string} [data.systemExpressCode] 系统快递编码(express 时必填)。 + * @return {Promise} { message: 操作结果 }。 + */ + async groupUpdate(data = {}) { + const { ctx } = this; + const { + id, groupType, subType, storeId, + expressInterfaces, systemExpressCode, aiEnabled, + } = data; + const warehouseId = Number(ctx.user?.store_id || 0); + + await ctx.service.systems.inbox.group.update({ + id, + warehouseId, + groupType, + subType, + storeId, + expressInterfaces, + systemExpressCode, + aiEnabled, + }); + + return { message: '群信息修改成功' }; + } + + /** + * 拉取指定群的消息列表。 + * warehouseId 从 ctx.user.store_id 自动注入。 + * + * @param {Object} data 请求数据。 + * @param {string} data.groupId 群ID(必填)。 + * @param {string} [data.direction] 消息方向筛选:inbound / outbound。 + * @param {string} [data.keyword] 关键词搜索(ext_id / content)。 + * @param {number} [data.page] 页码。 + * @param {number} [data.pageSize] 每页条数。 + * @return {Promise} { list, pagination }。 + */ + async groupMessages(data = {}) { + const { ctx } = this; + const { groupId, direction, keyword, page, pageSize } = data; + const warehouseId = Number(ctx.user?.store_id || 0); + + if (!groupId || typeof groupId !== 'string' || !groupId.trim()) { + throw new Error('groupId 不能为空'); + } + + return await ctx.service.inbox.message.list({ + warehouseId, + groupId: groupId.trim(), + direction, + keyword, + page, + pageSize, + }); + } +} + +module.exports = InboxSystemService; diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index db41349..fa27eb0 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -12732,7 +12732,7 @@ class WaveService extends OrderBaseService { try { const directFetchResult = await this.executeWaveStrategyDirectFetch({ plan, - waveBatchSource: 1, + waveBatchSource: 0, }); this.ctx.logger.info('[wave.waveStrategyFetchAdmin] 建波成功', { diff --git a/app/service/systems/inbox/group.js b/app/service/systems/inbox/group.js new file mode 100644 index 0000000..876daf3 --- /dev/null +++ b/app/service/systems/inbox/group.js @@ -0,0 +1,250 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * 站内信群管理业务逻辑层。 + * 提供群列表查询、禁用、修改等核心能力。 + */ +class InboxGroupService extends Service { + /** + * 拉取当前仓库的群列表。 + * + * @param {Object} data 请求数据。 + * @param {number} data.warehouseId 仓库ID(必填,由 controller 注入)。 + * @param {string} [data.groupType] 按群类型筛选:store / warehouse / express。 + * @param {string} [data.keyword] 按群名称模糊搜索。 + * @param {number} [data.page=1] 页码。 + * @param {number} [data.pageSize=20] 每页条数。 + * @return {Promise} { total, list }。 + */ + async list(data = {}) { + const { ctx } = this; + const { InboxGroup } = ctx.model; + const { Op } = ctx.app.Sequelize; + + const warehouseId = Number(data.warehouseId); + const groupType = String(data.groupType || '').trim(); + const keyword = String(data.keyword || '').trim(); + const page = Math.max(1, Number(data.page) || 1); + const pageSize = Math.min(100, Math.max(1, Number(data.pageSize) || 20)); + const offset = (page - 1) * pageSize; + + if (!warehouseId) throw new Error('warehouseId 无效'); + + const where = { warehouse_id: warehouseId }; + if (groupType) where.group_type = groupType; + if (keyword) where.group_name = { [Op.like]: `%${keyword}%` }; + + const { count, rows } = await InboxGroup.findAndCountAll({ + attributes: [ + 'id', 'group_name', 'group_id', 'warehouse_id', 'store_id', + 'group_type', 'sub_type', 'source_type', 'source_extra', + 'is_blocked', 'ai_enabled', 'express_interfaces', 'system_express_code', + 'created_at', 'updated_at', + ], + where, + order: [[ 'created_at', 'DESC' ]], + limit: pageSize, + offset, + raw: true, + }); + + // express_interfaces 输出为数组 + const list = rows.map(row => ({ + ...row, + express_interfaces: row.express_interfaces + ? row.express_interfaces.split(',').map(Number).filter(Boolean) + : [], + })); + + return { total: count, list }; + } + + /** + * 禁用 / 解禁群。 + * + * @param {Object} data 请求数据。 + * @param {number} data.id 群记录主键ID(必填)。 + * @param {number} data.warehouseId 仓库ID(必填,由 controller 注入)。 + * @param {number} data.isBlocked 是否屏蔽 1=禁用 0=启用。 + * @return {Promise} + */ + async disable(data = {}) { + const { ctx } = this; + const { InboxGroup } = ctx.model; + + const id = Number(data.id); + const warehouseId = Number(data.warehouseId); + const isBlocked = data.isBlocked === 1 ? 1 : 0; + + if (!id) throw new Error('群ID无效'); + if (!warehouseId) throw new Error('warehouseId 无效'); + + const [ affected ] = await InboxGroup.update( + { is_blocked: isBlocked }, + { where: { id, warehouse_id: warehouseId } } + ); + + if (!affected) { + throw new Error('群不存在或无权限操作'); + } + + ctx.logger.info( + `[inbox group] ${isBlocked ? '禁用' : '启用'}群 id=${id} warehouse_id=${warehouseId}` + ); + } + + /** + * 修改群信息。 + * 支持修改 group_type / sub_type / store_id / express_interfaces / system_express_code。 + * 群类型切为 express 时 system_express_code 必填, + * express_interfaces 仅在群类型为 express 时生效(非 express 类型忽略)。 + * + * @param {Object} data 请求数据。 + * @param {number} data.id 群记录主键ID(必填)。 + * @param {number} data.warehouseId 仓库ID(必填,由 controller 注入)。 + * @param {string} [data.groupType] 群类型:store / warehouse / express。 + * @param {string} [data.subType] 群子类型。 + * @param {number} [data.storeId] 关联货主ID。 + * @param {number[]} [data.expressInterfaces] 快递接口ID数组。 + * @param {string} [data.systemExpressCode] 系统快递编码。 + * @return {Promise} + */ + async update(data = {}) { + const { ctx } = this; + const { InboxGroup } = ctx.model; + + const id = Number(data.id); + const warehouseId = Number(data.warehouseId); + + if (!id) throw new Error('群ID无效'); + if (!warehouseId) throw new Error('warehouseId 无效'); + + // 查群是否存在 + const group = await InboxGroup.findOne({ + attributes: [ 'id', 'group_type', 'group_id', 'warehouse_id' ], + where: { id, warehouse_id: warehouseId }, + raw: true, + }); + if (!group) throw new Error('群不存在或无权限操作'); + + // 目标群类型(优先新值,否则保留原值) + const targetGroupType = data.groupType !== undefined + ? String(data.groupType).trim() + : group.group_type || ''; + const isExpress = targetGroupType === 'express'; + + // express_interfaces 处理 + let expressInterfaces = null; + if (data.expressInterfaces !== undefined) { + if (Array.isArray(data.expressInterfaces) && data.expressInterfaces.length > 0) { + // 校验快递接口ID有效性 + await this.validateExpressInterfaces(data.expressInterfaces); + expressInterfaces = data.expressInterfaces.join(','); + } else if (Array.isArray(data.expressInterfaces) && data.expressInterfaces.length === 0) { + // 空数组 = 清空 = 表示全部快递类型 + expressInterfaces = ''; + } else { + expressInterfaces = null; // 未传入 = 不修改 + } + } + + // system_express_code 校验 + let systemExpressCode; + if (data.systemExpressCode !== undefined) { + const code = String(data.systemExpressCode).trim(); + if (code) { + await this.validateSystemExpressCode(code); + systemExpressCode = code; + } else { + systemExpressCode = null; + } + } + + // 切换为 express 类型时 system_express_code 不能为空 + if (isExpress && data.groupType !== undefined) { + const finalCode = systemExpressCode !== undefined ? systemExpressCode : group.system_express_code; + if (!finalCode) { + throw new Error('群类型为快递群时,系统快递编码不能为空'); + } + } + + // 构建更新字段 + const updateData = {}; + if (data.groupType !== undefined) updateData.group_type = targetGroupType || null; + if (data.subType !== undefined) updateData.sub_type = String(data.subType || '').trim() || null; + if (data.storeId !== undefined) { + updateData.store_id = Number.isFinite(Number(data.storeId)) && Number(data.storeId) > 0 + ? Number(data.storeId) : null; + } + // 非 express 群类型时忽略 express 相关字段 + if (isExpress && expressInterfaces !== null) { + updateData.express_interfaces = expressInterfaces || null; + } + if (isExpress && systemExpressCode !== undefined) { + updateData.system_express_code = systemExpressCode || null; + } + // AI 开关(所有群类型均支持) + if (data.aiEnabled !== undefined) { + updateData.ai_enabled = data.aiEnabled === 1 ? 1 : 0; + } + + if (Object.keys(updateData).length === 0) { + throw new Error('未提供任何需要修改的字段'); + } + + await InboxGroup.update(updateData, { where: { id, warehouse_id: warehouseId } }); + ctx.logger.info( + `[inbox group] 修改群 id=${id} fields=${Object.keys(updateData).join(',')}` + ); + } + + /** + * 校验快递接口ID数组的有效性。 + * 所有ID必须在 wms_express_interface 表中存在。 + * + * @param {number[]} ids 快递接口ID数组。 + * @return {Promise} 无效时抛出异常。 + */ + async validateExpressInterfaces(ids) { + const { ctx } = this; + if (!Array.isArray(ids) || ids.length === 0) return; + + const numericIds = ids.map(Number).filter(id => Number.isFinite(id) && id > 0); + if (numericIds.length !== ids.length) { + throw new Error('快递接口ID包含无效值'); + } + + const count = await ctx.model.ExpressInterface.count({ + where: { id: { [ctx.app.Sequelize.Op.in]: numericIds } }, + }); + + if (count !== numericIds.length) { + throw new Error('部分快递接口ID不存在'); + } + } + + /** + * 校验系统快递编码有效性。 + * 必须在 wms_express 表中存在对应的 code。 + * + * @param {string} code 系统快递编码。 + * @return {Promise} 无效时抛出异常。 + */ + async validateSystemExpressCode(code) { + const { ctx } = this; + const trimmed = String(code).trim(); + if (!trimmed) throw new Error('系统快递编码不能为空'); + + const exists = await ctx.model.Express.count({ + where: { code: trimmed }, + }); + + if (!exists) { + throw new Error(`系统快递编码 "${trimmed}" 不存在`); + } + } +} + +module.exports = InboxGroupService; diff --git a/app/service/systems/store.js b/app/service/systems/store.js index 5358472..d43daf9 100644 --- a/app/service/systems/store.js +++ b/app/service/systems/store.js @@ -1004,6 +1004,73 @@ class StoreService extends Service { throw error; } } + + /** + * 生成货主绑群码。 + * 查询货主与仓库的有效合约,生成 12 位随机码并存入缓存(5分钟有效)。 + * + * @param {Object} data 请求数据。 + * @param {number} data.storeId 货主ID(必填)。 + * @param {number} data.warehouseId 仓库ID(必填,由 systemMethods 层注入)。 + * @param {string} [data.subType] 群子类型:after_sales / finance / receiving。 + * @return {Promise} { code: 绑群码 }。 + */ + async bindCode(data = {}) { + const { ctx } = this; + const storeId = Number(data.storeId); + const warehouseId = Number(data.warehouseId); + + if (!Number.isFinite(storeId) || storeId <= 0) { + throw new Error('storeId 无效'); + } + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw new Error('缺少仓库信息,请确认已登录并选择了仓库'); + } + + const contract = await ctx.model.StoreWarehouse.findOne({ + attributes: [ 'id', 'store_id', 'warehouse_id', 'initiator_subject_id' ], + where: { + store_id: storeId, + warehouse_id: warehouseId, + auth_status: 2, + warehouse_use_status: 1, + }, + raw: true, + }); + + if (!contract) { + throw new Error(`货主 ${storeId} 在仓库 ${warehouseId} 无有效合约`); + } + + const subType = String(data.subType || '').trim(); + const VALID_SUB_TYPES = [ 'after_sales', 'finance', 'receiving' ]; + if (subType && !VALID_SUB_TYPES.includes(subType)) { + throw new Error(`无效的子类型: ${subType},可选值: ${VALID_SUB_TYPES.join(' / ')}`); + } + + const code = Math.random().toString(36).slice(2, 8) + .toUpperCase() + + Math.random().toString(36).slice(2, 8) + .toUpperCase(); + const cacheKey = `chat:bind:${warehouseId}:${code}`; + + const cacheValue = { + store_id: contract.store_id, + initiator_subject_id: contract.initiator_subject_id || null, + warehouse_id: contract.warehouse_id, + group_type: 'store', + sub_type: subType || null, + }; + + await ctx.app.setCacheAsync(cacheKey, cacheValue, 300); + + ctx.logger.info( + `[store bindCode] 生成绑群码 code=${code} ` + + `store_id=${contract.store_id} warehouse_id=${warehouseId}` + ); + + return { code }; + } } module.exports = StoreService; diff --git a/app/service/warehouseMethods/inbox.js b/app/service/warehouseMethods/inbox.js index 7232976..23c7fa9 100644 --- a/app/service/warehouseMethods/inbox.js +++ b/app/service/warehouseMethods/inbox.js @@ -29,10 +29,6 @@ class WarehouseInboxService extends MainService { throw new Error('requestId 不能为空'); } - if (!body.targetChannel || !String(body.targetChannel).trim()) { - throw new Error('targetChannel 不能为空'); - } - // 构造 ext_id const extId = `api:${String(appKey || 'unknown')}:${String(body.requestId).trim()}`; @@ -40,13 +36,16 @@ class WarehouseInboxService extends MainService { const result = await ctx.service.inbox.receiver.receive({ ext_id: extId, warehouse_id: warehouseId, - store_id: body.storeId || null, direction: 'inbound', parent_id: body.parentId || null, source_type: body.sourceType || 'api', source_extra: String(appKey || ''), target_type: body.targetType || 'im', - target_channel: body.targetChannel, + group_name: body.groupName || null, + user_name: body.userName || null, + group_id: body.groupId || null, + user_id: body.userId || null, + content: body.content || null, ext_data: body.extData || null, flags: body.flags || {}, }); diff --git a/database/migrations/20260803120000-create-inbox-message.js b/database/migrations/20260803120000-create-inbox-message.js index d31b668..1e6a8d3 100644 --- a/database/migrations/20260803120000-create-inbox-message.js +++ b/database/migrations/20260803120000-create-inbox-message.js @@ -65,18 +65,33 @@ module.exports = { }, target_channel: { type: Sequelize.STRING(50), - allowNull: false, - comment: '目标渠道:wecom / dingtalk / feishu / warehouse_api / webhook', + allowNull: true, + comment: '目标渠道(仅供参考,出站路由由外部系统负责)', }, - target_url: { - type: Sequelize.STRING(500), - allowNull: false, - comment: '推送目标URL(IM Bot webhook 地址 / API 回调地址)', - }, - ref_code: { + group_name: { type: Sequelize.STRING(100), allowNull: true, - comment: '外部引用编码,推送/回执时原样携带', + comment: '群名称(外部传入)', + }, + user_name: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '用户名称(外部传入)', + }, + group_id: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '外部群ID', + }, + user_id: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '外部用户ID', + }, + content: { + type: Sequelize.TEXT, + allowNull: true, + comment: '消息正文/摘要,用于列表展示和关键词搜索', }, ext_data: { type: Sequelize.JSON, diff --git a/database/migrations/20260804120000-add-content-to-inbox-message.js b/database/migrations/20260804120000-add-content-to-inbox-message.js new file mode 100644 index 0000000..4cd1c9b --- /dev/null +++ b/database/migrations/20260804120000-add-content-to-inbox-message.js @@ -0,0 +1,33 @@ +'use strict'; + +const TABLE_NAME = 'wms_inbox_message'; +const COLUMN_NAME = 'content'; + +module.exports = { + /** + * 为站内信消息表添加消息正文字段。 + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @param {Object} Sequelize Sequelize 类。 + * @return {Promise} 迁移执行结果。 + */ + up: async (queryInterface, Sequelize) => { + const columns = await queryInterface.describeTable(TABLE_NAME); + if (columns[COLUMN_NAME]) return; + + await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, { + type: Sequelize.TEXT, + allowNull: true, + comment: '消息正文/摘要,用于列表展示和关键词搜索', + after: 'target_channel', + }); + }, + + /** + * 回滚:移除消息正文字段。 + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @return {Promise} 迁移回滚结果。 + */ + down: async queryInterface => { + await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME); + }, +}; diff --git a/database/migrations/20260804130000-create-inbox-block.js b/database/migrations/20260804130000-create-inbox-block.js new file mode 100644 index 0000000..2e22c45 --- /dev/null +++ b/database/migrations/20260804130000-create-inbox-block.js @@ -0,0 +1,57 @@ +'use strict'; + +const TABLE_NAME = 'wms_inbox_block'; + +module.exports = { + /** + * 创建站内信屏蔽表。 + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @param {Object} Sequelize Sequelize 类。 + * @return {Promise} 迁移执行结果。 + */ + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + group_name: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '群名称', + }, + user_name: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '用户名称', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'group_name', 'user_name' ], { + unique: true, + name: 'uk_group_user', + }); + }, + + /** + * 回滚:删除站内信屏蔽表。 + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @return {Promise} 迁移回滚结果。 + */ + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260804140000-create-inbox-group.js b/database/migrations/20260804140000-create-inbox-group.js new file mode 100644 index 0000000..875af02 --- /dev/null +++ b/database/migrations/20260804140000-create-inbox-group.js @@ -0,0 +1,92 @@ +'use strict'; + +const TABLE_NAME = 'wms_inbox_group'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + if (tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME)) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + group_name: { + type: Sequelize.STRING(100), + allowNull: false, + comment: '群名称', + }, + group_id: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '外部群ID', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '所属仓库ID', + }, + store_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联货主ID', + }, + group_type: { + type: Sequelize.ENUM('store', 'warehouse', 'express'), + allowNull: true, + comment: '群类型: store=货主 warehouse=仓库 express=快递', + }, + sub_type: { + type: Sequelize.STRING(20), + allowNull: true, + comment: '群子类型', + }, + source_type: { + type: Sequelize.STRING(20), + allowNull: true, + comment: '来源类型:im / api / system', + }, + source_extra: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '来源附加信息', + }, + is_blocked: { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否屏蔽 0=否 1=是', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '软删除时间', + }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'group_name', 'warehouse_id' ], { + unique: true, + name: 'uk_group_warehouse', + }); + }, + + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260805120000-add-express-fields-to-inbox-group.js b/database/migrations/20260805120000-add-express-fields-to-inbox-group.js new file mode 100644 index 0000000..c2ae5ec --- /dev/null +++ b/database/migrations/20260805120000-add-express-fields-to-inbox-group.js @@ -0,0 +1,42 @@ +'use strict'; + +/** + * 为 wms_inbox_group 添加快递相关字段: + * - express_interfaces:快递接口ID列表(逗号分隔) + * - system_express_code:系统快递编码 + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + const { STRING } = Sequelize; + + // 检查列是否已存在 + const tableInfo = await queryInterface.describeTable('wms_inbox_group'); + + if (!tableInfo.express_interfaces) { + await queryInterface.addColumn('wms_inbox_group', 'express_interfaces', { + type: STRING(500), + allowNull: true, + comment: '快递接口ID列表,逗号分隔(仅群类型为 express 时生效)', + }); + } + + if (!tableInfo.system_express_code) { + await queryInterface.addColumn('wms_inbox_group', 'system_express_code', { + type: STRING(50), + allowNull: true, + comment: '系统快递编码(仅群类型为 express 时必填)', + }); + } + }, + + down: async (queryInterface) => { + const tableInfo = await queryInterface.describeTable('wms_inbox_group'); + + if (tableInfo.express_interfaces) { + await queryInterface.removeColumn('wms_inbox_group', 'express_interfaces'); + } + if (tableInfo.system_express_code) { + await queryInterface.removeColumn('wms_inbox_group', 'system_express_code'); + } + }, +}; diff --git a/database/migrations/20260805140000-add-inbox-indexes.js b/database/migrations/20260805140000-add-inbox-indexes.js new file mode 100644 index 0000000..558a0dc --- /dev/null +++ b/database/migrations/20260805140000-add-inbox-indexes.js @@ -0,0 +1,73 @@ +'use strict'; + +/** + * 为站内信消息表和群表补充查询索引。 + * + * wms_inbox_message: + * - idx_warehouse_group_created: (warehouse_id, group_id, created_at) + * 用于按群拉取消息列表(最常用查询)。 + * + * wms_inbox_group: + * - idx_group_id: (group_id) + * 用于 receiver/processor 中按 group_id 查找群。 + * - idx_warehouse_group_id: (warehouse_id, group_id) + * 用于按仓库+群ID定位群。 + */ +module.exports = { + // eslint-disable-next-line no-unused-vars + up: async (queryInterface, Sequelize) => { + // ── wms_inbox_message 索引 ── + const msgTableInfo = await queryInterface.describeTable('wms_inbox_message'); + + // 检查已有索引(通过尝试添加,重复则忽略) + try { + await queryInterface.addIndex('wms_inbox_message', { + fields: ['warehouse_id', 'group_id', 'created_at'], + name: 'idx_warehouse_group_created', + }); + console.log('[idx] wms_inbox_message.idx_warehouse_group_created 已创建'); + } catch (e) { + if (e.message && e.message.includes('Duplicate')) { + console.log('[idx] wms_inbox_message.idx_warehouse_group_created 已存在,跳过'); + } else { + throw e; + } + } + + // ── wms_inbox_group 索引 ── + try { + await queryInterface.addIndex('wms_inbox_group', { + fields: ['group_id'], + name: 'idx_group_id', + }); + console.log('[idx] wms_inbox_group.idx_group_id 已创建'); + } catch (e) { + if (e.message && e.message.includes('Duplicate')) { + console.log('[idx] wms_inbox_group.idx_group_id 已存在,跳过'); + } else { + throw e; + } + } + + try { + await queryInterface.addIndex('wms_inbox_group', { + fields: ['warehouse_id', 'group_id'], + name: 'idx_warehouse_group_id', + }); + console.log('[idx] wms_inbox_group.idx_warehouse_group_id 已创建'); + } catch (e) { + if (e.message && e.message.includes('Duplicate')) { + console.log('[idx] wms_inbox_group.idx_warehouse_group_id 已存在,跳过'); + } else { + throw e; + } + } + }, + + // eslint-disable-next-line no-unused-vars + down: async (queryInterface, Sequelize) => { + await queryInterface.removeIndex('wms_inbox_message', 'idx_warehouse_group_created'); + await queryInterface.removeIndex('wms_inbox_group', 'idx_group_id'); + await queryInterface.removeIndex('wms_inbox_group', 'idx_warehouse_group_id'); + }, +}; diff --git a/database/migrations/20260805150000-add-group-api-permissions.js b/database/migrations/20260805150000-add-group-api-permissions.js new file mode 100644 index 0000000..95cc4e6 --- /dev/null +++ b/database/migrations/20260805150000-add-group-api-permissions.js @@ -0,0 +1,53 @@ +'use strict'; + +/** + * 为 inbox.group.* 方法创建 API 权限记录。 + * + * 固定 ID(当前 max_id=494): + * 495 — inbox.group.list + * 496 — inbox.group.disable + * 497 — inbox.group.update + * 498 — inbox.group.messages + */ +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const methods = [ + [495, 'inbox.group.list'], + [496, 'inbox.group.disable'], + [497, 'inbox.group.update'], + [498, 'inbox.group.messages'], + ]; + + for (const [id, method] of methods) { + await queryInterface.sequelize.query(` + INSERT INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at) + VALUES (${id}, '${method}', NULL, '${method}', NULL, 'API:${method}', NULL, 0, 0, NULL, 'api', 0, 1, NOW(), NOW()) + ON DUPLICATE KEY UPDATE path='${method}', meta_title='API:${method}', type='api' + `); + } + + // 授权给客服组-主管及以上角色 + const newIdSuffix = ', 495, 496, 497, 498'; + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = CONCAT(LEFT(permissions, LENGTH(permissions) - 1), '${newIdSuffix}]') + WHERE id IN (8, 26, 28, 29) + AND permissions != '*' + AND permissions IS NOT NULL + AND LENGTH(permissions) > 2 + `); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.sequelize.query( + 'DELETE FROM wms_permission WHERE id IN (495, 496, 497, 498)' + ); + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = REPLACE(permissions, ', 495, 496, 497, 498', '') + WHERE id IN (8, 26, 28, 29) + `); + }, +}; diff --git a/database/migrations/20260806120000-add-ai-thoughts-to-inbox-message.js b/database/migrations/20260806120000-add-ai-thoughts-to-inbox-message.js new file mode 100644 index 0000000..fe6095d --- /dev/null +++ b/database/migrations/20260806120000-add-ai-thoughts-to-inbox-message.js @@ -0,0 +1,27 @@ +'use strict'; + +/** + * 为 wms_inbox_message 新增 ai_thoughts 字段。 + * 存储 AI 多轮推理的思考过程数组。 + */ +module.exports = { + // eslint-disable-next-line no-unused-vars + up: async (queryInterface, Sequelize) => { + const tableInfo = await queryInterface.describeTable('wms_inbox_message'); + if (!tableInfo.ai_thoughts) { + await queryInterface.addColumn('wms_inbox_message', 'ai_thoughts', { + type: Sequelize.JSON, + allowNull: true, + comment: 'AI 多轮推理思考过程 [{round,action,function,params,reason,functionResult}]', + }); + } + }, + + // eslint-disable-next-line no-unused-vars + down: async (queryInterface) => { + const tableInfo = await queryInterface.describeTable('wms_inbox_message'); + if (tableInfo.ai_thoughts) { + await queryInterface.removeColumn('wms_inbox_message', 'ai_thoughts'); + } + }, +}; diff --git a/database/migrations/20260806150000-add-ai-enabled-to-inbox-group.js b/database/migrations/20260806150000-add-ai-enabled-to-inbox-group.js new file mode 100644 index 0000000..c7efcc3 --- /dev/null +++ b/database/migrations/20260806150000-add-ai-enabled-to-inbox-group.js @@ -0,0 +1,21 @@ +'use strict'; + +const TABLE_NAME = 'wms_inbox_group'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const columns = await queryInterface.describeTable(TABLE_NAME); + if (columns.ai_enabled) return; + + await queryInterface.addColumn(TABLE_NAME, 'ai_enabled', { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 1, + comment: '是否启用AI自动回复: 0=关闭 1=开启', + }); + }, + + down: async queryInterface => { + await queryInterface.removeColumn(TABLE_NAME, 'ai_enabled'); + }, +}; diff --git a/database/migrations/20260806160000-drop-target-channel-from-inbox-message.js b/database/migrations/20260806160000-drop-target-channel-from-inbox-message.js new file mode 100644 index 0000000..aea30e1 --- /dev/null +++ b/database/migrations/20260806160000-drop-target-channel-from-inbox-message.js @@ -0,0 +1,20 @@ +'use strict'; + +const TABLE_NAME = 'wms_inbox_message'; + +module.exports = { + up: async queryInterface => { + const columns = await queryInterface.describeTable(TABLE_NAME); + if (!columns.target_channel) return; + + await queryInterface.removeColumn(TABLE_NAME, 'target_channel'); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.addColumn(TABLE_NAME, 'target_channel', { + type: Sequelize.STRING(50), + allowNull: true, + comment: '目标渠道:wecom / dingtalk / feishu / warehouse_api / webhook', + }); + }, +}; diff --git a/methods/changes/system.json b/methods/changes/system.json index bc780e4..11f208f 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,21 @@ [ + { + "version": "2026.08.06-inbox-bindCode", + "date": "2026-08-06", + "type": "added", + "summary": "新增货主绑群码生成接口。校验 StoreWarehouse 合约有效性后生成12位随机码(大写字母+数字),缓存 key 为 chat:bind:{warehouseId}:{code},TTL 300秒。实现位于 systems/store.js → bindCode(),由 systemMethods/inbox.js → bindCode() 委托调用。", + "methods": [ + "inbox.bindCode" + ], + "notes": [ + "调用链:/system → systemMethods/inbox.bindCode → systems/store.bindCode。", + "前置校验:StoreWarehouse 合约 auth_status=2 AND warehouse_use_status=1,不满足则返回500。", + "缓存策略:app.setCacheAsync('chat:bind:{warehouseId}:{code}', { store_id, initiator_subject_id, warehouse_id, group_type, sub_type }, 300)。", + "绑定时消费:processor.tryBindGroup 匹配 '授权:CODE' 模式,读取缓存执行绑定,成功即清缓存。", + "warehouseId:从 ctx.user.store_id 自动注入,前端无需传递。" + ], + "module": "inbox" + }, { "version": "2026.08.05-inbox-group", "date": "2026-08-05", diff --git a/methods/system.json b/methods/system.json index 00db843..54c497f 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,7 +1,7 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.18", + "version": "0.3.19", "updatedAt": "2026-08-05", "headers": [ { @@ -31879,8 +31879,8 @@ "module": "inbox", "list": [ { - "method": "inbox.list", - "description": "站内信消息列表,按仓库/方向/状态/渠道筛选,支持关键词搜索(ext_id / ref_code),分页返回(默认20条/页,最大200条)", + "method": "inbox.message.list", + "description": "站内信消息列表,支持货主/群/用户名/正文/来源等多条件筛选,时间字段使用统一格式化输出,分页返回(默认20条/页,最大200条)", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -31892,6 +31892,48 @@ } ], "params": [ + { + "name": "storeId", + "type": "string", + "required": false, + "source": "body", + "description": "货主ID筛选,支持逗号分隔多选,如 \"1000000,1000001\"" + }, + { + "name": "groupId", + "type": "string", + "required": false, + "source": "body", + "description": "群ID筛选,支持逗号分隔多选" + }, + { + "name": "groupName", + "type": "string", + "required": false, + "source": "body", + "description": "群名称模糊搜索" + }, + { + "name": "userName", + "type": "string", + "required": false, + "source": "body", + "description": "用户名模糊搜索" + }, + { + "name": "content", + "type": "string", + "required": false, + "source": "body", + "description": "正文模糊搜索" + }, + { + "name": "sourceType", + "type": "string", + "required": false, + "source": "body", + "description": "来源类型筛选:im / api / system" + }, { "name": "direction", "type": "string", @@ -31906,20 +31948,6 @@ "source": "body", "description": "推送状态筛选:0=待推送 1=推送中 2=已送达 3=失败" }, - { - "name": "targetChannel", - "type": "string", - "required": false, - "source": "body", - "description": "目标渠道筛选:wecom / dingtalk / feishu / warehouse_api / webhook" - }, - { - "name": "keyword", - "type": "string", - "required": false, - "source": "body", - "description": "关键词搜索,模糊匹配 ext_id 和 ref_code" - }, { "name": "page", "type": "number", @@ -31942,7 +31970,7 @@ "name": "list", "type": "array", "required": true, - "description": "消息列表(不含 ext_data 和 push_response 大字段)", + "description": "消息列表(不含 ext_data、push_response、target_channel 字段,时间已格式化)", "children": [ { "name": "id", @@ -31962,6 +31990,18 @@ "required": true, "description": "所属仓库ID" }, + { + "name": "store_id", + "type": "number", + "required": false, + "description": "关联货主ID" + }, + { + "name": "store_name", + "type": "string", + "required": false, + "description": "货主名称(批量回填)" + }, { "name": "direction", "type": "string", @@ -31981,10 +32021,34 @@ "description": "目标类型:im / api / webhook" }, { - "name": "target_channel", + "name": "group_id", "type": "string", - "required": true, - "description": "目标渠道" + "required": false, + "description": "外部群ID" + }, + { + "name": "group_name", + "type": "string", + "required": false, + "description": "群名称" + }, + { + "name": "user_id", + "type": "string", + "required": false, + "description": "外部用户ID" + }, + { + "name": "user_name", + "type": "string", + "required": false, + "description": "用户名称" + }, + { + "name": "content", + "type": "string", + "required": false, + "description": "消息正文/摘要" }, { "name": "push_status", @@ -32002,7 +32066,19 @@ "name": "created_at", "type": "string", "required": true, - "description": "创建时间" + "description": "创建时间(YYYY-MM-DD HH:mm:ss 格式化)" + }, + { + "name": "updated_at", + "type": "string", + "required": true, + "description": "更新时间(YYYY-MM-DD HH:mm:ss 格式化)" + }, + { + "name": "pushed_at", + "type": "string", + "required": false, + "description": "推送完成时间(YYYY-MM-DD HH:mm:ss 格式化)" } ] }, @@ -32063,7 +32139,7 @@ ] }, { - "method": "inbox.detail", + "method": "inbox.message.detail", "description": "站内信消息详情,含完整 push_response 推送响应信息", "isNeedAuth": false, "isNeedLogin": true, @@ -32186,7 +32262,7 @@ ] }, { - "method": "inbox.thread", + "method": "inbox.message.thread", "description": "站内信对话链查询,返回原消息 + 所有回信(按 parent_id 递归),按时间升序排列", "isNeedAuth": false, "isNeedLogin": true, @@ -32231,7 +32307,7 @@ ] }, { - "method": "inbox.reply", + "method": "inbox.message.reply", "description": "系统回信:写入 outbound 记录 + 异步推送到目标渠道。自动继承原消息的 ext_data、ref_code 等字段", "isNeedAuth": false, "isNeedLogin": true, @@ -32316,7 +32392,7 @@ ] }, { - "method": "inbox.retry", + "method": "inbox.message.retry", "description": "手动重推失败(push_status=3)的站内信消息,重置为待推送状态并触发异步推送", "isNeedAuth": false, "isNeedLogin": true, @@ -32379,7 +32455,7 @@ ] }, { - "method": "inbox.stats", + "method": "inbox.message.stats", "description": "站内信推送统计:按方向汇总、按推送状态汇总、最近24小时新增数量", "isNeedAuth": false, "isNeedLogin": true, @@ -32461,7 +32537,7 @@ }, { "method": "inbox.bindCode", - "description": "生成货主绑群码。传入货主ID和子类型,生成5分钟有效12位随机码存入缓存", + "description": "生成货主绑群码。校验 StoreWarehouse 合约有效后,生成12位随机码(大写字母+数字),缓存 key 为 chat:bind:{warehouseId}:{code},TTL 300秒。warehouseId 从 token 自动注入", "isNeedAuth": true, "isNeedLogin": true, "headers": [ @@ -32478,14 +32554,14 @@ "type": "number", "required": true, "source": "body", - "description": "货主ID" + "description": "货主ID(需在目标仓库有有效合约 auth_status=2 warehouse_use_status=1)" }, { "name": "subType", "type": "string", "required": false, "source": "body", - "description": "群子类型编码:after_sales(售后) / finance(财务) / receiving(收货)" + "description": "群子类型:after_sales(售后) / finance(财务) / receiving(收货)" } ], "response": [ @@ -32493,13 +32569,13 @@ "name": "code", "type": "string", "required": true, - "description": "12位绑群随机码,5分钟有效" + "description": "12位绑群随机码(大写字母+数字),5分钟有效" } ], "errors": [ { "code": "400", - "message": "storeId 无效 / 缺少仓库信息" + "message": "storeId 无效 / 缺少仓库信息 / 子类型无效" }, { "code": "500", @@ -32561,7 +32637,7 @@ "name": "list", "type": "array", "required": true, - "description": "群记录列表,含id/group_name/group_id/store_id/group_type/sub_type/is_blocked/express_interfaces(数组)/system_express_code/created_at" + "description": "群记录列表,含id/group_name/group_id/store_id/group_type/sub_type/is_blocked/ai_enabled/express_interfaces(数组)/system_express_code/created_at" } ], "errors": [ @@ -32621,7 +32697,7 @@ }, { "method": "inbox.group.update", - "description": "修改群信息:群类型/子类型/货主/快递接口/系统快递编码。切换为express类型时systemExpressCode必填,expressInterfaces仅express类型生效", + "description": "修改群信息:群类型/子类型/货主/快递接口/系统快递编码/AI开关。aiEnabled支持灰度控制,切换为express类型时systemExpressCode必填", "isNeedAuth": true, "isNeedLogin": true, "headers": [ @@ -32674,6 +32750,13 @@ "required": false, "source": "body", "description": "系统快递编码,groupType=express时必填。需校验wms_express.code存在" + }, + { + "name": "aiEnabled", + "type": "number", + "required": false, + "source": "body", + "description": "是否启用AI自动回复: 0=关闭 1=开启,默认1(所有群类型均支持,用于灰度测试)" } ], "response": [ diff --git a/script/tmp-check-pending-migrations.cjs b/script/tmp-check-pending-migrations.cjs new file mode 100644 index 0000000..240e40f --- /dev/null +++ b/script/tmp-check-pending-migrations.cjs @@ -0,0 +1,87 @@ +'use strict'; + +const fs = require('node:fs'); +const path = require('node:path'); +const Sequelize = require('sequelize'); + +const ROOT = path.resolve(__dirname, '..'); +const MIGRATIONS_DIR = path.join(ROOT, 'database', 'migrations'); + +async function main() { + // 1. 收集本地所有迁移文件 + const allFiles = fs.readdirSync(MIGRATIONS_DIR).filter(f => f.endsWith('.js')).sort(); + console.log(`[本地] 迁移文件总数: ${allFiles.length}`); + + // 2. 连接生产数据库 + const dbConfig = { + host: '112.124.21.102', + port: 3306, + user: 'wms', + password: 'P6j3YTHTpirepYWz', + database: 'wms', + }; + + const sequelize = new Sequelize(dbConfig.database, dbConfig.user, dbConfig.password, { + host: dbConfig.host, + port: dbConfig.port, + dialect: 'mysql', + logging: false, + }); + + try { + await sequelize.authenticate(); + console.log('[DB] 生产数据库连接成功'); + } catch (e) { + console.error('[DB] 生产数据库连接失败:', e.message); + process.exit(2); + } + + // 3. 检查 SequelizeMeta 表是否存在 + let appliedNames = []; + try { + const [rows] = await sequelize.query('SELECT name FROM SequelizeMeta ORDER BY name'); + appliedNames = rows.map(r => (typeof r === 'string' ? r : r.name)).filter(Boolean); + } catch (e) { + console.error('[DB] 读取 SequelizeMeta 失败:', e.message); + await sequelize.close(); + process.exit(2); + } + + console.log(`[DB] SequelizeMeta 已记录迁移数: ${appliedNames.length}`); + + // 4. 找出未执行的迁移 + const appliedSet = new Set(appliedNames); + const pending = allFiles.filter(f => !appliedSet.has(f)); + const archived = allFiles.filter(f => f.startsWith('archive/')); + + console.log(`\n========== 结果汇总 ==========`); + console.log(`本地迁移文件总数: ${allFiles.length}`); + console.log(`已执行 (SequelizeMeta): ${appliedNames.length}`); + console.log(`未执行 (pending): ${pending.length}`); + console.log(`===============================\n`); + + if (pending.length === 0) { + console.log('✅ 所有迁移脚本均已执行,无 pending migration。'); + } else { + console.log(`❌ 发现 ${pending.length} 个未执行的迁移脚本:\n`); + pending.forEach((f, i) => { + console.log(` ${String(i + 1).padStart(3, ' ')}. ${f}`); + }); + + // 额外检查:有没有本地没有但 DB 已记录的(可能被删除了) + const localSet = new Set(allFiles); + const orphanInDb = appliedNames.filter(n => !localSet.has(n)); + if (orphanInDb.length > 0) { + console.log(`\n⚠️ DB 中记录了 ${orphanInDb.length} 个本地已不存在的迁移(可能已被删除):`); + orphanInDb.forEach(n => console.log(` - ${n}`)); + } + } + + await sequelize.close(); + console.log('\n[DONE] 检查完成'); +} + +main().catch(err => { + console.error('脚本执行异常:', err); + process.exit(1); +});