From b436b6dd9e2bc850a2520691419316a2b8e6f4a4 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 12 Aug 2026 20:47:19 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=8B=A6=E6=88=AA=E9=93=BE=E8=B7=AF?= =?UTF-8?q?=E5=85=A8=E6=B5=81=E7=A8=8B=E5=AE=8C=E5=96=84=20=E2=80=94=20?= =?UTF-8?q?=E6=96=B0=E5=A2=9EinterceptScan=20+=20=E8=BF=90=E5=8D=95?= =?UTF-8?q?=E8=A1=A8=E5=90=8C=E6=AD=A5=20+=20=E5=B7=A5=E5=8D=95=E9=80=9A?= =?UTF-8?q?=E7=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增: - order.recheckOrder.interceptScan: 拦截扫描接口,入参运单号,查express标记退回,处理工单,更新订单拦截状态 - afterSale.createInterceptWorkOrdersAndNotify: 共享方法,幂等创建工单+通知快递群 修复: - confirmIntercept: 补运单is_back同步(仅限is_intercept=Y),补工单创建+通知 - batchIntercept: 补运单is_intercept同步,补工单创建+通知 - batchUnintercept: 补运单is_intercept/is_back清除 - Qimen/OpenAPI cancel: 补运单is_intercept同步,补工单创建+通知 - interceptScan: 删除死查询,加空指针兜底 文档: - methods/system.json: interceptScan + confirmIntercept 完整API文档 - methods/changes/system.json: 变更记录 --- app/model/after_sale.js | 17 +- app/model/after_sale_detail.js | 23 +- app/model/inbox_group.js | 7 +- app/model/store_warehouse.js | 10 + app/service/inbox/ai.js | 370 ++++ app/service/inbox/functions.js | 1536 +++++++++++------ app/service/inbox/groups.js | 224 +++ app/service/inbox/processor.js | 355 ++-- app/service/openapiMethods/order.js | 34 + app/service/qimenMethods/order.js | 26 + app/service/systemMethods/afterSale.js | 239 ++- app/service/systemMethods/index.js | 7 +- .../systemMethods/order/deliveryOrder.js | 331 +++- .../systemMethods/order/pendingOrder.js | 38 + .../systemMethods/order/recheckOrder.js | 208 ++- app/service/systemMethods/pickCart.js | 39 +- .../systemMethods/storage/receiving.js | 2 +- .../systemMethods/storage/transaction.js | 4 +- app/service/systems/afterSale.js | 1120 +++++++++++- app/service/systems/inbox/group.js | 121 ++ app/service/systems/pick.js | 178 +- app/service/systems/pickCart.js | 11 + app/service/systems/setting/warehouse.js | 57 + app/service/systems/stock_transaction.js | 17 +- app/service/systems/storage/receiving.js | 61 +- app/service/systems/waybill.js | 219 ++- database/designs/after-sale-v2-design.md | 88 +- ...09140000-add-after-sale-workorder-pages.js | 42 + ...140100-grant-after-sale-workorder-pages.js | 103 ++ ...fter-sale-detail-step-status-to-varchar.js | 27 + ...00000-add-followup-at-to-wms-after-sale.js | 17 + ...60811120000-add-ext-data-to-inbox-group.js | 20 + ...260812120000-add-order-id-to-after-sale.js | 16 + methods/changes/system.json | 338 ++++ methods/system.json | 1157 ++++++++++++- 35 files changed, 5951 insertions(+), 1111 deletions(-) create mode 100644 app/service/inbox/ai.js create mode 100644 app/service/inbox/groups.js create mode 100644 database/migrations/20260809140000-add-after-sale-workorder-pages.js create mode 100644 database/migrations/20260809140100-grant-after-sale-workorder-pages.js create mode 100644 database/migrations/20260810140000-alter-wms-after-sale-detail-step-status-to-varchar.js create mode 100644 database/migrations/20260811100000-add-followup-at-to-wms-after-sale.js create mode 100644 database/migrations/20260811120000-add-ext-data-to-inbox-group.js create mode 100644 database/migrations/20260812120000-add-order-id-to-after-sale.js diff --git a/app/model/after_sale.js b/app/model/after_sale.js index 2ec2f60..05f3955 100644 --- a/app/model/after_sale.js +++ b/app/model/after_sale.js @@ -86,11 +86,12 @@ module.exports = app => { /** * 售后单状态枚举。 - * @type {{pending: string, processing: string, completed: string, closed: string, cancelled: string}} + * @type {{pending: string, processing: string, waiting: string, completed: string, closed: string, cancelled: string}} */ const AFTER_SALE_STATUS = { pending: '待处理', processing: '处理中', + pending_feedback: '等待外部反馈', completed: '已完成', closed: '已关闭', cancelled: '已取消', @@ -156,7 +157,7 @@ module.exports = app => { type: STRING(20), allowNull: false, defaultValue: 'pending', - comment: '售后状态:pending=待处理, processing=处理中, completed=已完成, closed=已关闭, cancelled=已取消', + comment: '售后状态:pending=待处理, processing=处理中, pending_feedback=等待外部反馈, completed=已完成, closed=已关闭, cancelled=已取消', }, /** 优先级 */ priority: { @@ -207,6 +208,12 @@ module.exports = app => { allowNull: true, comment: '完结时间(状态变为 completed 时写入)', }, + /** 下次跟进时间 */ + followup_at: { + type: DATE, + allowNull: true, + comment: '下次跟进时间:设为 pending_feedback 时可指定,超时后需二次跟进', + }, /** 仓库理赔标记 */ claim_needed: { type: TINYINT(1), @@ -258,6 +265,12 @@ module.exports = app => { allowNull: true, comment: '运单号(冗余字段,方便查询展示)', }, + /** 订单ID */ + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '订单ID(关联 wms_order.id),快递反馈建单时从 wms_order_express.order_id 填入', + }, /** 发货订单ID */ order_delivery_id: { type: BIGINT(20).UNSIGNED, diff --git a/app/model/after_sale_detail.js b/app/model/after_sale_detail.js index 9a828e2..f623b96 100644 --- a/app/model/after_sale_detail.js +++ b/app/model/after_sale_detail.js @@ -6,21 +6,22 @@ * @return {import('sequelize').ModelCtor} 售后进度步骤 Model(含常量挂载) */ module.exports = app => { - const { STRING, BIGINT, TEXT, TINYINT, DATE } = app.Sequelize; + const { STRING, BIGINT, TEXT, DATE } = app.Sequelize; // ============================ // 枚举常量定义 // ============================ /** - * 步骤状态枚举。 - * @type {{0: string, 1: string, 2: string, 3: string}} + * 步骤状态枚举(与 wms_after_sale.status 一致)。 */ const STEP_STATUS = { - 0: '待开始', - 1: '进行中', - 2: '已完成', - 3: '已跳过', + pending: '待处理', + processing: '处理中', + pending_feedback: '等待外部反馈', + completed: '已完成', + closed: '已关闭', + cancelled: '已取消', }; // ============================ @@ -41,12 +42,12 @@ module.exports = app => { allowNull: false, comment: '关联售后主表ID(wms_after_sale.id)', }, - /** 步骤状态 */ + /** 步骤记录时售后主表的状态 */ step_status: { - type: TINYINT(3).UNSIGNED, + type: STRING(20), allowNull: false, - defaultValue: 0, - comment: '步骤状态:0=待开始,1=进行中,2=已完成,3=已跳过', + defaultValue: 'processing', + comment: '步骤记录时售后主表的状态,与 wms_after_sale.status 一致: pending | processing | pending_feedback | completed | closed | cancelled', }, /** 操作人账户ID */ operator_id: { diff --git a/app/model/inbox_group.js b/app/model/inbox_group.js index 6a02825..4a3039b 100644 --- a/app/model/inbox_group.js +++ b/app/model/inbox_group.js @@ -8,7 +8,7 @@ * @return {Object} Sequelize Model 定义。 */ module.exports = app => { - const { BIGINT, STRING, TINYINT, DATE } = app.Sequelize; + const { BIGINT, STRING, TINYINT, DATE, JSON: JSON_TYPE } = app.Sequelize; const InboxGroup = app.model.define('inbox_group', { id: { @@ -80,6 +80,11 @@ module.exports = app => { allowNull: true, comment: '系统快递编码(仅群类型为 express 时必填)', }, + ext_data: { + type: JSON_TYPE, + allowNull: true, + comment: '群扩展数据(IM平台信息等)', + }, created_at: { type: DATE, allowNull: false, diff --git a/app/model/store_warehouse.js b/app/model/store_warehouse.js index 5e7a40c..1e5b37f 100644 --- a/app/model/store_warehouse.js +++ b/app/model/store_warehouse.js @@ -216,6 +216,16 @@ module.exports = app => { max: '23:59', description: '截单时间,格式 HH:mm,如 16:00', }), + Object.freeze({ + key: 'after_sale_followup_hours', + name: '售后跟进时间(h)', + type: 'integer', + default: 24, + required: false, + min: 1, + max: 720, + description: '售后单设为等待外部反馈后,默认多少小时需二次跟进。具体类型可在代码枚举中覆盖', + }), ]); const POLICY_CONFIG_FIELD_MAP = Object.freeze(POLICY_CONFIG_FIELDS.reduce((result, field) => { result[field.key] = field; diff --git a/app/service/inbox/ai.js b/app/service/inbox/ai.js new file mode 100644 index 0000000..fc41d87 --- /dev/null +++ b/app/service/inbox/ai.js @@ -0,0 +1,370 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * AI 推理引擎。 + * 负责调用 DeepSeek API 进行多轮推理:思考→调函数→评估→(重复或输出)。 + * 函数注册、分组管理等纯工具箱逻辑在 inbox/functions.js 中。 + */ +class InboxAIService extends Service { + + /** + * 调用 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 ai] 对话历史回退查询失败: ${error.message}`); + return []; + } + } + + // 智能查询:同一群,最近 maxMessages 条(入站+出站混合,含所有成员) + try { + const messages = await InboxMessage.findAll({ + attributes: [ 'id', 'parent_id', 'direction', 'content', 'user_id', 'user_name', 'created_at' ], + where: { + warehouse_id: warehouseId, + group_id: groupId, + direction: { [Op.in]: [ 'inbound', 'outbound' ] }, + }, + order: [[ 'created_at', 'DESC' ]], + limit: maxMessages, + raw: true, + }); + + if (messages.length === 0) return []; + + // 升序排列,附加上下文信息供 AI 判断真人接管 + const blockedUsers = ctx.inboxContext?._blockedUserIds || new Set(); + return messages.reverse().map(msg => { + const u = String(msg.user_id || '').trim(); + const name = String(msg.user_name || '').trim(); + const isBlocked = u && blockedUsers.has(u); + return { + role: msg.direction === 'inbound' ? 'user' : 'assistant', + content: msg.content || '', + user_id: u || null, + user_name: name || null, + blocked: isBlocked, + }; + }); + } catch (error) { + ctx.logger.warn(`[inbox ai] 智能对话历史查询失败: ${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 funcSvc = ctx.service.inbox.functions; + const groupsSvc = ctx.service.inbox.groups; + const activeGroups = groupsSvc.resolveActiveGroups(); + ctx.logger.info(`[inbox ai] 当前活跃分组: ${activeGroups.join(', ')}`); + + const functionListText = groupsSvc.buildFunctionListText(activeGroups); + if (!functionListText) { + ctx.logger.info('[inbox ai] 当前上下文无可用的 AI 函数'); + return { reply: null, functionName: null, functionResult: null }; + } + + // 拉取群历史(最多 10 条),同时注入 system prompt 和对话上下文 + const history = await this.getConversationHistory({ + parentId: data.parentId, + maxMessages: 10, + }); + const historyContext = history.length > 0 + ? history.map(h => { + const tag = h.blocked ? '[已屏蔽]' : ''; + return `[${h.role === 'user' ? h.user_name || h.user_id || '未知' : 'AI'}]${tag}: ${h.content}`; + }).join('\n') + : '(无历史)'; + + const MAX_ROUNDS = 5; + const executedFunctions = []; + const thoughts = []; + let finalReply = null; + let lastFunctionName = null; + let lastFunctionResult = null; + + const systemPrompt = `你是一个 WMS 仓库管理系统的智能助手,支持多步推理。 +已注册函数:\n${functionListText}\n +=== 群最近对话历史 === +${historyContext} +=== + +对话历史中 [已屏蔽] 标记表示该用户已主动要求屏蔽(不想被 AI 打扰)。 +如果 [已屏蔽] 用户发送了表示接手或正在处理的内容(如"我来处理""不用回复""稍等""我看看"),说明真人已接管 → 直接 silent。 + +你需要通过多轮调用来完成用户的复杂请求。每轮返回纯 JSON: + +如果还需要调用函数获取信息: +{ + "action": "call", + "function": "函数名", + "params": { "参数名": "参数值" }, + "reason": "为什么需要这个函数" +} + +如果信息充足可以回复用户了: +{ + "action": "reply", + "reply": "最终回复(中文纯文本,禁止Markdown,200字以内,可适当使用\\n换行分隔信息)" +} + +如果消息无需回复(用户只是确认、道谢、告别或表示自己处理): +{ + "action": "silent" +} + +真人接管判断规则(优先级最高,先于所有其他规则): +- 如果历史中某条消息 blocked=true 的用户发送了与当前问题相关的内容(如"我来处理""稍等""我看看"等表示接手的话术),说明真人客服已介入处理 → 直接 silent +- 如果 blocked 用户发送的内容与问题无关(如闲聊、询问其他事情),且当前用户仍在提问 → 正常回复当前用户 +- 如果历史中只有当前用户的连续消息,没有其他用户介入 → 正常回复 + +一般约束: +- 最多 ${MAX_ROUNDS} 轮函数调用,第 ${MAX_ROUNDS} 轮必须给出最终回复 +- 同一函数不要重复调用(除非参数不同) +- 信息中如果携带了@标记,说明信息是针对某个特定用户的,请注意是否需要回复该用户 +- 如果函数执行失败,换其他方式或直接告知用户 +- 回复使用中文纯文本,禁止 Markdown 语法,可用 \\n 换行提升可读性 +- silent 仅用于:用户已确认收到消息且无新问题("好的""收到""OK""谢谢""知道了""好"),或用户表示告别/离场("再见""拜拜""88") +- 以下情况严禁 silent,必须 reply:任何形式的提问(含"在吗""有人吗""在不在")、操作请求、函数执行完毕、自定义欢迎语"你好""嗨""hello"等首次问候 +- 无法判断时,宁可回复也不要 silent +- searchStock 返回多条结果时,必须列举让用户选择(告知 id/编码/名称/可用库存),不要擅自决定 +- createOrder 失败时告知失败原因(库存不足/商品不存在等),不要重试同一商品 +- searchStock 返回的 stock_available 为 0 时,提醒用户该商品无库存,建议选择其他商品 +- searchStock/searchWarehouseStock 返回的 image_url 为图片URL数组(可能多张),has_images 为 true 时给出链接 +- searchStock/searchWarehouseStock 返回的 barcodes 为关联条码,回复时可列出帮助核对 +- searchStock/searchWarehouseStock 返回的管理标识 is_sn_mgmt/is_shelf_life_mgmt/is_batch_mgmt 分别表示SN管理/效期管理/批次管理 +- searchStock/searchWarehouseStock 返回的 box_spec 为箱规(长宽高体积毛净重装箱数),packing_requirements 为打包要求,用户问及时告知 +- searchStock/searchWarehouseStock 返回的 prohibited_type 为违禁品类型,非空时告知用户 +- 用户说"第1个""第2个"时,按 searchStock 返回的顺序对应选择 +- 需要上下文但记忆不足时,主动调用 recallHistory 回顾对话历史 +- 【防误判规则 - interceptWaybill】讨论已有售后工单(AS开头编号)、询问物流进度、问"快递到哪了"、转发售后截图等均不是拦截请求,严禁调用 interceptWaybill。只有用户明确说"拦截/退回/召回/追回/取消"运单时才可调用 +- 【措辞规则 - interceptWaybill】拦截结果回复严禁使用"已拦截""拦截成功"等确定口吻,必须使用"拦截信息已登记""已提交拦截申请"等措辞。因为快递拦截可能失败,实际结果以快递公司反馈为准。回复时需列出工单号供用户跟进`; + + // 多轮推理循环 + 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 ai] 第 ${round}/${MAX_ROUNDS} 轮: ${raw}`); + + const result = JSON.parse(raw); + + // 记录思考过程 + thoughts.push({ + round, + action: result.action || 'unknown', + function: result.function || null, + params: result.params || null, + reason: result.reason || null, + }); + + if (result.action === 'reply') { + finalReply = String(result.reply || '').trim(); + if (!finalReply) finalReply = '已处理完成'; + break; + } + + if (result.action === 'silent') { + // 已调用过操作类函数(非 recallHistory)→ 必须回复结果,不能 silent + const actionFunctions = executedFunctions.filter(f => f.name !== 'recallHistory'); + if (actionFunctions.length > 0) { + ctx.logger.info('[inbox ai] 已有操作类函数调用,忽略 silent 继续要求回复'); + continue; + } + ctx.logger.info('[inbox ai] 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 funcSvc.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 ai] 执行 ${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 ai] 第 ${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 ai] 最终回复: ${finalReply}`); + return { + reply: finalReply, + functionName: lastFunctionName, + functionResult: lastFunctionResult, + thoughts, + }; + } +} + +module.exports = InboxAIService; diff --git a/app/service/inbox/functions.js b/app/service/inbox/functions.js index aeb389b..7bc7509 100644 --- a/app/service/inbox/functions.js +++ b/app/service/inbox/functions.js @@ -2,90 +2,13 @@ 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', -}; +// 群类型常量定义统一收口到 inbox/groups.js +const { GROUP } = require('./groups'); /** - * 子分组 → 主分组映射,用于 `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 调用的内部方法,支持按分组筛选, - * 根据当前上下文(群类型、绑定状态)自动选择可用函数集合。 + * 站内信函数注册表。 + * 负责注册 AI 可调用的函数(含 handler),支持按分组声明可见性。 + * 分组匹配与筛选逻辑在 {@link InboxGroupsService} 中。 */ class InboxFunctionsService extends Service { /** @@ -109,6 +32,8 @@ class InboxFunctionsService extends Service { name: { type: 'string', required: false, description: '用户名称' }, }, groups: [ GROUP.COMMON ], + weight: 0, + keywords: [ '你好', 'hi', 'hello', '在吗' ], handler: async (params = {}) => { const name = String(params.name || '').trim(); const greeting = name ? `你好,${name}!欢迎使用 WMS 站内信服务` : '你好!欢迎使用 WMS 站内信服务'; @@ -123,6 +48,8 @@ class InboxFunctionsService extends Service { description: '查询当前货主的面单余额。根据上下文中的货主ID和仓库ID查询合约中的面单剩余量和锁定量', params: {}, groups: [ GROUP.BOUND_STORE_WILDCARD ], + weight: 80, + keywords: [ '面单余额', '打印余额', '快递单余额', '还剩多少单', '面单' ], handler: async (params = {}) => { const { ctx } = this; void params; @@ -191,6 +118,8 @@ class InboxFunctionsService extends Service { order_code: { type: 'string', required: true, description: '平台订单号' }, }, groups: [ GROUP.BOUND_STORE_WILDCARD ], + weight: 90, + keywords: [ '创建快递单', '取号', '分配快递', '生成运单', '快递单号' ], handler: async (params = {}) => { const { ctx } = this; const orderCode = String(params.order_code || '').trim(); @@ -282,6 +211,8 @@ class InboxFunctionsService extends Service { keyword: { type: 'string', required: true, description: '搜索关键词:商品编码(item_code)、条码(barcode)、商品名称(item_name)' }, }, groups: [ GROUP.BOUND_STORE_WILDCARD ], + weight: 70, + keywords: [ '查商品', '搜商品', '找商品', '商品信息', '库存', '商品' ], handler: async (params = {}) => { const { ctx } = this; const storeId = Number(ctx.inboxContext?.store_id || 0); @@ -420,6 +351,8 @@ class InboxFunctionsService extends Service { keyword: { type: 'string', required: true, description: '搜索关键词:商品编码(item_code)、条码(barcode)、商品名称(item_name)' }, }, groups: [ GROUP.COMMON ], + weight: 60, + keywords: [ '仓库商品', '所有商品' ], handler: async (params = {}) => { const { ctx } = this; const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); @@ -556,6 +489,8 @@ class InboxFunctionsService extends Service { keyword: { type: 'string', required: true, description: '搜索关键词:运单号(waybill_code,精确匹配)、发货单号(delivery_order_code,模糊)、平台单号(source_platform_code,模糊)' }, }, groups: [ GROUP.BOUND_STORE_AFTER_SALES ], + weight: 85, + keywords: [ '查订单', '搜订单', '订单详情', '运单号', '快递单号', '发货单' ], handler: async (params = {}) => { const { ctx } = this; const storeId = Number(ctx.inboxContext?.store_id || 0); @@ -701,9 +636,12 @@ class InboxFunctionsService extends Service { limit: { type: 'number', required: false, description: '获取最近几条,默认5,最大10' }, }, groups: [ GROUP.COMMON ], + weight: 0, + keywords: [], handler: async (params = {}) => { + const { ctx } = this; const limit = Math.min(10, Math.max(1, Number(params.limit) || 5)); - const history = await this.getConversationHistory({ maxMessages: limit }); + const history = await ctx.service.inbox.ai.getConversationHistory({ maxMessages: limit }); if (history.length === 0) { return { success: true, data: { total: 0, messages: [], hint: '暂无对话历史' } }; } @@ -724,6 +662,8 @@ class InboxFunctionsService extends Service { this.register('createOrder', { description: '创建发货订单。传入商品 stock_id(来自 searchStock)及数量、收件人信息,使用手工建单流程创建发货单', + weight: 90, + keywords: [ '建单', '创建订单', '下单', '发货', '新建订单' ], params: { items: { type: 'array', required: true, description: '商品列表 [{item_id: stock_id, plan_qty: 数量}]' }, receiverName: { type: 'string', required: true, description: '收件人姓名' }, @@ -796,6 +736,8 @@ class InboxFunctionsService extends Service { description: '屏蔽用户消息。将当前群和用户加入屏蔽列表,后续不再回复', params: {}, groups: [ GROUP.COMMON ], + weight: 0, + keywords: [ '屏蔽', '不回复', '拉黑' ], handler: async (params = {}) => { const { ctx } = this; void params; @@ -855,10 +797,954 @@ class InboxFunctionsService extends Service { }, }); + this.register('interceptWaybill', { + description: '拦截运单(支持批量)。仅当用户明确要求"拦截/退回/召回/追回"快递运单时才调用。传入运单号(如SF123456),校验权限后批量创建售后工单,并合并通知对应快递的售后群。货主群需验store_id,仓库群无需。严禁:讨论已有售后工单(AS开头)不是拦截请求、询问物流进度不是拦截请求', + weight: 95, + keywords: [ '拦截', '退回', '召回', '追回', '取消快递', '不要了' ], + params: { + keyword: { type: 'string', required: true, description: '运单号,多个用逗号或空格分隔,如 SF111,SF222' }, + reason: { type: 'string', required: false, description: '拦截原因' }, + }, + groups: [ GROUP.BOUND_WAREHOUSE_CUSTOMER_SERVICE, GROUP.BOUND_STORE_AFTER_SALES ], + handler: async (params = {}) => { + const { ctx } = this; + const raw = String(params.keyword || '').trim(); + const reason = String(params.reason || '').trim(); + const storeId = Number(ctx.inboxContext?.store_id || 0); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const groupType = String(ctx.inboxContext?.group_type || '').trim(); + const groupName = String(ctx.inboxContext?.group_name || '').trim(); + const userName = String(ctx.inboxContext?.user_name || '').trim(); + + if (!raw) return { success: false, error: '请提供运单号' }; + if (!warehouseId) return { success: false, error: '无法获取仓库信息' }; + + // 解析多个运单号(逗号/空格/换行分隔) + const keywords = raw.split(/[,,\s\n]+/).map(s => s.trim()).filter(Boolean); + if (keywords.length === 0) return { success: false, error: '未解析到有效运单号' }; + + // 前置拦截:拒绝看起来像售后单号(AS...)的输入,防止误把售后讨论当拦截 + const asLikeList = keywords.filter(k => /^AS/i.test(k)); + if (asLikeList.length > 0) { + return { + success: false, + error: `${asLikeList.join('、')} 看起来是售后工单号而非运单号,如需查询工单请用 queryOrder,如需拦截请提供运单号`, + }; + } + + try { + // 第一步:批量查询运单 + const expressList = await ctx.model.OrderExpress.findAll({ + attributes: [ + 'id', 'waybill_code', 'logistics_name', 'store_id', + 'logistics_interface_id', 'logistics_code', 'order_id', + ], + where: { + waybill_code: { [ctx.app.Sequelize.Op.in]: keywords }, + warehouse_id: warehouseId, + }, + raw: true, + }); + + if (expressList.length === 0) { + return { success: false, error: `未找到运单号「${raw}」,请核实单号后重试` }; + } + + // 第二步:鉴权 + 过滤 + const validList = []; + const skipped = []; + for (const e of expressList) { + if (groupType === 'store') { + if (!storeId || Number(e.store_id) !== storeId) { + skipped.push(e.waybill_code); + continue; + } + } + validList.push(e); + } + + if (validList.length === 0) { + return { + success: false, + error: `运单${skipped.join('、')}不属于当前货主,无法操作`, + }; + } + + // 第三步:幂等检查(批量查已有工单) + const validIds = validList.map(e => e.id); + const existingASList = await ctx.model.AfterSale.findAll({ + attributes: [ 'waybill_id', 'after_sale_no' ], + where: { + waybill_id: { [ctx.app.Sequelize.Op.in]: validIds }, + type: 'order', + sub_type: 'intercept', + status: { [ctx.app.Sequelize.Op.notIn]: [ 'completed', 'closed', 'cancelled' ] }, + }, + raw: true, + }); + const existingWaybillIds = new Set(existingASList.map(r => r.waybill_id)); + + // 过滤掉已存在工单的 + const toCreate = validList.filter(e => !existingWaybillIds.has(e.id)); + const alreadyExist = existingASList.map(r => r.after_sale_no); + + if (toCreate.length === 0) { + return { + success: true, + data: { + existed: true, + message: `运单已存在处理中的拦截工单: ${alreadyExist.join('、')}`, + after_sale_nos: alreadyExist, + }, + }; + } + + // 第四步:批量创建工单(初始状态 pending,后续根据通知结果升级) + const creatorLabel = [ groupName, userName ].filter(Boolean).join('-') || 'AI系统'; + const createdNos = []; + const waybillToAsNo = {}; // waybill_id → after_sale_no 映射 + for (const e of toCreate) { + const afterSaleNo = await ctx.service.systemMethods.afterSale.generateAfterSaleNo(warehouseId); + const descParts = [ + `发起人: ${creatorLabel}`, + `运单号: ${e.waybill_code}`, + `快递公司: ${e.logistics_name || '未知'}`, + reason ? `拦截原因: ${reason}` : '', + ].filter(Boolean).join('\n'); + + await ctx.service.systems.afterSale.create({ + warehouse_id: warehouseId, + after_sale_no: afterSaleNo, + type: 'order', + sub_type: 'intercept', + title: `[AI工单] 拦截请求 - ${e.waybill_code}`, + description: descParts, + priority: 10, + creator_id: 0, + inbox_message_id: ctx.inboxContext?.inbound_message_id || null, + role_group: 'customer_service', + status: 'pending', + waybill_id: e.id, + waybill_no: e.waybill_code, + store_id: e.store_id || storeId || null, + order_id: e.order_id || null, + }); + createdNos.push(afterSaleNo); + waybillToAsNo[e.id] = afterSaleNo; + } + + ctx.logger.info( + `[inbox functions] 批量拦截: total=${keywords.length} found=${expressList.length} ` + + `valid=${validList.length} created=${createdNos.length} skipped=${skipped.length}` + ); + + // 第4.5步:波次感知拦截处理(仅操作待处理表中的订单) + const orderIds = toCreate.map(e => e.order_id).filter(id => id); + if (orderIds.length > 0) { + try { + const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + if (orderModel) { + const orders = await orderModel.findAll({ + attributes: [ 'id', 'step', 'wave_id', 'inspection_status' ], + where: { + id: { [ctx.app.Sequelize.Op.in]: orderIds }, + step: { [ctx.app.Sequelize.Op.in]: [ 1, 2, 3 ] }, + }, + raw: true, + }); + + if (orders.length > 0) { + // 按 wave_id 分组查波次信息 + const waveIds = [ ...new Set(orders.map(o => o.wave_id).filter(id => id > 0)) ]; + let waveMap = {}; + if (waveIds.length > 0) { + const waves = await ctx.model.WaveBatch.findAll({ + attributes: [ 'wave_id', 'wave_type', 'wave_status', 'total_orders' ], + where: { wave_id: { [ctx.app.Sequelize.Op.in]: waveIds } }, + raw: true, + }); + waveMap = Object.fromEntries(waves.map(w => [ w.wave_id, w ])); + } + + const interceptOrderIds = []; + const kickOutOrderIds = []; + + for (const order of orders) { + const wave = waveMap[order.wave_id]; + const orderId = order.id; + + // 规则1:团购未复核 / 散单未称重 → 设置拦截 + let needIntercept = false; + if (order.wave_id > 0 && wave) { + if (wave.wave_type === 1) { + // 团购波次:未复核 → 拦截 + needIntercept = order.inspection_status !== 'fin'; + } else if (wave.wave_type === 2) { + // 散单波次:未称重视同可拦截(订单表无称重状态,默认拦截) + needIntercept = true; + } + } else { + // 无波次订单:直接拦截 + needIntercept = true; + } + + if (needIntercept) { + interceptOrderIds.push(orderId); + } + + // 规则2:有波次且未打印 + if (order.wave_id > 0 && wave && wave.wave_status < 2) { + const minGroupQty = 13; // 默认大团购阈值 + if (wave.wave_type === 1 && wave.total_orders >= minGroupQty) { + // 大团购:踢出波次 + kickOutOrderIds.push(orderId); + } + // 小团购/散单:仅拦截,不踢出(已在 interceptOrderIds 中处理) + } + } + + // 执行拦截状态设置(订单表 + 运单表) + if (interceptOrderIds.length > 0) { + await orderModel.update( + { intercept_status: 'requested' }, + { where: { id: { [ctx.app.Sequelize.Op.in]: interceptOrderIds } } } + ); + // 同步更新运单表拦截标记 + await ctx.model.OrderExpress.update( + { is_intercept: 'Y' }, + { where: { order_id: { [ctx.app.Sequelize.Op.in]: interceptOrderIds }, warehouse_id: warehouseId } } + ); + ctx.logger.info( + `[inbox functions] 设置拦截状态: ${interceptOrderIds.length} 个订单` + ); + } + + // 执行踢出波次 + if (kickOutOrderIds.length > 0) { + await ctx.service.systemMethods.order.wave.batchRemoveOrders({ + ids: kickOutOrderIds, + }); + ctx.logger.info( + `[inbox functions] 踢出大团购波次: ${kickOutOrderIds.length} 个订单` + ); + } + } + } + } catch (e) { + ctx.logger.warn(`[inbox functions] 波次感知拦截处理失败: ${e.message}`); + } + } + + // 第五步:合并通知对应快递的售后群(按快递分组,每条消息包含该快递的所有运单) + const expressByCode = {}; + for (const e of toCreate) { + const code = e.logistics_code || '__unknown__'; + if (!expressByCode[code]) { + expressByCode[code] = { interfaceId: e.logistics_interface_id, waybills: [] }; + } + expressByCode[code].waybills.push(e.waybill_code); + } + + let notifiedTotal = 0; + const notifiedWaybillIds = new Set(); // 记录哪些运单成功通知了至少一个群 + for (const [ code, info ] of Object.entries(expressByCode)) { + if (code === '__unknown__' || !info.interfaceId) continue; + try { + const { afterSalesGroups } = await ctx.service.systems.inbox.group.findGroupsByExpress({ + expressInterfaceId: info.interfaceId, + expressCode: code, + warehouseId, + }); + + if (afterSalesGroups.length === 0) { + ctx.logger.info(`[inbox functions] 快递 ${code} 未配置售后群,跳过通知`); + continue; + } + + const notifyMsg = info.waybills.join('\n') + '\n拦截'; + for (const g of afterSalesGroups) { + ctx.service.inbox.processor.pushSystemNotification({ + warehouse_id: warehouseId, + group_id: g.group_id, + group_name: g.group_name, + content: notifyMsg, + ext_data: g.ext_data || null, + }); + notifiedTotal += 1; + } + // 有售后群即标记为已通知(推送是异步的,不计成败) + const codeWaybills = toCreate.filter(e => (e.logistics_code || '__unknown__') === code); + codeWaybills.forEach(e => notifiedWaybillIds.add(e.id)); + } catch (e) { + ctx.logger.warn(`[inbox functions] 查售后群失败 code=${code}: ${e.message}`); + } + } + + // 第六步:有通知的工单升级为 pending_feedback + const notifiedAsNos = []; + const notNotifiedAsNos = []; + for (const e of toCreate) { + const asNo = waybillToAsNo[e.id]; + if (notifiedWaybillIds.has(e.id)) { + notifiedAsNos.push(asNo); + } else { + notNotifiedAsNos.push(asNo); + } + } + + if (notifiedAsNos.length > 0) { + // 与 handleWorkOrder 一致:设置追踪时间 + 分配客服组 + const hours = await ctx.service.systems.afterSale._resolveFollowupHours( + warehouseId, 'order', 'intercept' + ); + await ctx.model.AfterSale.update( + { + status: 'pending_feedback', + followup_at: ctx.app.Sequelize.literal(`DATE_ADD(NOW(), INTERVAL ${hours} HOUR)`), + role_group: 'customer_service', + }, + { where: { after_sale_no: { [ctx.app.Sequelize.Op.in]: notifiedAsNos } } } + ); + ctx.logger.info( + `[inbox functions] ${notifiedAsNos.length} 个工单已通知快递群,` + + `升级为 pending_feedback,${hours}h 后追踪` + ); + } + + // 构造返回消息 + const parts = []; + if (notifiedAsNos.length > 0) { + parts.push(`拦截信息已登记并通知快递群,工单: ${notifiedAsNos.join('、')}`); + } + if (notNotifiedAsNos.length > 0) { + parts.push(`拦截信息已登记(未配置快递群,需人工跟进),工单: ${notNotifiedAsNos.join('、')}`); + } + if (alreadyExist.length > 0) { + parts.push(`已登记过,工单: ${alreadyExist.join('、')}`); + } + if (skipped.length > 0) { + parts.push(`无权操作: ${skipped.join('、')}`); + } + + return { + success: true, + data: { + created: createdNos.length, + existed: alreadyExist.length, + skipped: skipped.length, + after_sale_nos: [ ...createdNos, ...alreadyExist ], + notified_as_nos: notifiedAsNos, + not_notified_as_nos: notNotifiedAsNos, + notified_groups: notifiedTotal, + waybills: validList.map(e => e.waybill_code), + message: parts.join(';'), + }, + }; + } catch (error) { + ctx.logger.error(`[inbox functions] 批量拦截失败: ${error.message}`); + return { success: false, error: `拦截操作失败: ${error.message}` }; + } + }, + }); + + this.register('cancelIntercept', { + description: '取消拦截运单(支持批量)。当用户要求"取消拦截/撤销拦截/不拦截了"时调用。先查已有售后工单,有则追加取消记录,无则按拦截规则创建工单。同时设置订单和运单拦截状态并通知快递群', + weight: 94, + keywords: [ '取消拦截', '撤销拦截', '解除拦截', '不拦截了', '不用拦截' ], + params: { + keyword: { type: 'string', required: true, description: '运单号,多个用逗号或空格分隔' }, + reason: { type: 'string', required: false, description: '取消拦截原因' }, + }, + groups: [ GROUP.BOUND_WAREHOUSE_CUSTOMER_SERVICE, GROUP.BOUND_STORE_AFTER_SALES ], + handler: async (params = {}) => { + const { ctx } = this; + const raw = String(params.keyword || '').trim(); + const reason = String(params.reason || '').trim(); + const storeId = Number(ctx.inboxContext?.store_id || 0); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const groupType = String(ctx.inboxContext?.group_type || '').trim(); + const groupName = String(ctx.inboxContext?.group_name || '').trim(); + const userName = String(ctx.inboxContext?.user_name || '').trim(); + + if (!raw) return { success: false, error: '请提供运单号' }; + if (!warehouseId) return { success: false, error: '无法获取仓库信息' }; + + const keywords = raw.split(/[,,\s\n]+/).map(s => s.trim()).filter(Boolean); + if (keywords.length === 0) return { success: false, error: '未解析到有效运单号' }; + + const asLikeList = keywords.filter(k => /^AS/i.test(k)); + if (asLikeList.length > 0) { + return { success: false, error: `${asLikeList.join('、')} 是售后工单号而非运单号,请提供运单号` }; + } + + try { + // 第一步:批量查询运单 + const expressList = await ctx.model.OrderExpress.findAll({ + attributes: [ 'id', 'waybill_code', 'logistics_name', 'store_id', + 'logistics_interface_id', 'logistics_code', 'order_id' ], + where: { waybill_code: { [ctx.app.Sequelize.Op.in]: keywords }, warehouse_id: warehouseId }, + raw: true, + }); + if (expressList.length === 0) { + return { success: false, error: `未找到运单号「${raw}」,请核实单号后重试` }; + } + + // 第二步:鉴权 + const validList = []; + const skipped = []; + for (const e of expressList) { + if (groupType === 'store') { + if (!storeId || Number(e.store_id) !== storeId) { skipped.push(e.waybill_code); continue; } + } + validList.push(e); + } + if (validList.length === 0) { + return { success: false, error: `运单${skipped.join('、')}不属于当前货主,无法操作` }; + } + + // 第三步:查已有工单(不限制状态,找到即追加取消记录) + const validIds = validList.map(e => e.id); + const existingASList = await ctx.model.AfterSale.findAll({ + attributes: [ 'id', 'waybill_id', 'waybill_no', 'after_sale_no', 'status', 'store_id' ], + where: { + waybill_id: { [ctx.app.Sequelize.Op.in]: validIds }, + type: 'order', + status: { [ctx.app.Sequelize.Op.notIn]: [ 'completed', 'closed', 'cancelled' ] }, + }, + raw: true, + }); + + const existingWaybillIds = new Set(existingASList.map(r => r.waybill_id)); + const toCreate = validList.filter(e => !existingWaybillIds.has(e.id)); + + // 获取原消息内容用于反馈记录 + let cancelMsgContent = ''; + try { + const cid = ctx.inboxContext?.inbound_message_id; + if (cid) { + const cm = await ctx.model.InboxMessage.findByPk(cid, { attributes: [ 'content' ], raw: true }); + if (cm && cm.content) cancelMsgContent = String(cm.content); + } + } catch (e) { /* ignore */ } + + let feedbackCount = 0; + const cancelGroup = ctx.inboxContext?.group_name || '未知群'; + const cancelUser = ctx.inboxContext?.user_name || '未知用户'; + const cancelTime = new Date().toISOString().slice(0, 19) + .replace('T', ' '); + + // 已有工单:追加取消拦截记录 + for (const as of existingASList) { + try { + const remarkLines = [ + `群: ${cancelGroup}`, `用户: ${cancelUser}`, `时间: ${cancelTime}`, + ]; + if (cancelMsgContent) remarkLines.push(`原消息: ${cancelMsgContent}`); + if (reason) remarkLines.push(`取消原因: ${reason}`); + await ctx.service.systems.afterSale.addStep(as.id, { + step_status: 'processing', + action: '取消拦截', + remark: remarkLines.join('\n'), + }); + feedbackCount += 1; + } catch (e) { + ctx.logger.warn(`[inbox functions] 取消拦截反馈失败 as_no=${as.after_sale_no}: ${e.message}`); + } + } + + const parts = []; + if (feedbackCount > 0) parts.push(`已有工单追加取消拦截: ${feedbackCount}个`); + + // 第四步:无工单的按拦截规则创建 + const createdNos = []; + if (toCreate.length > 0) { + const creatorLabel = [ groupName, userName ].filter(Boolean).join('-') || 'AI系统'; + for (const e of toCreate) { + const afterSaleNo = await ctx.service.systemMethods.afterSale.generateAfterSaleNo(warehouseId); + const descParts = [ + `发起人: ${creatorLabel}`, `运单号: ${e.waybill_code}`, + `快递公司: ${e.logistics_name || '未知'}`, + reason ? `取消原因: ${reason}` : '', + '来源: 取消拦截', + ].filter(Boolean).join('\n'); + + await ctx.service.systems.afterSale.create({ + warehouse_id: warehouseId, after_sale_no: afterSaleNo, + type: 'order', sub_type: 'intercept', + title: `[AI工单] 取消拦截 - ${e.waybill_code}`, + description: descParts, priority: 10, creator_id: 0, + inbox_message_id: ctx.inboxContext?.inbound_message_id || null, + role_group: 'customer_service', status: 'pending', + waybill_id: e.id, waybill_no: e.waybill_code, + store_id: e.store_id || storeId || null, + order_id: e.order_id || null, + }); + createdNos.push(afterSaleNo); + } + } + if (createdNos.length > 0) parts.push(`已创建取消拦截工单: ${createdNos.length}个`); + + ctx.logger.info( + `[inbox functions] 取消拦截: total=${keywords.length} ` + + `feedback=${feedbackCount} created=${createdNos.length} skipped=${skipped.length}` + ); + + // 第4.5步:波次感知拦截(与 interceptWaybill 相同) + const orderIds = toCreate.map(e => e.order_id).filter(id => id); + if (orderIds.length > 0) { + try { + const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + if (orderModel) { + const orders = await orderModel.findAll({ + attributes: [ 'id', 'step', 'wave_id', 'inspection_status' ], + where: { id: { [ctx.app.Sequelize.Op.in]: orderIds }, step: { [ctx.app.Sequelize.Op.in]: [ 1, 2, 3 ] } }, + raw: true, + }); + if (orders.length > 0) { + const waveIds = [ ...new Set(orders.map(o => o.wave_id).filter(id => id > 0)) ]; + let waveMap = {}; + if (waveIds.length > 0) { + const waves = await ctx.model.WaveBatch.findAll({ + attributes: [ 'wave_id', 'wave_type', 'wave_status', 'total_orders' ], + where: { wave_id: { [ctx.app.Sequelize.Op.in]: waveIds } }, raw: true, + }); + waveMap = Object.fromEntries(waves.map(w => [ w.wave_id, w ])); + } + const interceptOrderIds = []; + for (const order of orders) { + const wave = waveMap[order.wave_id]; + let needIntercept = false; + if (order.wave_id > 0 && wave) { + needIntercept = wave.wave_type === 1 ? order.inspection_status !== 'fin' : true; + } else { + needIntercept = true; + } + if (needIntercept) interceptOrderIds.push(order.id); + } + if (interceptOrderIds.length > 0) { + await orderModel.update( + { intercept_status: 'requested' }, + { where: { id: { [ctx.app.Sequelize.Op.in]: interceptOrderIds } } } + ); + await ctx.model.OrderExpress.update( + { is_intercept: 'Y' }, + { where: { order_id: { [ctx.app.Sequelize.Op.in]: interceptOrderIds }, warehouse_id: warehouseId } } + ); + ctx.logger.info(`[inbox functions] 取消拦截-设置拦截状态: ${interceptOrderIds.length} 个订单`); + } + } + } + } catch (e) { + ctx.logger.warn(`[inbox functions] 取消拦截-波次处理失败: ${e.message}`); + } + } + + // 第五步:通知快递群 + const expressByCode = {}; + for (const e of toCreate) { + const code = e.logistics_code || '__unknown__'; + if (!expressByCode[code]) expressByCode[code] = { interfaceId: e.logistics_interface_id, waybills: [] }; + expressByCode[code].waybills.push(e.waybill_code); + } + let notifiedTotal = 0; + const notifiedNos = []; + for (const [ code, info ] of Object.entries(expressByCode)) { + if (code === '__unknown__' || !info.interfaceId) continue; + try { + const { afterSalesGroups } = await ctx.service.systems.inbox.group.findGroupsByExpress({ + expressInterfaceId: info.interfaceId, expressCode: code, warehouseId, + }); + if (afterSalesGroups.length === 0) continue; + const notifyMsg = info.waybills.join('\n') + '\n取消拦截'; + for (const g of afterSalesGroups) { + ctx.service.inbox.processor.pushSystemNotification({ + warehouse_id: warehouseId, group_id: g.group_id, + group_name: g.group_name, content: notifyMsg, ext_data: g.ext_data || null, + }); + notifiedTotal += 1; + } + } catch (e) { + ctx.logger.warn(`[inbox functions] 取消拦截查快递群失败 code=${code}: ${e.message}`); + } + } + if (notifiedTotal > 0) parts.push(`已通知 ${notifiedTotal} 个快递群`); + + // 有通知的工单升级 pending_feedback + if (notifiedNos.length > 0) { + const hours = await ctx.service.systems.afterSale._resolveFollowupHours(warehouseId, 'order', 'intercept'); + await ctx.model.AfterSale.update( + { status: 'pending_feedback', followup_at: ctx.app.Sequelize.literal(`DATE_ADD(NOW(), INTERVAL ${hours} HOUR)`), role_group: 'customer_service' }, + { where: { after_sale_no: { [ctx.app.Sequelize.Op.in]: notifiedNos }, warehouse_id: warehouseId } } + ); + } + + return { success: true, data: { feedback: feedbackCount, created: createdNos.length, skipped: skipped.length, notified_groups: notifiedTotal, message: parts.join(';') || '处理完成' } }; + } catch (error) { + ctx.logger.error(`[inbox functions] 取消拦截失败: ${error.message}`); + return { success: false, error: `操作失败: ${error.message}` }; + } + }, + }); + + this.register('handleExpressFeedback', { + description: '快递群售后通用反馈。传入运单号,优先找已有售后工单追加记录,无工单则按运单查订单并自动创建售后工单。AI 可根据快递反馈内容传入售后类型和子类型', + weight: 90, + keywords: [ '已处理', '已联系', '已通知', '核实', '反馈' ], + params: { + keyword: { type: 'string', required: true, description: '运单号,多个用逗号或空格分隔' }, + as_type: { type: 'string', required: false, description: '新建工单时的售后类型(order/receiving),默认 order' }, + as_sub_type: { type: 'string', required: false, description: '新建工单时的售后子类型,默认 logistics_issue。可选: logistics_issue(物流异常)/damage(破损)/missing_item(少发)/delivery_delay(发货延迟)/urge(催件)/verify_delivery(核实签收)/change_carrier(换快递)/rejected(拒收)/other(其他)' }, + }, + groups: [ GROUP.BOUND_EXPRESS_AFTER_SALES ], + handler: async (params = {}) => { + const { ctx } = this; + const raw = String(params.keyword || '').trim(); + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const asType = String(params.as_type || 'order').trim() || 'order'; + const asSubType = String(params.as_sub_type || 'logistics_issue').trim() || 'logistics_issue'; + + if (!raw) return { success: false, error: '请提供运单号' }; + if (!warehouseId) return { success: false, error: '无法获取仓库信息' }; + + const keywords = raw.split(/[,,\s\n]+/).map(s => s.trim()).filter(Boolean); + if (keywords.length === 0) return { success: false, error: '未解析到有效运单号' }; + + try { + // 第一步:查已有售后工单 + const existingAS = await ctx.model.AfterSale.findAll({ + attributes: [ 'id', 'after_sale_no', 'waybill_no', 'status', 'warehouse_id', 'inbox_message_id', 'store_id' ], + where: { + waybill_no: { [ctx.app.Sequelize.Op.in]: keywords }, + warehouse_id: warehouseId, + }, + raw: true, + }); + + const hasAS = new Set(existingAS.map(r => r.waybill_no)); + let feedbackCount = 0; + let createdCount = 0; + const parts = []; + + // 已有工单:追加反馈 + // 获取原始消息内容用于反馈记录 + let feedbackMsgContent = ''; + try { + const fbMsgId = ctx.inboxContext?.inbound_message_id; + if (fbMsgId) { + const fbMsg = await ctx.model.InboxMessage.findByPk(fbMsgId, { + attributes: [ 'content' ], + raw: true, + }); + if (fbMsg && fbMsg.content) feedbackMsgContent = String(fbMsg.content); + } + } catch (e) { + ctx.logger.warn(`[inbox functions] 获取原消息内容失败: ${e.message}`); + } + const feedbackGroup = ctx.inboxContext?.group_name || '未知群'; + const feedbackUser = ctx.inboxContext?.user_name || '未知用户'; + for (const as of existingAS) { + try { + const remarkLines = [ + `群: ${feedbackGroup}`, + `用户: ${feedbackUser}`, + `时间: ${new Date().toISOString().slice(0, 19) + .replace('T', ' ')}`, + ]; + if (feedbackMsgContent) { + remarkLines.push(`原消息: ${feedbackMsgContent}`); + } + await ctx.service.systems.afterSale.addStep(as.id, { + step_status: 'processing', + action: '快递反馈', + remark: remarkLines.join('\n'), + }); + feedbackCount += 1; + } catch (e) { + ctx.logger.warn(`[inbox functions] 快递反馈失败 as_no=${as.after_sale_no}: ${e.message}`); + } + } + if (feedbackCount > 0) { + parts.push(`已有工单追加反馈: ${feedbackCount}个`); + } + + // 第二步:无工单的运单,查订单并创建售后工单 + const needCreate = keywords.filter(k => !hasAS.has(k)); + let expressList = []; + const createdAsNos = []; + if (needCreate.length > 0) { + expressList = await ctx.model.OrderExpress.findAll({ + attributes: [ 'id', 'waybill_code', 'logistics_name', 'store_id', 'warehouse_id', 'order_id' ], + where: { + waybill_code: { [ctx.app.Sequelize.Op.in]: needCreate }, + warehouse_id: warehouseId, + }, + raw: true, + }); + + const foundCodes = new Set(expressList.map(e => e.waybill_code)); + const notFound = needCreate.filter(k => !foundCodes.has(k)); + + for (const e of expressList) { + try { + const afterSaleNo = await ctx.service.systemMethods.afterSale.generateAfterSaleNo(warehouseId); + const title = `[AI工单] 快递反馈 - ${e.waybill_code}`; + const description = [ + `运单号: ${e.waybill_code}`, + `快递公司: ${e.logistics_name || '未知'}`, + `售后类型: ${asType}.${asSubType}`, + '来源: 快递群反馈', + ].join('\n'); + + await ctx.service.systems.afterSale.create({ + warehouse_id: warehouseId, + after_sale_no: afterSaleNo, + type: asType, + sub_type: asSubType, + title, + description, + priority: 10, + creator_id: 0, + inbox_message_id: ctx.inboxContext?.inbound_message_id || null, + role_group: 'customer_service', + status: 'pending', + waybill_id: e.id, + waybill_no: e.waybill_code, + store_id: e.store_id || null, + order_id: e.order_id || null, + }); + createdAsNos.push(afterSaleNo); + createdCount += 1; + } catch (e) { + ctx.logger.warn(`[inbox functions] 快递反馈建单失败 wb=${e.waybill_code}: ${e.message}`); + } + } + if (createdCount > 0) { + parts.push(`已创建工单: ${createdCount}个`); + } + if (notFound.length > 0) { + parts.push(`未找到运单: ${notFound.join('、')}`); + } + } + + ctx.logger.info( + `[inbox functions] 快递反馈: total=${keywords.length} ` + + `feedback=${feedbackCount} created=${createdCount}` + ); + + // 第三步:排除回复检查(仓库配置 inbox_reply_exclude_keywords) + let skipReply = false; + try { + const inboundMsgId = ctx.inboxContext?.inbound_message_id; + if (inboundMsgId) { + const [ inboundMsg, store ] = await Promise.all([ + ctx.model.InboxMessage.findByPk(inboundMsgId, { + attributes: [ 'id', 'content' ], + raw: true, + }), + ctx.model.Store.findByPk(warehouseId, { + attributes: [ 'subject_config' ], + raw: true, + }), + ]); + + const excludeKeywords = (store && store.subject_config + && Array.isArray(store.subject_config.inbox_reply_exclude_keywords)) + ? store.subject_config.inbox_reply_exclude_keywords.filter(k => typeof k === 'string' && k.trim()) + : []; + + if (excludeKeywords.length > 0 && inboundMsg && inboundMsg.content) { + const msgContent = String(inboundMsg.content); + const matched = excludeKeywords.find(kw => msgContent.includes(kw)); + if (matched) { + skipReply = true; + ctx.logger.info( + `[inbox functions] 消息命中排除关键词「${matched}」,仅记录不通知` + ); + } + } + } + } catch (e) { + ctx.logger.warn(`[inbox functions] 排除回复检查失败: ${e.message}`); + } + + let replyTargets = new Map(); + if (!skipReply) { + // 第四步:回信路由 + // - 已有工单且带 inbox_message_id → 查原始消息获取群信息 → 回信到原群 + // - 无工单或无 inbox_message_id → 回信到货主售后群 + replyTargets = new Map(); // group_id → { group_id, group_name, user_id, ext_data } + const replyMsg = parts.join(';') || '处理完成'; + + // 4a. 已有工单带 inbox_message_id:回信到原消息所在群(排除快递群) + const asWithMsgId = existingAS.filter(as => as.inbox_message_id); + let expressGroupIds = new Set(); + if (asWithMsgId.length > 0) { + const msgIds = [ ...new Set(asWithMsgId.map(as => as.inbox_message_id)) ]; + try { + const messages = await ctx.model.InboxMessage.findAll({ + attributes: [ 'id', 'group_id', 'user_id', 'group_name', 'user_name' ], + where: { id: { [ctx.app.Sequelize.Op.in]: msgIds } }, + raw: true, + }); + // 过滤快递群:原消息来自快递群的,不回信到快递群,走 4b 货主售后群 + const candidateGroupIds = [ ...new Set(messages.map(m => m.group_id).filter(Boolean)) ]; + if (candidateGroupIds.length > 0) { + const expressGroups = await ctx.model.InboxGroup.findAll({ + attributes: [ 'group_id' ], + where: { + group_id: { [ctx.app.Sequelize.Op.in]: candidateGroupIds }, + warehouse_id: warehouseId, + group_type: 'express', + }, + raw: true, + }); + expressGroupIds = new Set(expressGroups.map(g => g.group_id)); + } + for (const msg of messages) { + if (msg.group_id && !replyTargets.has(msg.group_id) && !expressGroupIds.has(msg.group_id)) { + replyTargets.set(msg.group_id, { + group_id: msg.group_id, + group_name: msg.group_name || '', + user_id: msg.user_id || '', + user_name: msg.user_name || '', + ext_data: null, + }); + } + } + } catch (e) { + ctx.logger.warn(`[inbox functions] 查原消息群信息失败: ${e.message}`); + } + } + + // 4b. 已有工单无 inbox_message_id + 新建工单 + 原消息来自快递群:回信到货主售后群 + const storeIdsForReply = new Set(); + // 已有工单无 inbox_message_id 的 store_id + for (const as of existingAS) { + if (!as.inbox_message_id && as.store_id) { + storeIdsForReply.add(as.store_id); + } + } + // 已有工单 inbox_message_id 指向快递群的(4a 已排除),也走货主售后群 + if (expressGroupIds && expressGroupIds.size > 0) { + for (const as of asWithMsgId) { + if (as.store_id) storeIdsForReply.add(as.store_id); + } + } + // 新建工单的 store_id(来自 OrderExpress 记录) + for (const e of expressList) { + if (!hasAS.has(e.waybill_code) && e.store_id) { + storeIdsForReply.add(e.store_id); + } + } + + if (storeIdsForReply.size > 0) { + try { + const storeGroups = await ctx.service.systems.inbox.group.findStoreAfterSalesGroups({ + storeIds: [ ...storeIdsForReply ], + warehouseId, + }); + for (const g of storeGroups) { + if (g.group_id && !replyTargets.has(g.group_id)) { + replyTargets.set(g.group_id, { + group_id: g.group_id, + group_name: g.group_name || '', + user_id: '', + user_name: '', + ext_data: g.ext_data || null, + }); + } + } + } catch (e) { + ctx.logger.warn(`[inbox functions] 查货主售后群失败: ${e.message}`); + } + } + + // 3c. 发送回信 + for (const [ , target ] of replyTargets) { + ctx.service.inbox.processor.pushSystemNotification({ + warehouse_id: warehouseId, + group_id: target.group_id, + group_name: target.group_name, + content: `快递反馈: ${replyMsg}`, + ext_data: target.ext_data, + }); + } + + if (replyTargets.size > 0) { + parts.push(`已回信到 ${replyTargets.size} 个群`); + } + } // if (!skipReply) + + if (skipReply) { + parts.push('消息命中排除关键词,仅记录不通知'); + } + + // 第五步:更新新建工单状态 + // - 已回信 → pending_feedback(等待外部通知)+ 跟踪时间 + // - 未回信/排除关键词 → processing(处理中) + // 注意:已有工单仅追加反馈,不改变原有状态 + if (createdAsNos.length > 0) { + try { + if (!skipReply && replyTargets && replyTargets.size > 0) { + const hours = await ctx.service.systems.afterSale._resolveFollowupHours( + warehouseId, asType, asSubType + ); + await ctx.model.AfterSale.update( + { + status: 'pending_feedback', + followup_at: ctx.app.Sequelize.literal(`DATE_ADD(NOW(), INTERVAL ${hours} HOUR)`), + role_group: 'customer_service', + }, + { + where: { + after_sale_no: { [ctx.app.Sequelize.Op.in]: createdAsNos }, + warehouse_id: warehouseId, + }, + } + ); + ctx.logger.info( + `[inbox functions] ${createdAsNos.length} 个工单已通知客户群,升级 pending_feedback,${hours}h 后追踪` + ); + } else { + await ctx.model.AfterSale.update( + { status: 'processing', role_group: 'customer_service' }, + { + where: { + after_sale_no: { [ctx.app.Sequelize.Op.in]: createdAsNos }, + warehouse_id: warehouseId, + }, + } + ); + ctx.logger.info( + `[inbox functions] ${createdAsNos.length} 个工单未通知客户群,状态设为 processing` + ); + } + } catch (e) { + ctx.logger.warn(`[inbox functions] 更新工单状态失败: ${e.message}`); + } + } + + return { + success: true, + data: { + feedback: feedbackCount, + created: createdCount, + message: parts.join(';') || '处理完成', + }, + }; + } catch (error) { + ctx.logger.error(`[inbox functions] 快递反馈处理失败: ${error.message}`); + return { success: false, error: `操作失败: ${error.message}` }; + } + }, + }); + this.register('listGroups', { - description: '查询当前仓库的群列表,包含屏蔽状态', + description: '查询当前仓库的群列表,包含屏蔽状态(仅内部仓库群可用)', params: {}, - groups: [ GROUP.COMMON ], + groups: [ GROUP.BOUND_WAREHOUSE ], + weight: 0, + keywords: [ '群列表', '有哪些群', '群组' ], handler: async (params = {}) => { const { ctx } = this; void params; @@ -905,6 +1791,8 @@ class InboxFunctionsService extends Service { * @param {Object} def.params 参数定义。 * @param {string[]} def.groups 所属分组列表,按 {主分组}:{子分组} 格式。 * 例如 ['common'] 或 ['bound:store', 'bound:store:after_sales']。 + * @param {number} [def.weight=0] 权重,值越大优先级越高,用于 AI 多函数匹配时排序。 + * @param {string[]} [def.keywords] 触发关键词,用于 AI 快速匹配用户意图。 * @param {Function} def.handler 函数实现,接收 params 对象,返回结果。 */ register(name, def) { @@ -921,135 +1809,13 @@ class InboxFunctionsService extends Service { groups: Array.isArray(def.groups) && def.groups.length > 0 ? def.groups : [ GROUP.COMMON ], + weight: Number.isFinite(def.weight) ? def.weight : 0, + keywords: Array.isArray(def.keywords) ? def.keywords : [], 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'); - } - /** * 执行已注册的函数。 * @@ -1076,358 +1842,6 @@ class InboxFunctionsService extends Service { }; } } - - /** - * 调用 DeepSeek API。 - * - * @param {Array<{role: string, content: string}>} messages 消息列表。 - * @param {Object} [options] 额外选项。 - * @return {Promise} AI 返回的文本内容。 - */ - async callDeepSeek(messages, options = {}) { - const { ctx } = this; - const apiKey = ctx.app.config.deepseek.apiKey; - const baseUrl = ctx.app.config.deepseek.baseUrl || 'https://api.deepseek.com'; - - if (!apiKey) { - throw new Error('DeepSeek API Key 未配置'); - } - - const result = await ctx.curl(`${baseUrl}/v1/chat/completions`, { - method: 'POST', - contentType: 'json', - dataType: 'json', - headers: { Authorization: `Bearer ${apiKey}` }, - data: { - model: 'deepseek-v4-pro', - messages, - temperature: options.temperature ?? 0, - max_tokens: options.maxTokens ?? 1000, - }, - timeout: options.timeout || 30000, - }); - - if (result.status !== 200 || !result.data) { - throw new Error(`DeepSeek 请求失败, HTTP ${result.status}`); - } - - let content = result.data.choices?.[0]?.message?.content || ''; - // 清理 markdown 代码块 - content = content.replace(/^```json\s*/i, '').replace(/\s*```$/i, ''); - content = content.replace(/^```\s*/i, '').replace(/\s*```$/i, ''); - return content.trim(); - } - - /** - * 获取智能对话历史上下文。 - * 同一群 + 同一用户 → 最近 N 条消息(含 AI 回复),用于多轮对话短期记忆。 - * 按创建时间升序排列,并为每条消息附加序号供 AI 追踪。 - * - * @param {Object} opts 查询选项。 - * @param {number} [opts.parentId] 当前消息的 parent_id(兼容旧参数)。 - * @param {number} [opts.maxMessages=5] 最大历史消息数。 - * @return {Promise>} 历史消息列表。 - */ - async getConversationHistory(opts = {}) { - const parentId = Number(opts.parentId) || 0; - const maxMessages = Math.min(10, Math.max(1, Number(opts.maxMessages) || 5)); - - const { ctx } = this; - const { InboxMessage } = ctx.model; - const { Op } = ctx.app.Sequelize; - - const groupId = String(ctx.inboxContext?.group_id || '').trim(); - const userId = String(ctx.inboxContext?.user_id || '').trim(); - const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); - - // 无群/用户上下文时,退回旧逻辑:沿 parent_id 追溯 - if (!groupId || !userId || !warehouseId) { - if (!parentId) return []; - try { - const history = []; - let currentId = parentId; - const visited = new Set(); - while (currentId && history.length < maxMessages) { - if (visited.has(currentId)) break; - visited.add(currentId); - const msg = await InboxMessage.findOne({ - attributes: [ 'id', 'parent_id', 'direction', 'content' ], - where: { id: currentId }, - raw: true, - }); - if (!msg) break; - history.unshift({ role: msg.direction === 'inbound' ? 'user' : 'assistant', content: msg.content || '' }); - currentId = msg.parent_id; - } - return history; - } catch (error) { - ctx.logger.warn(`[inbox functions] 对话历史回退查询失败: ${error.message}`); - return []; - } - } - - // 智能查询:同一群,最近 maxMessages 条(入站+出站混合,含所有成员) - try { - const messages = await InboxMessage.findAll({ - attributes: [ 'id', 'parent_id', 'direction', 'content', 'user_id', 'user_name', 'created_at' ], - where: { - warehouse_id: warehouseId, - group_id: groupId, - direction: { [Op.in]: [ 'inbound', 'outbound' ] }, - }, - order: [[ 'created_at', 'DESC' ]], - limit: maxMessages, - raw: true, - }); - - if (messages.length === 0) return []; - - // 升序排列,附加上下文信息供 AI 判断真人接管 - const blockedUsers = ctx.inboxContext?._blockedUserIds || new Set(); - return messages.reverse().map(msg => { - const u = String(msg.user_id || '').trim(); - const name = String(msg.user_name || '').trim(); - const isBlocked = u && blockedUsers.has(u); - return { - role: msg.direction === 'inbound' ? 'user' : 'assistant', - content: msg.content || '', - user_id: u || null, - user_name: name || null, - blocked: isBlocked, - }; - }); - } catch (error) { - ctx.logger.warn(`[inbox functions] 智能对话历史查询失败: ${error.message}`); - return []; - } - } - - /** - * DeepSeek 多轮推理:思考→调函数→评估→(重复或输出)。 - * - * 每轮 AI 返回 JSON,通过 action 字段决定行为: - * { "action": "call", "function": "函数名", "params": {...}, "reason": "..." } - * { "action": "reply", "reply": "最终回复内容" } - * - * 最多 MAX_ROUNDS 轮,防止无限循环。 - * - * @param {Object} data 消息数据。 - * @param {string} data.content 消息正文。 - * @param {Object} [data.ext_data] 透传数据。 - * @param {number} [data.parentId] 父消息ID。 - * @return {Promise<{reply: string, functionName: string|null, functionResult: Object|null}>} AI 回复。 - */ - async processWithAI(data = {}) { - const { ctx } = this; - const content = String(data.content || '').trim(); - if (!content) { - return { reply: '消息正文为空,无法处理', functionName: null, functionResult: null }; - } - - const activeGroups = this.resolveActiveGroups(); - ctx.logger.info(`[inbox functions] 当前活跃分组: ${activeGroups.join(', ')}`); - - const functionListText = this.buildFunctionListText(activeGroups); - if (!functionListText) { - ctx.logger.info('[inbox functions] 当前上下文无可用的 AI 函数'); - return { reply: null, functionName: null, functionResult: null }; - } - - // 拉取群历史(最多 10 条),同时注入 system prompt 和对话上下文 - const history = await this.getConversationHistory({ - parentId: data.parentId, - maxMessages: 10, - }); - const historyContext = history.length > 0 - ? history.map(h => { - const tag = h.blocked ? '[已屏蔽]' : ''; - return `[${h.role === 'user' ? h.user_name || h.user_id || '未知' : 'AI'}]${tag}: ${h.content}`; - }).join('\n') - : '(无历史)'; - - const MAX_ROUNDS = 5; - const executedFunctions = []; - const thoughts = []; - let finalReply = null; - let lastFunctionName = null; - let lastFunctionResult = null; - - const systemPrompt = `你是一个 WMS 仓库管理系统的智能助手,支持多步推理。 -已注册函数:\n${functionListText}\n -=== 群最近对话历史 === -${historyContext} -=== - -对话历史中 [已屏蔽] 标记表示该用户已主动要求屏蔽(不想被 AI 打扰)。 -如果 [已屏蔽] 用户发送了表示接手或正在处理的内容(如"我来处理""不用回复""稍等""我看看"),说明真人已接管 → 直接 silent。 - -你需要通过多轮调用来完成用户的复杂请求。每轮返回纯 JSON: - -如果还需要调用函数获取信息: -{ - "action": "call", - "function": "函数名", - "params": { "参数名": "参数值" }, - "reason": "为什么需要这个函数" -} - -如果信息充足可以回复用户了: -{ - "action": "reply", - "reply": "最终回复(中文纯文本,禁止Markdown,200字以内,可适当使用\\n换行分隔信息)" -} - -如果消息无需回复(用户只是确认、道谢、告别或表示自己处理): -{ - "action": "silent" -} - -真人接管判断规则(优先级最高,先于所有其他规则): -- 如果历史中某条消息 blocked=true 的用户发送了与当前问题相关的内容(如"我来处理""稍等""我看看"等表示接手的话术),说明真人客服已介入处理 → 直接 silent -- 如果 blocked 用户发送的内容与问题无关(如闲聊、询问其他事情),且当前用户仍在提问 → 正常回复当前用户 -- 如果历史中只有当前用户的连续消息,没有其他用户介入 → 正常回复 - -一般约束: -- 最多 ${MAX_ROUNDS} 轮函数调用,第 ${MAX_ROUNDS} 轮必须给出最终回复 -- 同一函数不要重复调用(除非参数不同) -- 如果函数执行失败,换其他方式或直接告知用户 -- 回复使用中文纯文本,禁止 Markdown 语法,可用 \\n 换行提升可读性 -- silent 仅用于:用户已确认收到消息且无新问题("好的""收到""OK""谢谢""知道了""好"),或用户表示告别/离场("再见""拜拜""88") -- 以下情况严禁 silent,必须 reply:任何形式的提问(含"在吗""有人吗""在不在")、操作请求、函数执行完毕、自定义欢迎语"你好""嗨""hello"等首次问候 -- 无法判断时,宁可回复也不要 silent -- searchStock 返回多条结果时,必须列举让用户选择(告知 id/编码/名称/可用库存),不要擅自决定 -- createOrder 失败时告知失败原因(库存不足/商品不存在等),不要重试同一商品 -- searchStock 返回的 stock_available 为 0 时,提醒用户该商品无库存,建议选择其他商品 -- searchStock/searchWarehouseStock 返回的 image_url 为图片URL数组(可能多张),has_images 为 true 时给出链接 -- searchStock/searchWarehouseStock 返回的 barcodes 为关联条码,回复时可列出帮助核对 -- searchStock/searchWarehouseStock 返回的管理标识 is_sn_mgmt/is_shelf_life_mgmt/is_batch_mgmt 分别表示SN管理/效期管理/批次管理 -- searchStock/searchWarehouseStock 返回的 box_spec 为箱规(长宽高体积毛净重装箱数),packing_requirements 为打包要求,用户问及时告知 -- searchStock/searchWarehouseStock 返回的 prohibited_type 为违禁品类型,非空时告知用户 -- 用户说"第1个""第2个"时,按 searchStock 返回的顺序对应选择 -- 需要上下文但记忆不足时,主动调用 recallHistory 回顾对话历史`; - - // 多轮推理循环 - for (let round = 1; round <= MAX_ROUNDS; round++) { - const contextLines = []; - if (executedFunctions.length > 0) { - contextLines.push('已执行的函数及结果:'); - executedFunctions.forEach((f, i) => { - contextLines.push( - ` ${i + 1}. ${f.name}(${JSON.stringify(f.params)}) → ${JSON.stringify(f.result)}` - ); - }); - } - - const messages = [ - { role: 'system', content: systemPrompt }, - ...history, - ...(contextLines.length > 0 ? [{ role: 'system', content: contextLines.join('\n') }] : []), - { role: 'user', content: round === 1 - ? content - : (executedFunctions.length > 0 - ? `已获取到函数执行结果,请根据结果 reply 告知用户(禁止 silent)。第 ${round}/${MAX_ROUNDS} 轮` - : `请根据已获取的信息,决定下一步:继续调用函数还是给出最终回复。第 ${round}/${MAX_ROUNDS} 轮`), - }, - ]; - - let raw = ''; - try { - raw = await this.callDeepSeek(messages, { maxTokens: 600 }); - ctx.logger.info(`[inbox functions] 第 ${round}/${MAX_ROUNDS} 轮: ${raw}`); - - const result = JSON.parse(raw); - - // 记录思考过程 - thoughts.push({ - round, - action: result.action || 'unknown', - function: result.function || null, - params: result.params || null, - reason: result.reason || null, - }); - - if (result.action === 'reply') { - finalReply = String(result.reply || '').trim(); - if (!finalReply) finalReply = '已处理完成'; - break; - } - - if (result.action === 'silent') { - // 已调用过操作类函数(非 recallHistory)→ 必须回复结果,不能 silent - const actionFunctions = executedFunctions.filter(f => f.name !== 'recallHistory'); - if (actionFunctions.length > 0) { - ctx.logger.info('[inbox functions] 已有操作类函数调用,忽略 silent 继续要求回复'); - continue; - } - ctx.logger.info('[inbox functions] AI 判定无需回复,跳过回执'); - return { reply: null, functionName: null, functionResult: null, thoughts, skip: true }; - } - - if (result.action === 'call' && result.function) { - const fnName = String(result.function).trim(); - const params = result.params || {}; - - if (fnName === 'none' || fnName === 'stop') { - finalReply = result.reply || '已处理完成'; - break; - } - - lastFunctionName = fnName; - lastFunctionResult = await this.callFunction(fnName, params); - executedFunctions.push({ name: fnName, params, result: lastFunctionResult }); - - // 补充函数执行结果到思考记录 - const lastThought = thoughts[thoughts.length - 1]; - if (lastThought) lastThought.functionResult = lastFunctionResult; - ctx.logger.info(`[inbox functions] 执行 ${fnName}: ${JSON.stringify(lastFunctionResult)}`); - - // 最后一轮强制输出 - if (round === MAX_ROUNDS) { - finalReply = lastFunctionResult?.data?.message - || lastFunctionResult?.data?.greeting - || JSON.stringify(lastFunctionResult?.data || lastFunctionResult); - } - continue; - } - - // 无法解析 → 尝试提取 reply - finalReply = result.reply || result.message || '抱歉,暂时无法处理您的请求'; - break; - } catch (error) { - ctx.logger.warn(`[inbox functions] 第 ${round} 轮异常: ${error.message}, raw: ${raw}`); - - // 不是 JSON → 当作文本回复 - if (error instanceof SyntaxError && raw) { - finalReply = raw; - break; - } - - // 最后一轮兜底 - if (round === MAX_ROUNDS) { - finalReply = '抱歉,暂时无法处理您的请求,请稍后重试'; - } - continue; - } - } - - // 无回复的兜底 - if (!finalReply && lastFunctionResult) { - finalReply = lastFunctionResult?.data?.message - || lastFunctionResult?.data?.greeting - || (lastFunctionResult?.success !== false ? '操作已完成' : lastFunctionResult?.error || '处理完成'); - } - if (!finalReply) { - finalReply = '抱歉,暂时无法处理您的请求'; - } - - ctx.logger.info(`[inbox functions] 最终回复: ${finalReply}`); - return { - reply: finalReply, - functionName: lastFunctionName, - functionResult: lastFunctionResult, - thoughts, - }; - } } module.exports = InboxFunctionsService; diff --git a/app/service/inbox/groups.js b/app/service/inbox/groups.js new file mode 100644 index 0000000..e6f7977 --- /dev/null +++ b/app/service/inbox/groups.js @@ -0,0 +1,224 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * ## 群类型统一定义(唯一数据源) + * + * 所有 AI 函数分组常量(GROUP)、合法子类型映射(VALID_SUB_TYPES)、 + * 通配展开(WILDCARD_EXPAND)均由此结构自动派生,修改群类型只需维护此处。 + * + * @constant {Array<{type: string, label: string, mainGroup: string, wildcardGroup: string|null, subTypes: Array<{key: string, label: string}>}>} + */ +const GROUP_TYPES = [ + { + type: 'store', + label: '货主群', + mainGroup: 'bound:store', + wildcardGroup: 'bound:store:*', + subTypes: [ + { key: 'after_sales', label: '售后' }, + { key: 'finance', label: '财务' }, + { key: 'receiving', label: '收货' }, + ], + }, + { + type: 'warehouse', + label: '仓库群', + mainGroup: 'bound:warehouse', + wildcardGroup: null, + subTypes: [ + { key: 'receiving', label: '收货' }, + { key: 'production', label: '生产' }, + { key: 'stockout', label: '出库' }, + { key: 'finance', label: '财务' }, + { key: 'all', label: '全体' }, + { key: 'customer_service', label: '客服' }, + { key: 'exception', label: '异常' }, + ], + }, + { + type: 'express', + label: '快递群', + mainGroup: 'bound:express', + wildcardGroup: null, + subTypes: [ + { key: 'pickup', label: '揽收' }, + { key: 'after_sales', label: '售后' }, + ], + }, +]; + +// ========== 以下均为 GROUP_TYPES 的派生值,禁止手动修改 ========== + +/** + * AI 函数分组常量,由 {@link GROUP_TYPES} 自动生成。 + * @constant {Record} + */ +const GROUP = (() => { + const map = { COMMON: 'common' }; + for (const gt of GROUP_TYPES) { + const prefix = gt.mainGroup.split(':').pop(); + const upper = prefix.toUpperCase(); + map[`BOUND_${upper}`] = gt.mainGroup; + if (gt.wildcardGroup) { + map[`BOUND_${upper}_WILDCARD`] = gt.wildcardGroup; + } + for (const st of gt.subTypes) { + map[`BOUND_${upper}_${st.key.toUpperCase()}`] = `${gt.mainGroup}:${st.key}`; + } + } + return Object.freeze(map); +})(); + +/** + * 各群类型下合法的子类型 key → GROUP 常量映射,由 {@link GROUP_TYPES} 自动生成。 + * @constant {Record>} + */ +const VALID_SUB_TYPES = (() => { + const map = {}; + for (const gt of GROUP_TYPES) { + if (gt.subTypes.length === 0) continue; + const sub = {}; + for (const st of gt.subTypes) { + const prefix = gt.mainGroup.split(':').pop().toUpperCase(); + sub[st.key] = GROUP[`BOUND_${prefix}_${st.key.toUpperCase()}`]; + } + map[gt.type] = sub; + } + return Object.freeze(map); +})(); + +/** + * 通配展开映射,由 {@link GROUP_TYPES} 自动生成。 + * @constant {Record} + */ +const WILDCARD_EXPAND = (() => { + const map = {}; + for (const gt of GROUP_TYPES) { + if (!gt.wildcardGroup) continue; + const prefix = gt.mainGroup.split(':').pop().toUpperCase(); + const list = [ GROUP[`BOUND_${prefix}`] ]; + for (const st of gt.subTypes) { + list.push(GROUP[`BOUND_${prefix}_${st.key.toUpperCase()}`]); + } + map[gt.wildcardGroup] = list; + } + return Object.freeze(map); +})(); + +/** + * 群分组匹配服务。 + * 负责根据当前上下文解析可用分组、判断函数可见性、构建函数列表。 + * 纯策略/匹配逻辑,不涉及函数注册与执行。 + */ +class InboxGroupsService extends Service { + + /** + * 根据当前上下文解析可用分组集合。 + * + * - 始终包含 `common`(通用分组)。 + * - 根据 `groupType` + `subType` 查询 VALID_SUB_TYPES 激活对应的子分组。 + * - 只有 VALID_SUB_TYPES 中声明的 subType 才会生效,防止越界激活。 + * + * @param {Object} [opts] 可选覆盖参数。 + * @param {string} [opts.groupType] 群类型(store / warehouse / express)。 + * @param {string} [opts.subType] 子类型。 + * @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); + + const gtDef = GROUP_TYPES.find(gt => gt.type === groupType); + if (gtDef && (groupType === 'express' || storeId > 0)) { + groups.push(gtDef.mainGroup); + const subMap = VALID_SUB_TYPES[groupType]; + if (subMap && subMap[subType]) { + groups.push(subMap[subType]); + } + } + + return 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) { + if (WILDCARD_EXPAND[g]) { + expanded.push(...WILDCARD_EXPAND[g]); + } else { + expanded.push(g); + } + } + + return expanded.some(g => g === GROUP.COMMON || activeGroups.includes(g)); + } + + /** + * 获取指定分组下的函数列表。 + * + * @param {string[]} [activeGroups] 活跃分组列表,不传则返回全部已注册函数。 + * @return {Array<{name: string, description: string, params: Object}>} 函数列表。 + */ + getFunctionList(activeGroups) { + const { ctx } = this; + const funcSvc = ctx.service.inbox.functions; + const list = []; + for (const [ name, def ] of funcSvc.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 { ctx } = this; + const funcSvc = ctx.service.inbox.functions; + const lines = []; + for (const [ name, def ] of funcSvc.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(', ') + : '无参数'; + const weightStr = def.weight ? ` [权重:${def.weight}]` : ''; + const keywordStr = def.keywords && def.keywords.length > 0 + ? ` [触发词:${def.keywords.join(',')}]` + : ''; + lines.push(`- ${name}${weightStr}${keywordStr}: ${def.description}。参数: ${paramStr}`); + } + return lines.join('\n'); + } +} + +module.exports = InboxGroupsService; +module.exports.GROUP_TYPES = GROUP_TYPES; +module.exports.GROUP = GROUP; diff --git a/app/service/inbox/processor.js b/app/service/inbox/processor.js index 6b6fd0d..152d2b1 100644 --- a/app/service/inbox/processor.js +++ b/app/service/inbox/processor.js @@ -3,7 +3,6 @@ const Service = require('egg').Service; const WAREHOUSE_INTERFACE_TYPE_ID = 3; -const CALLBACK_TIMEOUT_MS = 10000; // 回执超时 10s /** * 站内信内容处理器。 @@ -11,6 +10,69 @@ const CALLBACK_TIMEOUT_MS = 10000; // 回执超时 10s * 将 warehouse_id 和 store_id 挂载到 ctx 上下文供下游使用。 */ class InboxProcessorService extends Service { + + constructor(ctx) { + super(ctx); + /** + * 群信息缓存(groupId:warehouseId → { group_type, sub_type, ai_enabled, ext_data })。 + * 生命周期跟随进程,写回 ext_data 时清除对应条目。 + */ + this._groupCache = new Map(); + } + + /** + * 从缓存或 DB 拉取群信息。若群 ext_data 为空且消息携带 ext_data,自动写回并清缓存。 + * @param {string} groupId 外部群ID + * @param {number} warehouseId 仓库ID + * @param {Object|null} msgExtData 入站消息的 ext_data + * @return {Promise<{group_type: string, sub_type: string, ai_enabled: number, ext_data: Object|null}>} + */ + async _loadGroupInfo(groupId, warehouseId, msgExtData) { + const { ctx } = this; + const cacheKey = `${groupId}:${warehouseId}`; + + // 命中缓存直接返回 + const cached = this._groupCache.get(cacheKey); + if (cached) return cached; + + let group = null; + try { + group = await ctx.model.InboxGroup.findOne({ + attributes: [ 'group_type', 'sub_type', 'ai_enabled', 'ext_data' ], + where: { group_id: groupId, warehouse_id: warehouseId }, + raw: true, + }); + } catch (e) { + ctx.logger.warn(`[inbox processor] 查询群分组信息失败: ${e.message}`); + } + + const info = { + group_type: (group && group.group_type) || '', + sub_type: (group && group.sub_type) || '', + ai_enabled: group ? group.ai_enabled : 0, + ext_data: (group && group.ext_data) || null, + }; + + // 群存在但 ext_data 为空,且入站消息带有 ext_data → 写回群配置 + if (group && !info.ext_data && msgExtData && typeof msgExtData === 'object' && Object.keys(msgExtData).length > 0) { + try { + await ctx.model.InboxGroup.update( + { ext_data: msgExtData }, + { where: { group_id: groupId, warehouse_id: warehouseId } } + ); + info.ext_data = msgExtData; + ctx.logger.info(`[inbox processor] 群 ext_data 写回成功: ${groupId}`); + } catch (e) { + ctx.logger.warn(`[inbox processor] 群 ext_data 写回失败: ${e.message}`); + // 写回失败不阻塞,直接返回 info(ext_data 仍为空) + return info; + } + } + + // 写入缓存 + this._groupCache.set(cacheKey, info); + return info; + } /** * 处理入站消息内容。 * 解析 content 后将 warehouse_id 和 store_id 写入 ctx 上下文。 @@ -88,8 +150,6 @@ class InboxProcessorService extends Service { const warehouseId = Number(data.warehouse_id) || 0; const extId = String(data.ext_id || ''); const parentId = Number(data.parent_id) || null; - let ackExtId = ''; - let callbackConfig = { url: null, appKey: null, appSecret: null }; try { // 1. 处理消息正文,挂载上下文 @@ -106,24 +166,16 @@ class InboxProcessorService extends Service { const bindHandled = await this.tryBindGroup(data); if (bindHandled) return; - // 4. 加载群的 group_type / sub_type / ai_enabled + // 4. 加载群的 group_type / sub_type / ai_enabled / ext_data(带缓存 + 自动写回) if (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, - }); - ctx.inboxContext.group_type = (group && group.group_type) || ''; - ctx.inboxContext.sub_type = (group && group.sub_type) || ''; - ctx.inboxContext.ai_enabled = group ? group.ai_enabled : 0; - } else { - ctx.inboxContext.ai_enabled = 0; - } - } catch (e) { - ctx.logger.warn(`[inbox processor] 查询群分组信息失败: ${e.message}`); + const groupId = String(ctx.inboxContext.group_id || '').trim(); + if (groupId) { + const info = await this._loadGroupInfo(groupId, warehouseId, data.ext_data || null); + ctx.inboxContext.group_type = info.group_type; + ctx.inboxContext.sub_type = info.sub_type; + ctx.inboxContext.ai_enabled = info.ai_enabled; + ctx.inboxContext.group_ext_data = info.ext_data; + } else { ctx.inboxContext.ai_enabled = 0; } } @@ -136,6 +188,7 @@ class InboxProcessorService extends Service { } // 5. 群未启用AI → 跳过(ai_enabled != 1 一律跳过,安全默认) + // 快递群默认 ai_enabled=0,需手动开启后才会走 AI 处理 if (ctx.inboxContext.ai_enabled !== 1) { ctx.logger.info(`[inbox processor] 群未启用AI自动回复,跳过 AI ext_id=${extId}`); return; @@ -158,8 +211,11 @@ class InboxProcessorService extends Service { } } + // 5.2 注入入站消息ID,供下游函数(如 interceptWaybill)关联工单 + ctx.inboxContext.inbound_message_id = parentId || null; + // 6. DeepSeek 两步交互(AI 内部自行判断真人接管) - const aiResult = await ctx.service.inbox.functions.processWithAI({ + const aiResult = await ctx.service.inbox.ai.processWithAI({ content: data.content || '', ext_data: data.ext_data || null, parentId: data.parent_id || null, @@ -189,182 +245,37 @@ class InboxProcessorService extends Service { `function=${aiResult.functionName || 'direct'} reply_length=${replyContent.length}` ); - // 7. 写入 outbound 回执记录 - ackExtId = `sys:ack:${extId}`; - - let outboundId = null; - try { - const existAck = await InboxMessage.findOne({ - where: { ext_id: ackExtId }, - attributes: [ 'id' ], - paranoid: false, - }); - - if (existAck) { - outboundId = existAck.id; - } else { - const created = 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: {}, - }); - outboundId = created.id; - - ctx.logger.info(`[inbox processor] 回执记录写入成功 parent_id=${parentId}`); + // 7. AI 推理写入入站消息(便于排查) + if (aiResult.thoughts && aiResult.thoughts.length > 0) { + try { + await InboxMessage.update( + { ai_thoughts: aiResult.thoughts }, + { where: { ext_id: extId } } + ); + } catch (e) { + ctx.logger.warn(`[inbox processor] 保存 AI 思考记录失败: ${e.message}`); } - } catch (writeError) { - ctx.logger.warn(`[inbox processor] 回执记录写入失败: ${writeError.message}`); } - // 8. 查回调地址并发送(带 MD5 签名) - callbackConfig = await this.getApiAppCallbackConfig(warehouseId); - const callbackUrl = callbackConfig.url; - if (!callbackUrl) { - ctx.logger.info(`[inbox processor] 仓库 ${warehouseId} 未配置回调地址,跳过回执 ext_id=${extId}`); + // 8. 快递群:仅执行函数,不回信 + if (groupType === 'express') { + ctx.logger.info(`[inbox processor] 快递群AI处理完成(不回信) ext_id=${extId}`); return; } - const crypto = require('crypto'); - const method = 'notify.reply'; - const notifyBody = { - code: 200, - data: { - type: 'ai', - content: replyContent, - ext_data: data.ext_data || null, - ext_id: String(outboundId || ''), - group_id: ctx.inboxContext?.group_id || data.group_id || '', - user_id: ctx.inboxContext?.user_id || data.user_id || '', - group_name: ctx.inboxContext?.group_name || data.group_name || '', - user_name: ctx.inboxContext?.user_name || data.user_name || '', - timestamp: Math.floor(Date.now() / 1000), - }, - }; - - const bodyJson = JSON.stringify(notifyBody); - const timestamp = Math.floor(Date.now() / 1000); - const appKey = callbackConfig.appKey || ''; - const appSecret = callbackConfig.appSecret || ''; - - const sign = appSecret - ? crypto.createHash('md5').update(appSecret + timestamp + bodyJson).digest('hex') - : ''; - - const urlWithSign = `${callbackUrl}?app_key=${encodeURIComponent(appKey)}&method=${encodeURIComponent(method)}×tamp=${timestamp}&sign=${encodeURIComponent(sign)}`; - - ctx.logger.info(`[inbox processor] 发送 API 回执 ext_id=${extId} url=${callbackUrl}`); - - const response = await ctx.curl(urlWithSign, { - method: 'POST', - dataType: 'json', - contentType: 'json', - data: notifyBody, - headers: { 'Content-Type': 'application/json' }, - timeout: CALLBACK_TIMEOUT_MS, - }); - - // 记录出站通知日志到 wms_warehouse_log - try { - const { WarehouseLog } = ctx.model; - await WarehouseLog.create({ - log_id: 'WN-' + Date.now() + '-' + crypto.randomBytes(3).toString('hex'), - app_key: appKey || null, - method, - warehouse_id: warehouseId || null, - url: urlWithSign || null, - http_status: response ? response.status : null, - body: JSON.stringify(notifyBody).substring(0, 65535), - result: response ? JSON.stringify(response.data || {}).substring(0, 65535) : '', - use_time: null, - created_at: new Date(), - }); - } catch (logErr) { - ctx.logger.error('[notify-log] 日志写入失败: ' + logErr.message); - } - - ctx.logger.info( - `[inbox processor] API 回执完成 ext_id=${extId} ` + - `http_status=${response.status}` - ); - - // 更新出站+入站推送状态 - if (response && response.status === 200 - && (!response.data || response.data.code === undefined || response.data.code === 200)) { - await InboxMessage.update( - { - push_status: 2, - push_response: { http_status: response.status, body: response.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 } } - ); - } - } else { - await InboxMessage.update( - { - push_status: 3, - push_response: { http_status: response ? response.status : null, body: response ? response.data : null }, - }, - { where: { ext_id: ackExtId } } - ); - } + // 9. 统一回信 + await this.writeOutboundReply({ + warehouse_id: warehouseId, + ext_id: extId, + parent_id: parentId, + ext_data: data.ext_data || null, + 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, + }, replyContent); } catch (error) { - ctx.logger.error( - `[inbox processor] API 回执失败 ext_id=${extId}: ${error.message}` - ); - - // 更新推送状态为失败 - try { - await InboxMessage.update( - { - push_status: 3, - push_response: { error: error.message }, - }, - { where: { ext_id: ackExtId } } - ); - } catch (updateErr) { - ctx.logger.error('[inbox processor] 更新推送状态失败: ' + updateErr.message); - } - - // 记录失败日志到 warehouse_log - try { - const { WarehouseLog } = ctx.model; - const crypto = require('crypto'); - await WarehouseLog.create({ - log_id: 'WN-' + Date.now() + '-' + crypto.randomBytes(3).toString('hex'), - app_key: callbackConfig.appKey || null, - method: 'notify.reply', - warehouse_id: warehouseId || null, - url: callbackConfig.url || null, - http_status: null, - body: '', result: 'Error: ' + error.message, - use_time: null, - created_at: new Date(), - }); - } catch (logErr) { - ctx.logger.error('[notify-log] 失败日志写入异常: ' + logErr.message); - } + ctx.logger.warn(`[inbox processor] API 回执失败 ext_id=${extId}: ${error.message}`); } } @@ -470,7 +381,8 @@ class InboxProcessorService extends Service { * @param {string} data.group_name 群名称(必填)。 * @param {string} data.user_name 用户名称(必填)。 * @param {string} replyContent 回复内容。 - * @param {string} [source='ai_reply'] 回调 source 类型:ai_reply / bind_confirm / balance / error。 + * @param {string} [source='ai_reply'] 回调 source 类型:ai_reply / bind_confirm / balance / error / system。 + * system 类型不要求 user_id/user_name。 * @return {Promise} */ async writeOutboundReply(data, replyContent, source = 'ai_reply') { @@ -480,18 +392,19 @@ class InboxProcessorService extends Service { const warehouseId = Number(data.warehouse_id || 0); const extId = String(data.ext_id || ''); const parentId = Number(data.parent_id || 0); + const isSystem = source === 'system'; - // 强制入参校验 + // 强制入参校验(system 类型不要求 user_id/user_name) 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 || '?'}` - ); + if (!groupId || !groupName) { + throw new Error(`回执缺少必填字段: group_id=${groupId || '?'}, group_name=${groupName || '?'}`); + } + if (!isSystem && (!userId || !userName)) { + throw new Error(`回执缺少必填字段: user_id=${userId || '?'}, user_name=${userName || '?'}`); } const ackExtId = `sys:ack:${extId}`; @@ -511,9 +424,9 @@ class InboxProcessorService extends Service { source_type: 'system', source_extra: null, target_type: 'api', group_id: groupId, - user_id: userId, + user_id: isSystem ? null : userId, group_name: groupName, - user_name: userName, + user_name: isSystem ? null : userName, content: replyContent, ext_data: data.ext_data || null, flags: {}, }); @@ -527,14 +440,13 @@ class InboxProcessorService extends Service { const notifyBody = { code: 200, data: { - type: source === 'ai_reply' ? 'ai' : source === 'bind_confirm' ? 'bind' : source === 'balance' ? 'balance' : 'error', + type: isSystem ? 'system' : source === 'ai_reply' ? 'ai' : source === 'bind_confirm' ? 'bind' : source === 'balance' ? 'balance' : 'error', content: replyContent, ext_data: data.ext_data || null, ext_id: String(outboundId), group_id: groupId, - user_id: userId, + ...(isSystem ? {} : { user_id: userId, user_name: userName }), group_name: groupName, - user_name: userName, timestamp: Math.floor(Date.now() / 1000), }, }; @@ -767,6 +679,45 @@ class InboxProcessorService extends Service { return config.url; } + /** + * 系统通知异步推送:仅 POST 回调,不写 inbox_message。 + * @param {Object} data 通知数据。 + * @param {number} data.warehouse_id 仓库ID。 + * @param {string} data.group_id 目标群ID。 + * @param {string} data.group_name 目标群名称。 + * @param {string} data.content 通知内容。 + * @param {Object} [data.ext_data] 群扩展数据(渠道信息)。 + */ + pushSystemNotification(data = {}) { + const { ctx } = this; + const warehouseId = Number(data.warehouse_id); + const groupId = String(data.group_id || '').trim(); + const groupName = String(data.group_name || '').trim(); + const content = String(data.content || '').trim(); + const extData = data.ext_data || null; + + if (!warehouseId || !groupId || !content) return; + + // 构造 data 对象,复用 writeOutboundReply + const replyData = { + warehouse_id: warehouseId, + ext_id: `sys:notify:${warehouseId}:${groupId}:${Date.now()}:${Math.random().toString(36).slice(2, 8)}`, + parent_id: null, + ext_data: extData, + group_id: groupId, + user_id: '', + group_name: groupName, + user_name: '', + }; + + // 写库 + POST,异步不阻塞 + setImmediate(() => { + this.writeOutboundReply(replyData, content, 'system').catch(err => { + ctx.logger.warn(`[pushNotify] 推送异常 group=${groupName}: ${err.message}`); + }); + }); + } + /** * 尝试从消息正文中提取仓库ID。 * 子类或业务方可覆盖此方法以实现自定义解析逻辑。 diff --git a/app/service/openapiMethods/order.js b/app/service/openapiMethods/order.js index 6c6764b..50c55e4 100644 --- a/app/service/openapiMethods/order.js +++ b/app/service/openapiMethods/order.js @@ -61,7 +61,41 @@ class OpenapiOrderService extends MainService { transaction, }); + // 同步更新运单表拦截标记 + try { + const { ctx } = this; + const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0; + if (warehouseId > 0) { + await ctx.model.OrderExpress.update( + { is_intercept: 'Y' }, + { where: { order_id: existingOrder.id, warehouse_id: warehouseId }, transaction } + ); + } + } catch (expressErr) { + this.ctx.logger.warn( + `[openapi order cancel] 更新运单拦截标记失败, orderId=${existingOrder.id}, error=${expressErr.message}` + ); + } + await transaction.commit(); + + // 创建售后工单 + 通知快递群(失败不影响主流程) + try { + const { ctx } = this; + const whId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0; + if (whId > 0) { + await ctx.service.systems.afterSale.createInterceptWorkOrdersAndNotify({ + orderIds: [ existingOrder.id ], + warehouseId: whId, + creatorLabel: ctx.user?.employees_name || 'OpenAPI系统', + }); + } + } catch (workOrderErr) { + this.ctx.logger.warn( + `[openapi order cancel] 创建工单/通知失败, orderId=${existingOrder.id}, error=${workOrderErr.message}` + ); + } + return this.fail('取消失败,已通知拦截执行'); } diff --git a/app/service/qimenMethods/order.js b/app/service/qimenMethods/order.js index a949a49..a390248 100644 --- a/app/service/qimenMethods/order.js +++ b/app/service/qimenMethods/order.js @@ -194,7 +194,33 @@ class orderServer extends MainService { transaction, }); + // 同步更新运单表拦截标记 + try { + await ctx.model.OrderExpress.update( + { is_intercept: 'Y' }, + { where: { order_id: existingOrder.id, warehouse_id: info.warehouseId }, transaction } + ); + } catch (expressErr) { + ctx.logger.warn( + `[qimen order cancel] 更新运单拦截标记失败, orderId=${existingOrder.id}, error=${expressErr.message}` + ); + } + await transaction.commit(); + + // 创建售后工单 + 通知快递群(失败不影响主流程) + try { + await ctx.service.systems.afterSale.createInterceptWorkOrdersAndNotify({ + orderIds: [ existingOrder.id ], + warehouseId: info.warehouseId, + creatorLabel: ctx.user?.employees_name || '奇门系统', + }); + } catch (workOrderErr) { + ctx.logger.warn( + `[qimen order cancel] 创建工单/通知失败, orderId=${existingOrder.id}, error=${workOrderErr.message}` + ); + } + await this.sendCancelInterceptNotice({ orderCode, existingOrder, diff --git a/app/service/systemMethods/afterSale.js b/app/service/systemMethods/afterSale.js index 78e9b43..a9ddb13 100644 --- a/app/service/systemMethods/afterSale.js +++ b/app/service/systemMethods/afterSale.js @@ -16,9 +16,10 @@ const BLOCK_PERMISSION_ROLE_GROUP_MAP = Object.freeze({ }); /** - * 售后模块工作列表排除的状态(已完成/已取消)。 + * 售后模块工作列表排除的终态(已完成/已关闭/已取消)。 + * pending_feedback 不在静态排除列表中,由 workList 根据 followup_at 动态判断。 */ -const WORK_LIST_EXCLUDED_STATUSES = Object.freeze([ 'completed', 'cancelled' ]); +const WORK_LIST_EXCLUDED_STATUSES = Object.freeze([ 'completed', 'closed', 'cancelled' ]); /** * 系统方法层:afterSale(售后模块接口包装层)。 @@ -29,9 +30,9 @@ class AfterSaleMethodService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'workList,auditList,detail,create,transfer,handleWorkOrder,registerClaim,export,exportTaskProgress'; - const _noNeedLog = 'workList,auditList,detail,export,exportTaskProgress'; - const _noNeedAuth = 'workList,auditList,detail,create,transfer,handleWorkOrder,registerClaim,export,exportTaskProgress'; + const _noNeedRight = 'workList,auditList,detail,create,transfer,handleWorkOrder,batchSetPendingFeedback,batchClose,registerClaim,export,exportTaskProgress,workCount'; + const _noNeedLog = 'workList,auditList,detail,export,exportTaskProgress,workCount'; + const _noNeedAuth = 'workList,auditList,detail,create,transfer,handleWorkOrder,batchSetPendingFeedback,batchClose,registerClaim,export,exportTaskProgress,workCount'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -62,7 +63,7 @@ class AfterSaleMethodService extends MainService { }); // 提取当前用户的售后 block 权限 → role_group 列表 - const allowedRoleGroups = this._resolveAfterSaleBlockRoleGroups(); + const allowedRoleGroups = await this._resolveAfterSaleBlockRoleGroups(); // 强制过滤:仅展示当前用户可处理的 role_group,且排除已完成/已取消 const enforcedWhere = { @@ -77,37 +78,112 @@ class AfterSaleMethodService extends MainService { }, }; - const result = await service.systems.afterSale.list(enforcedWhere, pagination, sort); + const result = await service.systems.afterSale.list(enforcedWhere, pagination, sort, { + order: [[ 'priority', 'DESC' ], [ 'updated_at', 'DESC' ]], + excludeFutureFollowup: true, + }); return this.success('ok', result); } /** * 解析当前用户所拥有的售后 block 权限对应的 role_group 列表。 - * 从 ctx.user.role.permissions 中筛选 type=block 且 ID 为 516/517/518 的权限项。 + * 从 wms_role.permissions 中查询当前激活角色的原始权限 ID, + * 若 permissions='*' 则返回全部 role_group,否则筛选 516/517/518。 * - * @return {string[]} 当前用户可处理的 role_group 列表 + * @return {Promise} 当前用户可处理的 role_group 列表 */ - _resolveAfterSaleBlockRoleGroups() { + async _resolveAfterSaleBlockRoleGroups() { const { ctx } = this; - const rolePermissions = ctx.user && ctx.user.role && Array.isArray(ctx.user.role.permissions) - ? ctx.user.role.permissions - : []; - - const allowedRoleGroups = []; - for (const perm of rolePermissions) { - const permId = Number(perm && (perm.id || perm.permission_id || 0)); - const permType = String(perm && (perm.type || '')).trim(); - if (permType === 'block' && BLOCK_PERMISSION_ROLE_GROUP_MAP[permId]) { - allowedRoleGroups.push(BLOCK_PERMISSION_ROLE_GROUP_MAP[permId]); - } - } - - // 如果未匹配到任何售后 block 权限,默认不给任何 role_group 可见范围 - if (allowedRoleGroups.length === 0) { + const employeeId = ctx.user && ctx.user.employees_id; + if (!employeeId) { return [ '__none__' ]; } - return allowedRoleGroups; + try { + // 1. 通过 EmployeeRole 找到 role_id + const employeeRole = await ctx.model.EmployeeRole.findOne({ + where: { employee_id: employeeId }, + attributes: [ 'role_id' ], + raw: true, + }); + if (!employeeRole || !employeeRole.role_id) { + return [ '__none__' ]; + } + + // 2. 读取 wms_role.permissions + const role = await ctx.model.Role.findOne({ + where: { id: employeeRole.role_id, status: 1 }, + attributes: [ 'permissions' ], + raw: true, + }); + if (!role) { + return [ '__none__' ]; + } + + // 3. 标准化解析 + const state = ctx.service.systems.auth.rolePermission.normalizePermissionSet(role.permissions); + + // 超级管理员 → 全部 role_group + if (state.allAccess) { + return [ 'customer_service', 'warehouse', 'finance' ]; + } + + // 匹配 block 权限 516/517/518 + const allowedRoleGroups = []; + for (const permId of state.permissionIds) { + if (BLOCK_PERMISSION_ROLE_GROUP_MAP[permId]) { + allowedRoleGroups.push(BLOCK_PERMISSION_ROLE_GROUP_MAP[permId]); + } + } + + if (allowedRoleGroups.length === 0) { + return [ '__none__' ]; + } + return allowedRoleGroups; + } catch (err) { + ctx.logger.warn(`[_resolveAfterSaleBlockRoleGroups] 权限查询失败: ${err.message}`); + return [ '__none__' ]; + } + } + + // =========================== + // 待处理工单计数(角标用) + // =========================== + + /** + * 快速查询当前用户待处理售后工单数量(用于角标显示)。 + * 过滤逻辑与 workList 一致:role_group 按 block 权限,排除已完成/已取消。 + * 返回 { count: number },前端自行判断 >99 显示 99+。 + * + * @param {Object} data 请求体(可选 where 条件) + * @return {Promise} { count: number } + */ + async workCount(data = {}) { + const { service } = this; + const { where } = this.prepareWhereContext(data, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + + // 与 workList 一致的角色组 + 状态过滤 + const allowedRoleGroups = await this._resolveAfterSaleBlockRoleGroups(); + const enforcedWhere = { + ...where, + role_group: { + operator: 'in', + value: allowedRoleGroups, + }, + status: { + operator: 'notin', + value: WORK_LIST_EXCLUDED_STATUSES, + }, + }; + + const result = await service.systems.afterSale.countPending(enforcedWhere, { excludeFutureFollowup: true }); + return this.success('ok', { count: result.count }); } // =========================== @@ -177,7 +253,7 @@ class AfterSaleMethodService extends MainService { * @param {string} [data.description] 售后详细描述 * @param {number} [data.priority=0] 优先级 * @param {number} [data.waybill_id] 关联运单ID - * @param {number} [data.order_delivery_id] 关联发货订单ID + * @param {number} [data.order_delivery_id] 关联发货订单ID(兼容别名 order_id) * @param {number} [data.entry_order_id] 关联入库单ID * @param {number} [data.order_stockout_id] 关联出库单ID * @param {number} [data.receiving_id] 关联收货单ID @@ -201,7 +277,8 @@ class AfterSaleMethodService extends MainService { description, priority, waybill_id: waybillId, - order_delivery_id: orderDeliveryId, + order_delivery_id: orderDeliveryIdRaw, + order_id: orderIdRaw, entry_order_id: entryOrderId, order_stockout_id: orderStockoutId, receiving_id: receivingId, @@ -209,6 +286,9 @@ class AfterSaleMethodService extends MainService { inbox_message_id: inboxMessageId, } = data || {}; + // 兼容 order_id 别名(优先 order_delivery_id,为空时取 order_id) + const orderDeliveryId = orderDeliveryIdRaw || orderIdRaw || null; + // 生成售后单号 const afterSaleNo = await this.generateAfterSaleNo(warehouseId); @@ -397,7 +477,6 @@ class AfterSaleMethodService extends MainService { * * @param {Object} data 请求体 * @param {number} data.id 售后单主键ID - * @param {string} data.action 操作动作描述 * @param {string} [data.remark] 处理备注 * @param {string} [data.status] 目标售后状态 * @param {string} [data.resolution] 完结处理结果(status=completed 时写入) @@ -408,7 +487,6 @@ class AfterSaleMethodService extends MainService { const { ctx, service } = this; const { id, - action, remark, status: targetStatus, resolution, @@ -418,9 +496,10 @@ class AfterSaleMethodService extends MainService { if (!id) { return this.fail('缺少售后单ID'); } - if (!action) { - return this.fail('缺少操作动作'); - } + + // status 不填或填错默认 processing;pending 是创建默认值,不适用于处理操作 + const ALLOWED_STATUSES = Object.keys(ctx.model.AfterSale.AFTER_SALE_STATUS).filter(s => s !== 'pending'); + const safeStatus = (targetStatus && ALLOWED_STATUSES.includes(targetStatus)) ? targetStatus : 'processing'; const operatorId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0; const operatorSnapshot = this._buildOperatorSnapshot(); @@ -428,9 +507,8 @@ class AfterSaleMethodService extends MainService { const result = await service.systems.afterSale.handleWorkOrder({ id: Number(id), - action, remark: remark || null, - targetStatus: targetStatus || null, + targetStatus: safeStatus, resolution: resolution || null, attachmentIds: Array.isArray(attachmentIds) ? attachmentIds : [], operatorId, @@ -441,6 +519,96 @@ class AfterSaleMethodService extends MainService { return this.success('处理成功', result); } + // =========================== + // 批量设为待反馈 + // =========================== + + /** + * 批量将售后工单设为"待反馈"状态,按仓库配置自动计算下次跟进时间。 + * 所有工单在同一事务中处理,任一失败则全部回滚。 + * + * @param {Object} data 请求体 + * @param {number[]} data.ids 售后单主键ID列表 + * @param {string} [data.remark] 统一处理备注(所有工单共用) + * @return {Promise} 统一 success 包装,包含 total/success/failed + */ + async batchSetPendingFeedback(data = {}) { + const { ctx, service } = this; + const { ids, remark } = data || {}; + + if (!Array.isArray(ids) || ids.length === 0) { + return this.fail('ids 不能为空且必须为数组'); + } + + const operatorId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0; + const operatorSnapshot = this._buildOperatorSnapshot(); + const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0; + + if (!warehouseId) { + return this.fail('无法获取当前仓库上下文'); + } + + const result = await service.systems.afterSale.batchSetPendingFeedback({ + ids, + remark: remark || null, + operatorId, + operatorSnapshot, + warehouseId, + }); + + return this.success('批量设为待反馈完成', result); + } + + // =========================== + // 批量完结/关闭 + // =========================== + + /** + * 批量将售后工单设为完结或关闭状态。 + * completed 时自动写入 resolved_at 并清除 followup_at。 + * 所有工单在同一事务中处理,任一失败则全部回滚。 + * + * @param {Object} data 请求体 + * @param {number[]} data.ids 售后单主键ID列表 + * @param {string} data.status 目标状态:completed | closed + * @param {string} [data.resolution] 完结处理结果(仅 status=completed 时写入) + * @param {string} [data.remark] 统一处理备注(所有工单共用) + * @return {Promise} 统一 success 包装,包含 total/success/failed + */ + async batchClose(data = {}) { + const { ctx, service } = this; + const { ids, status: targetStatus, resolution, remark } = data || {}; + + if (!Array.isArray(ids) || ids.length === 0) { + return this.fail('ids 不能为空且必须为数组'); + } + + const ALLOWED_TARGET_STATUSES = new Set([ 'completed', 'closed' ]); + if (!targetStatus || !ALLOWED_TARGET_STATUSES.has(targetStatus)) { + return this.fail('status 必须为 completed 或 closed'); + } + + const operatorId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0; + const operatorSnapshot = this._buildOperatorSnapshot(); + const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0; + + if (!warehouseId) { + return this.fail('无法获取当前仓库上下文'); + } + + const result = await service.systems.afterSale.batchClose({ + ids, + status: targetStatus, + resolution: resolution || null, + remark: remark || null, + operatorId, + operatorSnapshot, + warehouseId, + }); + + return this.success('批量操作完成', result); + } + // =========================== // 登记理赔 // =========================== @@ -838,6 +1006,7 @@ class AfterSaleMethodService extends MainService { return null; } } + } module.exports = AfterSaleMethodService; diff --git a/app/service/systemMethods/index.js b/app/service/systemMethods/index.js index 19f4bd7..de7eb76 100644 --- a/app/service/systemMethods/index.js +++ b/app/service/systemMethods/index.js @@ -1287,8 +1287,13 @@ class indexService extends MainService { // 构建嵌套路径 for (let i = 0; i < keys.length - 1; i++) { const key = keys[i]; - if (!current[key]) { + // 如果路径节点已存在但非对象(被其他叶子键占用),先保存旧值再转为对象 + if (!current[key] || typeof current[key] !== 'object') { + const oldValue = current[key]; current[key] = {}; + if (oldValue !== undefined) { + current[key]._self = oldValue; + } } current = current[key]; } diff --git a/app/service/systemMethods/order/deliveryOrder.js b/app/service/systemMethods/order/deliveryOrder.js index c0c59bc..8cc4f92 100644 --- a/app/service/systemMethods/order/deliveryOrder.js +++ b/app/service/systemMethods/order/deliveryOrder.js @@ -1,14 +1,24 @@ 'use strict'; const OrderBaseService = require('./base'); +const fs = require('fs'); +const path = require('path'); + +const DEBUG_LOG = path.join(__dirname, '..', '..', '..', '..', 'temp', 'quickSearch_debug.log'); + +function dbg(msg) { + const ts = new Date().toISOString(); + const line = `[${ts}] ${msg}\n`; + try { fs.appendFileSync(DEBUG_LOG, line, 'utf8'); } catch (_) { /* ignore */ } +} class DeliveryOrderService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,deliveryOrder'; - const _noNeedLog = 'list'; - const _noNeedAuth = 'list,deliveryOrder'; + const _noNeedRight = 'list,deliveryOrder,quickSearch'; + const _noNeedLog = 'list,quickSearch'; + const _noNeedAuth = 'list,deliveryOrder,quickSearch'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -50,6 +60,321 @@ class DeliveryOrderService extends OrderBaseService { return await super.detail(detailParams); } + /** + * 订单快速搜索。 + * 跨表联合搜索:运单号(wms_order_express,精确)、发货单号/外部订单号/平台交易单号(dispatch 表,模糊)。 + * 返回匹配的订单列表(最多 20 条),包含订单关键信息及关联运单号。 + * + * @param {Object} data 请求体。 + * @param {string} data.keyword 搜索关键词(必填)。 + * @return {Promise} { list, keyword } + */ + async quickSearch(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const requestData = this.isPlainObject(data) ? data : {}; + const keyword = String(requestData.keyword || '').trim(); + const warehouseId = this.getWarehouseId(); + + dbg('========== quickSearch START =========='); + dbg(`keyword="${keyword}" warehouseId=${warehouseId}`); + + if (!keyword) { + dbg('keyword empty → return []'); + return { list: [], keyword: '' }; + } + + if (!warehouseId) { + dbg('warehouseId empty → throw'); + throw new Error('缺少仓库上下文'); + } + + const MAX_RESULTS = 20; + + // 收集匹配的订单 ID(去重) + const matchedOrderIds = new Set(); + + // ====== 第一步:express 表 OR 搜索 ====== + dbg('--- Step1: express OR query ---'); + const expressWhere = { + warehouse_id: warehouseId, + [Op.or]: [ + { waybill_code: keyword }, + { delivery_order_code: { [Op.like]: `%${keyword}%` } }, + { source_order_codes: { [Op.like]: `%${keyword}%` } }, + ], + }; + dbg(`expressWhere: ${JSON.stringify(expressWhere)}`); + + let expressRecords; + try { + expressRecords = await ctx.model.OrderExpress.findAll({ + attributes: [ + 'id', 'order_id', 'waybill_code', 'delivery_order_code', 'source_order_codes', 'store_id', + 'logistics_code', 'logistics_name', + 'logistics_interface_id', 'logistics_interface_name', + 'platform_code', 'status', 'is_back', 'is_intercept', 'is_galaxy_receive', + 'weighing_weight', + ], + where: expressWhere, + raw: true, + limit: MAX_RESULTS, + }); + dbg(`expressRecords count: ${expressRecords.length}`); + } catch (e) { + dbg(`expressRecords ERROR: ${e.message}`); + expressRecords = []; + } + + const waybillMap = new Map(); + for (const er of expressRecords) { + dbg(` er: id=${er.id} order_id=${er.order_id} waybill_code=${er.waybill_code} delivery_order_code=${er.delivery_order_code}`); + if (er.order_id) { + matchedOrderIds.add(er.order_id); + if (!waybillMap.has(er.order_id)) { + waybillMap.set(er.order_id, []); + } + waybillMap.get(er.order_id).push(this.buildWaybillItem(er)); + } + } + dbg(`matchedOrderIds: [${[ ...matchedOrderIds ].join(',')}]`); + dbg(`waybillMap keys: [${[ ...waybillMap.keys() ].join(',')}]`); + + if (matchedOrderIds.size === 0) { + dbg('matchedOrderIds empty → return []'); + return { list: [], keyword }; + } + + // ====== 第二步:订单表 IN 查详情 ====== + const orderIds = [ ...matchedOrderIds ].slice(0, MAX_RESULTS); + const orderMap = new Map(); + dbg(`--- Step2: order detail IN query, orderIds=[${orderIds.join(',')}] ---`); + + if (orderIds.length > 0) { + const factory = ctx.model && ctx.model.OrderDeliveryFactory; + dbg(`factory exists: ${!!factory}`); + dbg(`factory keys: ${factory ? Object.keys(factory).join(',') : 'N/A'}`); + dbg(`factory.getDispatchModel type: ${factory && typeof factory.getDispatchModel}`); + + // 直接尝试调用,不判断 typeof,看具体报什么错 + if (factory) { + const tableDefs = [ + { label: 'dispatch', getModel: () => factory.getDispatchModel(warehouseId) }, + { label: 'current', getModel: () => factory.getCurrentModel(warehouseId) }, + { label: 'history', getModel: () => factory.getHistoryModel(warehouseId) }, + ]; + const remainingIds = new Set(orderIds.map(String)); + for (const entry of tableDefs) { + if (remainingIds.size === 0) break; + dbg(` trying table: ${entry.label}, remainingIds=[${[ ...remainingIds ].join(',')}]`); + try { + const model = await entry.getModel(); + dbg(` ${entry.label} model: ${!!model}, typeof findAll=${model && typeof model.findAll}`); + if (!model || typeof model.findAll !== 'function') { + dbg(` ${entry.label} model invalid, skip`); + continue; + } + const whereClause = { id: [ ...remainingIds ].map(Number) }; + dbg(` ${entry.label} where: ${JSON.stringify(whereClause)}`); + const rows = await model.findAll({ + attributes: [ + 'id', 'delivery_order_code', 'source_order_codes', 'pay_no', + 'store_id', 'status', + 'name', 'mobile', 'province', 'city', 'area', 'detail_address', + 'buyer_nick', 'seller_nick', 'shop_nick', + 'total_amount', 'item_amount', 'freight', + 'items_count', 'items_weight', + 'wave_no', 'delivery_time', 'create_at', + ], + where: whereClause, + raw: true, + }); + dbg(` ${entry.label} rows count: ${rows.length}`); + for (const r of (rows || [])) { + dbg(` row: id=${r.id} delivery_order_code=${r.delivery_order_code} status=${r.status}`); + const rid = String(r.id); + if (!orderMap.has(rid)) { orderMap.set(rid, r); remainingIds.delete(rid); } + } + } catch (e) { + dbg(` ${entry.label} ERROR: ${e.message} | stack: ${(e.stack || '').split('\n').slice(0, 3).join(' | ')}`); + continue; + } + } + } + } + dbg(`orderMap.size: ${orderMap.size}, keys: [${[ ...orderMap.keys() ].join(',')}]`); + + // ====== 第三步:货主备注 ====== + dbg('--- Step3: store remark ---'); + const storeRemarkMap = new Map(); + const allStoreIds = new Set(); + for (const oid of orderIds) { + const wb = (waybillMap.get(oid) || [])[0]; + const sid = (wb && wb.store_id) || (orderMap.get(String(oid)) || {}).store_id || 0; + if (sid) allStoreIds.add(sid); + } + dbg(`allStoreIds: [${[ ...allStoreIds ].join(',')}]`); + if (allStoreIds.size > 0 && ctx.model.StoreWarehouse) { + try { + const swRows = await ctx.model.StoreWarehouse.findAll({ + where: { store_id: { [Op.in]: [ ...allStoreIds ] }, warehouse_id: warehouseId }, + attributes: [ 'store_id', 'store_remask' ], raw: true, + }); + dbg(`store_warehouse rows: ${swRows.length}`); + for (const sw of swRows) { + dbg(` sw: store_id=${sw.store_id} store_remask="${sw.store_remask}"`); + storeRemarkMap.set(sw.store_id, sw.store_remask || ''); + } + } catch (e) { dbg(`store_warehouse ERROR: ${e.message}`); } + } + + // ====== 合并输出 ====== + dbg('--- Merge output ---'); + const list = []; + for (const oid of orderIds) { + const order = orderMap.get(String(oid)) || {}; + const waybills = waybillMap.get(oid) || []; + dbg(` oid=${oid} orderKeys=[${Object.keys(order).join(',')}] waybills=${waybills.length}`); + if (waybills.length === 0) { + list.push({ + order_id: oid, waybill_id: 0, waybill_code: '', + logistics_code: '', logistics_name: '', logistics_interface_id: 0, logistics_interface_name: '', + platform_code: '', waybill_status: null, waybill_status_text: '', + is_back: 'N', is_intercept: 'N', is_galaxy_receive: 'N', + weighing_weight: 0, weighing_weight_display: '0 kg', + delivery_order_code: order.delivery_order_code || '', + source_order_codes: order.source_order_codes || '', + pay_no: order.pay_no || '', + store_id: order.store_id || 0, store_name: order.store_name || '', + store_remask: storeRemarkMap.get(order.store_id) || '', + status: order.status || '', name: order.name || '', mobile: order.mobile || '', + province: order.province || '', city: order.city || '', area: order.area || '', + detail_address: order.detail_address || '', + buyer_nick: order.buyer_nick || '', seller_nick: order.seller_nick || '', shop_nick: order.shop_nick || '', + total_amount: order.total_amount || 0, item_amount: order.item_amount || 0, freight: order.freight || 0, + items_count: order.items_count || 0, items_weight: order.items_weight || 0, + wave_no: order.wave_no || '', + delivery_time: order.delivery_time ? app.formatDate(order.delivery_time) : null, + create_at: order.create_at ? app.formatDate(order.create_at) : null, + }); + } else { + for (const wb of waybills) { + list.push({ + order_id: oid, waybill_id: wb.id, waybill_code: wb.waybill_code, + logistics_code: wb.logistics_code, logistics_name: wb.logistics_name, + logistics_interface_id: wb.logistics_interface_id, logistics_interface_name: wb.logistics_interface_name, + platform_code: wb.platform_code, + waybill_status: wb.status, waybill_status_text: wb.status_text, + is_back: wb.is_back, is_intercept: wb.is_intercept, is_galaxy_receive: wb.is_galaxy_receive, + weighing_weight: wb.weighing_weight, weighing_weight_display: wb.weighing_weight_display, + delivery_order_code: wb.delivery_order_code || order.delivery_order_code || '', + source_order_codes: wb.source_order_codes || order.source_order_codes || '', + pay_no: order.pay_no || '', + store_id: wb.store_id || order.store_id || 0, store_name: order.store_name || '', + store_remask: storeRemarkMap.get(wb.store_id || order.store_id) || '', + status: order.status || '', name: order.name || '', mobile: order.mobile || '', + province: order.province || '', city: order.city || '', area: order.area || '', + detail_address: order.detail_address || '', + buyer_nick: order.buyer_nick || '', seller_nick: order.seller_nick || '', shop_nick: order.shop_nick || '', + total_amount: order.total_amount || 0, item_amount: order.item_amount || 0, freight: order.freight || 0, + items_count: order.items_count || 0, items_weight: order.items_weight || 0, + wave_no: order.wave_no || '', + delivery_time: order.delivery_time ? app.formatDate(order.delivery_time) : null, + create_at: order.create_at ? app.formatDate(order.create_at) : null, + }); + } + } + } + + dbg(`list.length: ${list.length}`); + dbg('========== quickSearch END =========='); + return { list, keyword }; + } + + buildWaybillItem(er) { + return { + id: er.id, + waybill_code: er.waybill_code, + delivery_order_code: er.delivery_order_code || '', + source_order_codes: er.source_order_codes || '', + store_id: er.store_id || 0, + logistics_code: er.logistics_code || '', + logistics_name: er.logistics_name || '', + logistics_interface_id: er.logistics_interface_id || 0, + logistics_interface_name: er.logistics_interface_name || '', + platform_code: er.platform_code || '', + status: er.status, + status_text: er.status === 1 ? '已分配' : '未分配', + is_back: er.is_back || 'N', + is_intercept: er.is_intercept || 'N', + is_galaxy_receive: er.is_galaxy_receive || 'N', + weighing_weight: er.weighing_weight || 0, + weighing_weight_display: er.weighing_weight > 0 + ? `${(er.weighing_weight / 1000).toFixed(2)} kg` : '0 kg', + }; + } + + /** + * 按订单 ID 列表批量查询订单关键字段(遍历 dispatch → current → history)。 + * @param {number[]} orderIds 订单ID列表 + * @param {number} warehouseId 仓库ID + * @return {Promise>} orderId → 订单行 + */ + async fetchOrderMapByIds(orderIds, warehouseId) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const orderDeliveryFactory = ctx.model && ctx.model.OrderDeliveryFactory; + + if (!orderDeliveryFactory || typeof orderDeliveryFactory.getDispatchModel !== 'function') { + return []; + } + + const tableOrders = [ + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'history', getModel: () => orderDeliveryFactory.getHistoryModel(warehouseId) }, + ]; + + const resultMap = new Map(); + const remainingIds = new Set(orderIds.map(id => String(id))); + + for (const entry of tableOrders) { + if (remainingIds.size === 0) break; + try { + const model = await entry.getModel(); + if (!model || typeof model.findAll !== 'function') continue; + + const rows = await model.findAll({ + attributes: [ + 'id', 'delivery_order_code', 'source_order_codes', 'pay_no', + 'store_id', 'status', + 'name', 'mobile', 'province', 'city', 'area', 'detail_address', + 'buyer_nick', 'seller_nick', 'shop_nick', + 'total_amount', 'item_amount', 'freight', + 'items_count', 'items_weight', + 'wave_no', 'delivery_time', 'create_at', + ], + where: { + id: { [Op.in]: [ ...remainingIds ].map(Number) }, + }, + raw: true, + }); + + for (const r of rows) { + const rid = String(r.id); + if (!resultMap.has(rid)) { + resultMap.set(rid, r); + remainingIds.delete(rid); + } + } + } catch (_err) { + continue; + } + } + + return resultMap; + } + } module.exports = DeliveryOrderService; diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index 6f6bb79..1c155f4 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -4105,6 +4105,32 @@ class PendingOrderService extends OrderBaseService { }, }); + // 同步更新运单表拦截标记 + try { + await ctx.model.OrderExpress.update( + { is_intercept: 'Y' }, + { where: { order_id: { [Op.in]: chunkOrderIds }, warehouse_id: warehouseId } } + ); + } catch (expressErr) { + ctx.logger.warn( + `[order.pendingOrder.batchIntercept] 更新运单拦截标记失败, count=${chunkOrderIds.length}, error=${expressErr.message}` + ); + } + + // 创建售后工单 + 通知快递群(失败不影响主流程) + try { + const op = this.getOrderLogOperator(); + await ctx.service.systems.afterSale.createInterceptWorkOrdersAndNotify({ + orderIds: chunkOrderIds, + warehouseId, + creatorLabel: op.name || '系统', + }); + } catch (workOrderErr) { + ctx.logger.warn( + `[order.pendingOrder.batchIntercept] 创建工单/通知失败, count=${chunkOrderIds.length}, error=${workOrderErr.message}` + ); + } + // 写入操作日志 const logPayloads = chunkRows.map(row => { const orderId = Number(row.id || 0); @@ -5635,6 +5661,18 @@ class PendingOrderService extends OrderBaseService { }, }); + // 同步清除运单表拦截+退回标记 + try { + await ctx.model.OrderExpress.update( + { is_intercept: 'N', is_back: 'N' }, + { where: { order_id: { [Op.in]: chunkOrderIds }, warehouse_id: warehouseId } } + ); + } catch (expressErr) { + ctx.logger.warn( + `[order.pendingOrder.batchUnintercept] 清除运单标记失败, count=${chunkOrderIds.length}, error=${expressErr.message}` + ); + } + // 写入操作日志 ORDER_INTERCEPT_CANCEL const logPayloads = chunkRows.map(row => { const orderId = Number(row.id || 0); diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index 5790498..1320033 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -10,9 +10,9 @@ class RecheckOrderService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck,batchQuickRecheckByWave,queryRecheckOrderSingleList'; - const _noNeedLog = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck,batchQuickRecheckByWave'; - const _noNeedAuth = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck,batchQuickRecheckByWave,queryRecheckOrderSingleList'; + const _noNeedRight = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck,batchQuickRecheckByWave,queryRecheckOrderSingleList,interceptScan'; + const _noNeedLog = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck,batchQuickRecheckByWave,interceptScan'; + const _noNeedAuth = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck,batchQuickRecheckByWave,queryRecheckOrderSingleList,interceptScan'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -3611,6 +3611,18 @@ class RecheckOrderService extends OrderBaseService { throw new Error('拦截状态更新失败,请稍后重试'); } + // 同步更新运单表:仅对已标记拦截的运单设置退回标记 + try { + await ctx.model.OrderExpress.update( + { is_back: 'Y' }, + { where: { order_id: orderId, warehouse_id: warehouseId, is_intercept: 'Y' } } + ); + } catch (expressErr) { + ctx.logger.warn( + `[recheckOrder.confirmIntercept] 更新运单退回标记失败, orderId=${orderId}, error=${expressErr.message}` + ); + } + // 拦截成功后释放储位分配(归还库存) try { await this.service.systems.orderStorageAllocation.cancelAllocateStorage({ @@ -3634,6 +3646,20 @@ class RecheckOrderService extends OrderBaseService { ); } + // 创建售后工单 + 通知快递群(失败不影响主流程) + try { + const operator = this.getOrderLogOperator(); + await this.service.systems.afterSale.createInterceptWorkOrdersAndNotify({ + orderIds: [ orderId ], + warehouseId, + creatorLabel: operator.name || '系统', + }); + } catch (workOrderErr) { + ctx.logger.warn( + `[recheckOrder.confirmIntercept] 创建工单/通知失败, orderId=${orderId}, error=${workOrderErr.message}` + ); + } + const orderNo = String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(); // 写入操作日志(失败不影响主流程) @@ -3668,6 +3694,182 @@ class RecheckOrderService extends OrderBaseService { }; } + /** + * 拦截扫描:通过运单号查找运单记录,标记退回并处理关联工单与订单拦截状态。 + * + * 处理流程: + * 1. 根据运单号查询 wms_order_express,找到则将 is_back 设为 'Y';未找到则创建新记录补充缺失快递 + * 2. 检查是否存在关联的未完结售后工单(wms_after_sale),若有则调用 handleWorkOrder 写入 + * "库内拦截成功"步骤并将工单置为 completed + * 3. 同步更新 wms_order_delivery 的 intercept_status 为 intercepted_at_warehouse, + * 并释放储位分配与订单锁(与 confirmIntercept 行为一致,订单级拦截覆盖所有面单含子面单) + * + * @param {Object} data 请求体。 + * @param {string} data.waybill_code 运单号。 + * @return {Promise} 拦截扫描结果,包含 waybill_code、is_back、after_sale(若有)、order。 + */ + async interceptScan(data = {}) { + const { ctx, service } = this; + const { waybill_code: waybillCode } = data || {}; + + if (!waybillCode || !String(waybillCode).trim()) { + throw new Error('运单号不能为空'); + } + + const normalizedWaybillCode = String(waybillCode).trim(); + const warehouseId = this.getWarehouseId(); + const now = new Date(); + + // 1. 查询运单记录 + let expressRecord = await ctx.model.OrderExpress.findOne({ + where: { waybill_code: normalizedWaybillCode, warehouse_id: warehouseId }, + raw: true, + }); + + // 1a. 缺失快递补充:运单记录不存在则创建新记录 + if (!expressRecord) { + const created = await ctx.model.OrderExpress.create({ + waybill_code: normalizedWaybillCode, + order_id: null, + warehouse_id: warehouseId, + is_back: 'Y', + is_intercept: 'Y', + create_at: now, + }); + + expressRecord = (created && created.toJSON ? created.toJSON() : created) || {}; + } else { + // 2. 标记退回 + await ctx.model.OrderExpress.update( + { is_back: 'Y', is_intercept: 'Y' }, + { where: { id: expressRecord.id } } + ); + } + + // 3. 检查关联的未完结售后工单 + const afterSale = await ctx.model.AfterSale.findOne({ + where: { + waybill_no: normalizedWaybillCode, + warehouse_id: warehouseId, + deleted_at: null, + status: { [ctx.app.Sequelize.Op.notIn]: [ 'completed', 'closed', 'cancelled' ] }, + }, + order: [[ 'id', 'DESC' ]], + raw: true, + }); + + let afterSaleResult = null; + if (afterSale) { + const operator = this.getOrderLogOperator(); + const operatorId = operator.id ? Number(operator.id) : 0; + const operatorSnapshot = JSON.stringify({ + id: String(operator.id || ''), + name: String(operator.name || ''), + }); + + try { + afterSaleResult = await service.systems.afterSale.handleWorkOrder({ + id: afterSale.id, + remark: '库内拦截成功', + targetStatus: 'completed', + resolution: '库内拦截成功', + attachmentIds: [], + operatorId, + operatorSnapshot, + warehouseId, + }); + } catch (workOrderErr) { + ctx.logger.warn( + `[recheckOrder.interceptScan] 处理工单失败, afterSaleId=${afterSale.id}, waybill=${normalizedWaybillCode}, error=${workOrderErr.message}` + ); + // 工单处理失败不阻断主流程 + } + } + + // 4. 更新订单拦截状态(与 confirmIntercept 一致:订单级拦截,覆盖所有面单含子面单) + const orderId = Number(expressRecord.order_id || 0); + let orderResult = null; + if (orderId > 0) { + const orderModel = await this.getOrderModelByTableType('current', warehouseId); + const orderWhere = this.buildOrderWhere([ orderId ], warehouseId); + const order = await orderModel.findOne({ + where: orderWhere, + attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code', 'intercept_status' ], + raw: true, + }); + + if (order) { + await orderModel.update( + { intercept_status: 'intercepted_at_warehouse', updated_at: now }, + { where: orderWhere } + ); + + // 释放储位分配 + try { + await service.systems.orderStorageAllocation.cancelAllocateStorage({ + order_ids: [ orderId ], + }); + } catch (allocErr) { + ctx.logger.warn( + `[recheckOrder.interceptScan] 释放储位分配失败, orderId=${orderId}, error=${allocErr.message}` + ); + } + + // 释放订单锁 + try { + await orderModel.update( + { lock_status: 'none', updated_at: now }, + { where: orderWhere } + ); + } catch (lockErr) { + ctx.logger.warn( + `[recheckOrder.interceptScan] 释放锁失败, orderId=${orderId}, error=${lockErr.message}` + ); + } + + const orderNo = String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(); + + // 写入操作日志 + try { + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'order', + businessId: logWarehouseId, + operationCode: 'ORDER_INTERCEPT_CONFIRM', + operator, + extras: { + warehouseId: logWarehouseId, + orderId, + orderNo, + previousInterceptStatus: String(order.intercept_status || '').trim(), + newInterceptStatus: 'intercepted_at_warehouse', + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn( + `[recheckOrder.interceptScan] 写入操作日志失败, orderId=${orderId}, error=${logErr.message}` + ); + } + + orderResult = { + order_id: orderId, + order_no: orderNo, + intercept_status: 'intercepted_at_warehouse', + }; + } + } + + return { + waybill_code: normalizedWaybillCode, + is_back: 'Y', + is_intercept: 'Y', + after_sale: afterSaleResult ? afterSaleResult.after_sale : null, + order: orderResult, + }; + } + /** * 批量快捷复核:对一批订单 IDs 依次执行前置条件检查与复核流程。 * 支持部分失败:不满足前置条件的订单直接跳过并记录失败原因,其余订单继续走完拣货完成 + 复核标记流程。 diff --git a/app/service/systemMethods/pickCart.js b/app/service/systemMethods/pickCart.js index 64479c6..4de4881 100644 --- a/app/service/systemMethods/pickCart.js +++ b/app/service/systemMethods/pickCart.js @@ -11,9 +11,9 @@ class PickCartService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'scan,bindTaskCart,create,update,delete,detail,list,codeDuplicateCheck'; + const _noNeedRight = 'scan,bindTaskCart,create,update,delete,batchDelete,detail,list,codeDuplicateCheck'; const _noNeedLog = ''; - const _noNeedAuth = 'scan,bindTaskCart,create,update,delete,detail,list,codeDuplicateCheck'; + const _noNeedAuth = 'scan,bindTaskCart,create,update,delete,batchDelete,detail,list,codeDuplicateCheck'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -208,6 +208,41 @@ class PickCartService extends MainService { } } + /** + * 批量删除拣货车。已绑定任务的将被跳过。 + * + * @param {Object} data 请求参数。 + * @param {Array} data.ids 拣货车ID列表。 + * @return {Promise} 统一 success/fail 包装结果。 + */ + async batchDelete(data = {}) { + const { service, ctx } = this; + const ids = Array.isArray(data && data.ids) ? data.ids : []; + + if (ids.length === 0) { + return this.fail('ids 必填且必须为非空数组', {}, 400); + } + + try { + const result = await service.systems.pickCart.batchDelete({ ids }); + return this.success('ok', { + data: result, + code: 200, + }); + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + const errorData = error && error.data && typeof error.data === 'object' && !Array.isArray(error.data) + ? error.data + : {}; + return this.fail(error.message || '批量删除失败', errorData, code); + } + + ctx.logger.error('[PickCartService.batchDelete] 批量删除拣货车失败: %s', error && error.message ? error.message : error); + return this.fail('批量删除失败', {}, 500); + } + } + /** * 查询拣货车详情。 * diff --git a/app/service/systemMethods/storage/receiving.js b/app/service/systemMethods/storage/receiving.js index ef2cc25..db61b3f 100644 --- a/app/service/systemMethods/storage/receiving.js +++ b/app/service/systemMethods/storage/receiving.js @@ -14,7 +14,7 @@ class configService extends MainService { super(ctx); const _noNeedLogin = ''; const _noNeedRight = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail,export,exportTaskProgress,storeExport,storeExportTaskProgress'; - const _noNeedLog = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,bindStore,bindDetailProduct,queryReceivingLogs,scanDetail,export,exportTaskProgress,storeExport,storeExportTaskProgress'; + const _noNeedLog = ''; const _noNeedAuth = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail,export,exportTaskProgress,storeExport,storeExportTaskProgress'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } diff --git a/app/service/systemMethods/storage/transaction.js b/app/service/systemMethods/storage/transaction.js index 8a031e5..48a6167 100644 --- a/app/service/systemMethods/storage/transaction.js +++ b/app/service/systemMethods/storage/transaction.js @@ -23,9 +23,9 @@ class StorageTransactionService extends MainService { */ async list(data = {}) { const { service } = this; - const { pagination, sort, group_by_batch } = data; + const { pagination, sort, group_by_batch, keyword } = data; this.prepareWhereContext(data); - const result = await service.systems.stockTransaction.list(pagination, sort, group_by_batch); + const result = await service.systems.stockTransaction.list(pagination, sort, group_by_batch, keyword); return this.success('ok', result); } } diff --git a/app/service/systems/afterSale.js b/app/service/systems/afterSale.js index b62a4fc..ceedfb6 100644 --- a/app/service/systems/afterSale.js +++ b/app/service/systems/afterSale.js @@ -33,9 +33,12 @@ class AfterSaleService extends Service { * @param {Object} [sort] 排序参数 * @param {string} [sort.sortField] 排序字段 * @param {string} [sort.sortOrder] 排序顺序(asc/desc) + * @param {Object} [opts] 额外选项 + * @param {Array} [opts.order] 自定义 Sequelize order(优先于 sort) + * @param {boolean} [opts.excludeFutureFollowup] 是否排除 followup_at 未到的 pending_feedback 工单 * @return {Promise} { list: Array, pagination: Object } */ - async list(where = {}, pagination = {}, sort = {}) { + async list(where = {}, pagination = {}, sort = {}, opts = {}) { const { ctx, app } = this; const { Op } = app.Sequelize; @@ -45,8 +48,32 @@ class AfterSaleService extends Service { // 构建 Sequelize where 条件 const queryWhere = this._buildListWhere(where, Op); - // 排序 - const order = this._buildListOrder(sort); + // 工作列表特殊逻辑:pending_feedback 状态的工单,若 followup_at 未到,暂不显示 + if (opts.excludeFutureFollowup) { + const pendingFeedbackWhere = { + [Op.or]: [ + { status: { [Op.ne]: 'pending_feedback' } }, + { + status: 'pending_feedback', + [Op.or]: [ + { followup_at: null }, + { followup_at: { [Op.lte]: app.Sequelize.literal('NOW()') } }, + ], + }, + ], + }; + // 合并到现有 where 中(AND 关系) + if (queryWhere[Op.and]) { + queryWhere[Op.and].push(pendingFeedbackWhere); + } else { + queryWhere[Op.and] = [ pendingFeedbackWhere ]; + } + } + + // 排序:opts.order 优先于 sort + const order = Array.isArray(opts.order) && opts.order.length > 0 + ? opts.order + : this._buildListOrder(sort); const { count, rows } = await ctx.model.AfterSale.findAndCountAll({ where: queryWhere, @@ -58,8 +85,10 @@ class AfterSaleService extends Service { const totalPages = Math.ceil(count / pageSize); + const list = rows.map(row => this._formatAfterSaleRow(row, app)); + return { - list: rows, + list, pagination: { page, pageSize, @@ -71,6 +100,49 @@ class AfterSaleService extends Service { }; } + /** + * 快速统计符合条件的售后单数量(用于角标显示,不做分页)。 + * 与 list() 共享相同的 where 构建逻辑,但只返回 count。 + * + * @param {Object} where 标准化 where 条件对象 + * @param {Object} [opts] 额外选项 + * @param {boolean} [opts.excludeFutureFollowup] 是否排除 followup_at 未到的 pending_feedback 工单 + * @return {Promise} { count: number } + */ + async countPending(where = {}, opts = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const queryWhere = this._buildListWhere(where, Op); + + // 工作列表特殊逻辑:pending_feedback 状态的工单,若 followup_at 未到,暂不计数 + if (opts.excludeFutureFollowup) { + const pendingFeedbackWhere = { + [Op.or]: [ + { status: { [Op.ne]: 'pending_feedback' } }, + { + status: 'pending_feedback', + [Op.or]: [ + { followup_at: null }, + { followup_at: { [Op.lte]: app.Sequelize.literal('NOW()') } }, + ], + }, + ], + }; + if (queryWhere[Op.and]) { + queryWhere[Op.and].push(pendingFeedbackWhere); + } else { + queryWhere[Op.and] = [ pendingFeedbackWhere ]; + } + } + + const count = await ctx.model.AfterSale.count({ + where: queryWhere, + }); + + return { count }; + } + /** * 根据标准化 where 条件构建 Sequelize 查询条件。 * @@ -189,7 +261,7 @@ class AfterSaleService extends Service { * @return {Array>} Sequelize order 数组 */ _buildListOrder(sort = {}) { - const sortField = sort.sortField || sort.sort_field || 'created_at'; + const sortField = sort.sortField || sort.sort_field || 'updated_at'; const sortOrderRaw = (sort.sortOrder || sort.sort_order || 'desc').toLowerCase(); const sortOrder = sortOrderRaw === 'asc' ? 'ASC' : 'DESC'; @@ -204,20 +276,21 @@ class AfterSaleService extends Service { return [[ safeSortField, sortOrder ]]; } - // =========================== // 明细查询 // =========================== /** * 售后单明细查询,包含主表信息、步骤列表及附件。 + * 若关联了订单(order_delivery_id),自动补充收件人/发件人/订单明细/打包视频。 + * 若关联了货主(store_id),自动补充货主合约备注。 * * @param {number} id 售后单主键ID - * @return {Promise} 售后单明细,包含主表、步骤列表(含附件) + * @return {Promise} 售后单明细,包含主表、步骤列表(含附件)、关联单据详情 * @throws {Error} 售后单不存在时抛出 */ async getDetail(id) { - const { ctx } = this; + const { ctx, app } = this; // 查询主表 const afterSale = await ctx.model.AfterSale.findOne({ @@ -239,9 +312,373 @@ class AfterSaleService extends Service { // 查询步骤附件 const stepsWithAttachments = await this._enrichStepsWithAttachments(steps); + // 格式化时间字段 + const formatRow = row => this._formatAfterSaleRow(row, app); + + // 补充关联单据详情 + const related = await this._enrichAfterSaleDetail(afterSale); + + // 开始处理时间:取首条步骤记录的创建时间 + const firstStep = stepsWithAttachments[0]; + const startedAt = firstStep ? (firstStep.created_at ? app.formatDate(firstStep.created_at) : null) : null; + return { - after_sale: afterSale, - steps: stepsWithAttachments, + after_sale: { ...formatRow(afterSale), started_at: startedAt }, + steps: stepsWithAttachments.map(formatRow), + related, + }; + } + + /** + * 根据售后单关联的业务单据ID,补充关联详情。 + * 包括:订单信息(收件人/发件人/明细/打包视频)、货主合约备注。 + * + * @param {Object} afterSale 售后主表记录 + * @return {Promise} 关联详情对象 + */ + async _enrichAfterSaleDetail(afterSale) { + const { ctx } = this; + const related = {}; + + // ======= 1. 关联订单详情 ======= + if (afterSale.order_delivery_id) { + try { + related.order = await this._resolveOrderDetail( + afterSale.order_delivery_id, + afterSale.warehouse_id + ); + } catch (err) { + ctx.logger.warn(`[_enrichAfterSaleDetail] 解析订单详情失败 id=${afterSale.order_delivery_id}: ${err.message}`); + } + } + + // ======= 2. 关联运单详情(快递公司 + 接口) ======= + if (afterSale.waybill_id) { + try { + related.waybill = await this._resolveWaybillDetail(afterSale.waybill_id); + } catch (err) { + ctx.logger.warn(`[_enrichAfterSaleDetail] 解析运单详情失败 id=${afterSale.waybill_id}: ${err.message}`); + } + } + + // ======= 3. 货主合约备注 ======= + if (afterSale.store_id && afterSale.warehouse_id) { + try { + related.store_contract = await this._resolveStoreContractNote( + afterSale.store_id, + afterSale.warehouse_id + ); + } catch (err) { + ctx.logger.warn(`[_enrichAfterSaleDetail] 解析货主合约备注失败 store_id=${afterSale.store_id}: ${err.message}`); + } + } + + return related; + } + + /** + * 解析关联订单的详细信息:收件人、发件人、订单明细、打包视频。 + * + * @param {number} orderDeliveryId 发货订单ID + * @param {number} warehouseId 仓库ID + * @return {Promise} 订单详情,查询失败返回 null + */ + async _resolveOrderDetail(orderDeliveryId, warehouseId) { + const { ctx, app } = this; + + try { + // 1. 查询订单主记录(优先主表,再尝试工厂分表) + let order = null; + try { + order = await ctx.model.OrderDelivery.findOne({ + where: { id: orderDeliveryId }, + raw: true, + }); + } catch (err) { + ctx.logger.warn(`[_resolveOrderDetail] 主表查询失败: ${err.message}`); + } + + if (!order && ctx.model.OrderDeliveryFactory) { + try { + const factoryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + if (factoryModel) { + order = await factoryModel.findOne({ + where: { id: orderDeliveryId }, + raw: true, + }); + } + } catch (err) { + ctx.logger.warn(`[_resolveOrderDetail] 工厂模型查询失败: ${err.message}`); + } + } + + if (!order) { + ctx.logger.info(`[_resolveOrderDetail] 未找到订单 id=${orderDeliveryId} warehouseId=${warehouseId}`); + return null; + } + + ctx.logger.info(`[_resolveOrderDetail] 找到订单 id=${orderDeliveryId} code=${order.delivery_order_code} status=${order.status}`); + + // 2. 构建收件人信息 + const recipient = { + name: order.name || '', + tel: order.tel || '', + mobile: order.mobile || '', + email: order.email || '', + zip_code: order.zip_code || '', + country: order.country_code || '', + province: order.province || '', + city: order.city || '', + district: order.district || '', + town: order.town || '', + address: order.detail_address || '', + }; + + // 3. 构建发件人信息(从货主 subject_config 中取) + let sender = null; + if (order.store_id) { + try { + const store = await ctx.model.Store.findOne({ + where: { id: order.store_id }, + attributes: [ 'id', 'subject_config', 'name' ], + raw: true, + }); + if (store) { + let subjectConfig = store.subject_config; + if (typeof subjectConfig === 'string') { + try { subjectConfig = JSON.parse(subjectConfig); } catch { subjectConfig = {}; } + } + sender = { + name: (subjectConfig && subjectConfig.sender_name) || store.name || '', + tel: (subjectConfig && subjectConfig.sender_tel) || '', + province: (subjectConfig && subjectConfig.province_name) || '', + city: (subjectConfig && subjectConfig.city_name) || '', + district: (subjectConfig && subjectConfig.district_name) || '', + town: (subjectConfig && subjectConfig.town_name) || '', + address: (subjectConfig && subjectConfig.address) || '', + }; + } + } catch (err) { + ctx.logger.warn(`[_resolveOrderDetail] 查询发件人信息失败: ${err.message}`); + } + } + + // 4. 订单明细(优先 order.items JSON,为空时回退到分表查询) + let orderItems = []; + if (order.items) { + try { + const parsed = typeof order.items === 'string' ? JSON.parse(order.items) : order.items; + orderItems = Array.isArray(parsed) ? parsed : []; + } catch { + // items 解析失败,忽略 + } + } + + // 回退:若 items 为空且 OrderItemsFactory 可用,从分表查询 + if (orderItems.length === 0 && ctx.model.OrderItemsFactory) { + try { + const itemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); + if (itemsModel) { + const dbItems = await itemsModel.findAll({ + where: { order_id: orderDeliveryId }, + raw: true, + }); + if (dbItems && dbItems.length > 0) { + // 收集 stock_id 用于批量查库存详情 + const stockIds = dbItems + .map(item => Number(item.stock_id)) + .filter(id => Number.isInteger(id) && id > 0); + + // 批量获取库存详情(带缓存的并行查询:条码 + 图片 + 库存属性) + let stockDetailsMap = new Map(); + if (stockIds.length > 0) { + try { + const details = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { + warehouseId, + cacheTTL: 300, + }); + for (const detail of details) { + stockDetailsMap.set(detail.id, detail); + } + } catch (err) { + ctx.logger.warn(`[_resolveOrderDetail] 批量获取库存详情失败: ${err.message}`); + } + } + + orderItems = dbItems.map(item => { + const stock = stockDetailsMap.get(Number(item.stock_id)) || {}; + return { + id: item.id, + order_line_no: item.order_line_no || '', + item_code: item.item_code || stock.item_code || '', + item_name: item.item_name || stock.item_name || '', + sku_property: stock.sku_property || '', + quantity: stock.quantity || 0, + locked_quantity: stock.locked_quantity || 0, + is_batch_mgmt: stock.is_batch_mgmt || 'N', + is_shelf_life_mgmt: stock.is_shelf_life_mgmt || 'N', + is_images: stock.is_images || 'N', + store_id: stock.store_id || null, + packing_requirements: stock.packing_requirements || '', + stock_unit: stock.stock_unit || '', + image_url: stock.image_url || [], + barcodes: stock.barcodes || [], + plan_qty: item.plan_qty || 0, + stock_id: item.stock_id || null, + order_item_id: item.id, + order_id: orderDeliveryId, + }; + }); + ctx.logger.info(`[_resolveOrderDetail] 从分表加载 ${orderItems.length} 条明细(含库存详情)`); + } + } + } catch (err) { + ctx.logger.warn(`[_resolveOrderDetail] 分表查询商品明细失败: ${err.message}`); + } + } + + // 5. 打包视频 + let packVideos = []; + try { + const packTasks = await ctx.model.PackTask.findAll({ + where: { order_id: orderDeliveryId, deleted_at: null }, + include: [ + { + model: ctx.model.PackTaskVideo, + as: 'videos', + where: { deleted_at: null }, + required: false, + }, + ], + order: [[ 'create_time', 'DESC' ]], + raw: false, + }); + + for (const task of packTasks) { + const taskJson = task.toJSON ? task.toJSON() : task; + const videos = (taskJson.videos || []).map(v => ({ + id: v.id, + video_url: v.video_url, + camera_id: v.camera_id, + status: v.status, + created_at: v.created_at ? app.formatDate(v.created_at) : null, + })); + packVideos.push({ + pack_task_id: taskJson.id, + status: taskJson.status, + pack_quantity: taskJson.pack_quantity, + start_time: taskJson.start_time ? app.formatDate(taskJson.start_time) : null, + end_time: taskJson.end_time ? app.formatDate(taskJson.end_time) : null, + operator_text: taskJson.operator_text || '', + videos, + }); + } + } catch (err) { + ctx.logger.warn(`[_resolveOrderDetail] 查询打包视频失败: ${err.message}`); + } + + // 6. 组装返回 + return { + id: order.id, + delivery_order_code: order.delivery_order_code || '', + warehouse_id: order.warehouse_id, + store_id: order.store_id, + // 重量(g) + items_weight: order.items_weight || 0, + // 波次 + wave_id: order.wave_id || 0, + wave_no: order.wave_no || '', + // 来源 + platform_name: order.source_platform_name || '', + source_order_codes: order.source_order_codes || '', + // 创建来源渠道 + create_channel: order.create_channel || '', + create_channel_label: this._getCreateChannelLabel(order.create_channel), + // 状态机 + sync_status: order.sync_status || 'padding', + inspection_status: order.inspection_status || 'none', + storage_status: order.storage_status || 'none', + post_status: order.post_status || 'none', + print_status: order.print_status || 'none', + pick_status: order.pick_status || 'none', + pack_status: order.pack_status || 'none', + intercept_status: order.intercept_status || 'none', + // 数量 + items_count: order.items_count, + items_total: order.items_total, + // 收件人 / 发件人 / 明细 / 打包视频 + recipient, + sender, + items: orderItems, + pack_videos: packVideos, + }; + } catch (err) { + ctx.logger.warn(`[_resolveOrderDetail] 整体异常 id=${orderDeliveryId}: ${err.message}`, err.stack); + return null; + } + } + + /** + * 解析货主在当前仓库下的合约备注。 + * + * @param {number} storeId 货主ID + * @param {number} warehouseId 仓库ID + * @return {Promise} 合约备注信息 + */ + async _resolveStoreContractNote(storeId, warehouseId) { + const { ctx } = this; + + const sw = await ctx.model.StoreWarehouse.findOne({ + where: { store_id: storeId, warehouse_id: warehouseId }, + attributes: [ 'id', 'store_remask', 'warehouse_remask', 'store_use_status', 'warehouse_use_status' ], + raw: true, + }); + + if (!sw) return null; + + return { + contract_id: sw.id, + store_remask: sw.store_remask || '', + warehouse_remask: sw.warehouse_remask || '', + store_use_status: sw.store_use_status, + warehouse_use_status: sw.warehouse_use_status, + }; + } + + /** + * 解析关联运单的快递公司名称与使用的物流接口。 + * + * @param {number} waybillId 运单ID(wms_order_express.id) + * @return {Promise} 运单详情,查询失败返回 null + */ + async _resolveWaybillDetail(waybillId) { + const { ctx } = this; + + const waybill = await ctx.model.OrderExpress.findOne({ + where: { id: waybillId }, + attributes: [ + 'id', 'waybill_code', 'order_id', 'logistics_code', + 'logistics_name', 'logistics_interface_id', 'logistics_interface_name', + 'status', 'is_back', 'is_intercept', 'warehouse_id', 'create_at', + ], + raw: true, + }); + + if (!waybill) return null; + + return { + id: waybill.id, + waybill_code: waybill.waybill_code || '', + order_id: waybill.order_id, + logistics_code: waybill.logistics_code || '', + logistics_name: waybill.logistics_name || '', + logistics_interface_id: waybill.logistics_interface_id, + logistics_interface_name: waybill.logistics_interface_name || '', + status: waybill.status, + is_back: waybill.is_back || 'N', + is_intercept: waybill.is_intercept || 'N', + warehouse_id: waybill.warehouse_id, + create_at: waybill.create_at ? ctx.app.formatDate(waybill.create_at) : null, }; } @@ -334,9 +771,10 @@ class AfterSaleService extends Service { * @return {Promise} 创建的售后单记录 */ async create(data, transaction = null) { - const { ctx } = this; + const { ctx, app } = this; const record = await ctx.model.AfterSale.create(data, { transaction }); - return record && record.toJSON ? record.toJSON() : record; + const json = record && record.toJSON ? record.toJSON() : record; + return this._formatAfterSaleRow(json, app); } // =========================== @@ -353,7 +791,7 @@ class AfterSaleService extends Service { * @throws {Error} 售后单不存在时抛出 */ async update(id, data, transaction = null) { - const { ctx } = this; + const { ctx, app } = this; const record = await ctx.model.AfterSale.findOne({ where: { id, deleted_at: null }, @@ -365,7 +803,27 @@ class AfterSaleService extends Service { } await record.update(data, { transaction }); - return record && record.toJSON ? record.toJSON() : record; + const json = record && record.toJSON ? record.toJSON() : record; + return this._formatAfterSaleRow(json, app); + } + + /** + * 格式化售后单记录的时间字段。 + * @param {Object} row 原始数据库行 + * @param {Object} app Egg app 实例 + * @return {Object} 格式化后的行 + */ + _formatAfterSaleRow(row, app) { + if (!row) return row; + return { + ...row, + created_at: row.created_at ? app.formatDate(row.created_at) : null, + updated_at: row.updated_at ? app.formatDate(row.updated_at) : null, + resolved_at: row.resolved_at ? app.formatDate(row.resolved_at) : null, + followup_at: row.followup_at ? app.formatDate(row.followup_at) : null, + started_at: row.started_at ? app.formatDate(row.started_at) : null, + completed_at: row.completed_at ? app.formatDate(row.completed_at) : null, + }; } // =========================== @@ -393,7 +851,7 @@ class AfterSaleService extends Service { const record = await ctx.model.AfterSaleDetail.create({ after_sale_id: afterSaleId, - step_status: stepData.step_status !== undefined ? stepData.step_status : 2, + step_status: stepData.step_status !== undefined ? stepData.step_status : 'processing', operator_id: stepData.operator_id || null, operator_snapshot: stepData.operator_snapshot || null, action: stepData.action || null, @@ -492,9 +950,9 @@ class AfterSaleService extends Service { updated_at: new Date(), }, transaction); - // 写入步骤记录 + // 写入步骤记录(step_status 与主表当前 status 一致) await this.addStep(id, { - step_status: 2, + step_status: updated.status || 'processing', operator_id: operatorId, operator_snapshot: operatorSnapshot, action: '转单', @@ -520,7 +978,6 @@ class AfterSaleService extends Service { * * @param {Object} params 处理参数 * @param {number} params.id 售后单主键ID - * @param {string} params.action 操作动作描述 * @param {string|null} params.remark 处理备注 * @param {string|null} params.targetStatus 目标售后状态 * @param {string|null} params.resolution 完结处理结果 @@ -533,7 +990,7 @@ class AfterSaleService extends Service { */ async handleWorkOrder(params = {}) { const { - id, action, remark, targetStatus, resolution, + id, remark, targetStatus, resolution, attachmentIds, operatorId, operatorSnapshot, warehouseId, } = params; @@ -549,7 +1006,11 @@ class AfterSaleService extends Service { throw new Error('售后单不存在'); } - // 2. 校验 role_group 权限:操作人必须有对应 role_group 的处理权限。 + // 2. status 不填或填错默认 processing;pending 是创建默认值,不适用于处理操作 + const ALLOWED_STATUSES = Object.keys(ctx.model.AfterSale.AFTER_SALE_STATUS).filter(s => s !== 'pending'); + const safeStatus = (targetStatus && ALLOWED_STATUSES.includes(targetStatus)) ? targetStatus : 'processing'; + + // 3. 校验 role_group 权限:操作人必须有对应 role_group 的处理权限。 // 实际权限解析已在方法层(systemMethods/afterSale.js)通过 block 权限完成, // 此处仅做兜底校验。 const allowedRoleGroups = [ 'customer_service', 'warehouse', 'finance' ]; @@ -559,43 +1020,53 @@ class AfterSaleService extends Service { throw new Error('无权限处理当前角色组的售后单'); } - // 3. 开启事务 + // 4. 开启事务 const transaction = await ctx.model.transaction(); try { const now = new Date(); - // 4. 写入步骤记录 + // 5. 写入步骤记录(action 由服务端固定为"处理工单",step_status 同步主表 status) const step = await this.addStep(id, { - step_status: 2, + step_status: safeStatus, operator_id: operatorId, operator_snapshot: operatorSnapshot, - action, + action: '处理工单', remark, started_at: now, completed_at: now, }, transaction); - // 5. 绑定附件 + // 6. 绑定附件 if (Array.isArray(attachmentIds) && attachmentIds.length > 0) { await this.bindAttachments(step.id, attachmentIds, transaction); } - // 6. 更新售后单状态 + // 7. 更新售后单状态 const updateFields = { updated_at: now }; - if (targetStatus) { - updateFields.status = targetStatus; + updateFields.status = safeStatus; - // 若完结,写入 resolution 和 resolved_at - if (targetStatus === 'completed') { - updateFields.resolution = resolution || null; - updateFields.resolved_at = now; - } + // 若完结,写入 resolution 和 resolved_at;清除 followup_at + if (safeStatus === 'completed') { + updateFields.resolution = resolution || null; + updateFields.resolved_at = now; + updateFields.followup_at = null; } - // 7. 若当前角色非客服组且状态非完结,自动回设为客服组 - if (currentRoleGroup && currentRoleGroup !== 'customer_service' && targetStatus !== 'completed') { + // 若设为 pending_feedback:按仓库配置自动计算下次跟进时间 + if (safeStatus === 'pending_feedback') { + const hours = await this._resolveFollowupHours(afterSale.warehouse_id, afterSale.type, afterSale.sub_type); + ctx.logger.info( + `[handleWorkOrder] id=%s warehouse=%s type=%s subType=%s hours=%d`, + id, afterSale.warehouse_id, afterSale.type, afterSale.sub_type, hours + ); + // 使用数据库 NOW() 确保与查询条件时区一致 + updateFields.followup_at = ctx.app.Sequelize.literal(`DATE_ADD(NOW(), INTERVAL ${hours} HOUR)`); + } + + // 8. 若当前角色非客服组且状态非完结,自动回设为客服组 + if (currentRoleGroup && currentRoleGroup !== 'customer_service' && safeStatus !== 'completed') { updateFields.role_group = 'customer_service'; } @@ -606,7 +1077,7 @@ class AfterSaleService extends Service { const updatedAfterSale = afterSale.toJSON ? afterSale.toJSON() : afterSale; return { - after_sale: updatedAfterSale, + after_sale: this._formatAfterSaleRow(updatedAfterSale, ctx.app), step, }; } catch (error) { @@ -615,6 +1086,559 @@ class AfterSaleService extends Service { } } + // =========================== + // 拦截链路:批量创建工单 + 通知快递群 + // =========================== + + /** + * 拦截链路共享方法:根据订单 ID 查找运单,幂等创建售后工单,并按快递分组通知售后群。 + * 用于 batchIntercept / confirmIntercept / Qimen cancel / OpenAPI cancel 等入口统一调用。 + * + * @param {Object} params 参数。 + * @param {number[]} params.orderIds 订单 ID 列表。 + * @param {number} params.warehouseId 仓库 ID。 + * @param {string} params.creatorLabel 创建人标签(如 "系统"、"王小明")。 + * @param {string} [params.reason] 拦截原因。 + * @return {Promise<{ createdCount: number, notifiedCount: number }>} 创建与通知统计。 + */ + async createInterceptWorkOrdersAndNotify(params = {}) { + const { ctx } = this; + const { orderIds, warehouseId, creatorLabel, reason } = params; + + if (!Array.isArray(orderIds) || orderIds.length === 0 || !warehouseId) { + return { createdCount: 0, notifiedCount: 0 }; + } + + try { + // 1. 查询运单信息 + const expressList = await ctx.model.OrderExpress.findAll({ + attributes: [ + 'id', 'waybill_code', 'logistics_name', 'store_id', + 'logistics_interface_id', 'logistics_code', 'order_id', + ], + where: { + order_id: { [ctx.app.Sequelize.Op.in]: orderIds }, + warehouse_id: warehouseId, + }, + raw: true, + }); + + if (expressList.length === 0) { + return { createdCount: 0, notifiedCount: 0 }; + } + + // 2. 幂等检查:已有未完结的拦截工单不再重复创建 + const expressIds = expressList.map(e => e.id); + const existingASList = await ctx.model.AfterSale.findAll({ + attributes: [ 'waybill_id' ], + where: { + waybill_id: { [ctx.app.Sequelize.Op.in]: expressIds }, + type: 'order', + sub_type: 'intercept', + status: { [ctx.app.Sequelize.Op.notIn]: [ 'completed', 'closed', 'cancelled' ] }, + }, + raw: true, + }); + const existingWaybillIds = new Set(existingASList.map(r => r.waybill_id)); + const toCreate = expressList.filter(e => !existingWaybillIds.has(e.id)); + + if (toCreate.length === 0) { + return { createdCount: 0, notifiedCount: 0 }; + } + + // 3. 批量创建工单 + const label = creatorLabel || '系统'; + let createdCount = 0; + const createdWaybillIds = []; + + for (const e of toCreate) { + try { + const afterSaleNo = await ctx.service.systemMethods.afterSale.generateAfterSaleNo(warehouseId); + const descParts = [ + `发起人: ${label}`, + `运单号: ${e.waybill_code}`, + `快递公司: ${e.logistics_name || '未知'}`, + reason ? `拦截原因: ${reason}` : '', + ].filter(Boolean).join('\n'); + + await this.create({ + warehouse_id: warehouseId, + after_sale_no: afterSaleNo, + type: 'order', + sub_type: 'intercept', + title: `[系统拦截] ${e.waybill_code}`, + description: descParts, + priority: 10, + creator_id: 0, + inbox_message_id: null, + role_group: 'warehouse', + status: 'pending', + waybill_id: e.id, + waybill_no: e.waybill_code, + store_id: e.store_id || null, + order_id: e.order_id || null, + }); + createdCount += 1; + createdWaybillIds.push(e.id); + } catch (createErr) { + ctx.logger.warn( + `[afterSale.createInterceptWorkOrdersAndNotify] 创建工单失败, waybill=${e.waybill_code}, error=${createErr.message}` + ); + } + } + + // 4. 按快递分组通知售后群 + const expressByCode = {}; + for (const e of toCreate) { + const code = e.logistics_code || '__unknown__'; + if (!expressByCode[code]) { + expressByCode[code] = { interfaceId: e.logistics_interface_id, waybills: [] }; + } + expressByCode[code].waybills.push(e.waybill_code); + } + + let notifiedCount = 0; + const notifiedWaybillIds = new Set(); + + for (const [ code, info ] of Object.entries(expressByCode)) { + if (code === '__unknown__' || !info.interfaceId) continue; + try { + const { afterSalesGroups } = await ctx.service.systems.inbox.group.findGroupsByExpress({ + expressInterfaceId: info.interfaceId, + expressCode: code, + warehouseId, + }); + + if (afterSalesGroups.length === 0) continue; + + const notifyMsg = info.waybills.join('\n') + '\n拦截'; + for (const g of afterSalesGroups) { + ctx.service.inbox.processor.pushSystemNotification({ + warehouse_id: warehouseId, + group_id: g.group_id, + group_name: g.group_name, + content: notifyMsg, + ext_data: g.ext_data || null, + }); + notifiedCount += 1; + } + // 标记该快递下所有运单已通知 + const codeWaybills = toCreate.filter(e => (e.logistics_code || '__unknown__') === code); + codeWaybills.forEach(e => notifiedWaybillIds.add(e.id)); + } catch (e) { + ctx.logger.warn(`[afterSale] 查售后群失败 code=${code}: ${e.message}`); + } + } + + // 5. 有通知的工单升级为 pending_feedback + if (notifiedWaybillIds.size > 0) { + const notifiedWaybillIdArr = [ ...notifiedWaybillIds ]; + const hours = await this._resolveFollowupHours(warehouseId, 'order', 'intercept'); + await ctx.model.AfterSale.update( + { + status: 'pending_feedback', + followup_at: ctx.app.Sequelize.literal(`DATE_ADD(NOW(), INTERVAL ${hours} HOUR)`), + role_group: 'customer_service', + }, + { + where: { + waybill_id: { [ctx.app.Sequelize.Op.in]: notifiedWaybillIdArr }, + warehouse_id: warehouseId, + type: 'order', + sub_type: 'intercept', + status: 'pending', + }, + } + ); + } + + return { createdCount, notifiedCount }; + } catch (error) { + ctx.logger.warn(`[afterSale.createInterceptWorkOrdersAndNotify] 整体失败: ${error.message}`); + return { createdCount: 0, notifiedCount: 0 }; + } + } + + // =========================== + // 跟进时间配置 + // =========================== + + /** + * 根据仓库配置解析跟进小时数。 + * 优先级:policy_config sub_type 精确匹配 → type._default → 整数兜底 → 24h。 + * + * @param {number} warehouseId 仓库ID + * @param {string} type 售后类型 + * @param {string} subType 售后子类型 + * @return {Promise} 跟进小时数 + */ + async _resolveFollowupHours(warehouseId, type, subType) { + const { ctx } = this; + + // 仓库配置值的最小有效阈值:≤1 视为未配置的占位值,回退到 DEFAULTS + // (实际业务最小合理值为 intercept/urge 的 4h,不存在 0/1h 的跟进场景) + const MIN_VALID_FOLLOWUP_HOURS = 2; + + // 1. 仓库已保存的配置 + const sw = await ctx.model.StoreWarehouse.findOne({ + where: { warehouse_id: warehouseId }, + attributes: [ 'policy_config' ], + order: [[ 'id', 'DESC' ]], + raw: true, + }); + + ctx.logger.info( + `[_resolveFollowupHours] warehouseId=%s type=%s subType=%s hasStoreWarehouse=%s`, + warehouseId, type, subType, !!(sw && sw.policy_config) + ); + + if (sw && sw.policy_config) { + let config = sw.policy_config; + if (typeof config === 'string') { + try { config = JSON.parse(config); } catch { config = {}; } + } + const whConfig = config && config.after_sale_followup_hours; + ctx.logger.info( + `[_resolveFollowupHours] whConfig type=%s value=%s`, + typeof whConfig, JSON.stringify(whConfig) + ); + + if (whConfig && typeof whConfig === 'object') { + const whTypeMap = whConfig[type]; + ctx.logger.info( + `[_resolveFollowupHours] whTypeMap for type=%s: %s`, + type, JSON.stringify(whTypeMap) + ); + + // 分支 A:嵌套对象格式 {"order": {"damage": 48, "_default": 24}} + if (whTypeMap && typeof whTypeMap === 'object') { + if (subType) { + const subVal = this._tryParseHours(whTypeMap[subType]); + if (typeof subVal === 'number' && subVal >= MIN_VALID_FOLLOWUP_HOURS) { + ctx.logger.info(`[_resolveFollowupHours] MATCH subType (nested): %s=%dh`, subType, subVal); + return subVal; + } + } + const defVal = this._tryParseHours(whTypeMap._default); + if (typeof defVal === 'number' && defVal >= MIN_VALID_FOLLOWUP_HOURS) { + ctx.logger.info(`[_resolveFollowupHours] MATCH type._default (nested): %s._default=%dh`, type, defVal); + return defVal; + } + } + + // 分支 B:扁平格式 {"order": "24"} 或 {"order": 24} + // 值为字符串或数字,直接作为该 type 下所有 subType 的统一时长 + const flatVal = this._tryParseHours(whTypeMap); + if (typeof flatVal === 'number' && flatVal >= MIN_VALID_FOLLOWUP_HOURS) { + ctx.logger.info(`[_resolveFollowupHours] MATCH type flat: %s=%dh`, type, flatVal); + return flatVal; + } + } + // 分支 C:全局数字 {"after_sale_followup_hours": 24} 或 {"after_sale_followup_hours": "24"} + { + const globalVal = this._tryParseHours(whConfig); + if (typeof globalVal === 'number' && globalVal >= MIN_VALID_FOLLOWUP_HOURS) { + ctx.logger.info(`[_resolveFollowupHours] MATCH whConfig global: %dh`, globalVal); + return globalVal; + } + } + ctx.logger.info(`[_resolveFollowupHours] whConfig found but no valid match (all < ${MIN_VALID_FOLLOWUP_HOURS}h or type mismatch), falling to DEFAULTS`); + } + + // 2. 仓库未配置时,使用字段默认值(与 setting.warehouse.getFieldMeta 返回一致) + const DEFAULTS = { + order: { _default: 24, intercept: 4, urge: 4, change_address: 8, change_carrier: 8, delivery_delay: 12, damage: 48, quality_issue: 48, missing_item: 24 }, + receiving: { _default: 24, shortage: 48, damage: 48 }, + entry: { _default: 24, shortage: 48, damage: 48 }, + stockout: { _default: 24, return_issue: 48, shortage: 48 }, + }; + const typeDefault = DEFAULTS[type]; + if (typeDefault) { + if (subType && typeof typeDefault[subType] === 'number') { + ctx.logger.info(`[_resolveFollowupHours] DEFAULTS subType match: %s=%dh`, subType, typeDefault[subType]); + return typeDefault[subType]; + } + if (typeof typeDefault._default === 'number') { + ctx.logger.info(`[_resolveFollowupHours] DEFAULTS type._default: %s=%dh`, type, typeDefault._default); + return typeDefault._default; + } + } + + // 3. 硬兜底 + ctx.logger.warn(`[_resolveFollowupHours] FALLBACK 24h for type=%s subType=%s`, type, subType); + return 24; + } + + /** + * 将配置值尝试转为有效的小时数。 + * 兼容数字 24 和字符串 "24" 两种格式;无法解析时返回 null。 + * + * @param {*} raw 原始配置值 + * @return {number|null} 有效小时数,或 null + */ + _tryParseHours(raw) { + if (raw === null || raw === undefined || raw === '') return null; + if (typeof raw === 'number' && Number.isFinite(raw)) return raw; + if (typeof raw === 'string') { + const parsed = Number(raw); + if (Number.isFinite(parsed)) return parsed; + } + return null; + } + + // =========================== + // 批量设为待反馈 + // =========================== + + /** + * 批量将售后工单设为"待反馈"状态,并按仓库配置自动计算 followup_at。 + * 对每个工单写入步骤记录,所有操作在同一事务中执行。 + * + * @param {Object} params 批量操作参数 + * @param {number[]} params.ids 售后单主键ID列表 + * @param {number} params.operatorId 操作人账户ID + * @param {string} params.operatorSnapshot 操作人快照 JSON + * @param {string} [params.remark] 统一处理备注(所有工单共用) + * @param {number} params.warehouseId 仓库ID(用于权限校验) + * @return {Promise} { total, success, failed: [{id, reason}] } + */ + async batchSetPendingFeedback(params = {}) { + const { ids, operatorId, operatorSnapshot, remark, warehouseId } = params; + const { ctx } = this; + + // 1. 入参校验 + if (!Array.isArray(ids) || ids.length === 0) { + return { total: 0, success: 0, failed: [] }; + } + + const numericIds = ids.map(id => Number(id)).filter(id => Number.isInteger(id) && id > 0); + if (numericIds.length === 0) { + return { total: 0, success: 0, failed: [] }; + } + + // 2. 查询所有目标工单 + const afterSales = await ctx.model.AfterSale.findAll({ + where: { + id: { [ctx.app.Sequelize.Op.in]: numericIds }, + deleted_at: null, + }, + }); + + const afterSaleMap = new Map(); + for (const record of afterSales) { + afterSaleMap.set(record.id, record); + } + + // 3. 预校验 & 分类 + const validRecords = []; + const failed = []; + + // 终态不可设为待反馈 + const TERMINAL_STATUSES = new Set([ 'completed', 'closed', 'cancelled' ]); + + for (const id of numericIds) { + const record = afterSaleMap.get(id); + if (!record) { + failed.push({ id, reason: '售后单不存在或已删除' }); + continue; + } + if (TERMINAL_STATUSES.has(record.status)) { + failed.push({ id, reason: `工单已完结(${record.status}),不可设为待反馈` }); + continue; + } + if (record.warehouse_id !== warehouseId) { + failed.push({ id, reason: '仓库不匹配,无权操作' }); + continue; + } + validRecords.push(record); + } + + // 4. 开启事务,逐条更新 + const transaction = await ctx.model.transaction(); + + try { + const now = new Date(); + let successCount = 0; + + for (const record of validRecords) { + // 4a. 解析该工单的跟进小时数 + const hours = await this._resolveFollowupHours( + record.warehouse_id, + record.type, + record.sub_type + ); + + ctx.logger.info( + `[batchSetPendingFeedback] id=%s type=%s subType=%s hours=%d`, + record.id, record.type, record.sub_type, hours + ); + + // 4b. 写入步骤记录 + await this.addStep(record.id, { + step_status: 'pending_feedback', + operator_id: operatorId, + operator_snapshot: operatorSnapshot, + action: '设为待反馈', + remark: remark || null, + started_at: now, + completed_at: now, + }, transaction); + + // 4c. 更新主表:status + followup_at + role_group 回客服组 + const updateFields = { + status: 'pending_feedback', + followup_at: ctx.app.Sequelize.literal(`DATE_ADD(NOW(), INTERVAL ${hours} HOUR)`), + updated_at: now, + }; + // 若非客服组,自动回设为客服组(与 handleWorkOrder 行为一致) + if (record.role_group && record.role_group !== 'customer_service') { + updateFields.role_group = 'customer_service'; + } + + await record.update(updateFields, { transaction }); + successCount++; + } + + await transaction.commit(); + + return { + total: numericIds.length, + success: successCount, + failed, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + // =========================== + // 批量完结/关闭 + // =========================== + + /** + * 批量将售后工单设为完结或关闭状态。 + * completed 时自动写入 resolved_at 并清除 followup_at;closed 仅更新状态。 + * 对每个工单写入步骤记录,所有操作在同一事务中执行。 + * + * @param {Object} params 批量操作参数 + * @param {number[]} params.ids 售后单主键ID列表 + * @param {string} params.status 目标状态:completed | closed + * @param {string} [params.resolution] 完结处理结果(仅 status=completed 时写入) + * @param {number} params.operatorId 操作人账户ID + * @param {string} params.operatorSnapshot 操作人快照 JSON + * @param {string} [params.remark] 统一处理备注(所有工单共用) + * @param {number} params.warehouseId 仓库ID(用于权限校验) + * @return {Promise} { total, success, failed: [{id, reason}] } + */ + async batchClose(params = {}) { + const { ids, status: targetStatus, resolution, operatorId, operatorSnapshot, remark, warehouseId } = params; + const { ctx } = this; + + // 1. 入参校验 + const ALLOWED_TARGET_STATUSES = new Set([ 'completed', 'closed' ]); + if (!targetStatus || !ALLOWED_TARGET_STATUSES.has(targetStatus)) { + return { total: 0, success: 0, failed: [{ id: 0, reason: 'status 必须为 completed 或 closed' }] }; + } + + if (!Array.isArray(ids) || ids.length === 0) { + return { total: 0, success: 0, failed: [] }; + } + + const numericIds = ids.map(id => Number(id)).filter(id => Number.isInteger(id) && id > 0); + if (numericIds.length === 0) { + return { total: 0, success: 0, failed: [] }; + } + + // 2. 查询所有目标工单 + const afterSales = await ctx.model.AfterSale.findAll({ + where: { + id: { [ctx.app.Sequelize.Op.in]: numericIds }, + deleted_at: null, + }, + }); + + const afterSaleMap = new Map(); + for (const record of afterSales) { + afterSaleMap.set(record.id, record); + } + + // 3. 预校验 & 分类 + const validRecords = []; + const failed = []; + + // 终态不可重复完结/关闭 + const TERMINAL_STATUSES = new Set([ 'completed', 'closed', 'cancelled' ]); + + for (const id of numericIds) { + const record = afterSaleMap.get(id); + if (!record) { + failed.push({ id, reason: '售后单不存在或已删除' }); + continue; + } + if (TERMINAL_STATUSES.has(record.status)) { + failed.push({ id, reason: `工单已是终态(${record.status}),不可重复${targetStatus === 'completed' ? '完结' : '关闭'}` }); + continue; + } + if (record.warehouse_id !== warehouseId) { + failed.push({ id, reason: '仓库不匹配,无权操作' }); + continue; + } + validRecords.push(record); + } + + // 4. 开启事务,逐条更新 + const transaction = await ctx.model.transaction(); + + try { + const now = new Date(); + let successCount = 0; + + // 操作动作名称 + const actionName = targetStatus === 'completed' ? '批量完结' : '批量关闭'; + + for (const record of validRecords) { + // 4a. 写入步骤记录 + await this.addStep(record.id, { + step_status: targetStatus, + operator_id: operatorId, + operator_snapshot: operatorSnapshot, + action: actionName, + remark: remark || null, + started_at: now, + completed_at: now, + }, transaction); + + // 4b. 更新主表 + const updateFields = { + status: targetStatus, + updated_at: now, + followup_at: null, + }; + + // completed:额外写入 resolution + resolved_at + if (targetStatus === 'completed') { + updateFields.resolution = resolution || null; + updateFields.resolved_at = now; + } + + await record.update(updateFields, { transaction }); + successCount++; + } + + await transaction.commit(); + + return { + total: numericIds.length, + success: successCount, + failed, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + // =========================== // 登记理赔 // =========================== @@ -674,9 +1698,9 @@ class AfterSaleService extends Service { await afterSale.update(updateFields, { transaction }); - // 写入步骤 + // 写入步骤(step_status 与主表当前 status 一致) const step = await this.addStep(id, { - step_status: 2, + step_status: afterSale.status || 'processing', operator_id: operatorId, operator_snapshot: operatorSnapshot, action, @@ -695,7 +1719,7 @@ class AfterSaleService extends Service { const updatedAfterSale = afterSale.toJSON ? afterSale.toJSON() : afterSale; return { - after_sale: updatedAfterSale, + after_sale: this._formatAfterSaleRow(updatedAfterSale, ctx.app), step, }; } catch (error) { @@ -858,6 +1882,24 @@ class AfterSaleService extends Service { }; } } + + // =========================== + // 工具方法 + // =========================== + + /** + * 获取创建来源渠道的中文标签。 + * @param {string} channel 创建渠道代码 + * @return {string} 中文标签 + */ + _getCreateChannelLabel(channel) { + const labels = { + MANUAL: '手工单', + API: '接口', + QM: '奇门', + }; + return labels[channel] || channel || ''; + } } module.exports = AfterSaleService; diff --git a/app/service/systems/inbox/group.js b/app/service/systems/inbox/group.js index 7f4abf4..0fb9a39 100644 --- a/app/service/systems/inbox/group.js +++ b/app/service/systems/inbox/group.js @@ -3,6 +3,9 @@ const Service = require('egg').Service; const { parseWhereConditions } = require('../../../lib/query_condition_parser'); +// 从分组服务导入群类型定义,用于两层类型校验 +const { GROUP_TYPES: INBOX_GROUP_TYPES } = require('../../inbox/groups'); + /** * 站内信群管理业务逻辑层。 * 提供群列表查询、禁用、修改等核心能力。 @@ -262,6 +265,25 @@ class InboxGroupService extends Service { const targetGroupType = data.groupType !== undefined ? String(data.groupType).trim() : group.group_type || ''; + + // 两层类型校验:subType 必须在对应 groupType 的合法子类型列表中 + if (data.subType !== undefined && targetGroupType) { + const gtDef = INBOX_GROUP_TYPES.find(gt => gt.type === targetGroupType); + if (!gtDef) { + throw new Error(`无效的群类型: ${targetGroupType}`); + } + const subType = String(data.subType || '').trim(); + if (subType) { + const validKeys = gtDef.subTypes.map(st => st.key); + if (!validKeys.includes(subType)) { + throw new Error( + `子类型 "${subType}" 不在群类型 "${targetGroupType}" 的合法范围内,` + + `可用值: ${validKeys.join(', ')}` + ); + } + } + } + const isExpress = targetGroupType === 'express'; // express_interfaces 处理 @@ -374,6 +396,105 @@ class InboxGroupService extends Service { throw new Error(`系统快递编码 "${trimmed}" 不存在`); } } + + /** + * 根据快递接口ID和快递编码,查询绑定的售后群和揽收群。 + * + * 匹配规则: + * 1. group_type = 'express' + * 2. system_express_code 精确匹配 expressCode + * 3. express_interfaces 为空(未设置)→ 视为匹配所有该快递的接口 + * 4. express_interfaces 不为空 → 必须包含传入的 expressInterfaceId + * + * @param {Object} params 查询参数。 + * @param {number} params.expressInterfaceId 快递接口ID(wms_express_interface.id)。 + * @param {string} params.expressCode 快递编码(wms_express.code)。 + * @param {number} [params.warehouseId] 仓库ID,不传则查所有仓库。 + * @return {Promise<{afterSalesGroups: Array, pickupGroups: Array}>} 售后群和揽收群列表。 + */ + async findGroupsByExpress({ expressInterfaceId, expressCode, warehouseId }) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + + const eid = Number(expressInterfaceId); + const code = String(expressCode || '').trim(); + if (!eid || !code) { + throw new Error('expressInterfaceId 和 expressCode 不能为空'); + } + + const where = { + group_type: 'express', + system_express_code: code, + [Op.or]: [ + { express_interfaces: { [Op.or]: [ null, '' ] } }, + { express_interfaces: { [Op.like]: `%${eid}%` } }, + ], + }; + + if (warehouseId) { + where.warehouse_id = Number(warehouseId); + } + + const rows = await ctx.model.InboxGroup.findAll({ + attributes: [ 'id', 'group_name', 'group_id', 'sub_type', 'express_interfaces', 'warehouse_id', 'ext_data' ], + where, + raw: true, + }); + + const afterSalesGroups = rows.filter(r => r.sub_type === 'after_sales'); + const pickupGroups = rows.filter(r => r.sub_type === 'pickup'); + + ctx.logger.info( + `[inbox group] 查快递绑定群 eid=${eid} code=${code} ` + + `after_sales=${afterSalesGroups.length} pickup=${pickupGroups.length}` + ); + + return { afterSalesGroups, pickupGroups }; + } + + /** + * 根据货主ID列表,查询绑定的货主售后群。 + * + * 匹配规则: + * 1. group_type = 'store' + * 2. sub_type = 'after_sales' + * 3. store_id 在传入列表中 + * + * @param {Object} params 查询参数。 + * @param {number[]} params.storeIds 货主ID列表。 + * @param {number} params.warehouseId 仓库ID。 + * @return {Promise} 货主售后群列表 [{group_id, group_name, store_id, ext_data}]。 + */ + async findStoreAfterSalesGroups({ storeIds, warehouseId }) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + + const ids = (Array.isArray(storeIds) ? storeIds : [ storeIds ]) + .map(id => Number(id)) + .filter(id => Number.isFinite(id) && id > 0); + + if (ids.length === 0) { + return []; + } + + const rows = await ctx.model.InboxGroup.findAll({ + attributes: [ 'id', 'group_name', 'group_id', 'store_id', 'ext_data' ], + where: { + warehouse_id: Number(warehouseId), + group_type: 'store', + sub_type: 'after_sales', + store_id: { [Op.in]: ids }, + }, + raw: true, + }); + + ctx.logger.info( + `[inbox group] 查货主售后群 warehouse=${warehouseId} ` + + `stores=[${ids.join(',')}] found=${rows.length}` + ); + + return rows; + } } module.exports = InboxGroupService; diff --git a/app/service/systems/pick.js b/app/service/systems/pick.js index d40c11c..9592a60 100644 --- a/app/service/systems/pick.js +++ b/app/service/systems/pick.js @@ -2592,42 +2592,54 @@ class PickSystemService extends Service { throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400); } - await this.assertPickCartCodeUnique(cartCode, warehouseId); + // 使用事务:唯一性检查 + INSERT + LAST_INSERT_ID() 在同一连接,避免竞态 + const transaction = await ctx.model.transaction(); + let cartId = 0; + try { + await this.assertPickCartCodeUnique(cartCode, warehouseId, 0, transaction); - const insertResult = await ctx.model.query(` - INSERT INTO wms_pick_cart ( - warehouse_id, - cart_code, - cart_name, - status, - create_time, - update_time - ) VALUES ( - :warehouseId, - :cartCode, - :cartName, - :status, - NOW(), - NOW() - ) - `, { - replacements: { - warehouseId, - cartCode, - cartName, - status, - }, - }); + await ctx.model.query(` + INSERT INTO wms_pick_cart ( + warehouse_id, + cart_code, + cart_name, + status, + create_time, + update_time + ) VALUES ( + :warehouseId, + :cartCode, + :cartName, + :status, + NOW(), + NOW() + ) + `, { + replacements: { + warehouseId, + cartCode, + cartName, + status, + }, + transaction, + }); - const insertHead = Array.isArray(insertResult) ? insertResult[0] : null; - const insertMeta = Array.isArray(insertResult) ? insertResult[1] : null; - const cartId = Number( - (insertMeta && (insertMeta.insertId || insertMeta.lastID || insertMeta.id)) - || (insertHead && (insertHead.insertId || insertHead.lastID || insertHead.id)) - || 0 - ); - if (!Number.isInteger(cartId) || cartId <= 0) { - throw this.createBusinessError('拣货车创建失败', 500); + const idRows = await ctx.model.query('SELECT LAST_INSERT_ID() AS cart_id', { + type: ctx.model.QueryTypes.SELECT, + transaction, + }); + cartId = Number(Array.isArray(idRows) && idRows.length > 0 ? (idRows[0].cart_id || 0) : 0); + if (!Number.isInteger(cartId) || cartId <= 0) { + throw new Error('cartId 无效'); + } + + await transaction.commit(); + } catch (error) { + await transaction.rollback(); + if (error.message === 'cartId 无效') { + throw this.createBusinessError('拣货车创建失败', 500); + } + throw error; } const cartRow = await this.getPickCartById(cartId, warehouseId); @@ -2823,6 +2835,104 @@ class PickSystemService extends Service { }; } + /** + * 批量删除拣货车。已绑定任务或存在有效绑定记录的将被跳过。 + * + * @param {Object} params 删除参数。 + * @param {Array} params.ids 拣货车ID列表。 + * @return {Promise} { deleted_ids, skipped_ids, deleted_count, skipped_count } + */ + async pickCartBatchDelete(params = {}) { + const { ctx } = this; + const rawIds = Array.isArray(params && params.ids) ? params.ids : []; + const { warehouseId } = this.resolveOperatorContext(); + + if (!Array.isArray(rawIds) || rawIds.length === 0) { + throw this.createBusinessError('ids 必填且必须为非空数组', 400); + } + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400); + } + + // 去重并转为数字,过滤非法值 + const idSet = new Set(); + for (const id of rawIds) { + const num = Number(id); + if (Number.isInteger(num) && num > 0) { + idSet.add(num); + } + } + const ids = Array.from(idSet); + if (ids.length === 0) { + throw this.createBusinessError('ids 中没有合法的拣货车ID', 400); + } + + // 1) 查出当前仓库下这些拣货车的 current_task_id + const cartRows = await ctx.model.query(` + SELECT id, cart_code, current_task_id + FROM wms_pick_cart + WHERE id IN (:ids) + AND warehouse_id = :warehouseId + `, { + replacements: { ids, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + }); + + // 2) 查出有效绑定记录 + const bindingRows = await ctx.model.query(` + SELECT cart_id + FROM wms_pick_task_cart_binding + WHERE cart_id IN (:ids) + AND warehouse_id = :warehouseId + AND is_active = 1 + `, { + replacements: { ids, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + }); + + const bindingCartIds = new Set( + (Array.isArray(bindingRows) ? bindingRows : []).map(r => Number(r.cart_id || 0)).filter(id => id > 0) + ); + + // 3) 分类:已绑定任务 / 有效绑定记录 → skip;其余 → delete + const skipIds = []; + const deleteIds = []; + for (const row of (Array.isArray(cartRows) ? cartRows : [])) { + const cartId = Number(row.id || 0); + if (Number(row.current_task_id || 0) > 0 || bindingCartIds.has(cartId)) { + skipIds.push(cartId); + } else { + deleteIds.push(cartId); + } + } + + // ids 中存在但 cartRows 中不存在的(不属于该仓库或已不存在),也归入 skip + const foundIds = new Set((Array.isArray(cartRows) ? cartRows : []).map(r => Number(r.id || 0))); + for (const id of ids) { + if (!foundIds.has(id) && !skipIds.includes(id)) { + skipIds.push(id); + } + } + + // 4) 执行删除 + if (deleteIds.length > 0) { + await ctx.model.query(` + DELETE FROM wms_pick_cart + WHERE id IN (:deleteIds) + AND warehouse_id = :warehouseId + `, { + replacements: { deleteIds, warehouseId }, + }); + } + + return { + deleted_ids: deleteIds, + skipped_ids: skipIds, + deleted_count: deleteIds.length, + skipped_count: skipIds.length, + }; + } + /** * 查询拣货车详情。 * diff --git a/app/service/systems/pickCart.js b/app/service/systems/pickCart.js index cb449e0..4799b0f 100644 --- a/app/service/systems/pickCart.js +++ b/app/service/systems/pickCart.js @@ -54,6 +54,17 @@ class PickCartSystemService extends Service { return await this.service.systems.pick.pickCartDelete(params); } + /** + * 批量删除拣货车。已绑定任务的将被跳过。 + * + * @param {Object} params 删除参数。 + * @param {Array} params.ids 拣货车ID列表。 + * @return {Promise} 批量删除结果。 + */ + async batchDelete(params = {}) { + return await this.service.systems.pick.pickCartBatchDelete(params); + } + /** * 查询拣货车详情。 * diff --git a/app/service/systems/setting/warehouse.js b/app/service/systems/setting/warehouse.js index 5cf0ca6..58b0512 100644 --- a/app/service/systems/setting/warehouse.js +++ b/app/service/systems/setting/warehouse.js @@ -59,6 +59,14 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([ required: false, description: '订单备注命中任一关键字时,跳过自动分配快递,默认 [](不排除任何订单)', }), + Object.freeze({ + key: 'inbox_reply_exclude_keywords', + name: '排除快递回复关键词', + type: 'string_array', + default: [], + required: false, + description: '消息命中任一关键词时仅记录工单不发送回信通知,默认 [](正常回信)', + }), Object.freeze({ key: 'default_express_code', name: '默认快递编码', @@ -228,6 +236,55 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([ max: '23:59', description: '截单时间,格式 HH:mm,如 18:00', }), + Object.freeze({ + key: 'after_sale_followup_hours', + name: '售后跟进时间(h)', + type: 'object', + required: false, + description: '按售后类型+子类型设置跟进小时数。_default 为该类型默认值,具体子类型可覆盖', + item_keys: [ + Object.freeze({ key: 'order', name: '订单售后', type: 'object', required: false, description: '订单类型跟进配置', + item_keys: [ + Object.freeze({ key: '_default', name: '默认', type: 'integer', default: 24, min: 1, max: 720 }), + Object.freeze({ key: 'intercept', name: '拦截', type: 'integer', default: 4, min: 1, max: 720 }), + Object.freeze({ key: 'urge', name: '催件', type: 'integer', default: 4, min: 1, max: 720 }), + Object.freeze({ key: 'change_address', name: '改地址', type: 'integer', default: 8, min: 1, max: 720 }), + Object.freeze({ key: 'change_carrier', name: '换快递', type: 'integer', default: 8, min: 1, max: 720 }), + Object.freeze({ key: 'delivery_delay', name: '发货延迟', type: 'integer', default: 12, min: 1, max: 720 }), + Object.freeze({ key: 'damage', name: '破损', type: 'integer', default: 48, min: 1, max: 720 }), + Object.freeze({ key: 'quality_issue', name: '质量问题', type: 'integer', default: 48, min: 1, max: 720 }), + Object.freeze({ key: 'missing_item', name: '少发', type: 'integer', default: 24, min: 1, max: 720 }), + ], + }), + Object.freeze({ key: 'receiving', name: '收货单售后', type: 'object', required: false, description: '收货单类型跟进配置', + item_keys: [ + Object.freeze({ key: '_default', name: '默认', type: 'integer', default: 24, min: 1, max: 720 }), + Object.freeze({ key: 'shortage', name: '少货', type: 'integer', default: 48, min: 1, max: 720 }), + Object.freeze({ key: 'damage', name: '破损', type: 'integer', default: 48, min: 1, max: 720 }), + ], + }), + Object.freeze({ key: 'entry', name: '入库单售后', type: 'object', required: false, description: '入库单类型跟进配置', + item_keys: [ + Object.freeze({ key: '_default', name: '默认', type: 'integer', default: 24, min: 1, max: 720 }), + Object.freeze({ key: 'shortage', name: '少货', type: 'integer', default: 48, min: 1, max: 720 }), + Object.freeze({ key: 'damage', name: '破损', type: 'integer', default: 48, min: 1, max: 720 }), + ], + }), + Object.freeze({ key: 'stockout', name: '出库单售后', type: 'object', required: false, description: '出库单类型跟进配置', + item_keys: [ + Object.freeze({ key: '_default', name: '默认', type: 'integer', default: 24, min: 1, max: 720 }), + Object.freeze({ key: 'return_issue', name: '退货异常', type: 'integer', default: 48, min: 1, max: 720 }), + Object.freeze({ key: 'shortage', name: '少发', type: 'integer', default: 48, min: 1, max: 720 }), + ], + }), + ], + default: Object.freeze({ + order: Object.freeze({ _default: 24, intercept: 4, urge: 4, change_address: 8, change_carrier: 8, delivery_delay: 12, damage: 48, quality_issue: 48, missing_item: 24 }), + receiving: Object.freeze({ _default: 24, shortage: 48, damage: 48 }), + entry: Object.freeze({ _default: 24, shortage: 48, damage: 48 }), + stockout: Object.freeze({ _default: 24, return_issue: 48, shortage: 48 }), + }), + }), Object.freeze({ key: INTERNAL_WAVE_STRATEGY_VERSION_KEY, name: '仓库波次策略版本号', diff --git a/app/service/systems/stock_transaction.js b/app/service/systems/stock_transaction.js index ec4dd98..2e0f6e7 100644 --- a/app/service/systems/stock_transaction.js +++ b/app/service/systems/stock_transaction.js @@ -193,7 +193,7 @@ class StockTransactionService extends Service { return ctx.model.StockTransaction.create(payload, options); } - async list(pageParams = {}, sortParams = {}, groupByBatch = false) { + async list(pageParams = {}, sortParams = {}, groupByBatch = false, keyword = '') { const { ctx, app } = this; const { Op, fn, col, literal } = app.Sequelize; @@ -208,6 +208,21 @@ class StockTransactionService extends Service { ], }; + // keyword 快捷搜索:按 item_code + barcode 匹配,解析为 stock_id IN 条件 + const normalizedKeyword = String(keyword || '').trim(); + if (normalizedKeyword) { + const stockIds = await this._resolveKeywordToStockIds(normalizedKeyword, 'warehouse_id', warehouseId); + if (stockIds.length > 0) { + baseWhere[Op.and].push({ stock_id: { [Op.in]: stockIds } }); + } else { + // keyword 无匹配结果,直接返回空列表 + return { + list: [], + pagination: { page, pageSize, total: 0, totalPages: 0 }, + }; + } + } + // 动态 where 条件 const parsed = ctx.whereParsed; if (parsed && parsed.dynamicConditions && parsed.dynamicConditions.length > 0) { diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index 3529a15..127315b 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -2689,9 +2689,14 @@ class ReceivingService extends Service { }), }; + // 判断是否为改绑(明细之前已绑定过其他商品) + const isRebind = receivingDetail.system_product_id + && Number(receivingDetail.system_product_id) !== systemProductId; + // 如果收货明细有条码且商品尚未包含该条码,则自动为商品新增条码 + // 但改绑操作不写入条码(条码属于旧商品上下文,不应污染新商品) const detailBarcode = String(receivingDetail.barcode || '').trim(); - if (detailBarcode && !barcodes.includes(detailBarcode)) { + if (!isRebind && detailBarcode && !barcodes.includes(detailBarcode)) { try { await app.model.StockBarcode.create({ stock_id: systemProductId, @@ -4620,6 +4625,28 @@ class ReceivingService extends Service { return { code: 0, message: '该入库单尚未关联收货单', data: null }; } + // 校验所有 receiving 属于当前仓库 + const validReceivings = await ctx.model.Receiving.findAll({ + where: { id: { [Op.in]: receivingIds }, warehouse_id: warehouseId }, + attributes: [ 'id' ], + raw: true, + }); + const validReceivingIds = validReceivings.map(r => r.id); + if (validReceivingIds.length === 0) { + return { code: 1, message: '收货单不存在或不属于当前仓库', list: [], total: 0 }; + } + + // 2.5 获取入库单的所有合法 stock_id(用于校验收货明细的 system_product_id) + const entryItems = await ctx.model.EntryItems.findAll({ + where: { order_id: normalizedEntryOrderId }, + attributes: [ 'stock_id' ], + raw: true, + }); + const validStockIds = [ ...new Set(entryItems.map(ei => ei.stock_id).filter(Boolean)) ]; + if (validStockIds.length === 0) { + return { code: 0, message: '入库单无明细,无法匹配收货明细', data: null }; + } + // 排除已绑定的收货明细(wms_inbound_direct_log 中有记录且未软删除) const notBoundCondition = app.Sequelize.literal( 'NOT EXISTS (SELECT 1 FROM wms_inbound_direct_log erb WHERE erb.receiving_detail_id = wms_receiving_detail.id AND erb.deleted_at IS NULL)' @@ -4629,7 +4656,8 @@ class ReceivingService extends Service { const details = await ctx.model.ReceivingDetail.findAll({ where: { [Op.and]: [ - { receiving_id: { [Op.in]: receivingIds } }, + { receiving_id: { [Op.in]: validReceivingIds } }, + { system_product_id: { [Op.in]: validStockIds } }, notBoundCondition, ], }, @@ -4667,7 +4695,10 @@ class ReceivingService extends Service { for (const detail of details) { // 优先按明细 ID 精确匹配(托盘唛头场景) if (isNumericBarcode && detail.id === Number(normalizedBarcode)) { - matchedDetails.push(detail); + const sd = stockDetailMap.get(Number(detail.system_product_id)); + if (sd) { + matchedDetails.push(detail); + } continue; } @@ -4687,15 +4718,21 @@ class ReceivingService extends Service { return { code: 0, message: '未找到匹配的收货明细', data: null }; } - const list = matchedDetails.map(matchedDetail => ({ - detail_id: matchedDetail.id, - receiving_id: matchedDetail.receiving_id, - barcode: matchedDetail.barcode || '', - product_name: matchedDetail.product_name || '', - actual_quantity: matchedDetail.actual_quantity || 0, - receiving_status: matchedDetail.receiving_status || '', - stock: stockDetailMap.get(Number(matchedDetail.system_product_id)) || null, - })); + const list = matchedDetails.map(matchedDetail => { + const sd = stockDetailMap.get(Number(matchedDetail.system_product_id)); + const stockBarcode = (sd && Array.isArray(sd.barcodes) && sd.barcodes.length > 0) + ? (sd.barcodes[0].barcode || '') + : ''; + return { + detail_id: matchedDetail.id, + receiving_id: matchedDetail.receiving_id, + barcode: stockBarcode || matchedDetail.barcode || '', + product_name: matchedDetail.product_name || '', + actual_quantity: matchedDetail.actual_quantity || 0, + receiving_status: matchedDetail.receiving_status || '', + stock: sd || null, + }; + }); return { code: 200, diff --git a/app/service/systems/waybill.js b/app/service/systems/waybill.js index 83a80f5..7231985 100644 --- a/app/service/systems/waybill.js +++ b/app/service/systems/waybill.js @@ -149,10 +149,27 @@ class WaybillService extends MainService { * @param {Object} [options.sort] 排序参数 { field, order },默认 create_at desc。 * @return {Promise} 运单列表与分页信息 { list, pagination }。 */ - async list({ where = {}, pagination = {}, sort = {} } = {}) { + async list({ where: rawWhere = {}, pagination = {}, sort = {} } = {}) { const { ctx, app } = this; const { Op } = app.Sequelize; + // 标准化 where 条件:将前端 operator/value 格式(如 {operator:"contains", value:"YT..."})统一转为标准条件对象 + const where = this.normalizeWhereParams(rawWhere); + + /** + * 从 where 条件中提取实际值。 + * 标准化后的条件为 {operator, value} 对象,本函数提取 .value; + * 对于未标准化的原始值(string/number)直接返回。 + * @param {*} c 条件值 + * @param {*} defaultValue 默认值 + * @return {*} 提取后的实际值 + */ + const val = (c, defaultValue) => { + if (c === undefined || c === null) return defaultValue; + if (typeof c === 'object' && !Array.isArray(c) && 'value' in c) return c.value; + return c; + }; + // 仓库隔离 const warehouseId = Number(ctx.user && ctx.user.store_id); if (!warehouseId) { @@ -172,8 +189,9 @@ class WaybillService extends MainService { const queryWhere = { warehouse_id: warehouseId }; // 主单号查询:先通过主单号定位 order_id,再查该 order 下所有运单 - if (where.mainWaybillCode && String(where.mainWaybillCode).trim()) { - const mainCode = String(where.mainWaybillCode).trim(); + const mainWaybillCode = val(where.mainWaybillCode); + if (mainWaybillCode && String(mainWaybillCode).trim()) { + const mainCode = String(mainWaybillCode).trim(); const mainRecord = await ctx.model.OrderExpress.findOne({ where: { waybill_code: mainCode, @@ -195,13 +213,15 @@ class WaybillService extends MainService { } // 运单号模糊搜索 - if (where.waybillCode && String(where.waybillCode).trim()) { - queryWhere.waybill_code = { [Op.like]: `%${String(where.waybillCode).trim()}%` }; + const waybillCode = val(where.waybillCode); + if (waybillCode && String(waybillCode).trim()) { + queryWhere.waybill_code = { [Op.like]: `%${String(waybillCode).trim()}%` }; } // 订单ID等值 - if (where.orderId !== undefined && where.orderId !== null && String(where.orderId).trim() !== '') { - queryWhere.order_id = Number(where.orderId); + const orderId = val(where.orderId); + if (orderId !== undefined && orderId !== null && String(orderId).trim() !== '') { + queryWhere.order_id = Number(orderId); } // 订单号模糊搜索 @@ -211,43 +231,51 @@ class WaybillService extends MainService { // } // 物流公司编码等值 - if (where.logisticsCode && String(where.logisticsCode).trim()) { - queryWhere.logistics_code = String(where.logisticsCode).trim(); + const logisticsCode = val(where.logisticsCode); + if (logisticsCode && String(logisticsCode).trim()) { + queryWhere.logistics_code = String(logisticsCode).trim(); } // 物流接口ID等值 - if (where.logisticsInterfaceId !== undefined && where.logisticsInterfaceId !== null && String(where.logisticsInterfaceId).trim() !== '') { - queryWhere.logistics_interface_id = Number(where.logisticsInterfaceId); + const logisticsInterfaceId = val(where.logisticsInterfaceId); + if (logisticsInterfaceId !== undefined && logisticsInterfaceId !== null && String(logisticsInterfaceId).trim() !== '') { + queryWhere.logistics_interface_id = Number(logisticsInterfaceId); } // 平台编码等值 - if (where.platformCode && String(where.platformCode).trim()) { - queryWhere.platform_code = String(where.platformCode).trim(); + const platformCode = val(where.platformCode); + if (platformCode && String(platformCode).trim()) { + queryWhere.platform_code = String(platformCode).trim(); } // 运单状态等值 - if (where.status !== undefined && where.status !== null && String(where.status).trim() !== '') { - queryWhere.status = Number(where.status); + const statusVal = val(where.status); + if (statusVal !== undefined && statusVal !== null && String(statusVal).trim() !== '') { + queryWhere.status = Number(statusVal); } // 是否退回 - if (where.isBack && String(where.isBack).trim()) { - queryWhere.is_back = String(where.isBack).trim(); + const isBack = val(where.isBack); + if (isBack && String(isBack).trim()) { + queryWhere.is_back = String(isBack).trim(); } // 是否拦截 - if (where.isIntercept && String(where.isIntercept).trim()) { - queryWhere.is_intercept = String(where.isIntercept).trim(); + const isIntercept = val(where.isIntercept); + if (isIntercept && String(isIntercept).trim()) { + queryWhere.is_intercept = String(isIntercept).trim(); } // 是否揽收 - if (where.isGalaxyReceive && String(where.isGalaxyReceive).trim()) { - queryWhere.is_galaxy_receive = String(where.isGalaxyReceive).trim(); + const isGalaxyReceive = val(where.isGalaxyReceive); + if (isGalaxyReceive && String(isGalaxyReceive).trim()) { + queryWhere.is_galaxy_receive = String(isGalaxyReceive).trim(); } // 运单类型:主单号 / 子单号 - if (where.waybillType && String(where.waybillType).trim()) { - const type = String(where.waybillType).trim(); + const waybillType = val(where.waybillType); + if (waybillType && String(waybillType).trim()) { + const type = String(waybillType).trim(); if (type === 'main' || type === '1') { queryWhere.business_key = 1; } else if (type === 'child' || type === '2') { @@ -256,18 +284,21 @@ class WaybillService extends MainService { } // 货主ID等值 - if (where.storeId !== undefined && where.storeId !== null && String(where.storeId).trim() !== '') { - queryWhere.store_id = Number(where.storeId); + const storeId = val(where.storeId); + if (storeId !== undefined && storeId !== null && String(storeId).trim() !== '') { + queryWhere.store_id = Number(storeId); } // 包材ID等值 - if (where.packageMaterialId !== undefined && where.packageMaterialId !== null && String(where.packageMaterialId).trim() !== '') { - queryWhere.package_material_id = Number(where.packageMaterialId); + const packageMaterialId = val(where.packageMaterialId); + if (packageMaterialId !== undefined && packageMaterialId !== null && String(packageMaterialId).trim() !== '') { + queryWhere.package_material_id = Number(packageMaterialId); } // 是否已称重 - if (where.hasWeighingWeight !== undefined && where.hasWeighingWeight !== null && String(where.hasWeighingWeight).trim() !== '') { - const hasWeight = String(where.hasWeighingWeight).trim(); + const hasWeighingWeight = val(where.hasWeighingWeight); + if (hasWeighingWeight !== undefined && hasWeighingWeight !== null && String(hasWeighingWeight).trim() !== '') { + const hasWeight = String(hasWeighingWeight).trim(); if (hasWeight === 'true') { queryWhere.weighing_weight = { [Op.gt]: 0 }; } else if (hasWeight === 'false') { @@ -276,19 +307,22 @@ class WaybillService extends MainService { } // 关键词模糊搜索 - if (where.keyword && String(where.keyword).trim()) { - queryWhere.waybill_code = { [Op.like]: `%${String(where.keyword).trim()}%` }; + const keyword = val(where.keyword); + if (keyword && String(keyword).trim()) { + queryWhere.waybill_code = { [Op.like]: `%${String(keyword).trim()}%` }; } // 创建时间范围 - if (where.createdAtStart && String(where.createdAtStart).trim()) { - const startDate = this.normalizeDate(String(where.createdAtStart).trim(), false); + const createdAtStart = val(where.createdAtStart); + if (createdAtStart && String(createdAtStart).trim()) { + const startDate = this.normalizeDate(String(createdAtStart).trim(), false); if (startDate) { queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.gte]: startDate }; } } - if (where.createdAtEnd && String(where.createdAtEnd).trim()) { - const endDate = this.normalizeDate(String(where.createdAtEnd).trim(), true); + const createdAtEnd = val(where.createdAtEnd); + if (createdAtEnd && String(createdAtEnd).trim()) { + const endDate = this.normalizeDate(String(createdAtEnd).trim(), true); if (endDate) { queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.lte]: endDate }; } @@ -302,6 +336,7 @@ class WaybillService extends MainService { attributes: [ 'id', 'waybill_code', 'order_id', 'business_key', 'status', 'warehouse_id', 'store_id', + 'delivery_order_code', 'source_order_codes', 'logistics_code', 'logistics_name', 'logistics_interface_id', 'logistics_interface_name', 'platform_code', @@ -401,13 +436,11 @@ class WaybillService extends MainService { main_waybill_code: mainCode, waybill_type: Number(row.business_key) === 1 ? '主单号' : '子单号', order_id: row.order_id, - // TODO: 快照列未落库,暂时填空;快照就绪后替换为 row.delivery_order_code - order_no: '', + order_no: row.delivery_order_code || row.source_order_codes || '', + source_order_codes: row.source_order_codes || '', warehouse_id: row.warehouse_id, - // TODO: 快照列未落库,暂时填空;快照就绪后替换为 row.warehouse_name_snapshot warehouse_name: '', store_id: row.store_id || 0, - // TODO: 快照列未落库,暂时填空;快照就绪后替换为 row.store_name_snapshot store_name: '', store_remark_name: storeRemarkMap.get(`${row.store_id}:${row.warehouse_id}`) || '', business_key: row.business_key, @@ -636,10 +669,24 @@ class WaybillService extends MainService { * @param {Function} [options.onProgress] 进度回调,接收 `{ status, progress, currentCount, totalCount, message, result }`。 * @return {Promise} 导出结果 { list, current_count, total_count, url }。 */ - async export({ where = {}, sort = {}, exportFields, onProgress } = {}) { + async export({ where: rawWhere = {}, sort = {}, exportFields, onProgress } = {}) { const { ctx, app } = this; const { Op } = app.Sequelize; + // 标准化 where 条件 + const where = this.normalizeWhereParams(rawWhere); + /** + * 从标准化后的 where 条件中提取实际值。 + * @param {*} c 条件值 + * @param {*} defaultValue 默认值 + * @return {*} 提取后的实际值 + */ + const val = (c, defaultValue) => { + if (c === undefined || c === null) return defaultValue; + if (typeof c === 'object' && !Array.isArray(c) && 'value' in c) return c.value; + return c; + }; + // 仓库隔离 const warehouseId = Number(ctx.user && ctx.user.store_id); if (!warehouseId) { @@ -655,8 +702,9 @@ class WaybillService extends MainService { const queryWhere = { warehouse_id: warehouseId }; // 主单号查询 - if (where.mainWaybillCode && String(where.mainWaybillCode).trim()) { - const mainCode = String(where.mainWaybillCode).trim(); + const mainWaybillCodeExport = val(where.mainWaybillCode); + if (mainWaybillCodeExport && String(mainWaybillCodeExport).trim()) { + const mainCode = String(mainWaybillCodeExport).trim(); const mainRecord = await ctx.model.OrderExpress.findOne({ where: { waybill_code: mainCode, @@ -676,36 +724,46 @@ class WaybillService extends MainService { } } - if (where.waybillCode && String(where.waybillCode).trim()) { - queryWhere.waybill_code = { [Op.like]: `%${String(where.waybillCode).trim()}%` }; + const waybillCodeExport = val(where.waybillCode); + if (waybillCodeExport && String(waybillCodeExport).trim()) { + queryWhere.waybill_code = { [Op.like]: `%${String(waybillCodeExport).trim()}%` }; } - if (where.orderId !== undefined && where.orderId !== null && String(where.orderId).trim() !== '') { - queryWhere.order_id = Number(where.orderId); + const orderIdExport = val(where.orderId); + if (orderIdExport !== undefined && orderIdExport !== null && String(orderIdExport).trim() !== '') { + queryWhere.order_id = Number(orderIdExport); } // TODO: 快照字段 delivery_order_code 未落库,暂跳过订单号筛选;快照列就绪后取消注释 - if (where.logisticsCode && String(where.logisticsCode).trim()) { - queryWhere.logistics_code = String(where.logisticsCode).trim(); + const logisticsCodeExport = val(where.logisticsCode); + if (logisticsCodeExport && String(logisticsCodeExport).trim()) { + queryWhere.logistics_code = String(logisticsCodeExport).trim(); } - if (where.logisticsInterfaceId !== undefined && where.logisticsInterfaceId !== null && String(where.logisticsInterfaceId).trim() !== '') { - queryWhere.logistics_interface_id = Number(where.logisticsInterfaceId); + const logisticsInterfaceIdExport = val(where.logisticsInterfaceId); + if (logisticsInterfaceIdExport !== undefined && logisticsInterfaceIdExport !== null && String(logisticsInterfaceIdExport).trim() !== '') { + queryWhere.logistics_interface_id = Number(logisticsInterfaceIdExport); } - if (where.platformCode && String(where.platformCode).trim()) { - queryWhere.platform_code = String(where.platformCode).trim(); + const platformCodeExport = val(where.platformCode); + if (platformCodeExport && String(platformCodeExport).trim()) { + queryWhere.platform_code = String(platformCodeExport).trim(); } - if (where.status !== undefined && where.status !== null && String(where.status).trim() !== '') { - queryWhere.status = Number(where.status); + const statusExport = val(where.status); + if (statusExport !== undefined && statusExport !== null && String(statusExport).trim() !== '') { + queryWhere.status = Number(statusExport); } - if (where.isBack && String(where.isBack).trim()) { - queryWhere.is_back = String(where.isBack).trim(); + const isBackExport = val(where.isBack); + if (isBackExport && String(isBackExport).trim()) { + queryWhere.is_back = String(isBackExport).trim(); } - if (where.isIntercept && String(where.isIntercept).trim()) { - queryWhere.is_intercept = String(where.isIntercept).trim(); + const isInterceptExport = val(where.isIntercept); + if (isInterceptExport && String(isInterceptExport).trim()) { + queryWhere.is_intercept = String(isInterceptExport).trim(); } - if (where.isGalaxyReceive && String(where.isGalaxyReceive).trim()) { - queryWhere.is_galaxy_receive = String(where.isGalaxyReceive).trim(); + const isGalaxyReceiveExport = val(where.isGalaxyReceive); + if (isGalaxyReceiveExport && String(isGalaxyReceiveExport).trim()) { + queryWhere.is_galaxy_receive = String(isGalaxyReceiveExport).trim(); } - if (where.waybillType && String(where.waybillType).trim()) { - const type = String(where.waybillType).trim(); + const waybillTypeExport = val(where.waybillType); + if (waybillTypeExport && String(waybillTypeExport).trim()) { + const type = String(waybillTypeExport).trim(); if (type === 'main' || type === '1') { queryWhere.business_key = 1; } else if (type === 'child' || type === '2') { @@ -713,31 +771,37 @@ class WaybillService extends MainService { } } // 货主ID等值 - if (where.storeId !== undefined && where.storeId !== null && String(where.storeId).trim() !== '') { - queryWhere.store_id = Number(where.storeId); + const storeIdExport = val(where.storeId); + if (storeIdExport !== undefined && storeIdExport !== null && String(storeIdExport).trim() !== '') { + queryWhere.store_id = Number(storeIdExport); } - if (where.packageMaterialId !== undefined && where.packageMaterialId !== null && String(where.packageMaterialId).trim() !== '') { - queryWhere.package_material_id = Number(where.packageMaterialId); + const packageMaterialIdExport = val(where.packageMaterialId); + if (packageMaterialIdExport !== undefined && packageMaterialIdExport !== null && String(packageMaterialIdExport).trim() !== '') { + queryWhere.package_material_id = Number(packageMaterialIdExport); } - if (where.hasWeighingWeight !== undefined && where.hasWeighingWeight !== null && String(where.hasWeighingWeight).trim() !== '') { - const hasWeight = String(where.hasWeighingWeight).trim(); + const hasWeighingWeightExport = val(where.hasWeighingWeight); + if (hasWeighingWeightExport !== undefined && hasWeighingWeightExport !== null && String(hasWeighingWeightExport).trim() !== '') { + const hasWeight = String(hasWeighingWeightExport).trim(); if (hasWeight === 'true') { queryWhere.weighing_weight = { [Op.gt]: 0 }; } else if (hasWeight === 'false') { queryWhere.weighing_weight = { [Op.eq]: 0 }; } } - if (where.keyword && String(where.keyword).trim()) { - queryWhere.waybill_code = { [Op.like]: `%${String(where.keyword).trim()}%` }; + const keywordExport = val(where.keyword); + if (keywordExport && String(keywordExport).trim()) { + queryWhere.waybill_code = { [Op.like]: `%${String(keywordExport).trim()}%` }; } - if (where.createdAtStart && String(where.createdAtStart).trim()) { - const startDate = this.normalizeDate(String(where.createdAtStart).trim(), false); + const createdAtStartExport = val(where.createdAtStart); + if (createdAtStartExport && String(createdAtStartExport).trim()) { + const startDate = this.normalizeDate(String(createdAtStartExport).trim(), false); if (startDate) { queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.gte]: startDate }; } } - if (where.createdAtEnd && String(where.createdAtEnd).trim()) { - const endDate = this.normalizeDate(String(where.createdAtEnd).trim(), true); + const createdAtEndExport = val(where.createdAtEnd); + if (createdAtEndExport && String(createdAtEndExport).trim()) { + const endDate = this.normalizeDate(String(createdAtEndExport).trim(), true); if (endDate) { queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.lte]: endDate }; } @@ -768,10 +832,10 @@ class WaybillService extends MainService { for (let page = 0; page < totalPages; page++) { const pageRows = await ctx.model.OrderExpress.findAll({ where: queryWhere, - // TODO: 快照列未落库,暂时只查已有字段;快照就绪后补充 attributes: [ 'id', 'waybill_code', 'order_id', 'business_key', 'status', 'warehouse_id', 'store_id', + 'delivery_order_code', 'source_order_codes', 'logistics_code', 'logistics_name', 'logistics_interface_id', 'logistics_interface_name', 'platform_code', @@ -826,8 +890,8 @@ class WaybillService extends MainService { main_waybill_code: r => mainWaybillMap.get(r.order_id) || r.waybill_code || '', waybill_type: r => (Number(r.business_key) === 1 ? '主单号' : '子单号'), order_id: r => r.order_id, - // TODO: 快照列未落库,暂时填空;快照就绪后替换 - order_no: () => '', + order_no: r => r.delivery_order_code || r.source_order_codes || '', + source_order_codes: r => r.source_order_codes || '', warehouse_id: r => r.warehouse_id, warehouse_name: () => '', store_id: r => r.store_id || 0, @@ -915,6 +979,7 @@ class WaybillService extends MainService { waybill_type: '运单类型', order_id: '订单ID', order_no: '订单号', + source_order_codes: '原始订单号', warehouse_id: '仓库ID', warehouse_name: '仓库名称', store_id: '货主ID', diff --git a/database/designs/after-sale-v2-design.md b/database/designs/after-sale-v2-design.md index 1244763..a9f44f4 100644 --- a/database/designs/after-sale-v2-design.md +++ b/database/designs/after-sale-v2-design.md @@ -93,7 +93,7 @@ erDiagram wms_after_sale_detail { BIGINT id PK "主键" BIGINT after_sale_id FK "关联售后主表" - TINYINT step_status "步骤状态" + VARCHAR step_status "步骤记录时主表状态" BIGINT operator_id "操作人ID" TEXT operator_snapshot "操作人信息快照" VARCHAR action "操作动作" @@ -277,6 +277,7 @@ const AFTER_SALE_TYPES = [ |----|------| | `pending` | 待处理 | | `processing` | 处理中 | +| `pending_feedback` | 等待外部反馈(内部处理完成,等待外部反馈后再决定是否继续处理) | | `completed` | 已完成 | | `closed` | 已关闭 | | `cancelled` | 已取消 | @@ -331,7 +332,7 @@ const AFTER_SALE_TYPES = [ |------|------|------|--------|------| | `id` | `BIGINT UNSIGNED` | ✅ | AUTO | 主键 | | `after_sale_id` | `BIGINT UNSIGNED` | ✅ | — | 关联售后主表ID(`wms_after_sale.id`) | -| `step_status` | `TINYINT UNSIGNED` | ✅ | 0 | 步骤状态:0=待开始,1=进行中,2=已完成,3=已跳过 | +| `step_status` | `VARCHAR(20)` | ✅ | `processing` | 步骤记录时售后主表的状态,与 `wms_after_sale.status` 完全一致: pending / processing / completed / closed / cancelled。每次写入步骤时取主表当前 status 快照 | | `operator_id` | `BIGINT UNSIGNED` | — | NULL | 操作人账户ID(关联 `accounts` 表);可为空,外部系统回调/自动触发的步骤无人操作 | | `operator_snapshot` | `TEXT` | — | NULL | 操作人信息快照(JSON),如 `{"name":"张三","role":"客服"}`,防止账户删除后历史丢失 | | `action` | `VARCHAR(100)` | — | NULL | 操作动作描述,如"确认收货"、"审核驳回"、"发起退款" | @@ -342,18 +343,19 @@ const AFTER_SALE_TYPES = [ | `updated_at` | `DATETIME` | ✅ | `CURRENT_TIMESTAMP ON UPDATE` | 更新时间 | | `deleted_at` | `DATETIME` | — | NULL | 软删除时间 | -#### 3.2.2 步骤状态 `step_status` 枚举 +#### 3.2.2 步骤状态 `step_status` 说明 -| 值 | 说明 | 典型场景 | -|----|------|---------| -| `0` | 待开始 | 步骤尚未触发,等待前置步骤完成 | -| `1` | 进行中 | 步骤正在处理中 | -| `2` | 已完成 | 步骤处理完毕 | -| `3` | 已跳过 | 因条件不满足或审批豁免而跳过此步骤 | +`step_status` 与 `wms_after_sale.status` 完全一致(类型、枚举均相同),每次写入步骤时记录步骤发生时主表的当前状态快照。枚举值: -> **设计考量**:`step_status` 决定步骤的当前状态。步骤按 `created_at` 自然时间排序,通过 `action` 描述步骤内容。后续步骤在前置步骤全部 `completed` 或 `skipped` 后才能开始。步骤可在创建售后单时预置(如按 `type` 生成一套标准步骤),也可在处理过程中动态追加。 -> -> **外部系统触发说明**:当步骤由外部系统触发(如快递签收回调、支付平台退款回调、ERP 同步等)时,`operator_id` 为 NULL,`action` 记录触发来源(如"快递签收回调"、"支付宝退款通知")。这确保自动触发的步骤可追溯来源,同时与人工操作步骤明确区分。 +| 值 | 说明 | +|----|------| +| `pending` | 待处理 | +| `processing` | 处理中 | +| `completed` | 已完成 | +| `closed` | 已关闭 | +| `cancelled` | 已取消 | + +> **设计考量**:`step_status` 记录的是"该步骤发生时,售后主表处于什么状态",而非步骤本身的"进行中/已完成"标记。这使得每条步骤都能直接追溯到该步骤执行时的工单状态上下文,无需 JOIN 主表查阅历史状态。步骤按 `created_at` 自然时间排序。 ### 3.2.3 附件关联 @@ -426,8 +428,11 @@ stateDiagram-v2 [*] --> pending: 创建售后单 pending --> processing: 指派处理人 / 开始处理 pending --> cancelled: 取消 + processing --> pending_feedback: 内部处理完毕,等待外部反馈 processing --> completed: 处理完成 processing --> closed: 强制关闭 + pending_feedback --> processing: 收到外部反馈,继续处理 + pending_feedback --> completed: 外部反馈确认完成 completed --> [*] closed --> [*] cancelled --> [*] @@ -437,9 +442,11 @@ stateDiagram-v2 |------|---------|------| | `pending` → `processing` | 指派处理人 or 手动开始处理 | 通过 `wms_after_sale_detail` 记录的处理步骤追踪 | | `pending` → `cancelled` | 创建人取消 | 仅待处理状态可取消 | +| `processing` → `pending_feedback` | 内部处理完毕,等待外部反馈 | 如已将拦截信息发给运方,等待运方反馈拦截结果 | | `processing` → `completed` | 处理完毕 | 写入 `resolution` + `resolved_at` | | `processing` → `closed` | 管理员强制关闭 | 如重复单、无效单等 | -| 转单(跨角色组) | 客服转仓库 / 仓库转财务等 | 更新 `role_group` 为目标角色组,如 `customer_service` → `warehouse`;同时可在 `wms_after_sale_detail` 记录转单步骤 | +| `pending_feedback` → `processing` | 收到外部反馈,继续处理 | 如运方反馈已拦截/未拦截,回到内部通知客户 | +| `pending_feedback` → `completed` | 外部反馈确认完成 | 如平台退款回调确认到账 | **理赔状态流转**(仓库理赔 & 运方理赔通用):`pending` → `reviewing` → `approved` → `paid`,任意阶段可 → `rejected`,或走 `monthly`(月结)通道。 @@ -457,9 +464,9 @@ stateDiagram-v2 ├─ waybill_id / waybill_no: 客户寄回的快递单号 ├─ receiving_id / receiving_no: 仓库收货单 └─ 进度步骤: - ├─ step_status=2(已完成), operator_id=1001, action=客服接单-受理退货申请 - ├─ step_status=2(已完成), operator_id=2001, action=仓库收货-确认收货入库 - └─ step_status=0(待开始), action=退款打款 + ├─ step_status=processing, operator_id=1001, action=客服接单-受理退货申请 + ├─ step_status=processing, operator_id=2001, action=仓库收货-确认收货入库 + └─ step_status=processing, action=退款打款 ``` > **转单说明**:当客服接单后发现需要仓库核实实物时,可将 `role_group` 从 `customer_service` 更新为 `warehouse`,仓库组即可在自己的待办列表中看到该工单。 @@ -471,9 +478,9 @@ stateDiagram-v2 ├─ waybill_id / waybill_no: 客户寄回的快递单号 ├─ order_delivery_id / order_delivery_no: 仓库补发的发货订单 └─ 进度步骤: - ├─ step_status=2(已完成), action=客服接单-确认换货申请 - ├─ step_status=2(已完成), action=退回入库-客户退回商品已入库 - └─ step_status=1(进行中), action=补发换货-仓库补发新商品 + ├─ step_status=processing, action=客服接单-确认换货申请 + ├─ step_status=processing, action=退回入库-客户退回商品已入库 + └─ step_status=processing, action=补发换货-仓库补发新商品 ``` ### 场景3:订单售后(仓库理赔) @@ -482,9 +489,9 @@ stateDiagram-v2 售后单 type=order, sub_type=damage ├─ claim_needed=1, claim_amount=50.00, claim_status=pending └─ 进度步骤: - ├─ step_status=2(已完成), action=客服接单-受理仓库理赔 - ├─ step_status=2(已完成), action=核实定损, remark=仓库出库破损, 核定赔偿50元 - └─ step_status=1(进行中), action=审批打款 + ├─ step_status=processing, action=客服接单-受理仓库理赔 + ├─ step_status=processing, action=核实定损, remark=仓库出库破损, 核定赔偿50元 + └─ step_status=processing, action=审批打款 ``` ### 场景3b:订单售后(运方理赔) @@ -494,9 +501,9 @@ stateDiagram-v2 ├─ carrier_claim_needed=1, carrier_claim_amount=200.00, carrier_claim_status=pending ├─ waybill_id / waybill_no: 涉损运单 └─ 进度步骤: - ├─ step_status=2(已完成), action=客服接单-受理运方理赔 - ├─ step_status=2(已完成), action=核实定损, remark=运输途中破损, 核定赔偿200元 - └─ step_status=1(进行中), action=快递审批 + ├─ step_status=processing, action=客服接单-受理运方理赔 + ├─ step_status=processing, action=核实定损, remark=运输途中破损, 核定赔偿200元 + └─ step_status=processing, action=快递审批 ``` > **说明**:仓库理赔与运方理赔可同时存在(如货物在仓库出库&运输途中均发生破损),分别使用 `claim_*` 和 `carrier_claim_*` 字段组记录。 @@ -509,10 +516,10 @@ stateDiagram-v2 ├─ receiving_id / receiving_no: 仓库收货单 ├─ order_stockout_id / order_stockout_no: 退货出库单 └─ 进度步骤: - ├─ step_status=2(已完成), action=客服接单-批量退货受理 - ├─ step_status=2(已完成), operator_id=3001, action=验货签收, remark=SKU001×3, SKU002×1 均完好(可挂附件:破损照片 × 2) - ├─ step_status=2(已完成), action=退货入库 - └─ step_status=0(待开始), action=退款打款 + ├─ step_status=processing, action=客服接单-批量退货受理 + ├─ step_status=processing, operator_id=3001, action=验货签收, remark=SKU001×3, SKU002×1 均完好(可挂附件:破损照片 × 2) + ├─ step_status=processing, action=退货入库 + └─ step_status=processing, action=退款打款 ``` > **说明**:此场景中 `role_group=warehouse` 表示当前由仓库组负责验货入库环节;验货完成后如需财务退款,转单时将 `role_group` 更新为 `finance`。 @@ -601,13 +608,16 @@ app/model/after_sale_detail.js → wms_after_sale_detail | 生产组-主管 | 517 | 519, 520, 521 | 522, 508, 510, 512 | | 拣货组-组长 | 517 | 519, 520, 521 | 522, 508, 510, 512 | | 财务 | 518 | 519, 520, 521 | 522, 508 | +| 经理 | — | 519, 520, 521 | 522, 523, 508, 509, 510, 511, 512, 513, 514, 515 | > - 客服:全部权限(创建、更新、转单、查理赔) > - 仓库:只读查询 + 更新处理结果 > - 生产组-主管 / 拣货组-组长:共享仓库组视角(同仓库组权限),处理退货验货入库等实物操作。普通生产组员工不授权任何售后权限。 > - 财务:只读查询(理赔审核通过财务系统操作,不走 WMS) +> - 经理:全部售后权限 > **生产组其他角色**(普通员工、复核、其他普工)不授权任何售后权限。 +> **财务组角色**:role_code=`finance`,role_name=`财务组`,自动创建并授权。 --- @@ -750,14 +760,13 @@ app/model/after_sale_detail.js → wms_after_sale_detail ```json { "method": "afterSale.handleWorkOrder", - "description": "处理售后工单。员工在工作列表中对工单进行操作,写入进度步骤并绑定附件。操作人信息从登录上下文自动获取。非客服组处理完成后自动转回客服组继续跟进。", + "description": "处理售后工单。员工在工作列表中对工单进行操作,写入进度步骤并绑定附件。操作人信息从登录上下文自动获取。步骤 action 由服务端固定为\"处理工单\",前端无需传入。status 不填或填错默认 processing。非客服组处理完成后自动转回客服组继续跟进。", "isNeedAuth": false, "isNeedLogin": true, "params": [ { "name": "id", "type": "integer", "required": true, "source": "body", "description": "售后工单主表ID(wms_after_sale.id)" }, - { "name": "status", "type": "string", "required": false, "source": "body", "description": "更新售后单状态(pending/processing/completed/closed),不传则保持当前状态" }, - { "name": "action", "type": "string", "required": true, "source": "body", "description": "操作动作描述,如"客服接单"、"仓库验货"、"确认收货入库"、"退款打款"" }, - { "name": "remark", "type": "string", "required": false, "source": "body", "description": "处理备注/消息主体" }, + { "name": "status", "type": "string", "required": false, "source": "body", "description": "更新售后单状态: processing | completed | closed | cancelled。不填或填错默认 processing。注意:pending 不适用于处理操作" }, + { "name": "remark", "type": "string", "required": false, "source": "body", "description": "处理备注" }, { "name": "attachment_ids", "type": "array", "required": false, "source": "body", "description": "附件 file_id 数组,如 [123, 456]。处理时自动绑定到本次步骤。" } ], "response": [ @@ -766,7 +775,6 @@ app/model/after_sale_detail.js → wms_after_sale_detail ], "errors": [ { "code": 400, "message": "工单不存在或参数缺失" }, - { "code": 403, "message": "无权限处理该工单(role_group 不匹配)" }, { "code": 500, "message": "处理失败" } ] } @@ -777,8 +785,8 @@ app/model/after_sale_detail.js → wms_after_sale_detail 1. 校验工单 `id` 存在,且当前用户 `role_group` 与工单 `role_group` 匹配(否则 403) 2. 从登录上下文(JWT token)提取操作人 `operator_id` 和 `operator_snapshot` 3. 写入 `wms_after_sale_detail`: - - `step_status = 2`(已完成) - - `action` = 入参 `action` + - `step_status` = 主表当前 status(由 safeStatus 决定,不填或填错默认 processing) + - `action` = 服务端固定 `"处理工单"` - `remark` = 入参 `remark` - `operator_id` / `operator_snapshot` = 当前用户 - `started_at = now`, `completed_at = now` @@ -786,9 +794,9 @@ app/model/after_sale_detail.js → wms_after_sale_detail - `business_type = 'after_sale_detail'` - `business_id` = 刚写入的 `detail.id` - `file_id = attachment_id` -5. 若传入了 `status`,更新 `wms_after_sale.status` -6. 若当前 `role_group` ≠ `'customer_service'` 且 `status` ≠ `'completed'`,自动将 `role_group` 回设为 `'customer_service'`(仓库/财务处理完本环节后自动退回客服组继续跟进) -7. 若 `status = 'completed'`,同时写入 `resolution` 和 `resolved_at` +5. 更新 `wms_after_sale.status`:始终写入 safeStatus(默认 processing,白名单校验,不含 pending) +6. 若当前 `role_group` ≠ `'customer_service'` 且 status ≠ `'completed'`,自动将 `role_group` 回设为 `'customer_service'`(仓库/财务处理完本环节后自动退回客服组继续跟进) +7. 若 status = `'completed'`,同时写入 `resolution` 和 `resolved_at` ### 10.8 理赔登记 `afterSale.registerClaim` @@ -826,7 +834,7 @@ app/model/after_sale_detail.js → wms_after_sale_detail 1. 校验工单 `id` 存在 2. 从登录上下文提取操作人信息 3. 更新 `wms_after_sale` 中传入的非空理赔字段(`claim_needed/amount/status`、`carrier_claim_needed/amount/status`) -4. 写入 `wms_after_sale_detail`(step_status=2,action/remark/operator) +4. 写入 `wms_after_sale_detail`(step_status=主表当前 status,action/remark/operator) 5. 若有 `attachment_ids`,绑定到本次步骤 **使用场景:** diff --git a/database/migrations/20260809140000-add-after-sale-workorder-pages.js b/database/migrations/20260809140000-add-after-sale-workorder-pages.js new file mode 100644 index 0000000..370dd2f --- /dev/null +++ b/database/migrations/20260809140000-add-after-sale-workorder-pages.js @@ -0,0 +1,42 @@ +'use strict'; + +/** + * 新增售后模块页面权限(售后工单 + 工单列表)。 + * + * 新增: + * Web Pages: + * 524 — afterSale.workOrder 售后工单(根菜单) + * 525 — afterSale.workOrder.list 工单列表(子页面,parent_id=524) + * + * 幂等设计:使用 INSERT IGNORE,已存在的 id 不会重复插入。 + */ + +const TABLE = 'wms_permission'; +const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at'; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const pages = [ + [524, 'afterSale.workOrder', null, 'afterSale.workOrder', null, '售后工单', null, 0, 0, null, 'web_pages', 15, 1], + [525, 'afterSale.workOrder.list', null, 'afterSale.workOrder.list', null, '工单列表', null, 0, 0, 524, 'web_pages', 0, 1], + ]; + + for (const [id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status] of pages) { + await queryInterface.sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + { replacements: [id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status] } + ); + } + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + const ids = [524, 525]; + const placeholders = ids.map(() => '?').join(', '); + await queryInterface.sequelize.query( + `DELETE FROM \`${TABLE}\` WHERE id IN (${placeholders})`, + { replacements: ids } + ); + }, +}; diff --git a/database/migrations/20260809140100-grant-after-sale-workorder-pages.js b/database/migrations/20260809140100-grant-after-sale-workorder-pages.js new file mode 100644 index 0000000..1e4f238 --- /dev/null +++ b/database/migrations/20260809140100-grant-after-sale-workorder-pages.js @@ -0,0 +1,103 @@ +'use strict'; + +/** + * 为售后模块新增页面权限授权,并创建财务组角色。 + * + * 操作: + * 1. 新建财务组角色(role_code='finance') + * 2. 为以下角色追加页面权限 524 (afterSale.workOrder)、525 (afterSale.workOrder.list): + * - 经理 (role_code=2) + * - 客服组-主管 (role_code=05) + * - 客服组-员工 (role_code=04) + * - 仓库组-主管 (role_code=warehouse) + * - 仓库组-员工 (role_code=warehouse_role) + * - 生产组-主管 (role_code=03) + * - 生产组-拣货 (role_code=021) + * + * 幂等设计: + * - 财务组角色使用 INSERT IGNORE,已存在则跳过 + * - 权限追加使用 JSON_ARRAY_APPEND,不重复添加 + */ + +const NEW_PAGE_IDS = [524, 525]; + +// 财务组基础权限:block(518) + 所有web_pages(519,520,521,524,525) + 只读API(522,508) +const FINANCE_PERMISSIONS = [518, 519, 520, 521, 524, 525, 522, 508]; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const { sequelize } = queryInterface; + + // ── 1. 创建财务组角色(如果不存在)── + await sequelize.query(` + INSERT IGNORE INTO wms_role (role_code, role_name, description, role_type, scope, is_system, status, pid, created_by, permissions, created_at, updated_at) + VALUES ('finance', '财务组', '售后模块财务审核角色', 1, 1, 1, 1, 8, 1, ?, NOW(), NOW()) + `, { + replacements: [JSON.stringify(FINANCE_PERMISSIONS)], + }); + + // ── 2. 为已有角色追加页面权限 ── + const targetRoleCodes = ['2', '05', '04', 'warehouse', 'warehouse_role', '03', '021']; + + for (const roleCode of targetRoleCodes) { + for (const permId of NEW_PAGE_IDS) { + // 仅当该角色的 permissions 数组中不包含此权限ID时才追加 + // JSON_CONTAINS 检查是否已存在 + // 注意:permissions 列为 LONGTEXT,JSON 函数需显式 CAST + // 安全守卫:permissions 必须是合法 JSON 数组(以 [ 开头且非 NULL), + // 避免在非法 JSON(如旧版范围格式 [4-121])或 NULL 上执行 JSON_ARRAY_APPEND 导致权限被清空。 + await sequelize.query( + `UPDATE wms_role + SET permissions = JSON_ARRAY_APPEND(CAST(permissions AS JSON), '$', CAST(? AS UNSIGNED)), + updated_at = NOW() + WHERE role_code = ? + AND permissions IS NOT NULL + AND permissions != '' + AND permissions != '*' + AND JSON_VALID(permissions) = 1 + AND LEFT(permissions, 1) = '[' + AND JSON_CONTAINS(CAST(permissions AS JSON), CAST(? AS JSON), '$') = 0`, + { replacements: [permId, roleCode, String(permId)] } + ); + } + } + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + const { sequelize } = queryInterface; + + // ── 1. 移除财务组角色 ── + await sequelize.query( + "DELETE FROM wms_role WHERE role_code = 'finance'" + ); + + // ── 2. 从各角色移除页面权限 ── + const targetRoleCodes = ['2', '05', '04', 'warehouse', 'warehouse_role', '03', '021']; + + for (const roleCode of targetRoleCodes) { + for (const permId of NEW_PAGE_IDS) { + // 从 JSON 数组中移除指定值(MySQL 5.7+ 无直接 JSON_REMOVE_BY_VALUE,用 JSON_SEARCH) + // 注意:permissions 列为 LONGTEXT,JSON 函数需显式 CAST + // 安全守卫:同 up(),防止在非法 JSON 上操作 + await sequelize.query( + `UPDATE wms_role + SET permissions = JSON_REMOVE( + CAST(permissions AS JSON), + REPLACE(JSON_UNQUOTE(JSON_SEARCH(CAST(permissions AS JSON), 'one', CAST(? AS CHAR), NULL, '$')), '', '') + ), + updated_at = NOW() + WHERE role_code = ? + AND permissions IS NOT NULL + AND permissions != '' + AND permissions != '*' + AND JSON_VALID(permissions) = 1 + AND LEFT(permissions, 1) = '[' + AND JSON_CONTAINS(CAST(permissions AS JSON), CAST(? AS JSON), '$') = 1`, + { replacements: [permId, roleCode, String(permId)] } + ); + } + } + }, +}; diff --git a/database/migrations/20260810140000-alter-wms-after-sale-detail-step-status-to-varchar.js b/database/migrations/20260810140000-alter-wms-after-sale-detail-step-status-to-varchar.js new file mode 100644 index 0000000..eeff6e7 --- /dev/null +++ b/database/migrations/20260810140000-alter-wms-after-sale-detail-step-status-to-varchar.js @@ -0,0 +1,27 @@ +'use strict'; + +const TABLE_NAME = 'wms_after_sale_detail'; + +module.exports = { + up: async queryInterface => { + // 将 step_status 从 TINYINT 改为 VARCHAR(20),与 wms_after_sale.status 枚举保持一致 + // 使用原生 SQL 一步完成:改类型 + 更新已有数据为 processing + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` MODIFY COLUMN step_status VARCHAR(20) NOT NULL DEFAULT 'processing' COMMENT '步骤记录时售后主表的状态,与 wms_after_sale.status 一致: pending | processing | pending_feedback | completed | closed | cancelled'` + ); + // 已有数据(原 TINYINT 值)统一回填为 processing + await queryInterface.sequelize.query( + `UPDATE \`${TABLE_NAME}\` SET step_status = 'processing'` + ); + }, + + down: async queryInterface => { + // 回退:先更新数据,再改回 TINYINT + await queryInterface.sequelize.query( + `UPDATE \`${TABLE_NAME}\` SET step_status = '2'` + ); + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` MODIFY COLUMN step_status TINYINT(3) UNSIGNED NOT NULL DEFAULT 2 COMMENT '步骤状态:0=待开始,1=进行中,2=已完成,3=已跳过'` + ); + }, +}; diff --git a/database/migrations/20260811100000-add-followup-at-to-wms-after-sale.js b/database/migrations/20260811100000-add-followup-at-to-wms-after-sale.js new file mode 100644 index 0000000..b90618d --- /dev/null +++ b/database/migrations/20260811100000-add-followup-at-to-wms-after-sale.js @@ -0,0 +1,17 @@ +'use strict'; + +const TABLE_NAME = 'wms_after_sale'; + +module.exports = { + up: async queryInterface => { + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` ADD COLUMN followup_at DATETIME NULL DEFAULT NULL COMMENT '下次跟进时间:设为 pending_feedback 时可指定,超时后需二次跟进' AFTER resolved_at` + ); + }, + + down: async queryInterface => { + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` DROP COLUMN followup_at` + ); + }, +}; diff --git a/database/migrations/20260811120000-add-ext-data-to-inbox-group.js b/database/migrations/20260811120000-add-ext-data-to-inbox-group.js new file mode 100644 index 0000000..402f25e --- /dev/null +++ b/database/migrations/20260811120000-add-ext-data-to-inbox-group.js @@ -0,0 +1,20 @@ +'use strict'; + +const TABLE_NAME = 'wms_inbox_group'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const columns = await queryInterface.describeTable(TABLE_NAME); + if (columns.ext_data) return; + + await queryInterface.addColumn(TABLE_NAME, 'ext_data', { + type: Sequelize.JSON, + allowNull: true, + comment: '群扩展数据(IM平台信息等)', + }); + }, + + down: async queryInterface => { + await queryInterface.removeColumn(TABLE_NAME, 'ext_data'); + }, +}; diff --git a/database/migrations/20260812120000-add-order-id-to-after-sale.js b/database/migrations/20260812120000-add-order-id-to-after-sale.js new file mode 100644 index 0000000..0b0c1f8 --- /dev/null +++ b/database/migrations/20260812120000-add-order-id-to-after-sale.js @@ -0,0 +1,16 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_after_sale', 'order_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '订单ID(关联 wms_order.id),快递反馈建单时从 wms_order_express.order_id 填入', + after: 'waybill_no', + }); + }, + + async down(queryInterface) { + await queryInterface.removeColumn('wms_after_sale', 'order_id'); + }, +}; diff --git a/methods/changes/system.json b/methods/changes/system.json index 6879912..a22f3e1 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,99 @@ [ + { + "version": "2026.08.12-confirmIntercept-doc", + "date": "2026-08-12", + "type": "updated", + "summary": "order.recheckOrder.confirmIntercept 文档描述补全:补充释放储位分配、释放订单锁等副作用说明,明确各副作用失败不阻断主流程的容错语义", + "methods": [ + "order.recheckOrder.confirmIntercept" + ], + "notes": [ + "description 补充:拦截成功后会释放储位分配(cancelAllocateStorage)与订单锁(lock_status=none)", + "description 补充:储位释放、锁释放、日志写入失败均不影响主流程(try/catch 容错)", + "仅文档变更,不修改业务代码" + ], + "module": "order" + }, + { + "version": "2026.08.12-interceptScan", + "date": "2026-08-12", + "type": "added", + "summary": "order.recheckOrder.interceptScan 新增拦截扫描接口:通过运单号查找运单,标记退回+拦截(is_back='Y', is_intercept='Y');运单记录不存在时自动创建补充;处理关联售后工单(写入「库内拦截成功」并完结);订单级拦截覆盖所有面单含子面单(与 confirmIntercept 一致)", + "methods": [ + "order.recheckOrder.interceptScan" + ], + "notes": [ + "入参:waybill_code(string, required),运单号", + "运单记录不存在时自动创建(INSERT wms_order_express),而非抛 404,确保缺失快递被补充", + "同时设置 is_back='Y' 和 is_intercept='Y'", + "查 wms_after_sale 表(未完结工单),命中则调用 handleWorkOrder 写入「库内拦截成功」步骤并置 status=completed;工单处理失败不阻断主流程", + "订单拦截与 confirmIntercept 一致:只要有 order_id 即更新 wms_order_delivery.intercept_status = intercepted_at_warehouse,并释放储位分配与订单锁,写入 ORDER_INTERCEPT_CONFIRM 操作日志;不再区分 business_key,子面单同样会触发订单级拦截", + "免权限/免日志/免鉴权(与 confirmIntercept 同级)", + "代码变更:recheckOrder.js 构造函数 + interceptScan 方法(~180行);methods/system.json 新增 API 文档" + ], + "module": "order" + }, + { + "version": "2026.08.10-storageTransaction-keyword", + "date": "2026-08-10", + "type": "updated", + "summary": "storage.transaction.list 新增 keyword 快捷搜索参数,支持按 item_code(商品编码) 和 barcode(条码) 模糊匹配,内部解析为 stock_id 列表后以 IN 条件合并到查询中", + "methods": [ + "storage.transaction.list" + ], + "notes": [ + "新增 keyword 参数(string, optional),搜索范围为 stock_warehouse.item_code + stock_barcodes.barcode", + "keyword 解析复用已有 _resolveKeywordToStockIds 方法,与 stock.report.search 的 keyword 解析逻辑一致", + "keyword 可与 where 条件叠加使用(交集),无匹配结果时直接返回空列表", + "代码变更:stock_transaction.js list() 增加 keyword 参数并在 baseWhere 中注入 stock_id IN 条件;systemMethods/storage/transaction.js 透传 keyword" + ], + "module": "storage" + }, + { + "version": "2026.08.10-stockTransaction-keyword-doc", + "date": "2026-08-10", + "type": "updated", + "summary": "stock.transaction.list 补全 keyword 快捷搜索参数文档。代码层已支持 keyword(通过 queryList → _resolveKeywordToStockIds),本次仅补文档", + "methods": [ + "stock.transaction.list" + ], + "notes": [ + "新增 where.keyword 参数文档(string, optional),搜索范围为 stock_warehouse.item_code/item_name/goods_code + stock_barcodes.barcode + SKU ID", + "keyword 解析复用已有 _resolveKeywordToStockIds 方法,与 stock.report.search 逻辑一致", + "keyword 与 stock_ids 互斥(keyword 优先),无匹配结果时返回空列表", + "仅文档变更,不修改业务代码" + ], + "module": "stock" + }, + { + "version": "2026.08.09-afterSale-doc", + "date": "2026-08-09", + "type": "updated", + "summary": "补全 afterSale 组全部 11 个 method 的文档:workList/auditList/detail/create/transfer/handleWorkOrder/registerClaim/export/exportTaskProgress/workCount 的 params 与 response 补全 description,移除 create 中冗余 warehouse_id 参数(后端自动注入),明确各枚举值、关联表、业务语义。", + "methods": [ + "afterSale.workList", + "afterSale.auditList", + "afterSale.detail", + "afterSale.create", + "afterSale.transfer", + "afterSale.handleWorkOrder", + "afterSale.registerClaim", + "afterSale.export", + "afterSale.exportTaskProgress", + "afterSale.workCount" + ], + "notes": [ + "afterSale.create:移除 warehouse_id 参数(后端从 ctx.user.store_id 自动注入),补全所有 12 个参数的 description(含 type/sub_type 枚举值),response 新增 status 和 role_group 字段。", + "afterSale.transfer:补全 id/role_group/remark 的 description,response 新增 role_group 字段。", + "afterSale.handleWorkOrder:补全 action/status/attachment_ids 的 description,明确 action 示例和 status 枚举。", + "afterSale.registerClaim:补全 10 个参数的 description,明确 claim_status/carrier_claim_status 枚举值(pending/reviewing/approved/paid/monthly/rejected)。", + "afterSale.workList/auditList:补全 pagination/where/sort 与 response 的 description。", + "afterSale.export/exportTaskProgress:补全参数和响应的 description,明确 task_id 用途。", + "afterSale.workCount:已有完整 description,本次未修改。", + "仅文档变更,不修改任何业务代码或接口语义。" + ], + "module": "afterSale" + }, { "version": "2026.08.07-stockout-express", "date": "2026-08-07", @@ -5415,5 +5510,248 @@ "apiApp.update: sign_method 字段改为不可修改,传入即报错", "apiApp.list / apiApp.detail: sign_method 响应描述更新为「当前仅支持 md5」" ] + }, + { + "version": "2026.08.10-afterSale-handleWorkOrder-remove-action", + "date": "2026-08-10", + "type": "changed", + "summary": "afterSale.handleWorkOrder 移除 action 参数:action 不再由前端传入,改为服务端固定写入\"处理工单\";处理说明统一使用 remark 字段。", + "methods": [ + "afterSale.handleWorkOrder" + ], + "notes": [ + "移除 action 参数(原为必填 string,前端传入操作动作描述),前端不再需要也不接受此参数。", + "步骤记录的 action 字段由服务端在 systems/afterSale.js handleWorkOrder 中硬编码为\"处理工单\"。", + "处理说明统一使用 remark 字段承载。", + "代码变更:systemMethods/afterSale.js handleWorkOrder 移除 action 解构与必填校验;systems/afterSale.js handleWorkOrder 移除 message 参数,addStep action 固定为\"处理工单\"。" + ], + "module": "afterSale" + }, + { + "version": "2026.08.10-afterSale-handleWorkOrder-status-whitelist", + "date": "2026-08-10", + "type": "changed", + "summary": "afterSale.handleWorkOrder 新增 status 枚举白名单校验:status 必须与 wms_after_sale 主表 AFTER_SALE_STATUS 枚举一致(pending/processing/completed/closed/cancelled),补全 cancelled 枚举值文档。", + "methods": [ + "afterSale.handleWorkOrder" + ], + "notes": [ + "status 参数新增枚举白名单校验:从 AfterSale.AFTER_SALE_STATUS 取 key 列表,不在白名单内返回 400。", + "文档 status 枚举值补全 cancelled,与主表模型保持一致(pending | processing | completed | closed | cancelled)。", + "校验同时在 systemMethods/afterSale.js(方法层)和 systems/afterSale.js(业务层)两层生效。", + "仅代码校验增强 + 文档修正,不改变业务语义。" + ], + "module": "afterSale" + }, + { + "version": "2026.08.10-afterSale-handleWorkOrder-status-default-processing", + "date": "2026-08-10", + "type": "changed", + "summary": "afterSale.handleWorkOrder status 参数改为容错模式:不填或填错时默认 processing(处理中),不再返回 400 错误。status 始终写入主表。", + "methods": [ + "afterSale.handleWorkOrder" + ], + "notes": [ + "status 参数行为变更:原来不传时保持当前状态(有 if 判断),现在不填或填错默认 processing,始终写入主表。", + "校验方式从白名单拒绝改为容错兜底:safeStatus = (targetStatus 合法) ? targetStatus : 'processing'。", + "updateFields.status 从条件写入改为始终写入 safeStatus。", + "role_group 回退判断同步从 targetStatus 改为 safeStatus。", + "代码变更:systemMethods/afterSale.js + systems/afterSale.js 两层均改为容错逻辑。" + ], + "module": "afterSale" + }, + { + "version": "2026.08.10-afterSale-handleWorkOrder-exclude-pending", + "date": "2026-08-10", + "type": "changed", + "summary": "afterSale.handleWorkOrder status 白名单排除 pending:pending 是创建默认值(表示尚未处理),处理工单时不允许回退到此状态。", + "methods": [ + "afterSale.handleWorkOrder" + ], + "notes": [ + "handleWorkOrder 允许的 status 从全部 AFTER_SALE_STATUS 中排除 pending,剩余:processing | completed | closed | cancelled。", + "若前端传 status=pending 视为填错,容错兜底为 processing。", + "代码变更:两处 ALLOWED_STATUSES 增加 .filter(s => s !== 'pending')。" + ], + "module": "afterSale" + }, + { + "version": "2026.08.10-afterSale-step-status-align-main-table", + "date": "2026-08-10", + "type": "changed", + "summary": "wms_after_sale_detail.step_status 改为与 wms_after_sale.status 完全一致:字段类型从 TINYINT 改为 VARCHAR(20),每次写入步骤时记录主表当前 status 快照。", + "methods": [ + "afterSale.handleWorkOrder" + ], + "notes": [ + "DB 迁移:20260810140000-alter-wms-after-sale-detail-step-status-to-varchar.js — step_status 从 TINYINT UNSIGNED 改为 STRING(20),已有数据回填 processing。", + "Model:after_sale_detail.js 移除 TINYINT 引用,step_status 改为 STRING(20),STEP_STATUS 枚举对齐主表 AFTER_SALE_STATUS。", + "addStep 默认值从 2 改为 'processing'。", + "transfer:step_status 取 update() 返回的 updated.status。", + "handleWorkOrder:step_status 取 safeStatus(与写入主表的 status 完全一致)。", + "registerClaim:step_status 取 afterSale.status(主表当前状态)。" + ], + "module": "afterSale" + }, + { + "version": "2026.08.11-afterSale-add-waiting-status", + "date": "2026-08-11", + "type": "added", + "summary": "新增 waiting(等待外部处理)状态:用于内部处理完成后等待外部第三方(快递、客户、平台)响应的场景。", + "methods": [ + "afterSale.handleWorkOrder" + ], + "notes": [ + "Model:after_sale.js AFTER_SALE_STATUS 新增 waiting: '等待外部处理'。", + "Model:after_sale_detail.js STEP_STATUS 同步新增 waiting。", + "handleWorkOrder 白名单自动包含 waiting(从 AFTER_SALE_STATUS 派生,仅排除 pending)。", + "状态流转:processing → waiting → processing/completed。", + "设计文档同步更新 ER 图、状态流转图、枚举表。" + ], + "module": "afterSale" + }, + { + "version": "2026.08.11-afterSale-rename-pending-feedback", + "date": "2026-08-11", + "type": "changed", + "summary": "waiting 重命名为 pending_feedback(等待外部反馈):语义更精确——内部已处理完并将信息发给外部,等待反馈后再决定是否继续处理,等待期间不需要内部介入。", + "methods": [ + "afterSale.handleWorkOrder" + ], + "notes": [ + "Model/DB/文档中 waiting 全部替换为 pending_feedback", + "workList/workCount 排除列表新增 pending_feedback(等待反馈期间不需要内部处理)", + "典型场景:客服收到拦截工单 → 发信息给运方 → 设为 pending_feedback 等待运方反馈 → 收到反馈后回到 processing 通知客户" + ], + "module": "afterSale" + }, + { + "version": "2026.08.11-afterSale-batchSetPendingFeedback", + "date": "2026-08-11", + "type": "added", + "summary": "新增 afterSale.batchSetPendingFeedback 批量设为待反馈接口:传入 ids 列表,按仓库 policy_config.after_sale_followup_hours 配置自动计算 followup_at,事务内批量更新状态并写入步骤记录。", + "methods": [ + "afterSale.batchSetPendingFeedback" + ], + "notes": [ + "新增 method:afterSale.batchSetPendingFeedback,入参 ids(number[])和 remark(string, optional)", + "业务层 systems/afterSale.js 新增 batchSetPendingFeedback:预校验 ids 有效性/终态/跨仓库,事务内逐条更新 status=pending_feedback + followup_at=NOW()+INTERVAL hours HOUR + 步骤记录", + "方法层 systemMethods/afterSale.js 新增 batchSetPendingFeedback:从 ctx.user 提取 operator 信息和 warehouseId,委托 systems 层执行", + "followup_at 时长复用现有 _resolveFollowupHours 三级查找:仓库 policy_config → 内置 DEFAULTS 映射 → 兜底 24h", + "终态工单(completed/closed/cancelled)不可设为待反馈,跨仓库工单被拒绝,均返回在 failed 列表中", + "已在 _noNeedRight 和 _noNeedAuth 中注册,写入操作会记录日志" + ], + "module": "afterSale" + }, + { + "version": "2026.08.11-afterSale-batchClose", + "date": "2026-08-11", + "type": "added", + "summary": "新增 afterSale.batchClose 批量完结/关闭接口:传入 ids + status(completed|closed),事务内批量更新状态、写入步骤记录,completed 时自动写入 resolved_at 并清除 followup_at。", + "methods": [ + "afterSale.batchClose" + ], + "notes": [ + "新增 method:afterSale.batchClose,入参 ids(number[])、status(completed|closed)、resolution(string, optional)、remark(string, optional)", + "业务层 systems/afterSale.js 新增 batchClose:预校验 ids 有效性/终态/跨仓库,事务内逐条更新 status + resolved_at + followup_at 清除 + 步骤记录", + "方法层 systemMethods/afterSale.js 新增 batchClose:从 ctx.user 提取 operator 信息和 warehouseId,委托 systems 层执行", + "终态工单(completed/closed/cancelled)不可重复完结/关闭,跨仓库工单被拒绝,均返回在 failed 列表中", + "已在 _noNeedRight 和 _noNeedAuth 中注册,写入操作会记录日志" + ], + "module": "afterSale" + }, + { + "version": "2026.08.11-afterSale-detail-enrich", + "date": "2026-08-11", + "type": "enhanced", + "summary": "enhance: afterSale.detail 响应新增 related 字段,自动补充关联订单详情(收件人/发件人/商品明细/打包视频)和货主合约备注(store_remask)。", + "methods": [ + "afterSale.detail" + ], + "notes": [ + "响应新增 related 对象:含 related.order(订单详情)和 related.store_contract(货主合约备注),仅在售后单有关联单据时有值", + "related.order.recipient:从 wms_order_delivery 提取收件人姓名/电话/手机/邮箱/省市区/详细地址", + "related.order.sender:从货主 store.subject_config 提取发件人信息(sender_name/sender_tel/地址)", + "related.order.current_table:根据 dispatch_status/outbound_status/status 判断订单当前所在表(main/dispatch/history)", + "related.order.items:从 order_delivery.items JSON 字段解析商品明细数组", + "related.order.pack_videos:通过 PackTask → PackTaskVideo 关联查询打包视频列表(含 video_url/camera_id)", + "related.store_contract:从 wms_store_warehouse 查询 store_remask(商家备注)/warehouse_remask(仓库备注)/使用状态", + "所有关联查询使用 try-catch 兜底,查询失败时仅打 warn 日志,不影响主流程", + "systems/afterSale.js 新增 _enrichAfterSaleDetail / _resolveOrderDetail / _resolveStoreContractNote 三个私有方法" + ], + "module": "afterSale" + }, + { + "version": "2026.08.11-afterSale-detail-waybill", + "date": "2026-08-11", + "type": "enhanced", + "summary": "enhance: afterSale.detail 响应 related 新增 waybill 字段,自动补充运单详情(快递公司名称 + 使用的物流接口)。", + "methods": [ + "afterSale.detail" + ], + "notes": [ + "响应 related 新增 related.waybill 字段(waybill_id 不为空时自动返回)", + "related.waybill.logistics_name:快递公司名称(如 圆通/中通/顺丰),来源 wms_order_express.logistics_name", + "related.waybill.logistics_interface_name:使用的物流接口名称,来源 wms_order_express.logistics_interface_name", + "related.waybill.logistics_code:物流编码,来源 wms_order_express.logistics_code", + "related.waybill 同时返回 waybill_code/status/is_back/is_intercept/create_at 等基础字段", + "systems/afterSale.js 新增 _resolveWaybillDetail 私有方法,查询失败仅打 warn 日志不影响主流程", + "仅文档 + 代码变更,不涉及数据库变更" + ], + "module": "afterSale" + }, + { + "version": "2026.08.11-afterSale-create-order-id-alias", + "date": "2026-08-11", + "type": "enhanced", + "summary": "enhance: afterSale.create 入参新增 order_id 别名,与 order_delivery_id 等效,优先取 order_delivery_id,为空时回退到 order_id。", + "methods": [ + "afterSale.create" + ], + "notes": [ + "create 方法解构时新增 order_id 别名读取;优先使用 order_delivery_id,为空时取 order_id", + "仅方法层变更(systemMethods/afterSale.js),业务层无改动", + "同时更新 JSDoc 注释,标注 order_delivery_id 兼容别名 order_id" + ], + "module": "afterSale" + }, + { + "version": "2026.08.11-inbox-group-update-subtype-enum", + "date": "2026-08-11", + "summary": "enhance: inbox.group.update 子类型枚举补全三层约束。groupType=store 可用 after_sales/finance/receiving,groupType=warehouse 新增 production/stockout/all/exception,groupType=express 补全 pickup/after_sales。同步更新 subType description 和 400 错误码描述", + "type": "enhance", + "methods": [ + "inbox.group.update" + ], + "notes": [ + "subType 枚举由 GROUP_TYPES 统一定义,与 AI 函数分组同源", + "后端已新增两层类型校验:subType 必须在对应 groupType 的合法子类型列表中" + ] + }, + { + "version": "2026.08.11-inbox-group-update-subtype-enum-v2", + "date": "2026-08-11", + "summary": "enhance: inbox.group.update 子类型枚举补全三层约束。groupType=store 可用 after_sales/finance/receiving,groupType=warehouse 新增 production/stockout/all/exception,groupType=express 补全 pickup/after_sales。同步更新 subType description 和 400 错误码描述", + "type": "enhance", + "methods": [ + "inbox.group.update" + ], + "notes": [ + "subType 枚举由 GROUP_TYPES 统一定义,与 AI 函数分组同源", + "后端已新增两层类型校验:subType 必须在对应 groupType 的合法子类型列表中" + ] + }, + { + "version": "2026.08.11-inbox-group-update-subtype-enum-v3", + "date": "2026-08-11", + "summary": "enhance: inbox.group.update 子类型枚举补全三层约束。groupType=store 可用 after_sales/finance/receiving,groupType=warehouse 新增 production/stockout/all/exception,groupType=express 补全 pickup/after_sales。同步更新 subType description 和 400 错误码描述", + "type": "enhance", + "methods": [ + "inbox.group.update" + ], + "notes": [ + "subType 枚举由 GROUP_TYPES 统一定义,与 AI 函数分组同源", + "后端已新增两层类型校验:subType 必须在对应 groupType 的合法子类型列表中" + ] } ] diff --git a/methods/system.json b/methods/system.json index 8145c8b..5044a83 100644 --- a/methods/system.json +++ b/methods/system.json @@ -2,7 +2,7 @@ "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", "version": "0.3.21", - "updatedAt": "2026-08-09", + "updatedAt": "2026-08-11", "headers": [ { "name": "platform", @@ -5925,7 +5925,7 @@ }, { "method": "order.recheckOrder.confirmIntercept", - "description": "确认拦截:通过订单ID直接匹配订单,将其拦截状态更新为 intercepted_at_warehouse(仓库已拦截)。仅拦截当前指定订单,不波及波次内其他订单。操作成功后写入操作日志(ORDER_INTERCEPT_CONFIRM),日志写入失败不影响主流程。", + "description": "确认拦截:通过订单ID直接匹配订单,将其拦截状态更新为 intercepted_at_warehouse(仓库已拦截),同时释放储位分配(cancelAllocateStorage)与订单锁(lock_status=none)。仅拦截当前指定订单,不波及波次内其他订单。操作成功后写入操作日志(ORDER_INTERCEPT_CONFIRM)。储位释放、锁释放、日志写入失败均不影响主流程。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -5988,6 +5988,67 @@ } ] }, + { + "method": "order.recheckOrder.interceptScan", + "description": "拦截扫描:通过运单号查找运单记录,标记退回与拦截(is_back='Y', is_intercept='Y')。运单记录不存在时自动创建补充。处理关联的未完结售后工单(写入「库内拦截成功」步骤并置为 completed)。同步更新订单拦截状态为 intercepted_at_warehouse 并释放储位分配与订单锁(与 confirmIntercept 一致,订单级拦截覆盖所有面单含子面单)。工单处理失败不阻断主流程。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "waybill_code", + "type": "string", + "required": true, + "source": "body", + "description": "运单号" + } + ], + "response": [ + { + "name": "waybill_code", + "type": "string", + "required": true, + "description": "运单号" + }, + { + "name": "is_back", + "type": "string", + "required": true, + "description": "退回标记(固定为 'Y')" + }, + { + "name": "is_intercept", + "type": "string", + "required": true, + "description": "拦截标记(固定为 'Y')" + }, + { + "name": "after_sale", + "type": "object|null", + "required": false, + "description": "关联的售后工单处理结果(仅当存在未完结工单时返回);工单处理失败时为 null" + }, + { + "name": "order", + "type": "object|null", + "required": false, + "description": "订单拦截结果(仅当运单关联到订单时返回),包含 order_id、order_no、intercept_status;无法关联订单时为 null" + } + ], + "errors": [ + { + "code": 400, + "message": "运单号不能为空" + } + ] + }, { "method": "order.recheckOrder.recheckOrderList", "description": "复核订单列表查询,通过入参 list_type 区分散单模式与团购模式。散单模式(single,默认)返回待复核订单列表(每项为一个订单,排除 pick_status='none' 和 recheck_status='fin'),团购模式(group)返回波次维度的复核汇总列表(每项为一个波次及其订单复核统计,含 review_assignment_status 计算字段)。统一使用 list 字段名输出,均支持分页与筛选。", @@ -10813,6 +10874,251 @@ "message": "内部错误" } ] + }, + { + "method": "order.deliveryOrder.quickSearch", + "description": "订单快速搜索。跨表联合搜索:运单号(wms_order_express 精确匹配)、发货单号/外部订单号/平台交易单号(dispatch 表模糊匹配)。返回匹配的订单列表(最多20条),包含关键字段及关联运单号。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { + "name": "keyword", + "type": "string", + "required": true, + "source": "body", + "description": "搜索关键词。同时匹配运单号(精确)、发货单号 delivery_order_code(模糊)、外部订单号 source_order_codes(模糊)、平台交易单号 pay_no(模糊)" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "匹配的订单列表", + "children": [ + { + "name": "order_id", + "type": "number", + "required": true, + "description": "订单ID" + }, + { + "name": "waybill_id", + "type": "number", + "required": true, + "description": "运单记录ID(wms_order_express.id),0=无关联运单" + }, + { + "name": "waybill_code", + "type": "string", + "required": true, + "description": "运单号" + }, + { + "name": "logistics_code", + "type": "string", + "required": true, + "description": "快递公司编码" + }, + { + "name": "logistics_name", + "type": "string", + "required": true, + "description": "快递公司名称" + }, + { + "name": "logistics_interface_id", + "type": "number", + "required": true, + "description": "快递接口ID" + }, + { + "name": "logistics_interface_name", + "type": "string", + "required": true, + "description": "快递接口名称" + }, + { + "name": "platform_code", + "type": "string", + "required": true, + "description": "平台编码" + }, + { + "name": "waybill_status", + "type": "number", + "required": true, + "description": "运单状态 0/1" + }, + { + "name": "waybill_status_text", + "type": "string", + "required": true, + "description": "运单状态文本" + }, + { + "name": "weighing_weight", + "type": "number", + "required": true, + "description": "称重重量(g)" + }, + { + "name": "delivery_order_code", + "type": "string", + "required": true, + "description": "发货单号" + }, + { + "name": "source_order_codes", + "type": "string", + "required": true, + "description": "原始平台订单号" + }, + { + "name": "pay_no", + "type": "string", + "required": true, + "description": "平台交易单号" + }, + { + "name": "store_id", + "type": "number", + "required": true, + "description": "货主ID" + }, + { + "name": "store_name", + "type": "string", + "required": true, + "description": "货主名称" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "订单状态" + }, + { + "name": "name", + "type": "string", + "required": true, + "description": "收件人" + }, + { + "name": "mobile", + "type": "string", + "required": true, + "description": "手机号" + }, + { + "name": "province", + "type": "string", + "required": true, + "description": "省" + }, + { + "name": "city", + "type": "string", + "required": true, + "description": "市" + }, + { + "name": "area", + "type": "string", + "required": true, + "description": "区" + }, + { + "name": "detail_address", + "type": "string", + "required": true, + "description": "详细地址" + }, + { + "name": "buyer_nick", + "type": "string", + "required": true, + "description": "买家昵称" + }, + { + "name": "seller_nick", + "type": "string", + "required": true, + "description": "卖家昵称" + }, + { + "name": "shop_nick", + "type": "string", + "required": true, + "description": "店铺名称" + }, + { + "name": "total_amount", + "type": "number", + "required": true, + "description": "订单总金额" + }, + { + "name": "item_amount", + "type": "number", + "required": true, + "description": "商品金额" + }, + { + "name": "freight", + "type": "number", + "required": true, + "description": "运费" + }, + { + "name": "items_count", + "type": "number", + "required": true, + "description": "商品件数" + }, + { + "name": "items_weight", + "type": "number", + "required": true, + "description": "商品总重量(g)" + }, + { + "name": "wave_no", + "type": "string", + "required": true, + "description": "波次号" + }, + { + "name": "delivery_time", + "type": "string", + "required": true, + "description": "发货时间" + }, + { + "name": "create_at", + "type": "string", + "required": true, + "description": "创建时间" + } + ] + }, + { + "name": "keyword", + "type": "string", + "required": true, + "description": "回显搜索关键词" + } + ], + "errors": [ + { + "code": 400, + "message": "缺少 keyword 参数或仓库上下文" + }, + { + "code": 500, + "message": "搜索失败" + } + ] } ] }, @@ -17102,7 +17408,7 @@ }, { "method": "stock.transaction.list", - "description": "商品出入库流水列表查询(wms_stock_transaction),支持 where 条件筛选与分页", + "description": "商品出入库流水列表查询(wms_stock_transaction),支持 where 条件筛选与分页,支持 keyword 快捷搜索", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -17152,6 +17458,12 @@ "required": false, "description": "商品库存ID数组,为空或未传表示不筛选" }, + { + "name": "keyword", + "type": "string", + "required": false, + "description": "快捷搜索关键字,支持按商品编码(item_code)、商品名称(item_name)、货物编码(goods_code)、条码(barcode)、SKU ID 模糊匹配。内部解析为 stock_id 列表后以 IN 条件合并查询。与 stock_ids 互斥(keyword 优先)" + }, { "name": "transaction_type", "type": "string", @@ -18904,6 +19216,66 @@ } ] }, + { + "method": "pickCart.batchDelete", + "description": "批量删除拣货车。已绑定任务的拣货车将被跳过,不会删除。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "array", + "required": true, + "source": "body", + "description": "拣货车ID列表,如 [1,2,3]" + } + ], + "response": [ + { + "name": "deleted_ids", + "type": "array", + "required": true, + "description": "成功删除的拣货车ID列表" + }, + { + "name": "skipped_ids", + "type": "array", + "required": true, + "description": "跳过的拣货车ID列表(已绑定任务或存在有效绑定记录)" + }, + { + "name": "deleted_count", + "type": "number", + "required": true, + "description": "成功删除数量" + }, + { + "name": "skipped_count", + "type": "number", + "required": true, + "description": "跳过数量" + } + ], + "errors": [ + { + "code": 400, + "message": "ids 参数不合法或缺少仓库上下文。" + }, + { + "code": 500, + "message": "批量删除失败。" + } + ] + }, { "method": "pickCart.detail", "description": "查询拣货车详情。", @@ -22791,7 +23163,7 @@ }, { "method": "storage.transaction.list", - "description": "出入库记录列表查询,支持 where 条件、分页、排序、批次分组切换。默认按库位合并数量(合并模式),group_by_batch=true 时返回每条明细(明细模式)", + "description": "出入库记录列表查询,支持 where 条件、keyword 快捷搜索、分页、排序、批次分组切换。默认按库位合并数量(合并模式),group_by_batch=true 时返回每条明细(明细模式)", "name": "出入库流水记录列表", "isNeedAuth": false, "isNeedLogin": true, @@ -22804,6 +23176,13 @@ "source": "body", "description": "统一 where 条件对象,可用字段:transaction_type(ENUM INBOUND/OUTBOUND)、stock_id、space_id、store_id、order_type(SCRK/MATCH)、order_no、inventory_type(ZP/CC/JS/XS/ZT/DJ/FP)、operator_name、created_at(支持 between)" }, + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "快捷搜索关键字,支持按商品编码(item_code)、条码(barcode)模糊匹配。内部先解析为 stock_id 列表,再以 IN 条件合并到 where 中。与 where.stock_id/stock_ids 可叠加使用(交集)" + }, { "name": "pagination", "type": "object", @@ -30452,7 +30831,13 @@ "name": "order_no", "type": "string", "required": true, - "description": "订单号(来自 delivery_order_code 快照列)" + "description": "订单号。优先取 wms_order_express.delivery_order_code(快照列),为空时回退取 source_order_codes" + }, + { + "name": "source_order_codes", + "type": "string", + "required": true, + "description": "原始订单号(平台订单号),来自 wms_order_express.source_order_codes 快照列" }, { "name": "warehouse_id", @@ -30470,13 +30855,13 @@ "name": "store_id", "type": "number", "required": true, - "description": "货主ID(来自 store_id_snapshot 快照列)" + "description": "货主ID(来自 wms_order_express.store_id)" }, { "name": "store_name", "type": "string", "required": true, - "description": "货主名称(来自 store_name_snapshot 快照列)" + "description": "货主名称。通过订单ID批量关联订单发货表(current/history/dispatch)获取 store_name 字段" }, { "name": "business_key", @@ -32119,7 +32504,7 @@ ] }, { - "groupName": "站内信模块", + "groupName": "站内信", "module": "inbox", "list": [ { @@ -32955,7 +33340,7 @@ }, { "method": "inbox.group.update", - "description": "修改群信息:群类型/子类型/货主/快递接口/系统快递编码/AI开关。aiEnabled支持灰度控制,切换为express类型时systemExpressCode必填", + "description": "修改群信息:群类型/子类型/货主/快递接口/系统快递编码/AI开关。子类型受群类型约束,合法取值见 groupType.list[].subTypes。aiEnabled支持灰度控制,切换为express类型时systemExpressCode必填", "isNeedAuth": true, "isNeedLogin": true, "headers": [ @@ -32979,14 +33364,82 @@ "type": "string", "required": false, "source": "body", - "description": "群类型:store(货主) / warehouse(仓库) / express(快递)" + "description": "群类型:store(货主群) / warehouse(仓库群) / express(快递群)", + "list": [ + { + "value": "store", + "description": "货主群", + "subTypes": [ + { + "value": "after_sales", + "description": "售后" + }, + { + "value": "finance", + "description": "财务" + }, + { + "value": "receiving", + "description": "收货" + } + ] + }, + { + "value": "warehouse", + "description": "仓库群", + "subTypes": [ + { + "value": "receiving", + "description": "收货" + }, + { + "value": "production", + "description": "生产" + }, + { + "value": "stockout", + "description": "出库" + }, + { + "value": "finance", + "description": "财务" + }, + { + "value": "all", + "description": "全体" + }, + { + "value": "customer_service", + "description": "客服" + }, + { + "value": "exception", + "description": "异常" + } + ] + }, + { + "value": "express", + "description": "快递群", + "subTypes": [ + { + "value": "pickup", + "description": "揽收" + }, + { + "value": "after_sales", + "description": "售后" + } + ] + } + ] }, { "name": "subType", "type": "string", "required": false, "source": "body", - "description": "群子类型:after_sales(售后) / finance(财务) / receiving(收货)" + "description": "群子类型,值取决于groupType。store→after_sales(售后)/finance(财务)/receiving(收货)。warehouse→receiving(收货)/production(生产)/stockout(出库)/finance(财务)/all(全体)/customer_service(客服)/exception(异常)。express→pickup(揽收)/after_sales(售后)" }, { "name": "storeId", @@ -33028,11 +33481,11 @@ "errors": [ { "code": "400", - "message": "群ID无效 / 系统快递编码不能为空(express类型时)" + "message": "群ID无效 / 子类型不在对应群类型的合法范围内 / 系统快递编码不能为空(express类型时)" }, { "code": "500", - "message": "群不存在 / 系统快递编码不存在 / 快递接口ID无效" + "message": "群不存在或无权限操作 / 系统快递编码不存在 / 快递接口ID无效" } ] }, @@ -33595,7 +34048,7 @@ ] }, { - "groupName": "售后管理", + "groupName": "售后模块", "module": "afterSale", "list": [ { @@ -33604,13 +34057,41 @@ "isNeedAuth": false, "isNeedLogin": true, "params": [ - { "name": "pagination", "type": "object", "required": false, "source": "body", "description": "分页参数 page/pageSize" }, - { "name": "where", "type": "object", "required": false, "source": "body", "description": "筛选条件:type/sub_type/status/priority/after_sale_no/waybill_no 等" }, - { "name": "sort", "type": "object", "required": false, "source": "body", "description": "排序参数 sortField/sortOrder" } + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页 { page: 1, pageSize: 20 }" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "可选筛选字段: type/sub_type/status/priority/after_sale_no/waybill_no/store_id/claim_status/carrier_claim_status" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序 { sortField: 'id'|'priority'|'created_at', sortOrder: 'asc'|'desc' }" + } ], "response": [ - { "name": "list", "type": "array", "required": true }, - { "name": "pagination", "type": "object", "required": true } + { + "name": "list", + "type": "array", + "required": true, + "description": "售后单列表,每条含主表字段 + detail_count" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息 { page, pageSize, total, totalPages }" + } ] }, { @@ -33619,120 +34100,462 @@ "isNeedAuth": false, "isNeedLogin": true, "params": [ - { "name": "pagination", "type": "object", "required": false, "source": "body" }, - { "name": "where", "type": "object", "required": false, "source": "body", "description": "同 workList,额外支持 claim_status/carrier_claim_status" }, - { "name": "sort", "type": "object", "required": false, "source": "body" } + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页 { page: 1, pageSize: 20 }" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "可选筛选字段: type/sub_type/status/priority/after_sale_no/waybill_no/store_id/role_group/claim_status/carrier_claim_status。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序 { sortField: 'id'|'priority'|'created_at', sortOrder: 'asc'|'desc' }" + } ], "response": [ - { "name": "list", "type": "array", "required": true }, - { "name": "pagination", "type": "object", "required": true } + { + "name": "list", + "type": "array", + "required": true, + "description": "全局售后单列表" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息 { page, pageSize, total, totalPages }" + } ] }, { "method": "afterSale.detail", - "description": "售后明细(主表+步骤列表+附件)。", + "description": "售后单明细查询:返回主表信息、步骤列表(含附件)、关联详情(订单/运单/货主合约)。关联数据按 afterSale 中的 order_delivery_id / waybill_id / store_id 自动解析,任一查询失败不影响主流程。", "isNeedAuth": false, "isNeedLogin": true, + "headers": [], "params": [ - { "name": "id", "type": "integer", "required": true, "source": "body", "description": "售后工单主表ID" } + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "售后单主键ID" + } ], "response": [ - { "name": "after_sale", "type": "object", "required": true, "description": "主表数据" }, - { "name": "steps", "type": "array", "required": true, "description": "步骤列表(含附件)" } + { + "name": "after_sale", + "type": "object", + "required": true, + "description": "售后主表完整记录(含格式化时间字段)" + }, + { + "name": "steps", + "type": "array", + "required": true, + "description": "售后进度步骤列表(含附件 attachments),按创建时间升序", + "list": [ + { + "value": "object", + "label": "{ id, after_sale_id, step_status, operator_id, action, remark, attachments: [{id,file_url,file_name}] }" + } + ] + }, + { + "name": "related", + "type": "object", + "required": true, + "description": "关联单据详情。仅在售后单关联了对应业务单据时有值,其他情况为空对象。" + }, + { + "name": "related.order", + "type": "object", + "required": false, + "description": "关联发货订单详情(order_delivery_id 不为空时)。含 delivery_order_code、status、current_table(main/dispatch/history)、recipient(收件人)、sender(发件人,从货主 subject_config 取)、items(订单商品明细数组)、pack_videos(打包视频列表)" + }, + { + "name": "related.waybill", + "type": "object", + "required": false, + "description": "关联运单详情(waybill_id 不为空时)。含 waybill_code、logistics_name(快递公司名称)、logistics_code(物流编码)、logistics_interface_name(使用的物流接口)、logistics_interface_id、status、is_back、is_intercept" + }, + { + "name": "related.store_contract", + "type": "object", + "required": false, + "description": "货主合约备注(store_id + warehouse_id 匹配时)。含 contract_id、store_remask(商家备注)、warehouse_remask(仓库备注)、store_use_status、warehouse_use_status" + } + ], + "errors": [ + { + "code": 404, + "message": "售后单不存在" + } ] }, { "method": "afterSale.create", - "description": "创建售后单。", + "description": "创建售后单:生成售后单号(AS+YYYYMMDD+6位序号),写入主表记录。warehouse_id 由服务端从 ctx.user.store_id 自动注入。关联单据ID可自动同步对应单号(如传 order_delivery_id 自动查 delivery_order_code)。role_group 默认 customer_service,status 默认 pending。", "isNeedAuth": false, "isNeedLogin": true, + "headers": [], "params": [ - { "name": "warehouse_id", "type": "integer", "required": true, "source": "body" }, - { "name": "store_id", "type": "integer", "required": false, "source": "body" }, - { "name": "type", "type": "string", "required": true, "source": "body", "description": "order/receiving/entry/stockout" }, - { "name": "sub_type", "type": "string", "required": true, "source": "body" }, - { "name": "priority", "type": "integer", "required": false, "source": "body" }, - { "name": "title", "type": "string", "required": true, "source": "body" }, - { "name": "description", "type": "string", "required": false, "source": "body" }, - { "name": "waybill_id", "type": "integer", "required": false, "source": "body" }, - { "name": "order_delivery_id", "type": "integer", "required": false, "source": "body" }, - { "name": "entry_order_id", "type": "integer", "required": false, "source": "body" }, - { "name": "order_stockout_id", "type": "integer", "required": false, "source": "body" }, - { "name": "receiving_id", "type": "integer", "required": false, "source": "body" }, - { "name": "inbox_message_id", "type": "integer", "required": false, "source": "body" } + { + "name": "type", + "type": "string", + "required": true, + "source": "body", + "description": "售后类型:order | receiving | entry | stockout" + }, + { + "name": "sub_type", + "type": "string", + "required": true, + "source": "body", + "description": "售后子类型,与 type 组成二级分类,详见模型枚举" + }, + { + "name": "title", + "type": "string", + "required": true, + "source": "body", + "description": "售后标题(简要描述)" + }, + { + "name": "description", + "type": "string", + "required": false, + "source": "body", + "description": "售后详细描述" + }, + { + "name": "priority", + "type": "integer", + "required": false, + "source": "body", + "description": "优先级,默认0(0=普通,10=紧急)" + }, + { + "name": "order_delivery_id", + "type": "integer", + "required": false, + "source": "body", + "description": "关联发货订单ID,兼容别名 order_id" + }, + { + "name": "waybill_id", + "type": "integer", + "required": false, + "source": "body", + "description": "关联运单ID(wms_order_express.id)" + }, + { + "name": "entry_order_id", + "type": "integer", + "required": false, + "source": "body", + "description": "关联入库单ID" + }, + { + "name": "order_stockout_id", + "type": "integer", + "required": false, + "source": "body", + "description": "关联出库单ID" + }, + { + "name": "receiving_id", + "type": "integer", + "required": false, + "source": "body", + "description": "关联收货单ID" + }, + { + "name": "store_id", + "type": "integer", + "required": false, + "source": "body", + "description": "关联货主ID" + }, + { + "name": "inbox_message_id", + "type": "integer", + "required": false, + "source": "body", + "description": "关联站内信ID" + } ], "response": [ - { "name": "id", "type": "integer", "required": true }, - { "name": "after_sale_no", "type": "string", "required": true } - ] + { + "name": "after_sale_no", + "type": "string", + "required": true, + "description": "售后单号" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "售后状态,创建默认 pending" + }, + { + "name": "role_group", + "type": "string", + "required": true, + "description": "角色组,创建默认 customer_service" + }, + { + "name": "id", + "type": "integer", + "required": true, + "description": "售后单主键ID" + } + ], + "errors": [] }, { "method": "afterSale.transfer", - "description": "转单(更新 role_group)。", + "description": "转单:将售后工单转给其他角色组处理。转单后原角色组不可见,目标角色组可见。", "isNeedAuth": false, "isNeedLogin": true, "params": [ - { "name": "id", "type": "integer", "required": true, "source": "body" }, - { "name": "role_group", "type": "string", "required": true, "source": "body", "description": "customer_service/warehouse/finance" }, - { "name": "remark", "type": "string", "required": false, "source": "body" } + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "售后工单主表ID" + }, + { + "name": "role_group", + "type": "string", + "required": true, + "source": "body", + "description": "目标角色组: customer_service(客服组) | warehouse(仓库组) | finance(财务组)" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "转单备注/原因" + } ], "response": [ - { "name": "after_sale_id", "type": "integer", "required": true } + { + "name": "after_sale_id", + "type": "integer", + "required": true, + "description": "售后工单ID" + }, + { + "name": "role_group", + "type": "string", + "required": true, + "description": "更新后的 role_group" + } ] }, { "method": "afterSale.handleWorkOrder", - "description": "处理售后工单(写步骤+绑附件+自动转回客服)。", + "description": "处理售后工单:写入进度步骤并绑定附件。操作人信息从登录上下文自动获取。非客服组处理完成后自动将 role_group 回退到 customer_service;status=completed 时自动写入 resolution + resolved_at。步骤 action 由服务端固定为\"处理工单\",step_status 与主表 status 完全一致。status 不填或填错时默认 processing。新增 pending_feedback 状态用于内部处理完成等待外部反馈(如已将拦截信息发给运方,等待运方反馈后再决定是否继续处理)。", "isNeedAuth": false, "isNeedLogin": true, + "headers": [], "params": [ - { "name": "id", "type": "integer", "required": true, "source": "body" }, - { "name": "status", "type": "string", "required": false, "source": "body", "description": "更新状态" }, - { "name": "action", "type": "string", "required": true, "source": "body" }, - { "name": "remark", "type": "string", "required": false, "source": "body" }, - { "name": "attachment_ids", "type": "array", "required": false, "source": "body", "description": "附件 file_id 数组" } + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "售后工单主表ID" + }, + { + "name": "status", + "type": "string", + "required": false, + "source": "body", + "description": "更新售后单状态: processing | pending_feedback | completed | closed | cancelled。不填或填错默认 processing。不含 pending(创建默认值)。pending_feedback=等待外部反馈" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "处理备注" + }, + { + "name": "attachment_ids", + "type": "array", + "required": false, + "source": "body", + "description": "附件 file_id 数组,如 [123, 456]。自动绑定到本次步骤" + } ], "response": [ - { "name": "detail_id", "type": "integer", "required": true }, - { "name": "after_sale_id", "type": "integer", "required": true } - ] + { + "name": "detail_id", + "type": "integer", + "required": true, + "description": "本次写入的步骤ID(wms_after_sale_detail.id)" + }, + { + "name": "after_sale_id", + "type": "integer", + "required": true, + "description": "售后工单ID" + } + ], + "errors": [] }, { "method": "afterSale.registerClaim", - "description": "登记售后理赔信息(仓库+运方一次性填入)。", + "description": "登记售后理赔信息:一次性填入仓库理赔和运方理赔字段,同时写入进度步骤。两套理赔可同时填写(双赔场景)。", "isNeedAuth": false, "isNeedLogin": true, "params": [ - { "name": "id", "type": "integer", "required": true, "source": "body" }, - { "name": "claim_needed", "type": "integer", "required": false, "source": "body" }, - { "name": "claim_amount", "type": "number", "required": false, "source": "body" }, - { "name": "claim_status", "type": "string", "required": false, "source": "body" }, - { "name": "carrier_claim_needed", "type": "integer", "required": false, "source": "body" }, - { "name": "carrier_claim_amount", "type": "number", "required": false, "source": "body" }, - { "name": "carrier_claim_status", "type": "string", "required": false, "source": "body" }, - { "name": "action", "type": "string", "required": true, "source": "body" }, - { "name": "remark", "type": "string", "required": false, "source": "body" }, - { "name": "attachment_ids", "type": "array", "required": false, "source": "body" } + { + "name": "id", + "type": "integer", + "required": true, + "source": "body", + "description": "售后工单主表ID" + }, + { + "name": "claim_needed", + "type": "integer", + "required": false, + "source": "body", + "description": "仓库理赔标记: 0=不需要, 1=需要" + }, + { + "name": "claim_amount", + "type": "number", + "required": false, + "source": "body", + "description": "仓库理赔金额(元)" + }, + { + "name": "claim_status", + "type": "string", + "required": false, + "source": "body", + "description": "仓库理赔状态: pending | reviewing | approved | paid | monthly | rejected" + }, + { + "name": "carrier_claim_needed", + "type": "integer", + "required": false, + "source": "body", + "description": "运方理赔标记: 0=不需要, 1=需要" + }, + { + "name": "carrier_claim_amount", + "type": "number", + "required": false, + "source": "body", + "description": "运方理赔金额(元)" + }, + { + "name": "carrier_claim_status", + "type": "string", + "required": false, + "source": "body", + "description": "运方理赔状态: pending | reviewing | approved | paid | monthly | rejected" + }, + { + "name": "action", + "type": "string", + "required": true, + "source": "body", + "description": "操作动作描述,如\"登记仓库理赔\"、\"登记运方理赔\"" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "处理备注,如\"快递破损核定赔200元\"" + }, + { + "name": "attachment_ids", + "type": "array", + "required": false, + "source": "body", + "description": "附件 file_id 数组(破损照片、理赔单据等)" + } ], "response": [ - { "name": "detail_id", "type": "integer", "required": true }, - { "name": "after_sale_id", "type": "integer", "required": true } + { + "name": "detail_id", + "type": "integer", + "required": true, + "description": "本次写入的步骤ID" + }, + { + "name": "after_sale_id", + "type": "integer", + "required": true, + "description": "售后工单ID" + } ] }, { "method": "afterSale.export", - "description": "提交售后审计列表导出任务(异步)。返回 task_id。", + "description": "提交售后审计列表导出任务(异步)。返回 task_id,通过 exportTaskProgress 查询进度。", "isNeedAuth": false, "isNeedLogin": true, "params": [ - { "name": "where", "type": "object", "required": false, "source": "body" }, - { "name": "sort", "type": "object", "required": false, "source": "body" } + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选条件,同 auditList.where" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序,同 auditList.sort" + } ], "response": [ - { "name": "task_id", "type": "string", "required": true }, - { "name": "status", "type": "string", "required": true }, - { "name": "progress", "type": "number", "required": true }, - { "name": "message", "type": "string", "required": true } + { + "name": "task_id", + "type": "string", + "required": true, + "description": "导出任务ID,用于轮询进度" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "pending | processing | completed | failed" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "进度百分比 0-100" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "状态说明" + } ] }, { @@ -33741,14 +34564,180 @@ "isNeedAuth": false, "isNeedLogin": true, "params": [ - { "name": "task_id", "type": "string", "required": true, "source": "body" } + { + "name": "task_id", + "type": "string", + "required": true, + "source": "body", + "description": "export 接口返回的 task_id" + } ], "response": [ - { "name": "task_id", "type": "string", "required": true }, - { "name": "status", "type": "string", "required": true }, - { "name": "progress", "type": "number", "required": true }, - { "name": "download_url", "type": "string", "required": false } + { + "name": "task_id", + "type": "string", + "required": true, + "description": "导出任务ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "pending | processing | completed | failed" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "进度百分比 0-100" + }, + { + "name": "download_url", + "type": "string", + "required": false, + "description": "完成后的文件下载链接(仅 status=completed 时返回)" + } ] + }, + { + "method": "afterSale.workCount", + "description": "快速查询当前用户待处理售后工单数量(角标用),返回count字段,前端>99显示99+。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [], + "response": [ + { + "name": "count", + "type": "integer", + "required": true + } + ] + }, + { + "method": "afterSale.batchSetPendingFeedback", + "description": "批量将售后工单设为“待反馈”状态,按仓库 policy_config.after_sale_followup_hours 配置自动计算每个工单的 followup_at(下次跟进时间)。所有工单在同一事务中处理,任一失败则全部回滚。终态工单(completed/closed/cancelled)不可回退、跨仓库工单会被拒绝并返回 failed 列表。非客服组工单自动将 role_group 回设为 customer_service。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "ids", + "type": "array", + "required": true, + "source": "body", + "description": "售后单主键ID列表,如 [1, 2, 3]。非正整数会被自动过滤。", + "list": [ + { + "value": "number", + "label": "售后单ID(正整数)" + } + ] + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "统一处理备注,所有工单共用同一备注内容" + } + ], + "response": [ + { + "name": "total", + "type": "integer", + "required": true, + "description": "传入的工单总数(过滤非正整数后)" + }, + { + "name": "success", + "type": "integer", + "required": true, + "description": "成功设为待反馈的工单数量" + }, + { + "name": "failed", + "type": "array", + "required": true, + "description": "失败的工单列表,每项包含 id 和 reason", + "list": [ + { + "value": "object", + "label": "{ id: number, reason: string }" + } + ] + } + ], + "errors": [] + }, + { + "method": "afterSale.batchClose", + "description": "批量将售后工单完结或关闭。status=completed 时自动写入 resolved_at 并清除 followup_at;status=closed 时仅更新状态。所有工单在同一事务中处理,任一失败则全部回滚。终态工单(completed/closed/cancelled)不可重复操作、跨仓库工单会被拒绝并返回 failed 列表。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "ids", + "type": "array", + "required": true, + "source": "body", + "description": "售后单主键ID列表,如 [1, 2, 3]。非正整数会被自动过滤。", + "list": [ + { + "value": "number", + "label": "售后单ID(正整数)" + } + ] + }, + { + "name": "status", + "type": "string", + "required": true, + "source": "body", + "description": "目标状态:completed=完结(写入 resolved_at + resolution),closed=关闭(仅更新状态,不写入完结信息)" + }, + { + "name": "resolution", + "type": "string", + "required": false, + "source": "body", + "description": "完结处理结果说明,仅 status=completed 时写入" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "统一处理备注,所有工单共用同一备注内容" + } + ], + "response": [ + { + "name": "total", + "type": "integer", + "required": true, + "description": "传入的工单总数(过滤非正整数后)" + }, + { + "name": "success", + "type": "integer", + "required": true, + "description": "成功操作的工单数量" + }, + { + "name": "failed", + "type": "array", + "required": true, + "description": "失败的工单列表,每项包含 id 和 reason", + "list": [ + { + "value": "object", + "label": "{ id: number, reason: string }" + } + ] + } + ], + "errors": [] } ] }