diff --git a/app/model/return_query_log.js b/app/model/return_query_log.js index ff693b9..e3de87c 100644 --- a/app/model/return_query_log.js +++ b/app/model/return_query_log.js @@ -30,6 +30,26 @@ module.exports = app => { allowNull: false, comment: '查询过的运单号', }, + group_id: { + type: STRING(100), + allowNull: true, + comment: '触发查询的群ID(站内信外部群ID)', + }, + group_name: { + type: STRING(100), + allowNull: true, + comment: '触发查询的群名称', + }, + user_id: { + type: STRING(100), + allowNull: true, + comment: '触发查询的用户ID(站内信外部用户ID)', + }, + user_name: { + type: STRING(100), + allowNull: true, + comment: '触发查询的用户名称', + }, remark: { type: STRING(500), allowNull: true, diff --git a/app/service/inbox/functions.js b/app/service/inbox/functions.js index 35b6eff..ae145d1 100644 --- a/app/service/inbox/functions.js +++ b/app/service/inbox/functions.js @@ -1698,6 +1698,10 @@ class InboxFunctionsService extends Service { waybill_code: waybill, warehouse_id: warehouseId, store_id: storeId, + group_id: ctx.inboxContext?.group_id, + group_name: ctx.inboxContext?.group_name, + user_id: ctx.inboxContext?.user_id, + user_name: ctx.inboxContext?.user_name, }); const warehouseLabel = result.warehouse_name || '仓库'; diff --git a/app/service/systems/return_unpack.js b/app/service/systems/return_unpack.js index efe375e..695cc4b 100644 --- a/app/service/systems/return_unpack.js +++ b/app/service/systems/return_unpack.js @@ -674,7 +674,7 @@ class ReturnUnpackService extends Service { ctx.logger.warn(`[returnUnpack.submit] 更新退回查询记录 is_back 失败: ${err.message}`); } - // 拆包完成后通知货主群:登记表/拆包单有货主归属且未通知的,推送到货主售后群并标记 is_notified=1 + // 拆包完成后按原查询登记来源通知(登记时记录的来源群/用户):推送成功后标记 is_notified=1 await this._notifyUnpacked(unpack); const updated = await ctx.model.ReturnUnpack.findOne({ @@ -688,9 +688,11 @@ class ReturnUnpackService extends Service { } /** - * 拆包完成后通知货主群。 - * 通知集合:仅退回查询登记表中该运单已退回(is_back=1)且未通知(is_notified=0)、有货主归属的记录; - * 货主从未查询过退回(登记表无匹配)的不通知。推送成功后标记 is_notified=1。 + * 拆包完成后按原查询登记来源通知(不再泛推货主售后群)。 + * 通知集合:仅退回查询登记表中该运单已退回(is_back=1)且未通知(is_notified=0)的记录; + * 按登记来源(group_id + user_id)聚合后逐来源回信:有用户信息时走 writeOutboundReply + * 定向回原查询用户,无用户信息时退化为该群的系统通知;登记时无来源群的记录(如后台 API 登记)不通知。 + * 仅推送成功的登记标记 is_notified=1。 * * @param {Object} unpack 拆包单主表记录 * @return {Promise} 异常仅记日志不阻塞主流程 @@ -700,8 +702,16 @@ class ReturnUnpackService extends Service { const { Op } = ctx.app.Sequelize; const warehouseId = Number(unpack.warehouse_id || 0); try { + const processor = ctx.service.inbox && ctx.service.inbox.processor; + if (!processor || typeof processor.pushSystemNotification !== 'function') { + ctx.logger.warn( + `[returnUnpack._notifyUnpacked] inbox processor 不可用,跳过通知 waybill=${unpack.waybill_code}` + ); + return; + } + const logs = await ctx.model.ReturnQueryLog.findAll({ - attributes: [ 'id', 'store_id', 'waybill_code' ], + attributes: [ 'id', 'store_id', 'waybill_code', 'group_id', 'group_name', 'user_id', 'user_name' ], where: { warehouse_id: warehouseId, [Op.or]: this._buildWaybillMatch(unpack.waybill_code), @@ -711,52 +721,118 @@ class ReturnUnpackService extends Service { raw: true, }); - // 通知对象:store_id → 运单号集合(仅货主查询过退回的登记,store_id 必须有归属) - const notifyMap = new Map(); + if (logs.length === 0) { + ctx.logger.info( + `[returnUnpack._notifyUnpacked] 无待通知的退回查询登记,跳过通知 waybill=${unpack.waybill_code}` + ); + return; + } + + // 按登记来源聚合:key=group_id|user_id → 运单号集合(同一来源的多条登记合并为一条消息) + const buckets = new Map(); + const bucketIds = new Map(); + const skippedIds = []; for (const log of logs) { - const sid = Number(log.store_id || 0); - if (sid <= 0) continue; - if (!notifyMap.has(sid)) notifyMap.set(sid, new Set()); - notifyMap.get(sid).add(log.waybill_code || unpack.waybill_code); + const groupId = String(log.group_id || '').trim(); + if (!groupId) { + // 登记时无来源群(如后台 API 登记):不通知,保留 is_notified=0 + skippedIds.push(log.id); + continue; + } + const userId = String(log.user_id || '').trim(); + const key = `${groupId}\u0000${userId}`; + if (!buckets.has(key)) { + buckets.set(key, { + groupId, + groupName: String(log.group_name || '').trim(), + userId, + userName: String(log.user_name || '').trim(), + waybills: new Set(), + storeId: 0, + }); + bucketIds.set(key, []); + } + const bucket = buckets.get(key); + bucket.waybills.add(log.waybill_code || unpack.waybill_code); + if (!bucket.storeId) bucket.storeId = Number(log.store_id || 0); + bucketIds.get(key).push(log.id); } - if (notifyMap.size === 0) { + if (buckets.size === 0) { ctx.logger.info( - `[returnUnpack._notifyUnpacked] 无货主查询过退回的登记,跳过通知 waybill=${unpack.waybill_code}` + `[returnUnpack._notifyUnpacked] 登记均无来源群信息,跳过通知 waybill=${unpack.waybill_code} skipped=${skippedIds.length}` ); return; } - // 查货主售后群 - const storeIds = [ ...notifyMap.keys() ]; - const groups = await ctx.service.systems.inbox.group.findStoreAfterSalesGroups({ - storeIds, - warehouseId, - }); - if (groups.length === 0) { - ctx.logger.info( - `[returnUnpack._notifyUnpacked] 未找到货主售后群,跳过通知 storeIds=${storeIds.join(',')}` - ); - return; - } - - // 按群推送(一条消息含该货主的全部运单) - for (const g of groups) { - const waybills = [ ...(notifyMap.get(Number(g.store_id)) || new Set()) ]; - if (waybills.length === 0) continue; - const content = `退回包裹已拆包完成:\n${waybills.join('\n')}\n发送:查退回+运单号,可查看拆包明细`; - ctx.service.inbox.processor.pushSystemNotification({ - warehouse_id: warehouseId, - group_id: g.group_id, - group_name: g.group_name, - content, - ext_data: g.ext_data || null, - store_id: g.store_id || null, + // 批量反查群信息(补全 group_name/ext_data/store_id;群已解绑时用登记快照兑底) + const groupMap = new Map(); + const groupIds = [ ...buckets.values() ].map(bucket => bucket.groupId); + try { + const groupRows = await ctx.model.InboxGroup.findAll({ + attributes: [ 'group_id', 'group_name', 'store_id', 'ext_data' ], + where: { group_id: { [Op.in]: groupIds }, warehouse_id: warehouseId }, + raw: true, }); + for (const g of groupRows) { + groupMap.set(String(g.group_id), g); + } + } catch (err) { + ctx.logger.warn(`[returnUnpack._notifyUnpacked] 批量查询群信息失败: ${err.message}`); } - // 标记已通知 - const notifiedIds = logs.map(l => l.id); + // 逐来源回信(一条消息含该来源登记的全部运单) + const notifiedIds = []; + let bucketIdx = 0; + for (const [ key, bucket ] of buckets) { + bucketIdx += 1; + const groupRow = groupMap.get(bucket.groupId) || null; + const groupName = String(bucket.groupName || (groupRow && groupRow.group_name) || '').trim(); + if (!groupName) { + skippedIds.push(...bucketIds.get(key)); + ctx.logger.warn( + `[returnUnpack._notifyUnpacked] 来源群名缺失,跳过通知 group=${bucket.groupId}` + ); + continue; + } + const storeId = bucket.storeId || Number(groupRow && groupRow.store_id) || null; + const extData = (groupRow && groupRow.ext_data) || null; + const waybills = [ ...bucket.waybills ]; + const content = `退回包裹已拆包完成:\n${waybills.join('\n')}\n发送:查退回+运单号,可查看拆包明细`; + try { + if (bucket.userId && bucket.userName && typeof processor.writeOutboundReply === 'function') { + // 定向回原查询用户(登记来源用户信息完整时) + await processor.writeOutboundReply({ + warehouse_id: warehouseId, + group_id: bucket.groupId, + group_name: groupName, + user_id: bucket.userId, + user_name: bucket.userName, + store_id: storeId, + ext_data: extData, + ext_id: `unpack:notify:${unpack.id}:${bucketIdx}`, + }, content, 'ai_reply'); + } else { + // 无用户信息:退化为来源群系统通知 + processor.pushSystemNotification({ + warehouse_id: warehouseId, + group_id: bucket.groupId, + group_name: groupName, + content, + ext_data: extData, + store_id: storeId, + }); + } + notifiedIds.push(...bucketIds.get(key)); + } catch (err) { + skippedIds.push(...bucketIds.get(key)); + ctx.logger.warn( + `[returnUnpack._notifyUnpacked] 通知失败 group=${bucket.groupId}: ${err.message}` + ); + } + } + + // 仅标记推送成功的登记(失败/无来源的保留 is_notified=0) if (notifiedIds.length > 0) { await ctx.model.ReturnQueryLog.update( { is_notified: 1 }, @@ -765,7 +841,7 @@ class ReturnUnpackService extends Service { } ctx.logger.info( `[returnUnpack._notifyUnpacked] 拆包通知完成 waybill=${unpack.waybill_code} ` + - `groups=${groups.length} logs=${notifiedIds.length}` + `notified=${notifiedIds.length} skipped=${skippedIds.length} buckets=${buckets.size}` ); } catch (err) { ctx.logger.warn(`[returnUnpack._notifyUnpacked] 拆包通知失败: ${err.message}`); @@ -1599,10 +1675,14 @@ class ReturnUnpackService extends Service { * @param {string} params.waybill_code 退回包裹运单号(必填)。 * @param {number} params.warehouse_id 仓库ID(必填)。 * @param {number} [params.store_id] 货主ID(可选,用于货主隔离与未退回登记)。 + * @param {string} [params.group_id] 触发查询的群ID(站内信外部群ID,登记来源)。 + * @param {string} [params.group_name] 触发查询的群名称(登记来源)。 + * @param {string} [params.user_id] 触发查询的用户ID(站内信外部用户ID,登记来源)。 + * @param {string} [params.user_name] 触发查询的用户名称(登记来源)。 * @return {Promise} { status, waybill_code, warehouse_name, ... }。 * status:unpacked(已拆包)/ received(已收到未拆包)/ not_returned(未退回)/ hidden(跨货主不可见)。 */ - async queryByWaybill({ waybill_code, warehouse_id, store_id } = {}) { + async queryByWaybill({ waybill_code, warehouse_id, store_id, group_id, group_name, user_id, user_name } = {}) { const { ctx, app } = this; const { Op } = app.Sequelize; @@ -1617,6 +1697,12 @@ class ReturnUnpackService extends Service { } const storeId = Number(store_id || 0); + // 登记来源(站内信「查退回」触发):群/用户信息写入退回查询登记表,用于追溯与定向通知 + const sourceGroupId = String(group_id || '').trim() || null; + const sourceGroupName = String(group_name || '').trim() || null; + const sourceUserId = String(user_id || '').trim() || null; + const sourceUserName = String(user_name || '').trim() || null; + const warehouseName = await this._resolveWarehouseName(warehouseId); // 1. 已拆包:同一运单号取最新一条有效拆包单(跳过已作废) @@ -1746,6 +1832,10 @@ class ReturnUnpackService extends Service { remark: '站内信查询退回自动登记(已收到未拆包)', is_notified: 0, is_back: 0, + group_id: sourceGroupId, + group_name: sourceGroupName, + user_id: sourceUserId, + user_name: sourceUserName, }); queryLog = created && typeof created.toJSON === 'function' ? created.toJSON() : created; } catch (err) { @@ -1802,6 +1892,10 @@ class ReturnUnpackService extends Service { remark: '站内信查询退回自动登记', is_notified: 0, is_back: 0, + group_id: sourceGroupId, + group_name: sourceGroupName, + user_id: sourceUserId, + user_name: sourceUserName, }); createdRow = created && typeof created.toJSON === 'function' ? created.toJSON() : created; } catch (err) { diff --git a/database/migrations/20260924160000-add-source-ids-to-wms-return-query-log.js b/database/migrations/20260924160000-add-source-ids-to-wms-return-query-log.js new file mode 100644 index 0000000..3549df8 --- /dev/null +++ b/database/migrations/20260924160000-add-source-ids-to-wms-return-query-log.js @@ -0,0 +1,50 @@ +'use strict'; + +const TABLE = 'wms_return_query_log'; + +/** + * 退回查询记录表新增登记来源字段:group_id / group_name / user_id / user_name。 + * 站内信「查退回」触发登记时写入查询来源的群/用户信息(后台 API 登记路径为 null), + * 用于登记追溯与后续定向回信。字段口径与 wms_video_record_request 保持一致。 + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + const columns = await queryInterface.describeTable(TABLE); + if (!columns.group_id) { + await queryInterface.addColumn(TABLE, 'group_id', { + type: Sequelize.STRING(100), + allowNull: true, + comment: '触发查询的群ID(站内信外部群ID)', + }); + } + if (!columns.group_name) { + await queryInterface.addColumn(TABLE, 'group_name', { + type: Sequelize.STRING(100), + allowNull: true, + comment: '触发查询的群名称', + }); + } + if (!columns.user_id) { + await queryInterface.addColumn(TABLE, 'user_id', { + type: Sequelize.STRING(100), + allowNull: true, + comment: '触发查询的用户ID(站内信外部用户ID)', + }); + } + if (!columns.user_name) { + await queryInterface.addColumn(TABLE, 'user_name', { + type: Sequelize.STRING(100), + allowNull: true, + comment: '触发查询的用户名称', + }); + } + }, + + down: async queryInterface => { + const columns = await queryInterface.describeTable(TABLE); + if (columns.group_id) await queryInterface.removeColumn(TABLE, 'group_id'); + if (columns.group_name) await queryInterface.removeColumn(TABLE, 'group_name'); + if (columns.user_id) await queryInterface.removeColumn(TABLE, 'user_id'); + if (columns.user_name) await queryInterface.removeColumn(TABLE, 'user_name'); + }, +}; diff --git a/methods/changes/system.json b/methods/changes/system.json index 79232f3..2082a12 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -20,6 +20,35 @@ "发布顺序:迁移(20260925100000-create-wms-client-error-log)先于代码发布;迁移为纯建表、无回填,先迁移无风险。" ] }, + { + "version": "2026.09.24-return-unpack-notify-by-source", + "date": "2026-09-24", + "type": "updated", + "summary": "拆包完成通知改为按原查询登记来源定向回信:_notifyUnpacked 不再按货主泛推售后群,改为按 wms_return_query_log 登记时记录的 group_id+user_id 聚合回信原查询群/用户(有用户信息时 writeOutboundReply 定向回原查询用户,否则退化为来源群系统通知);登记无来源群的记录不通知;仅推送成功的登记标记 is_notified=1。", + "methods": [ + "returnUnpack.submit" + ], + "notes": [ + "代码位置:app/service/systems/return_unpack.js _notifyUnpacked(依赖此前新增的登记来源字段 group_id/group_name/user_id/user_name)", + "回信链路与 video_record_request._replyResult 口径一致:批量反查 wms_inbox_group 补全 group_name/ext_data/store_id,缺失时用登记快照兜底;定向回信 source=ai_reply(wms_inbox_message 记录 user_id/user_name)" + ] + }, + { + "version": "2026.09.24-return-query-log-source-ids", + "date": "2026-09-24", + "type": "updated", + "summary": "退回查询登记表 wms_return_query_log 新增登记来源字段 group_id/group_name/user_id/user_name(迁移 20260924160000-add-source-ids-to-wms-return-query-log):站内信「查退回」触发登记时写入查询来源群/用户信息,用于登记追溯与后续定向通知;returnWaybill.create/list/detail 响应记录同步包含新字段(后台登记路径为 null)。", + "methods": [ + "returnWaybill.create", + "returnWaybill.list", + "returnWaybill.detail" + ], + "notes": [ + "代码位置:app/model/return_query_log.js 新增 4 字段;app/service/systems/return_unpack.js queryByWaybill 增加可选入参并在 received/not_returned 两处自动登记时写入来源;app/service/inbox/functions.js queryReturn 透传 ctx.inboxContext 的 group_id/group_name/user_id/user_name", + "迁移执行:npx sequelize-cli db:migrate(生产:$env:NODE_ENV='production'; npx sequelize-cli db:migrate --migrations-path database/migrations --env production)", + "库表化维护:method-doc-update.cjs 更新 3 个方法 response 说明并 --bump 至 0.3.184,method-doc-export.cjs 回写 methods/system.json" + ] + }, { "version": "2026.09.24-big-group-pack-coefficient-desc", "date": "2026-09-24", diff --git a/methods/system.json b/methods/system.json index d8bd118..9feaeba 100644 --- a/methods/system.json +++ b/methods/system.json @@ -44855,7 +44855,7 @@ }, { "method": "returnUnpack.submit", - "description": "提交确认:未完成(unpacking)拆包单转 completed 终态并回写 end_time(拆包结束时间;结束时间超过仓库配置的拆包最大录制时长上限时,自动截断为 开始时间+上限——仓库配置项 subject_config.return_unpack_max_record_minutes,默认 5 分钟,配置缺失/非法或开始时间缺失时不约束);同步按 warehouse_id+waybill_code 更新 wms_return_query_log.is_back=1(标记该运单号已退回,更新失败不阻断主流程)。提交后进入终态,不可再录/移除明细。仓库隔离校验(仅本仓库拆包单)。", + "description": "提交确认:未完成(unpacking)拆包单转 completed 终态并回写 end_time(拆包结束时间;结束时间超过仓库配置的拆包最大录制时长上限时,自动截断为 开始时间+上限——仓库配置项 subject_config.return_unpack_max_record_minutes,默认 5 分钟,配置缺失/非法或开始时间缺失时不约束);同步按 warehouse_id+waybill_code 更新 wms_return_query_log.is_back=1(标记该运单号已退回,更新失败不阻断主流程)。提交后进入终态,不可再录/移除明细。仓库隔离校验(仅本仓库拆包单)。拆包完成后按退回查询登记来源定向通知:仅登记表 is_back=1 且 is_notified=0 的记录,按登记时记录的 group_id+user_id 回信原查询群/用户(有用户信息时定向回原查询用户,否则退化为来源群系统通知;登记无来源群的记录不通知),不再泛推货主售后群;推送成功标记 is_notified=1。", "isNeedAuth": true, "isNeedLogin": true, "headers": [], @@ -45663,7 +45663,7 @@ "name": "record", "type": "object", "required": true, - "description": "登记记录包装对象,含登记记录完整字段(id、warehouse_id、store_id、waybill_code、remark、is_notified、is_back、created_at、updated_at,时间字段为格式化字符串)" + "description": "登记记录包装对象,含登记记录完整字段(id、warehouse_id、store_id、waybill_code、group_id、group_name、user_id、user_name、remark、is_notified、is_back、created_at、updated_at,时间字段为格式化字符串;group_id/group_name/user_id/user_name 为登记来源,仅站内信「查退回」触发登记时写入,后台登记为 null)" }, { "name": "duplicated", @@ -45859,7 +45859,7 @@ "name": "list", "type": "array", "required": true, - "description": "运单退回登记列表,每条含登记字段(id、warehouse_id、store_id、waybill_code、remark、is_notified、is_back)及格式化时间字段" + "description": "运单退回登记列表,每条含登记字段(id、warehouse_id、store_id、waybill_code、group_id、group_name、user_id、user_name、remark、is_notified、is_back)及格式化时间字段;group_id/group_name/user_id/user_name 为登记来源(站内信「查退回」触发时写入,后台登记为 null)" }, { "name": "pagination", @@ -45903,7 +45903,7 @@ "name": "record", "type": "object", "required": true, - "description": "登记记录完整信息(id、warehouse_id、store_id、waybill_code、remark、is_notified、is_back 及格式化时间字段)" + "description": "登记记录完整信息(id、warehouse_id、store_id、waybill_code、group_id、group_name、user_id、user_name、remark、is_notified、is_back 及格式化时间字段;来源字段仅站内信「查退回」触发登记时写入,后台登记为 null)" } ], "errors": [