From bcf6a5b38484b53be24e66f504c0411978827c63 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 13 Aug 2026 23:13:07 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=9F=A5=E9=80=80=E5=9B=9E=E6=98=8E?= =?UTF-8?q?=E7=BB=86=EF=BC=88queryReturn=EF=BC=89+=20=E9=80=80=E5=9B=9E?= =?UTF-8?q?=E6=8B=86=E5=8C=85=E5=BD=95=E6=98=8E=E7=BB=86=E6=9D=A1=E7=A0=81?= =?UTF-8?q?=E4=B8=8E=E8=AE=A2=E5=8D=95=E4=BF=A1=E6=81=AF=E5=BF=AB=E7=85=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 站内信新增 queryReturn(查退回+运单号):跨退回相关表查询(拆包/退回收到/退回查询登记),未退回自动预登记,未收到时回填退回登记表货主 - 模板消息直发机制 direct_reply:函数返回模板原样回复,不经 AI 改写 - 退回拆包 addDetail 支持 barcode(仅作记录)、未指定 stock_id 标注未知商品、跨货主 stock_id 403 - wms_return_unpack 新增 source_order_codes/shop_name 快照(迁移 20260813170000),原单退回时回填 - ai.js 加固:DeepSeek 推理模型 max_tokens 提升、截断/空 JSON 重试、查询类请求强制调函数规则 - 新增调试脚本 script/debug-inbox-push.cjs;同步 methods 文档与变更记录 --- app/model/return_unpack.js | 10 + app/service/inbox/ai.js | 45 ++- app/service/inbox/functions.js | 94 +++++ app/service/systemMethods/returnUnpack.js | 5 +- app/service/systems/return_unpack.js | 364 +++++++++++++++++- ...0813170000-add-return-unpack-order-info.js | 36 ++ methods/changes/system.json | 48 +++ methods/system.json | 17 +- script/debug-inbox-push.cjs | 243 ++++++++++++ 9 files changed, 844 insertions(+), 18 deletions(-) create mode 100644 database/migrations/20260813170000-add-return-unpack-order-info.js create mode 100644 script/debug-inbox-push.cjs diff --git a/app/model/return_unpack.js b/app/model/return_unpack.js index 60316b7..6772771 100644 --- a/app/model/return_unpack.js +++ b/app/model/return_unpack.js @@ -100,6 +100,16 @@ module.exports = app => { allowNull: true, comment: '货主ID,原单退回/识别到系统商品时回填', }, + source_order_codes: { + type: STRING(500), + allowNull: true, + comment: '平台交易单号快照(原单退回时回填)', + }, + shop_name: { + type: STRING(50), + allowNull: true, + comment: '店铺名称快照(货主自定义店铺名称 store_remask)', + }, camera_ids: { type: JSON_TYPE, allowNull: true, diff --git a/app/service/inbox/ai.js b/app/service/inbox/ai.js index fc41d87..8d25d1f 100644 --- a/app/service/inbox/ai.js +++ b/app/service/inbox/ai.js @@ -44,6 +44,17 @@ class InboxAIService extends Service { } let content = result.data.choices?.[0]?.message?.content || ''; + const reasoning = result.data.choices?.[0]?.message?.reasoning_content || ''; + const finishReason = result.data.choices?.[0]?.finish_reason || ''; + + // 推理模型会把 max_tokens 消耗在 reasoning 上,导致 content 为空(finish_reason=length) + if (!content.trim() && finishReason === 'length') { + ctx.logger.warn( + `[inbox ai] DeepSeek 输出被截断: reasoning=${reasoning.length} 字符, content 为空, finish_reason=length` + ); + throw new Error('DeepSeek 输出被截断(max_tokens 被推理过程占满),请提高 max_tokens'); + } + // 清理 markdown 代码块 content = content.replace(/^```json\s*/i, '').replace(/\s*```$/i, ''); content = content.replace(/^```\s*/i, '').replace(/\s*```$/i, ''); @@ -185,6 +196,7 @@ class InboxAIService extends Service { let finalReply = null; let lastFunctionName = null; let lastFunctionResult = null; + let jsonRetryNote = ''; const systemPrompt = `你是一个 WMS 仓库管理系统的智能助手,支持多步推理。 已注册函数:\n${functionListText}\n @@ -241,7 +253,10 @@ ${historyContext} - 用户说"第1个""第2个"时,按 searchStock 返回的顺序对应选择 - 需要上下文但记忆不足时,主动调用 recallHistory 回顾对话历史 - 【防误判规则 - interceptWaybill】讨论已有售后工单(AS开头编号)、询问物流进度、问"快递到哪了"、转发售后截图等均不是拦截请求,严禁调用 interceptWaybill。只有用户明确说"拦截/退回/召回/追回/取消"运单时才可调用 -- 【措辞规则 - interceptWaybill】拦截结果回复严禁使用"已拦截""拦截成功"等确定口吻,必须使用"拦截信息已登记""已提交拦截申请"等措辞。因为快递拦截可能失败,实际结果以快递公司反馈为准。回复时需列出工单号供用户跟进`; +- 【措辞规则 - interceptWaybill】拦截结果回复严禁使用"已拦截""拦截成功"等确定口吻,必须使用"拦截信息已登记""已提交拦截申请"等措辞。因为快递拦截可能失败,实际结果以快递公司反馈为准。回复时需列出工单号供用户跟进 +- 【模板消息 - queryReturn】queryReturn 返回的 data.message 是已排版好的模板消息,必须原样作为最终回复输出,禁止改写、删减、增补内容,禁止添加 Markdown 或额外说明 +- 用户发送"查退回+运单号"时,调用 queryReturn 查询退回明细,不要误调 queryOrder 或 interceptWaybill +- 【查询类请求强制调函数】查订单/查退回/查库存等查询类请求必须实际调用对应函数获取结果后再回复,严禁仅凭历史对话或猜测臆测"服务不可用/无法处理"而跳过函数调用`; // 多轮推理循环 for (let round = 1; round <= MAX_ROUNDS; round++) { @@ -261,7 +276,7 @@ ${historyContext} ...(contextLines.length > 0 ? [{ role: 'system', content: contextLines.join('\n') }] : []), { role: 'user', content: round === 1 ? content - : (executedFunctions.length > 0 + : (jsonRetryNote ? `${jsonRetryNote}\n` : '') + (executedFunctions.length > 0 ? `已获取到函数执行结果,请根据结果 reply 告知用户(禁止 silent)。第 ${round}/${MAX_ROUNDS} 轮` : `请根据已获取的信息,决定下一步:继续调用函数还是给出最终回复。第 ${round}/${MAX_ROUNDS} 轮`), }, @@ -269,7 +284,8 @@ ${historyContext} let raw = ''; try { - raw = await this.callDeepSeek(messages, { maxTokens: 600 }); + // 推理模型(deepseek-v4-pro)需要充足 max_tokens:推理过程会先占用配额,过小会导致 content 被截断为空 + raw = await this.callDeepSeek(messages, { maxTokens: 4000 }); ctx.logger.info(`[inbox ai] 第 ${round}/${MAX_ROUNDS} 轮: ${raw}`); const result = JSON.parse(raw); @@ -318,6 +334,19 @@ ${historyContext} if (lastThought) lastThought.functionResult = lastFunctionResult; ctx.logger.info(`[inbox ai] 执行 ${fnName}: ${JSON.stringify(lastFunctionResult)}`); + // 函数携带模板消息(direct_reply=true)→ 直接作为最终回复,不再交由 AI 改写 + const directReply = lastFunctionResult + && lastFunctionResult.data + && lastFunctionResult.data.direct_reply === true + && lastFunctionResult.data.message + ? String(lastFunctionResult.data.message) + : ''; + if (directReply) { + ctx.logger.info(`[inbox ai] 函数 ${fnName} 返回模板消息,直接回复 (length=${directReply.length})`); + finalReply = directReply; + break; + } + // 最后一轮强制输出 if (round === MAX_ROUNDS) { finalReply = lastFunctionResult?.data?.message @@ -333,9 +362,15 @@ ${historyContext} } catch (error) { ctx.logger.warn(`[inbox ai] 第 ${round} 轮异常: ${error.message}, raw: ${raw}`); - // 不是 JSON → 当作文本回复 + // 模型输出疑似被截断的 JSON → 提醒后重试,避免把原始 JSON 当作回复发给用户 if (error instanceof SyntaxError && raw) { - finalReply = raw; + const trimmedRaw = String(raw).trim(); + if (trimmedRaw.startsWith('{') || trimmedRaw.startsWith('[')) { + jsonRetryNote = '上一轮模型输出不是合法 JSON(疑似截断),请重新输出完整合法的纯 JSON,不要包含任何额外文字'; + continue; + } + // 不是 JSON → 当作文本回复 + finalReply = trimmedRaw; break; } diff --git a/app/service/inbox/functions.js b/app/service/inbox/functions.js index d10c39c..a577cbd 100644 --- a/app/service/inbox/functions.js +++ b/app/service/inbox/functions.js @@ -1193,6 +1193,100 @@ class InboxFunctionsService extends Service { }, }); + this.register('queryReturn', { + description: '查询退回包裹明细(查退回)。用户发送"查退回+运单号"时调用。传入运单号,查询退回收到/退回拆包/未退回登记状态:已拆包返回拆包明细与录像地址模板消息,未退回则自动登记到退回查询表。注意:仅查询退回状态使用,与 interceptWaybill 拦截、queryOrder 订单查询不同', + weight: 90, + keywords: [ '查退回', '查退件', '退回查询', '退回明细', '查拆包', '退件查询', '退回进度' ], + params: { + waybill_code: { type: 'string', required: true, description: '退回包裹运单号,如"查退回 465570943491370"中的465570943491370' }, + }, + groups: [ GROUP.COMMON ], + handler: async (params = {}) => { + const { ctx } = this; + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const storeId = Number(ctx.inboxContext?.store_id || 0); + + let raw = String(params.waybill_code || '').trim(); + if (!raw) return { success: false, error: '请提供退回包裹运单号' }; + + // 兼容把"查退回 123456"整体传入的情况 + const match = raw.match(/查退[回件]\s*[::]?\s*(.+)$/); + if (match) raw = String(match[1]).trim(); + // 去掉空白与常见中文标点,保留运单号本体(字母/数字/横线等) + const waybill = raw.replace(/[\s,,。;;]+/g, ''); + if (!waybill) return { success: false, error: '未解析到有效运单号' }; + if (!warehouseId) return { success: false, error: '无法获取仓库信息' }; + + try { + const result = await ctx.service.systems.returnUnpack.queryByWaybill({ + waybill_code: waybill, + warehouse_id: warehouseId, + store_id: storeId, + }); + + const warehouseLabel = result.warehouse_name || '仓库'; + let message = ''; + + if (result.status === 'unpacked') { + const unpack = result.unpack || {}; + const details = result.details || []; + const videos = result.videos || []; + const orderInfo = result.order_info || {}; + + const lines = []; + lines.push(`${waybill}已在已退件中登记,登记信息为:`); + lines.push(''); + lines.push(`运单号:${waybill}`); + lines.push(`是否原单:${unpack.order_express_id ? '是' : '否'}`); + lines.push(`交易单号:${orderInfo.trade_no || ''}`); + lines.push(`快递:${orderInfo.express || ''}`); + lines.push(`店铺名称:${orderInfo.shop_name || ''}`); + lines.push(`${warehouseLabel}收到且已拆包,拆包明细为:`); + if (details.length > 0) { + for (const detail of details) { + lines.push(`商品名称:${detail.item_name || ''}`); + lines.push(`条码:${detail.barcode || ''}`); + lines.push(`数量:${detail.quantity || 0}`); + lines.push(`是否破损:${detail.product_status === 'damaged' ? '是' : '否'}`); + } + } else { + lines.push('暂无拆包明细,拆包完成后可再次查询'); + } + lines.push(''); + lines.push('退件录像地址为:'); + if (videos.length > 0) { + for (const video of videos) { + if (video.video_url) lines.push(String(video.video_url)); + } + } else { + lines.push('暂无'); + } + lines.push('拆包视频保存会有延迟,可以在稍后发送:查退回+运单号,查询'); + message = lines.join('\n'); + } else if (result.status === 'received') { + message = `包裹${waybill}已收到未拆包,拆包登记后,将自动发送通知拆包信息`; + } else if (result.status === 'not_returned') { + message = `${waybill}尚未退回仓库,已在未退回表中登记成功,等待包裹退件登记后,将自动发送通知包裹信息`; + } else { + message = `未查询到运单号${waybill}的退回信息,请核实单号后重试`; + } + + return { + success: true, + data: { + status: result.status, + waybill_code: waybill, + message, + direct_reply: true, + }, + }; + } catch (error) { + ctx.logger.error(`[inbox functions] 退回查询失败: ${error.message}`); + return { success: false, error: `退回查询失败: ${error.message}` }; + } + }, + }); + this.register('cancelIntercept', { description: '取消拦截运单(支持批量)。当用户要求"取消拦截/撤销拦截/不拦截了"时调用。先查已有售后工单,有则追加取消记录,无则按拦截规则创建工单。同时设置订单和运单拦截状态并通知快递群', weight: 94, diff --git a/app/service/systemMethods/returnUnpack.js b/app/service/systemMethods/returnUnpack.js index 39884be..e8d6a0e 100644 --- a/app/service/systemMethods/returnUnpack.js +++ b/app/service/systemMethods/returnUnpack.js @@ -66,15 +66,16 @@ class ReturnUnpackMethodService extends MainService { * @param {Object} data 请求体。 * @param {number} data.id 拆包单ID。 * @param {number} [data.stock_id] 系统商品ID(wms_stock_warehouse.id)。 + * @param {string} [data.barcode] 扫描条码(stock_id 为空时按条码反查商品)。 * @param {number} [data.quantity] 数量。 * @param {string} [data.product_status] 产品状态 normal/damaged。 * @param {string} [data.remark] 备注。 * @return {Promise} 统一 success 包装。 */ async addDetail(data = {}) { - const { id, stock_id, quantity, product_status, remark } = data; + const { id, stock_id, barcode, quantity, product_status, remark } = data; return this._call( - () => this.service.systems.returnUnpack.addDetail({ id, stock_id, quantity, product_status, remark }), + () => this.service.systems.returnUnpack.addDetail({ id, stock_id, barcode, quantity, product_status, remark }), '录明细失败' ); } diff --git a/app/service/systems/return_unpack.js b/app/service/systems/return_unpack.js index 413046c..4a5bd96 100644 --- a/app/service/systems/return_unpack.js +++ b/app/service/systems/return_unpack.js @@ -68,16 +68,18 @@ class ReturnUnpackService extends Service { let orderExpressId = null; let orderId = null; let storeId = null; + let sourceOrderCodes = null; try { const orderExpress = await ctx.model.OrderExpress.findOne({ where: { waybill_code: waybillCode }, - attributes: [ 'id', 'order_id', 'store_id' ], + attributes: [ 'id', 'order_id', 'store_id', 'source_order_codes' ], raw: true, }); if (orderExpress) { orderExpressId = orderExpress.id; orderId = orderExpress.order_id; storeId = orderExpress.store_id; + sourceOrderCodes = orderExpress.source_order_codes || null; } } catch (err) { ctx.logger.warn(`[returnUnpack.create] 反查原运单失败: ${err.message}`); @@ -132,6 +134,8 @@ class ReturnUnpackService extends Service { order_express_id: orderExpressId, order_id: orderId, store_id: storeId, + source_order_codes: sourceOrderCodes, + shop_name: storeRemark || null, camera_ids: normalizedCameraIds, remark: remark ? String(remark).slice(0, 500) : null, }; @@ -184,22 +188,26 @@ class ReturnUnpackService extends Service { /** * 录明细:以拆包单ID为依据录入一条明细(识别到系统商品时回填快照)。 + * 仅以 stock_id 识别商品;不指定 stock_id 时一律标注未知商品, + * 不做条码自动匹配(同一商品可能存在多条条码记录/多个 stock_id,自动匹配易误配)。 * * @param {Object} params 明细参数。 * @param {number} params.id 拆包单ID。 - * @param {number} [params.stock_id] 系统商品ID(wms_stock_warehouse.id),为空即无关联货物。 + * @param {number} [params.stock_id] 系统商品ID(wms_stock_warehouse.id),为空即无关联货物(商品名称标注未知商品)。 + * @param {string} [params.barcode] 扫描条码(仅作记录,不参与商品匹配)。 * @param {number} [params.quantity] 数量,默认 1。 * @param {string} [params.product_status] 产品状态 normal/damaged,默认 normal。 * @param {string} [params.remark] 备注。 * @return {Promise} 明细ID + 明细行 + 主表最新汇总。 */ - async addDetail({ id, stock_id, quantity, product_status, remark }) { + async addDetail({ id, stock_id, barcode, quantity, product_status, remark }) { const { ctx } = this; const unpack = await this._findByIdChecked(id); this._assertUnpacking(unpack); const normalizedStockId = stock_id ? Number(stock_id) : null; + const normalizedBarcode = barcode ? String(barcode).trim().slice(0, 100) : null; const normalizedQuantity = Math.max(1, parseInt(quantity) || 1); const normalizedStatus = product_status === 'damaged' ? 'damaged' : 'normal'; @@ -239,19 +247,25 @@ class ReturnUnpackService extends Service { item_type: stock.item_type || '', }); - // 主表货主为空时回填(首个识别商品确定货主) + // 主表货主为空时回填(首个识别商品确定货主),并同步回填自定义店铺名称快照 if (currentStoreId === 0 && stockStoreId > 0) { + const backfillFields = { store_id: stockStoreId }; + const shopName = await this._resolveStoreRemark(stockStoreId, unpack.warehouse_id); + if (shopName) backfillFields.shop_name = shopName; await ctx.model.ReturnUnpack.update( - { store_id: stockStoreId }, + backfillFields, { where: { id: unpack.id } } ); } + } else { + // 未指定系统商品:一律标注未知商品,不做条码自动匹配(同条码可能对应多个 stock_id,易误配) + itemName = '未知商品'; } const created = await ctx.model.ReturnUnpackDetail.create({ unpack_id: unpack.id, warehouse_id: unpack.warehouse_id, - barcode: null, + barcode: normalizedBarcode, stock_id: normalizedStockId, is_recognized: isRecognized, item_code: itemCode, @@ -599,6 +613,344 @@ class ReturnUnpackService extends Service { }; } + /** + * 查询退回明细(按运单号,跨退回相关表汇总)。 + * 依次查询:拆包主表+明细+视频(已拆包)→ 退回收到表(已收到未拆包)→ 退回查询登记表(未退回)。 + * 未退回且无登记记录时自动登记到 wms_return_query_log,等待拆包后处理。 + * + * @param {Object} params 查询参数。 + * @param {string} params.waybill_code 退回包裹运单号(必填)。 + * @param {number} params.warehouse_id 仓库ID(必填)。 + * @param {number} [params.store_id] 货主ID(可选,用于货主隔离与未退回登记)。 + * @return {Promise} { status, waybill_code, warehouse_name, ... }。 + * status:unpacked(已拆包)/ received(已收到未拆包)/ not_returned(未退回)/ hidden(跨货主不可见)。 + */ + async queryByWaybill({ waybill_code, warehouse_id, store_id } = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const waybillCode = String(waybill_code || '').trim(); + if (!waybillCode) { + throw this.createBusinessError('waybill_code 不能为空', 400); + } + + const warehouseId = Number(warehouse_id || 0); + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少仓库上下文', 400); + } + const storeId = Number(store_id || 0); + + const warehouseName = await this._resolveWarehouseName(warehouseId); + + // 1. 已拆包:同一运单号取最新一条有效拆包单(跳过已作废) + const unpack = await ctx.model.ReturnUnpack.findOne({ + where: { + warehouse_id: warehouseId, + waybill_code: waybillCode, + status: { [Op.ne]: 'cancelled' }, + }, + order: [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]], + raw: true, + }); + + if (unpack) { + // 货主隔离:限定货主查询且拆包单已归属其他货主 → 不暴露数据 + if (storeId > 0 && Number(unpack.store_id || 0) > 0 && Number(unpack.store_id) !== storeId) { + return { status: 'hidden', waybill_code: waybillCode, warehouse_name: warehouseName }; + } + + const details = await ctx.model.ReturnUnpackDetail.findAll({ + where: { unpack_id: unpack.id }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const videos = await ctx.model.ReturnUnpackVideo.findAll({ + where: { unpack_id: unpack.id, deleted_at: null }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + let received = null; + if (unpack.return_received_id) { + received = await ctx.model.ReturnReceived.findOne({ + where: { id: unpack.return_received_id }, + raw: true, + }); + } + + const orderInfo = await this._resolveReturnOrderInfo({ + order_express_id: unpack.order_express_id, + order_id: unpack.order_id, + warehouse_id: warehouseId, + store_id: unpack.store_id, + source_order_codes: unpack.source_order_codes, + shop_name: unpack.shop_name, + }); + + return { + status: 'unpacked', + waybill_code: waybillCode, + warehouse_name: warehouseName, + unpack, + details, + videos, + received, + order_info: orderInfo, + }; + } + + // 2. 已收到未拆包:退回收到表登记过 + const received = await ctx.model.ReturnReceived.findOne({ + where: { warehouse_id: warehouseId, waybill_code: waybillCode }, + order: [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]], + raw: true, + }); + + if (received) { + if (storeId > 0 && Number(received.store_id || 0) > 0 && Number(received.store_id) !== storeId) { + return { status: 'hidden', waybill_code: waybillCode, warehouse_name: warehouseName }; + } + + // 货主确定优先级:入参 store_id > 退回登记表 store_id > 原运单反查 store_id > 0(未知) + let resolvedStoreId = storeId || Number(received.store_id || 0); + if (!resolvedStoreId) { + resolvedStoreId = await this._resolveStoreIdByWaybill(waybillCode, warehouseId); + } + + // 退回登记表货主为空 → 回填变更(后续拆包/通知依赖货主) + if (Number(received.store_id || 0) <= 0 && resolvedStoreId > 0) { + try { + await ctx.model.ReturnReceived.update( + { store_id: resolvedStoreId }, + { where: { id: received.id } } + ); + received.store_id = resolvedStoreId; + ctx.logger.info( + `[returnUnpack.queryByWaybill] 退回登记表回填货主: id=${received.id} store_id=${resolvedStoreId}` + ); + } catch (err) { + ctx.logger.warn(`[returnUnpack.queryByWaybill] 回填退回登记表货主失败: ${err.message}`); + } + } + + // 照常登记退回查询记录(幂等:已存在则不重复创建) + let queryLog = await ctx.model.ReturnQueryLog.findOne({ + where: { warehouse_id: warehouseId, waybill_code: waybillCode }, + order: [[ 'id', 'DESC' ]], + raw: true, + }); + if (!queryLog) { + try { + const created = await ctx.model.ReturnQueryLog.create({ + warehouse_id: warehouseId, + store_id: resolvedStoreId || 0, + waybill_code: waybillCode, + remark: '站内信查询退回自动登记(已收到未拆包)', + is_notified: 0, + is_back: 0, + }); + queryLog = created && typeof created.toJSON === 'function' ? created.toJSON() : created; + } catch (err) { + ctx.logger.warn(`[returnUnpack.queryByWaybill] 已收到未拆包登记退回查询记录失败: ${err.message}`); + } + } + + const orderInfo = await this._resolveReturnOrderInfo({ + order_express_id: received.order_express_id, + order_id: received.order_id, + warehouse_id: warehouseId, + store_id: resolvedStoreId || Number(received.store_id || 0), + }); + + return { + status: 'received', + waybill_code: waybillCode, + warehouse_name: warehouseName, + received, + query_log: queryLog, + order_info: orderInfo, + }; + } + + // 3. 未退回:查询退回查询登记表,无登记则自动登记(等待拆包后处理) + const queryLog = await ctx.model.ReturnQueryLog.findOne({ + where: { warehouse_id: warehouseId, waybill_code: waybillCode }, + order: [[ 'id', 'DESC' ]], + raw: true, + }); + + if (queryLog) { + return { + status: 'not_returned', + waybill_code: waybillCode, + warehouse_name: warehouseName, + query_log: queryLog, + registered_now: false, + }; + } + + // 货主确定优先级:入参 store_id > 原运单反查 store_id > 0(未知货主) + let regStoreId = storeId; + if (!regStoreId) { + regStoreId = await this._resolveStoreIdByWaybill(waybillCode, warehouseId); + } + + let createdRow = null; + try { + const created = await ctx.model.ReturnQueryLog.create({ + warehouse_id: warehouseId, + store_id: regStoreId || 0, + waybill_code: waybillCode, + remark: '站内信查询退回自动登记', + is_notified: 0, + is_back: 0, + }); + createdRow = created && typeof created.toJSON === 'function' ? created.toJSON() : created; + } catch (err) { + // 并发/异常兜底:登记失败不影响查询结论,回查已有登记 + ctx.logger.warn(`[returnUnpack.queryByWaybill] 自动登记退回查询记录失败: ${err.message}`); + try { + createdRow = await ctx.model.ReturnQueryLog.findOne({ + where: { warehouse_id: warehouseId, waybill_code: waybillCode }, + order: [[ 'id', 'DESC' ]], + raw: true, + }); + } catch (e) { + ctx.logger.warn(`[returnUnpack.queryByWaybill] 回查退回查询记录失败: ${e.message}`); + } + } + + return { + status: 'not_returned', + waybill_code: waybillCode, + warehouse_name: warehouseName, + query_log: createdRow, + registered_now: Boolean(createdRow), + }; + } + + /** + * 解析仓库名称(wms_store.company_name)。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 仓库名称,查询失败返回空字符串。 + */ + async _resolveWarehouseName(warehouseId) { + const { ctx } = this; + try { + const store = await ctx.model.Store.findOne({ + where: { id: warehouseId }, + attributes: [ 'company_name' ], + raw: true, + }); + return store && store.company_name ? String(store.company_name) : ''; + } catch (err) { + ctx.logger.warn(`[returnUnpack._resolveWarehouseName] 查询仓库名称失败: ${err.message}`); + return ''; + } + } + + /** + * 按运单号反查货主(wms_order_express)。 + * + * @param {string} waybillCode 运单号。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 货主ID,未命中返回 0。 + */ + async _resolveStoreIdByWaybill(waybillCode, warehouseId) { + const { ctx } = this; + try { + const express = await ctx.model.OrderExpress.findOne({ + where: { waybill_code: waybillCode, warehouse_id: warehouseId }, + attributes: [ 'store_id' ], + raw: true, + }); + return express && Number(express.store_id) > 0 ? Number(express.store_id) : 0; + } catch (err) { + ctx.logger.warn(`[returnUnpack._resolveStoreIdByWaybill] 反查货主失败: ${err.message}`); + return 0; + } + } + + /** + * 解析退回包裹关联的原单信息:平台交易单号 / 快递 / 自定义店铺名称。 + * 优先取主表快照(source_order_codes / shop_name),为空时实时兜底: + * 交易单号取原运单/原订单的 source_order_codes,店铺名称取货主合约 store_remask。 + * + * @param {Object} params 关联参数。 + * @param {number} [params.order_express_id] 原运单ID。 + * @param {number} [params.order_id] 原订单ID。 + * @param {number} [params.warehouse_id] 仓库ID(分表查询/合约查询用)。 + * @param {number} [params.store_id] 货主ID(自定义店铺名称查询用)。 + * @param {string} [params.source_order_codes] 平台交易单号快照。 + * @param {string} [params.shop_name] 店铺名称快照。 + * @return {Promise<{trade_no: string, express: string, shop_name: string}>} 原单信息。 + */ + async _resolveReturnOrderInfo({ order_express_id, order_id, warehouse_id, store_id, source_order_codes, shop_name } = {}) { + const { ctx } = this; + const info = { + trade_no: String(source_order_codes || '').trim(), + express: '', + shop_name: String(shop_name || '').trim(), + }; + + if (order_express_id) { + try { + const express = await ctx.model.OrderExpress.findOne({ + where: { id: order_express_id }, + attributes: [ 'logistics_name', 'source_order_codes' ], + raw: true, + }); + if (express) { + if (express.logistics_name) info.express = String(express.logistics_name); + if (!info.trade_no && express.source_order_codes) { + info.trade_no = String(express.source_order_codes); + } + } + } catch (err) { + ctx.logger.warn(`[returnUnpack._resolveReturnOrderInfo] 查询原运单失败: ${err.message}`); + } + } + + if (order_id && !info.trade_no) { + try { + let order = null; + try { + order = await ctx.model.OrderDelivery.findOne({ + where: { id: order_id }, + raw: true, + }); + } catch (err) { + // 主表查询失败,继续走工厂分表兜底 + } + if (!order && ctx.model.OrderDeliveryFactory) { + try { + const factoryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouse_id); + if (factoryModel) { + order = await factoryModel.findOne({ where: { id: order_id }, raw: true }); + } + } catch (err) { + // 分表查询失败忽略 + } + } + if (order) { + info.trade_no = String(order.source_order_codes || order.source_platform_code || ''); + if (!info.express && order.logistics_name) info.express = String(order.logistics_name); + } + } catch (err) { + ctx.logger.warn(`[returnUnpack._resolveReturnOrderInfo] 查询原订单失败: ${err.message}`); + } + } + + // 自定义店铺名称兜底:货主合约 store_remask + if (!info.shop_name && store_id) { + info.shop_name = await this._resolveStoreRemark(store_id, warehouse_id); + } + + return info; + } + /** * 删除拆包单(后台管理,不限制状态):事务内物理删除主表 + 明细,同步软删视频。 * diff --git a/database/migrations/20260813170000-add-return-unpack-order-info.js b/database/migrations/20260813170000-add-return-unpack-order-info.js new file mode 100644 index 0000000..f0f5a9c --- /dev/null +++ b/database/migrations/20260813170000-add-return-unpack-order-info.js @@ -0,0 +1,36 @@ +'use strict'; + +/** + * wms_return_unpack 主表补充订单信息快照字段: + * - source_order_codes:平台交易单号(原单退回时回填,来源 wms_order_express.source_order_codes) + * - shop_name:店铺名称(货主自定义店铺名称快照,来源 wms_store_warehouse.store_remask) + * + * 用途:退回查询(查退回模板消息)直接取主表快照,避免依赖原运单/订单表实时关联。 + */ + +const TABLE_NAME = 'wms_return_unpack'; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const { STRING } = Sequelize; + await queryInterface.addColumn(TABLE_NAME, 'source_order_codes', { + type: STRING(500), + allowNull: true, + comment: '平台交易单号快照(原单退回时回填)', + after: 'store_id', + }); + await queryInterface.addColumn(TABLE_NAME, 'shop_name', { + type: STRING(50), + allowNull: true, + comment: '店铺名称快照(货主自定义店铺名称 store_remask)', + after: 'source_order_codes', + }); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.removeColumn(TABLE_NAME, 'shop_name'); + await queryInterface.removeColumn(TABLE_NAME, 'source_order_codes'); + }, +}; diff --git a/methods/changes/system.json b/methods/changes/system.json index 9ef0b36..6adaad4 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -5916,5 +5916,53 @@ "仅文档同步,其余接口与模块不动" ], "module": "returnUnpack" + }, + { + "version": "2026.08.13-returnUnpack.addDetailBarcode", + "date": "2026-08-13", + "type": "updated", + "summary": "returnUnpack.addDetail 新增 barcode 入参(可选):stock_id 为空时按条码反查本仓库商品(wms_stock_barcodes)再走识别流程,反查不到按无关联货物处理;条码同步写入明细作记录(此前固定写 null)。复用基础模块条码索引,支持 PDA 扫描条码录明细。", + "methods": [ + "returnUnpack.addDetail" + ], + "notes": [ + "params 新增 barcode(string,可选,最长100,body)", + "识别优先级:stock_id > barcode 反查 > 无关联货物", + "明细 barcode 字段由固定 null 改为记录扫描条码", + "business 层按 warehouse_id+barcode 匹配 wms_stock_barcodes(uk_barcode 全局唯一,加仓库过滤防跨仓串货)" + ], + "module": "returnUnpack" + }, + { + "version": "2026.08.13-returnUnpack.addDetailBarcodeV2", + "date": "2026-08-13", + "type": "updated", + "summary": "returnUnpack.addDetail 识别策略调整:未指定 stock_id 时一律标注未知商品(item_name=未知商品),移除按条码自动反查 stock_id 的逻辑(同一条码可能对应多个 stock_id,自动匹配易误配);barcode 仍写入明细作记录。", + "methods": [ + "returnUnpack.addDetail" + ], + "notes": [ + "移除 barcode 反查 wms_stock_barcodes 自动识别逻辑(v1 新增,本次回退)", + "未指定 stock_id:is_recognized=0,item_name=未知商品(此前为 null)", + "barcode 参数保留:仅作记录写入明细,不参与商品匹配", + "docs 同步:addDetail description / stock_id / barcode 参数说明更新" + ], + "module": "returnUnpack" + }, + { + "version": "2026.08.13-returnUnpack.orderInfoSnapshot", + "date": "2026-08-13", + "type": "updated", + "summary": "wms_return_unpack 主表新增订单信息快照字段 source_order_codes(平台交易单号)/ shop_name(店铺名称=货主自定义店铺名称 store_remask),returnUnpack.create 原单退回时回填;退回查询(查退回)优先取主表快照返回交易单号与自定义店铺。", + "methods": [ + "returnUnpack.create" + ], + "notes": [ + "迁移 20260813170000-add-return-unpack-order-info.js:addColumn source_order_codes VARCHAR(500) + shop_name VARCHAR(50)", + "create 原单退回:source_order_codes 取 wms_order_express.source_order_codes,shop_name 取 store_remask", + "addDetail 首个识别商品回填主表 store_id 时同步回填 shop_name", + "退回查询 _resolveReturnOrderInfo 优先主表快照,空时实时兜底(交易单号→原运单/原订单,店铺→store_remask)" + ], + "module": "returnUnpack" } ] diff --git a/methods/system.json b/methods/system.json index 36faa19..e92a56a 100644 --- a/methods/system.json +++ b/methods/system.json @@ -35031,7 +35031,7 @@ "list": [ { "method": "returnUnpack.create", - "description": "开拆包单(明细不在此提交,由 returnUnpack.addDetail 逐件录入)。用 waybill_code 反查 wms_order_express 判定是否原单退回,命中则回填 order_express_id/order_id/store_id 并返回原订单详情;未命中原单时按 warehouse_id+waybill_code 从 wms_return_query_log 反查货主(限最近 3 个月内登记)。拆包单号规则 RP+YYYYMMDD+6位序号。仓库隔离:warehouse_id 由服务端注入 ctx.user.store_id,禁止前端传入。", + "description": "开拆包单(明细不在此提交,由 returnUnpack.addDetail 逐件录入)。用 waybill_code 反查 wms_order_express 判定是否原单退回,命中则回填 order_express_id/order_id/store_id 及订单信息快照(source_order_codes 平台交易单号 / shop_name 店铺名称=货主自定义店铺名称 store_remask)并返回原订单详情;未命中原单时按 warehouse_id+waybill_code 从 wms_return_query_log 反查货主(限最近 3 个月内登记)。拆包单号规则 RP+YYYYMMDD+6位序号。仓库隔离:warehouse_id 由服务端注入 ctx.user.store_id,禁止前端传入。", "isNeedAuth": true, "isNeedLogin": true, "headers": [], @@ -35076,7 +35076,7 @@ "name": "record", "type": "object", "required": true, - "description": "拆包单主表记录(含 unpack_no、waybill_code、unpack_date、start_time、unpacker_id/unpacker_name、status、detail_status、camera_ids 数组、回填的 order_express_id/order_id/store_id 及 is_original_return 派生字段)" + "description": "拆包单主表记录(含 unpack_no、waybill_code、unpack_date、start_time、unpacker_id/unpacker_name、status、detail_status、camera_ids 数组、回填的 order_express_id/order_id/store_id/source_order_codes/shop_name 快照及 is_original_return 派生字段)" }, { "name": "is_original_return", @@ -35126,7 +35126,7 @@ }, { "method": "returnUnpack.addDetail", - "description": "录明细:以拆包单ID为依据录入一条明细。主单非终态(unpacking)校验;stock_id 有值时校验货主归属并回填识别快照(is_recognized=1 + item_code/item_name/spec/product_snapshot),为空即无关联货物(is_recognized=0);主表 store_id 为空时以首个识别商品回填主表货主。写明细后重算主表 total_items/total_quantity/detail_status。仓库隔离校验(仅本仓库拆包单)。", + "description": "录明细:以拆包单ID为依据录入一条明细。主单非终态(unpacking)校验;stock_id 有值时校验货主归属并回填识别快照(is_recognized=1 + item_code/item_name/spec/product_snapshot),未指定 stock_id 时一律标注未知商品(is_recognized=0,item_name=未知商品),不做条码自动匹配(同一条码可能对应多个 stock_id,自动匹配易误配),barcode 仅作记录;主表 store_id 为空时以首个识别商品回填主表货主。写明细后重算主表 total_items/total_quantity/detail_status。仓库隔离校验(仅本仓库拆包单)。", "isNeedAuth": true, "isNeedLogin": true, "headers": [], @@ -35143,7 +35143,14 @@ "type": "integer", "required": false, "source": "body", - "description": "系统商品ID(wms_stock_warehouse.id),为空即无关联货物" + "description": "系统商品ID(wms_stock_warehouse.id),为空即无关联货物(商品名称标注未知商品)" + }, + { + "name": "barcode", + "type": "string", + "required": false, + "source": "body", + "description": "扫描条码(最长100字符,仅作记录,不参与商品匹配)" }, { "name": "quantity", @@ -35178,7 +35185,7 @@ "name": "detail", "type": "object", "required": true, - "description": "新增的明细行(含 is_recognized/item_code/item_name/spec/product_snapshot 等识别结果快照)" + "description": "新增的明细行(含 barcode/is_recognized/item_code/item_name(未知商品)/spec/product_snapshot 等)" }, { "name": "total_items", diff --git a/script/debug-inbox-push.cjs b/script/debug-inbox-push.cjs new file mode 100644 index 0000000..be486f9 --- /dev/null +++ b/script/debug-inbox-push.cjs @@ -0,0 +1,243 @@ +'use strict'; + +/** + * 站内信消息推送调试脚本(模拟 IM 桥向仓库推送入站消息,走真实验签链路)。 + * + * 用法: + * node script/debug-inbox-push.cjs + * 默认: 向 test-stock-group 推送「查退回 <随机不存在运单号>」 + * node script/debug-inbox-push.cjs --content "查退回 888888888888888" + * node script/debug-inbox-push.cjs --waybill 888888888888888 --groupId test-stock-group --userName 测试用户 + * + * 行为: + * 1. 按 app/lib/api_sign.js 规则签名,POST /warehouse?method=inbox.push + * 2. 等待 AI 异步处理(默认 15s) + * 3. 回查本地库: 入站消息 / AI 思考过程 / 回信内容 / wms_return_query_log 登记 + */ + +const crypto = require('crypto'); +const http = require('http'); +const mysql = require('mysql2/promise'); + +// ========================== 稳定序列化(与 app/lib/api_sign.js 一致) ========================== + +function isPlainObject(value) { + return Object.prototype.toString.call(value) === '[object Object]'; +} + +function stableStringify(value) { + if (value === undefined) return ''; + if (value === null || typeof value !== 'object') return JSON.stringify(value); + if (Array.isArray(value)) { + return `[${value.map(item => stableStringify(item)).join(',')}]`; + } + if (!isPlainObject(value)) return JSON.stringify(value); + const keys = Object.keys(value).sort(); + return `{${keys.map(key => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(',')}}`; +} + +function md5(str) { + return crypto.createHash('md5').update(str, 'utf8').digest('hex').toLowerCase(); +} + +function buildSign(query, body, secret) { + const ignoreSet = new Set([ 'sign', 'signature' ]); + const keys = Object.keys(query) + .filter(key => !ignoreSet.has(String(key).toLowerCase())) + .filter(key => query[key] !== undefined) + .sort(); + const canonicalQuery = keys.map(key => { + const v = query[key]; + if (v === undefined || v === null) return `${key}=`; + if (typeof v === 'object') return `${key}=${stableStringify(v)}`; + return `${key}=${String(v)}`; + }).join('&'); + const bodySign = md5(stableStringify(body)); + const signText = `${canonicalQuery}${secret}${bodySign}`; + return { canonicalQuery, bodySign, sign: md5(signText) }; +} + +// ========================== 参数解析 ========================== + +const ARGS = {}; +for (let i = 2; i < process.argv.length; i++) { + const arg = process.argv[i]; + const match = arg.match(/^--([^=]+)=(.*)$/); + if (match) { + ARGS[match[1]] = match[2]; + } else if (arg.startsWith('--')) { + ARGS[arg.slice(2)] = process.argv[i + 1]; + i++; + } +} + +const CONFIG = { + baseUrl: ARGS.baseUrl || 'http://127.0.0.1:6060', + appKey: ARGS.appKey || 'APP2025011514315678', + appSecret: ARGS.appSecret || 'sec_xyz789uvw012abc345def678ghi901jkl234mno567pqr890', + groupId: ARGS.groupId || 'test-stock-group', + groupName: ARGS.groupName || '库存查询测试群', + userName: ARGS.userName || '测试用户', + waitMs: Number(ARGS.waitMs || 15000), + waybill: ARGS.waybill || `${Date.now()}99`, +}; + +if (ARGS.content) { + CONFIG.content = ARGS.content; +} else { + CONFIG.content = `查退回 ${CONFIG.waybill}`; +} + +// ========================== HTTP 推送 ========================== + +function postWarehouse(method, body) { + const query = { + method, + v: '1.0', + timestamp: Math.floor(Date.now() / 1000), + app_key: CONFIG.appKey, + }; + const { sign } = buildSign(query, body, CONFIG.appSecret); + query.sign = sign; + + const qs = Object.entries(query) + .map(([ k, v ]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`) + .join('&'); + const bodyStr = JSON.stringify(body); + const url = `${CONFIG.baseUrl}/warehouse?${qs}`; + + return new Promise((resolve, reject) => { + const req = http.request(url, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Content-Length': Buffer.byteLength(bodyStr), + }, + timeout: 20000, + }, res => { + let data = ''; + res.on('data', chunk => (data += chunk)); + res.on('end', () => { + try { resolve({ status: res.statusCode, body: JSON.parse(data) }); } catch (e) { resolve({ status: res.statusCode, body: data }); } + }); + }); + req.on('error', reject); + req.on('timeout', () => { req.destroy(); reject(new Error('Request timeout')); }); + req.write(bodyStr); + req.end(); + }); +} + +function sleep(ms) { + return new Promise(resolve => setTimeout(resolve, ms)); +} + +// ========================== 本地库回查 ========================== + +async function queryDb(sql) { + const conn = await mysql.createConnection({ + host: '127.0.0.1', + port: 3307, + user: 'wms', + password: 'dspxmRwRdRbWtbm7', + database: 'wms', + }); + try { + const [ rows ] = await conn.query(sql); + return rows; + } finally { + await conn.end(); + } +} + +// ========================== 主流程 ========================== + +(async () => { + const requestId = `debug-return-${Date.now()}`; + console.log('========== 站内信模拟推送 =========='); + console.log(` 群: ${CONFIG.groupId} (${CONFIG.groupName})`); + console.log(` 用户: ${CONFIG.userName}`); + console.log(` 内容: ${CONFIG.content}`); + console.log(` requestId: ${requestId}`); + + const r = await postWarehouse('inbox.push', { + requestId, + content: CONFIG.content, + groupId: CONFIG.groupId, + groupName: CONFIG.groupName, + userId: 'debug_user', + userName: CONFIG.userName, + targetType: 'im', + }); + + console.log(` HTTP ${r.status}: ${JSON.stringify(r.body).slice(0, 300)}`); + if (r.status !== 200 || (r.body && r.body.ok === false)) { + console.error('推送失败,请检查签名与仓库应用配置'); + process.exit(1); + } + + console.log(`\n等待 AI 异步处理 ${CONFIG.waitMs / 1000}s ...`); + await sleep(CONFIG.waitMs); + + const extId = `api:${CONFIG.appKey}:${requestId}`; + + // 1. 入站消息 + AI 思考 + const inbound = await queryDb( + `SELECT id, direction, content, ai_thoughts, push_status, created_at + FROM wms_inbox_message WHERE ext_id='${extId}' ORDER BY id DESC LIMIT 1` + ); + console.log('\n[入站消息]'); + if (inbound.length === 0) { + console.log(' 未找到(消息可能尚未入库)'); + } else { + console.log(` id=${inbound[0].id} push_status=${inbound[0].push_status}`); + console.log(` content: ${inbound[0].content}`); + const thoughts = inbound[0].ai_thoughts; + if (thoughts && typeof thoughts === 'string') { + try { + const parsed = JSON.parse(thoughts); + console.log(` ai_thoughts: ${JSON.stringify(parsed).slice(0, 400)}`); + } catch (e) { + console.log(` ai_thoughts(raw): ${String(thoughts).slice(0, 400)}`); + } + } else { + console.log(' ai_thoughts: 无'); + } + } + + // 2. 回信内容 + const outbound = await queryDb( + `SELECT id, direction, content, created_at + FROM wms_inbox_message + WHERE direction='outbound' AND group_id='${CONFIG.groupId}' + ORDER BY id DESC LIMIT 1` + ); + console.log('\n[最新回信]'); + if (outbound.length === 0) { + console.log(' 无回信'); + } else { + console.log(` id=${outbound[0].id} created_at=${outbound[0].created_at}`); + console.log(` content:\n${outbound[0].content}`); + } + + // 3. 退回查询登记 + const waybill = CONFIG.waybill; + const queryLog = await queryDb( + `SELECT id, warehouse_id, store_id, waybill_code, remark, is_notified, is_back, created_at + FROM wms_return_query_log WHERE waybill_code='${waybill}' ORDER BY id DESC LIMIT 3` + ); + console.log('\n[wms_return_query_log 登记]'); + if (queryLog.length === 0) { + console.log(' 无登记'); + } else { + queryLog.forEach(row => { + console.log(` id=${row.id} store_id=${row.store_id} is_back=${row.is_back} is_notified=${row.is_notified} remark=${row.remark} ${row.created_at}`); + }); + } + + console.log('\n完成。测试记录按需保留,无需删除。'); + process.exit(0); +})().catch(e => { + console.error('异常:', e.message); + process.exit(1); +});