From 35c71e13c4a38384e939e9405f34d0d5a98c5175 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 8 Aug 2026 01:58:06 +0800 Subject: [PATCH] =?UTF-8?q?feat(inbox):=20=E7=BE=A4=E5=88=97=E8=A1=A8?= =?UTF-8?q?=E5=AD=97=E6=AE=B5=E4=BC=98=E5=8C=96=E3=80=81where=E6=9F=A5?= =?UTF-8?q?=E8=AF=A2=E6=94=AF=E6=8C=81=E3=80=81=E5=BF=AB=E9=80=92=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3=E5=8A=A0=E8=BD=BD=E5=8F=8A=E6=97=B6=E9=97=B4=E6=A0=BC?= =?UTF-8?q?=E5=BC=8F=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit inbox.group.list 优化: - 移除 warehouse_id 返回字段 - 新增 store_name(StoreWarehouse.store_remask) - express_interfaces 改为 {id,name} 对象数组 - 新增 system_express_name(wms_express.name) - created_at/updated_at 使用 app.formatDate 格式化 - 支持 pagination 对象 + where 结构化查询(parseWhereConditions) - keyword 虚拟字段映射为 group_name LIKE - groupType 驼峰映射为 group_type - 增加 specialFieldMap 声明合法字段 新增 index.loadExpressInterfaces: - 参考 loadStores 模式,拉取仓库下快递接口下拉列表 - 支持 systemExpressCode 入参过滤 - systemMethods/index.js 注册 + methods/system.json 文档 其他: - delivery_order_code + store_id 联合索引迁移 --- app/service/inbox/functions.js | 157 ++++++++++++++++-- app/service/inbox/processor.js | 7 + app/service/systemMethods/inbox.js | 4 +- app/service/systemMethods/index.js | 10 +- app/service/systems/inbox/group.js | 143 +++++++++++++++- .../systems/setting/expressInterface.js | 31 ++++ ...808100000-add-delivery-code-store-index.js | 14 ++ methods/system.json | 53 ++++++ 8 files changed, 399 insertions(+), 20 deletions(-) create mode 100644 database/migrations/20260808100000-add-delivery-code-store-index.js diff --git a/app/service/inbox/functions.js b/app/service/inbox/functions.js index 6c9ed95..aeb389b 100644 --- a/app/service/inbox/functions.js +++ b/app/service/inbox/functions.js @@ -126,16 +126,8 @@ class InboxFunctionsService extends Service { 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 - ); + const storeId = Number(ctx.inboxContext?.store_id || 0); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); if (!Number.isFinite(storeId) || storeId <= 0) { return { @@ -558,6 +550,151 @@ class InboxFunctionsService extends Service { }, }); + this.register('queryOrder', { + description: '查询订单。先精确匹配运单号,未命中则模糊搜索发货单号/平台单号。自动定位订单在待处理表/配送表/历史表中的位置,返回订单关键信息和重量。重量字段说明:items_weight 为订单商品总重量(g),waybills[].weighing_weight 为快递实际称重重量(g),仅已分配运单号时才有称重值', + params: { + keyword: { type: 'string', required: true, description: '搜索关键词:运单号(waybill_code,精确匹配)、发货单号(delivery_order_code,模糊)、平台单号(source_platform_code,模糊)' }, + }, + groups: [ GROUP.BOUND_STORE_AFTER_SALES ], + handler: async (params = {}) => { + const { ctx } = this; + const storeId = Number(ctx.inboxContext?.store_id || 0); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const keyword = String(params.keyword || '').trim(); + const { Op } = ctx.app.Sequelize; + + if (!keyword) return { success: false, error: '请提供搜索关键词' }; + if (!warehouseId || !storeId) return { success: false, error: '无法获取仓库或货主信息' }; + + // 公共:三张订单表配置 + const attributes = [ + 'id', 'delivery_order_code', 'source_platform_code', 'source_order_codes', + 'store_id', 'warehouse_id', 'status', 'step', + 'name', 'mobile', 'province', 'city', 'area', 'detail_address', + 'items_count', 'items_total', 'items_weight', + 'express_code', 'logistics_name', 'logistics_code', + 'total_amount', 'freight', + 'create_at', 'updated_at', 'delivery_time', + ]; + const tableConfigs = [ + { key: 'current', label: '待处理表', getModel: (f, wid) => f.getCurrentModel(wid) }, + { key: 'dispatch', label: '配送表', getModel: (f, wid) => f.getDispatchModel(wid) }, + { key: 'history', label: '历史表', getModel: (f, wid) => f.getHistoryModel(wid) }, + ]; + const factory = ctx.model.OrderDeliveryFactory; + + /** + * 在三张订单表中查找匹配行 + * @param {Object} where WHERE 条件 + * @return {Object|null} 找到的行(含 table/key),或 null + */ + const findInDeliveryTables = async where => { + for (const cfg of tableConfigs) { + const model = await cfg.getModel(factory, warehouseId); + if (!model) continue; + const row = await model.findOne({ attributes, where, raw: true }); + if (row) return { table: cfg.key, table_label: cfg.label, ...row }; + } + return null; + }; + + try { + let found = null; + + // ========== 第一步:运单号精确匹配 ========== + const exactExpress = await ctx.model.OrderExpress.findOne({ + attributes: [ 'delivery_order_code' ], + where: { + waybill_code: keyword, + store_id: storeId, + warehouse_id: warehouseId, + }, + raw: true, + }); + + if (exactExpress && exactExpress.delivery_order_code) { + // 用运单关联的发货单号精确查找订单 + found = await findInDeliveryTables({ + store_id: storeId, + delivery_order_code: exactExpress.delivery_order_code, + }); + } + + // ========== 第二步:运单未命中 → 模糊搜索发货单号 / 平台单号 ========== + if (!found) { + found = await findInDeliveryTables({ + store_id: storeId, + [Op.or]: [ + { delivery_order_code: { [Op.like]: `%${keyword}%` } }, + { source_platform_code: { [Op.like]: `%${keyword}%` } }, + ], + }); + } + + if (!found) { + return { + success: false, + error: `未找到与「${keyword}」匹配的订单,请核实单号后重试(支持运单号精确匹配 / 发货单号模糊 / 平台单号模糊查询)`, + }; + } + + // ========== 第三步:查关联运单信息 ========== + const linkedExpress = await ctx.model.OrderExpress.findAll({ + attributes: [ 'waybill_code', 'logistics_name', 'weighing_weight', 'status', 'is_galaxy_receive' ], + where: { + delivery_order_code: found.delivery_order_code, + store_id: storeId, + }, + raw: true, + }); + + const hasWaybill = linkedExpress.length > 0; + + return { + success: true, + data: { + table: found.table, + table_label: found.table_label, + order_id: found.id, + delivery_order_code: found.delivery_order_code || '', + source_platform_code: found.source_platform_code || '', + source_order_codes: found.source_order_codes || '', + status: found.status, + step: found.step, + receiver_name: found.name || '', + receiver_mobile: found.mobile || '', + receiver_address: [ found.province, found.city, found.area, found.detail_address ] + .filter(Boolean).join(''), + items_count: found.items_count || 0, + items_total: found.items_total || 0, + // 重量信息(必须区分说明) + items_weight: found.items_weight || 0, + items_weight_note: '商品总重量(克),订单中所有商品SKU的合计重量', + has_waybill: hasWaybill, + has_waybill_note: hasWaybill ? '' : '该订单尚未分配运单号,无实际称重重量', + waybills: linkedExpress.map(e => ({ + waybill_code: e.waybill_code || '', + logistics_name: e.logistics_name || '', + weighing_weight: e.weighing_weight || 0, + weighing_weight_note: '快递实际称重重量(克),仅已分配运单号并完成称重时才有值', + status: e.status, + is_received: e.is_galaxy_receive === 'Y', + })), + express_code: found.express_code || '', + logistics_name: found.logistics_name || '', + total_amount: found.total_amount, + freight: found.freight, + created_at: found.create_at, + updated_at: found.updated_at, + delivery_time: found.delivery_time || null, + }, + }; + } catch (error) { + return { success: false, error: `订单查询失败: ${error.message}` }; + } + }, + }); + this.register('recallHistory', { description: '回顾当前群+用户的最近对话历史。当需要上下文但信息不足时调用,获取最近N条消息记录(含AI回复),每条带序号', params: { diff --git a/app/service/inbox/processor.js b/app/service/inbox/processor.js index bec7f8b..6b6fd0d 100644 --- a/app/service/inbox/processor.js +++ b/app/service/inbox/processor.js @@ -128,6 +128,13 @@ class InboxProcessorService extends Service { } } + // 4.5 群未绑定任务类型 → 跳过 AI 处理 + const groupType = String(ctx.inboxContext.group_type || '').trim(); + if (!groupType) { + ctx.logger.info(`[inbox processor] 群未绑定任务类型,跳过 AI ext_id=${extId}`); + return; + } + // 5. 群未启用AI → 跳过(ai_enabled != 1 一律跳过,安全默认) if (ctx.inboxContext.ai_enabled !== 1) { ctx.logger.info(`[inbox processor] 群未启用AI自动回复,跳过 AI ext_id=${extId}`); diff --git a/app/service/systemMethods/inbox.js b/app/service/systemMethods/inbox.js index f3314f5..c0dccee 100644 --- a/app/service/systemMethods/inbox.js +++ b/app/service/systemMethods/inbox.js @@ -83,7 +83,7 @@ class InboxSystemService extends MainService { */ async groupList(data = {}) { const { ctx } = this; - const { groupType, keyword, page, pageSize } = data; + const { groupType, keyword, page, pageSize, pagination, where } = data; const warehouseId = Number(ctx.user?.store_id || 0); return await ctx.service.systems.inbox.group.list({ @@ -92,6 +92,8 @@ class InboxSystemService extends MainService { keyword, page, pageSize, + pagination, + where, }); } diff --git a/app/service/systemMethods/index.js b/app/service/systemMethods/index.js index 080f03b..19f4bd7 100644 --- a/app/service/systemMethods/index.js +++ b/app/service/systemMethods/index.js @@ -1053,9 +1053,9 @@ class indexService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = 'getI18nMessage,putI18nCollect,test,getCainiaoStfTemplates,polyapiAuthorizeUrl'; - const _noNeedRight = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder'; + const _noNeedRight = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,loadExpressInterfaces,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder'; const _noNeedLog = '*'; - const _noNeedAuth = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,getImages,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,test,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder'; + const _noNeedAuth = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,loadExpressInterfaces,getImages,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,test,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } async fastWhereTree(data) { @@ -1074,6 +1074,12 @@ class indexService extends MainService { const result = await service.systems.store.loadWarehouses(); return this.success('ok', { warehouses: result, code: 200 }); } + async loadExpressInterfaces(data = {}) { + const { service } = this; + const { systemExpressCode } = data; + const result = await service.systems.setting.expressInterface.loadExpressInterfaces({ systemExpressCode }); + return this.success('ok', { expressInterfaces: result, code: 200 }); + } async getCOSUploadConfig(datas) { const { service } = this; const { data } = datas; diff --git a/app/service/systems/inbox/group.js b/app/service/systems/inbox/group.js index 876daf3..7f4abf4 100644 --- a/app/service/systems/inbox/group.js +++ b/app/service/systems/inbox/group.js @@ -1,6 +1,7 @@ 'use strict'; const Service = require('egg').Service; +const { parseWhereConditions } = require('../../../lib/query_condition_parser'); /** * 站内信群管理业务逻辑层。 @@ -20,25 +21,84 @@ class InboxGroupService extends Service { */ async list(data = {}) { const { ctx } = this; - const { InboxGroup } = ctx.model; + const { InboxGroup, StoreWarehouse, ExpressInterface, Express } = 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)); + + // 分页:优先取 pagination 对象,兜底扁平参数 + const pag = data.pagination || {}; + const page = Math.max(1, Number(pag.page || data.page) || 1); + const pageSize = Math.min(100, Math.max(1, Number(pag.pageSize || data.pageSize) || 20)); const offset = (page - 1) * pageSize; if (!warehouseId) throw new Error('warehouseId 无效'); const where = { warehouse_id: warehouseId }; + + // ── 扁平参数(向后兼容)── + const groupType = String(data.groupType || '').trim(); + const keyword = String(data.keyword || '').trim(); if (groupType) where.group_type = groupType; if (keyword) where.group_name = { [Op.like]: `%${keyword}%` }; + // ── 结构化 where(operator 模式)── + if (data.where && typeof data.where === 'object') { + // 从 where 中提取虚拟字段(不允许直接作为列名查询) + const whereInput = { ...data.where }; + + // keyword:虚拟字段 → 模糊搜索 group_name + if (whereInput.keyword !== undefined) { + const kw = whereInput.keyword; + delete whereInput.keyword; + const kwValue = kw && typeof kw === 'object' && kw.value !== undefined ? kw.value : kw; + const kwArr = Array.isArray(kwValue) ? kwValue : [ kwValue ]; + const kwStr = kwArr.filter(Boolean).join('').trim(); + if (kwStr && !keyword) { + where.group_name = { [Op.like]: `%${kwStr}%` }; + } + } + + // groupType: camelCase → group_type(优先已从扁平参数设置的 group_type) + if (whereInput.groupType !== undefined) { + const gt = whereInput.groupType; + delete whereInput.groupType; + const gtValue = gt && typeof gt === 'object' && gt.value !== undefined ? gt.value : gt; + const gtStr = String(gtValue || '').trim(); + if (gtStr && !groupType) { + where.group_type = gtStr; + } + } + + if (Object.keys(whereInput).length > 0) { + const parsed = parseWhereConditions({ + where: whereInput, + app: ctx.app, + specialFieldMap: { + store_id: { field: 'store_id' }, + group_id: { field: 'group_id' }, + group_name: { field: 'group_name' }, + sub_type: { field: 'sub_type' }, + source_type: { field: 'source_type' }, + is_blocked: { field: 'is_blocked' }, + ai_enabled: { field: 'ai_enabled' }, + system_express_code: { field: 'system_express_code' }, + }, + }); + + if (!parsed.ok) { + throw new Error(`where 参数解析失败: ${parsed.reason}`); + } + + if (Array.isArray(parsed.result.dynamicConditions)) { + Object.assign(where, ...parsed.result.dynamicConditions); + } + } + } + const { count, rows } = await InboxGroup.findAndCountAll({ attributes: [ - 'id', 'group_name', 'group_id', 'warehouse_id', 'store_id', + 'id', 'group_name', 'group_id', 'store_id', 'group_type', 'sub_type', 'source_type', 'source_extra', 'is_blocked', 'ai_enabled', 'express_interfaces', 'system_express_code', 'created_at', 'updated_at', @@ -50,12 +110,81 @@ class InboxGroupService extends Service { raw: true, }); - // express_interfaces 输出为数组 + // 收集需要批量查询的 ID + const storeIds = [ ...new Set(rows.map(r => r.store_id).filter(Boolean)) ]; + const allExpressInterfaceIds = []; + const expressCodes = [ ...new Set(rows.map(r => r.system_express_code).filter(Boolean)) ]; + + rows.forEach(row => { + if (row.express_interfaces) { + const ids = row.express_interfaces.split(',').map(Number).filter(Boolean); + ids.forEach(id => allExpressInterfaceIds.push(id)); + } + }); + const uniqueExpressInterfaceIds = [ ...new Set(allExpressInterfaceIds) ]; + + // 批量查询货主仓库合约备注 + let storeWarehouseMap = {}; + if (storeIds.length > 0) { + const swRows = await StoreWarehouse.findAll({ + attributes: [ 'store_id', 'store_remask' ], + where: { + store_id: { [Op.in]: storeIds }, + warehouse_id: warehouseId, + }, + raw: true, + }); + storeWarehouseMap = swRows.reduce((acc, sw) => { + acc[sw.store_id] = sw.store_remask || ''; + return acc; + }, {}); + } + + // 批量查询快递接口名称 + let expressInterfaceMap = {}; + if (uniqueExpressInterfaceIds.length > 0) { + const eiRows = await ExpressInterface.findAll({ + attributes: [ 'id', 'name' ], + where: { id: { [Op.in]: uniqueExpressInterfaceIds } }, + raw: true, + }); + expressInterfaceMap = eiRows.reduce((acc, ei) => { + acc[ei.id] = ei.name || ''; + return acc; + }, {}); + } + + // 批量查询系统快递名称 + let expressNameMap = {}; + if (expressCodes.length > 0) { + const expressRows = await Express.findAll({ + attributes: [ 'code', 'name' ], + where: { code: { [Op.in]: expressCodes } }, + raw: true, + }); + expressNameMap = expressRows.reduce((acc, e) => { + acc[e.code] = e.name || ''; + return acc; + }, {}); + } + + // 组装返回数据 + const formatDate = ctx.app.formatDate; const list = rows.map(row => ({ ...row, + store_name: row.store_id ? (storeWarehouseMap[row.store_id] || '') : '', express_interfaces: row.express_interfaces ? row.express_interfaces.split(',').map(Number).filter(Boolean) + .map(id => ({ + id, + name: expressInterfaceMap[id] || '', + })) : [], + system_express_name: row.system_express_code + ? (expressNameMap[row.system_express_code] || '') + : '', + created_at: row.created_at ? formatDate(row.created_at) : '', + updated_at: row.updated_at ? formatDate(row.updated_at) : '', })); return { total: count, list }; diff --git a/app/service/systems/setting/expressInterface.js b/app/service/systems/setting/expressInterface.js index 0d95bf0..9fa73fc 100644 --- a/app/service/systems/setting/expressInterface.js +++ b/app/service/systems/setting/expressInterface.js @@ -1643,6 +1643,37 @@ class SettingExpressInterfaceService extends Service { }, }; } + + /** + * 加载当前仓库下所有快递接口的下拉选项(id + name)。 + * 供 index.loadExpressInterfaces 调用,用于前端下拉框。 + * + * @param {Object} [data={}] 请求参数 + * @param {string} [data.systemExpressCode] 系统快递编码,传入时按 sys_express_code 过滤 + * @return {Promise>} 快递接口下拉列表 + */ + async loadExpressInterfaces(data = {}) { + const { ctx } = this; + const warehouseId = this.getCurrentStoreId(); + const systemExpressCode = String(data.systemExpressCode || '').trim().toUpperCase(); + + const where = { warehouse_id: warehouseId }; + if (systemExpressCode) { + where.sys_express_code = systemExpressCode; + } + + const rows = await ctx.model.ExpressInterface.findAll({ + where, + attributes: [ 'id', 'name' ], + order: [[ 'weight', 'ASC' ], [ 'id', 'ASC' ]], + raw: true, + }); + + return rows.map(row => ({ + value: row.id, + label: row.name || '', + })); + } } module.exports = SettingExpressInterfaceService; diff --git a/database/migrations/20260808100000-add-delivery-code-store-index.js b/database/migrations/20260808100000-add-delivery-code-store-index.js new file mode 100644 index 0000000..6537aaf --- /dev/null +++ b/database/migrations/20260808100000-add-delivery-code-store-index.js @@ -0,0 +1,14 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + // Query 3 关联查询:delivery_order_code + store_id 联合索引(最高频缺失索引) + await queryInterface.addIndex('wms_order_express', ['delivery_order_code', 'store_id'], { + name: 'idx_delivery_code_store', + }); + }, + + async down(queryInterface, Sequelize) { + await queryInterface.removeIndex('wms_order_express', 'idx_delivery_code_store'); + }, +}; diff --git a/methods/system.json b/methods/system.json index 4c069d1..def17fe 100644 --- a/methods/system.json +++ b/methods/system.json @@ -468,6 +468,59 @@ "response": [], "errors": [] }, + { + "method": "index.loadExpressInterfaces", + "description": "index.loadExpressInterfaces 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "systemExpressCode", + "type": "string", + "required": false, + "source": "body", + "description": "系统快递编码(wms_express.code),传入时仅返回该编码对应的快递接口" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "description": "业务状态码,200 表示成功" + }, + { + "name": "message", + "type": "string", + "description": "业务提示信息" + }, + { + "name": "expressInterfaces", + "type": "array", + "description": "当前仓库下的快递接口下拉列表", + "children": [ + { + "name": "value", + "type": "number", + "description": "快递接口ID(wms_express_interface.id)" + }, + { + "name": "label", + "type": "string", + "description": "快递接口名称(wms_express_interface.name)" + } + ] + } + ], + "errors": [] + }, { "method": "index.getCOSUploadConfig", "description": "index.getCOSUploadConfig 接口",