diff --git a/app/controller/docs.js b/app/controller/docs.js index 319c4b9..9fcc600 100644 --- a/app/controller/docs.js +++ b/app/controller/docs.js @@ -465,6 +465,20 @@ function resolveDocEntryPath(docData) { return '/system'; } +/** + * 渲染 seeAlso 交叉引用链接。 + * @param {Array<{name: string, path: string, description: string}>|undefined} seeAlso 交叉引用列表。 + * @return {string} HTML 片段。 + */ +function renderSeeAlsoLinks(seeAlso) { + if (!Array.isArray(seeAlso) || seeAlso.length === 0) return ''; + const links = seeAlso.map(item => { + const href = `/api/docs/${(item.path || '').replace(/^\/?methods\//, '').replace(/\.json$/, '')}`; + return `${escapeHtml(item.name)}`; + }).join(''); + return `
关联文档:${links}
`; +} + /** * 渲染键值表格。 * @param {Array} items 数据项列表。 @@ -535,7 +549,7 @@ function renderMethodCard(item, entryPath, moduleName) { const description = item.description || ''; const isQimen = moduleName === 'qimen'; const isOpenapi = moduleName === 'openapi'; - const isWarehouse = moduleName === 'warehouse'; + const isWarehouse = moduleName === 'warehouse' || moduleName === 'warehouse_notify'; const isExternalApi = isOpenapi || isWarehouse; const queryHint = isQimen ? 'app_key=xxx&method=...&v=2.0&format=json&sign_method=md5&sign=xxx×tamp=1700000000' @@ -610,7 +624,24 @@ function renderMethodCard(item, entryPath, moduleName) { -
+ ${moduleName === 'warehouse_notify' ? `
+ 模拟推送 +
+ + + + + + + + +
+ + 模拟 WMS 向 notify_url 推送通知,sign 在浏览器端 MD5 计算 +
+
点击发送后显示响应
+
+
` : `
在线调试
@@ -631,7 +662,7 @@ function renderMethodCard(item, entryPath, moduleName) {
点击发送后显示响应
-
+
`} `; } @@ -648,14 +679,14 @@ function renderHtmlPage({ entryPath, }) { const isOpenapi = docData.module === 'openapi'; - const isWarehouse = docData.module === 'warehouse'; + const isWarehouse = docData.module === 'warehouse' || docData.module === 'warehouse_notify'; const isExternalApi = isOpenapi || isWarehouse; const methodsCount = groups.reduce((sum, group) => sum + toArray(group.list).length, 0); const globalHeaders = toArray(docData.headers); const globalHeadersControls = renderGlobalHeadersControls(globalHeaders); const rawUrl = `/api/docs/${encodeURIComponent(docName)}/raw`; const changesUrl = `/api/docs/${encodeURIComponent(docName)}/changes`; - const navHtml = isExternalApi ? '' : docs.filter(name => name !== 'openapi' && name !== 'warehouse').map(name => { + const navHtml = isExternalApi ? '' : docs.filter(name => name !== 'openapi' && name !== 'warehouse' && name !== 'warehouse_notify').map(name => { const activeClass = name === docName ? 'active' : ''; return `${escapeHtml(name)}`; }).join(''); @@ -1074,6 +1105,7 @@ function renderHtmlPage({ 更新: ${escapeHtml(docData.updatedAt || 'N/A')} 方法数: ${methodsCount} 统一入口: ${escapeHtml(entryPath)} + ${renderSeeAlsoLinks(docData.seeAlso)}
${navHtml} @@ -1101,7 +1133,42 @@ function renderHtmlPage({
点击上方按钮后,可直接预览当前文档的变更记录或原文 JSON。
`} - ${isExternalApi ? `
+ ${isExternalApi ? (docData.module === 'warehouse_notify' ? `
+

请求方式

+
POST {notify_url}?app_key={app_key}&method={方法名}&timestamp={时间戳}&sign={签名}
+Content-Type: application/json
+
+{
+  "code": 200,
+  "data": { ... }
+}
+ +

签名算法(MD5)

+
sign = MD5(self_app_secret + timestamp + bodyJson).toLowerCase()
+
+其中:
+  self_app_secret = 平台分配的密钥
+  timestamp = Unix 秒级时间戳
+  bodyJson = JSON.stringify(请求体)
+
+示例(假设 self_app_secret=abc123,请求体={"code":200,"data":{...}}):
+  bodyJson = {"code":200,"data":{...}}
+  timestamp = 1700000000
+  signText = abc1231700000000{"code":200,"data":{...}}
+  sign = md5(signText).toLowerCase() = ...
+ +

注意事项(外部系统接收方)

+
    +
  • 通知由 WMS 主动推送到您配置的 notify_url,外部系统接收并返回 HTTP 200即可
  • +
  • 根据 query 中的 method 字段路由到不同处理逻辑(notify.ping / notify.reply)
  • +
  • 根据 data.type 区分消息类别(ai / bind / balance / error)
  • +
  • 验签时从 query 取 sign,本地计算 MD5(self_app_secret + timestamp + bodyJson) 比对
  • +
  • 时间戳 timestamp 为 Unix 秒级时间戳,校验 ±10 分钟时效
  • +
  • 签名结果为 32 位小写十六进制字符串
  • +
  • 接收成功返回 {"code":200},非 200 或 HTTP 状态码非 200 视为推送失败
  • +
  • WMS 推送超时 10 秒,失败不重试,仅记录日志
  • +
+
` : `

请求方式

POST ${isOpenapi ? '/openapi' : '/warehouse'}?method={方法名}&v=1.0×tamp={时间戳}&app_key={app_key}&sign={签名}
 Content-Type: application/json
@@ -1146,7 +1213,7 @@ Content-Type: application/json
           → 回调测试工具
           (模拟接收回调通知,验证回调链路)
         

` : ''} -
` : ''} +
`) : ''}
@@ -1171,7 +1238,7 @@ Content-Type: application/json (function() { var DOC_NAME = ${JSON.stringify(docName)}; var IS_OPENAPI_DOC = DOC_NAME === 'openapi'; - var IS_EXTERNAL_API_DOC = DOC_NAME === 'openapi' || DOC_NAME === 'warehouse'; + var IS_EXTERNAL_API_DOC = DOC_NAME === 'openapi' || DOC_NAME === 'warehouse' || DOC_NAME === 'warehouse_notify'; var AUTH_KEY = 'wms_docs_global_auth'; var HEADER_STORE_KEY = 'wms_docs_global_headers_' + ${JSON.stringify(docName)}; var OPENAPI_APP_KEY_STORE_KEY = 'wms_docs_' + DOC_NAME + '_app_key'; @@ -1939,6 +2006,51 @@ Content-Type: application/json initDefaultQueries(); applySearch(''); + + // ── warehouse_notify 模拟推送(每个方法卡上的按钮)── + document.querySelectorAll('.notify-send-btn').forEach(function(btn) { + btn.addEventListener('click', function() { + var card = btn.closest('.method-card'); + var methodName = btn.getAttribute('data-method'); + var notifyUrlInput = card.querySelector('.notify-url-input'); + var appKeyInput = card.querySelector('.req-app-key'); + var appSecretInput = card.querySelector('.req-self-app-secret'); + var bodyTextarea = card.querySelector('.req-body'); + var resultEl = card.querySelector('.req-result'); + + var url = (notifyUrlInput && notifyUrlInput.value || '').trim(); + var appKey = (appKeyInput && appKeyInput.value || '').trim(); + var appSecret = (appSecretInput && appSecretInput.value || '').trim(); + var bodyStr = (bodyTextarea && bodyTextarea.value || '{}').trim(); + + if (!url) { resultEl.textContent = '请填写 notify_url'; resultEl.className = 'req-result error'; return; } + if (!appKey) { resultEl.textContent = '请填写 app_key'; resultEl.className = 'req-result error'; return; } + if (!appSecret) { resultEl.textContent = '请填写 self_app_secret'; resultEl.className = 'req-result error'; return; } + + var bodyJson; + try { bodyJson = JSON.stringify(JSON.parse(bodyStr)); } catch (e) { resultEl.textContent = 'Body JSON 格式错误'; resultEl.className = 'req-result error'; return; } + + var ts = Math.floor(Date.now() / 1000); + var sign = md5(appSecret + ts + bodyJson); + + resultEl.textContent = '发送中...'; + resultEl.className = 'req-result'; + + fetch(url + '?app_key=' + encodeURIComponent(appKey) + '&method=' + encodeURIComponent(methodName) + '×tamp=' + ts + '&sign=' + sign, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: bodyJson, + }).then(function(res) { + return res.text().then(function(txt) { return { status: res.status, body: txt }; }); + }).then(function(r) { + resultEl.textContent = 'HTTP ' + r.status + '\n' + r.body; + resultEl.className = r.status === 200 ? 'req-result success' : 'req-result error'; + }).catch(function(err) { + resultEl.textContent = '推送失败: ' + err.message; + resultEl.className = 'req-result error'; + }); + }); + }); })(); diff --git a/app/controller/warehouse.js b/app/controller/warehouse.js index 4e79e32..d34a440 100644 --- a/app/controller/warehouse.js +++ b/app/controller/warehouse.js @@ -1,8 +1,12 @@ 'use strict'; const { Controller } = require('egg'); +const crypto = require('crypto'); const { toSuccess, toFailure } = require('../lib/api_response'); +/** 日志内容长度上限 */ +const LOG_BODY_MAX = 65535; + class WarehouseController extends Controller { /** * 输出仓库 API 统一失败响应。 @@ -23,14 +27,33 @@ class WarehouseController extends Controller { } /** - * 仓库 API 统一入口,仅负责转发到 warehouse service 并输出标准响应。 + * 截断日志内容到上限长度。 + * @param {string} value 原始字符串。 + * @return {string} 截断后的字符串。 + */ + truncateLogBody(value) { + const str = typeof value === 'string' ? value : JSON.stringify(value); + if (str.length > LOG_BODY_MAX) { + return str.substring(0, LOG_BODY_MAX); + } + return str; + } + + /** + * 仓库 API 统一入口,记录请求日志并转发到 warehouse service。 * @return {Promise} 无返回值,结果写入 ctx.body。 */ async index() { - const { ctx } = this; + const { ctx, app } = this; + const startTime = Date.now(); + const logId = 'WL-' + Date.now() + '-' + crypto.randomBytes(3).toString('hex'); + + const query = ctx.query || {}; + let result; try { - const result = await ctx.service.warehouse.processRequest(); + result = await ctx.service.warehouse.processRequest(); + if (result.ok) { ctx.status = Number(result.httpStatus) || 200; ctx.body = toSuccess(result.data, result.message || 'ok'); @@ -49,6 +72,36 @@ class WarehouseController extends Controller { const message = String(error && error.message || '请求失败'); this.writeFailureResponse(500, `接口错误: ${message}`, 500); ctx.type = 'application/json'; + // 异常情况下 result 为 undefined,构造一个 fallback + result = { + ok: false, + httpStatus: 500, + message: error.message || '未知错误', + warehouseId: null, + appKey: String(query.app_key || '').trim() || null, + }; + } finally { + // 异步写日志,不阻塞响应 + try { + const logData = { + log_id: logId, + app_key: (result && result.appKey) || String(query.app_key || '').trim() || null, + method: String(query.method || '').trim() || null, + warehouse_id: (result && result.warehouseId) || null, + url: ctx.request.href || null, + http_status: ctx.status || (result && result.httpStatus) || null, + body: this.truncateLogBody(ctx.request.rawBody || JSON.stringify(ctx.request.body || {})), + result: this.truncateLogBody(typeof ctx.body === 'string' ? ctx.body : JSON.stringify(ctx.body || {})), + use_time: Date.now() - startTime, + created_at: new Date(), + }; + + app.fileWriter.writeRecord('warehouse-logs', logData).catch(writeErr => { + ctx.logger.error('[warehouse-log-sink] 写入文件失败: ' + writeErr.message); + }); + } catch (logErr) { + ctx.logger.error('[warehouse-log] 日志记录异常: ' + logErr.message); + } } } } diff --git a/app/lib/qimen_client.js b/app/lib/qimen_client.js index 09ff933..d50fa0c 100644 --- a/app/lib/qimen_client.js +++ b/app/lib/qimen_client.js @@ -153,7 +153,7 @@ class QimenClient { const baseUrl = 'http://qimen.api.taobao.com/router/qimen/service'; const requestPayload = this.normalizeRequestPayload(data); const xmlData = await helpers.toXml(requestPayload); - const queryData = method === 'taobao.qimen.deliveryorder.confirm' + const queryData = method === 'taobao.qimen.deliveryorder.confirm' || method === 'taobao.qimen.stockout.confirm' ? this.replaceDeliveryConfirmPayloadTags(xmlData) : this.replaceXmlTagsWithString(xmlData, 'item', 'orderLine'); const sign = await helpers.signTopRequest(baseQueryParams, queryData, this.app.config.qimen.security, 'md5'); diff --git a/app/model/api_app.js b/app/model/api_app.js index b81db1b..4d19535 100644 --- a/app/model/api_app.js +++ b/app/model/api_app.js @@ -108,10 +108,10 @@ module.exports = app => { allowNull: true, defaultValue: 'md5', validate: { - isIn: [[ 'md5', 'hmac', 'sha256' ]], + isIn: [[ 'md5' ]], len: [ 0, 50 ], }, - comment: '签名方法', + comment: '签名方法(当前仅支持 md5)', }, rate_limit: { type: INTEGER(11), diff --git a/app/model/inbox_block.js b/app/model/inbox_block.js index 4baa2dd..e2fefba 100644 --- a/app/model/inbox_block.js +++ b/app/model/inbox_block.js @@ -2,14 +2,14 @@ /** * 站内信屏蔽表 Model。 - * 记录被屏蔽的群/用户,后续来自该群+用户的消息不再触发 AI 回信。 - * group_name 和 user_name 均为 NULL 时表示全局屏蔽(预留)。 + * 按群ID+用户ID维度屏蔽,后续来自该群+用户的消息不再触发 AI 回信。 + * group_id 和 user_id 均为 NULL 时表示全局屏蔽(预留)。 * * @param {Object} app Egg.js Application 实例。 * @return {Object} Sequelize Model 定义。 */ module.exports = app => { - const { BIGINT, STRING, DATE } = app.Sequelize; + const { BIGINT, STRING, INTEGER, DATE } = app.Sequelize; const InboxBlock = app.model.define('inbox_block', { id: { @@ -19,15 +19,20 @@ module.exports = app => { allowNull: false, comment: '主键', }, - group_name: { - type: STRING(100), - allowNull: true, - comment: '群名称', + warehouse_id: { + type: INTEGER(10), + allowNull: false, + comment: '仓库ID', }, - user_name: { + group_id: { type: STRING(100), allowNull: true, - comment: '用户名称', + comment: '群ID', + }, + user_id: { + type: STRING(100), + allowNull: true, + comment: '用户ID', }, created_at: { type: DATE, @@ -39,6 +44,13 @@ module.exports = app => { tableName: 'wms_inbox_block', timestamps: false, comment: '站内信屏蔽表', + indexes: [ + { + name: 'uk_warehouse_group_user', + unique: true, + fields: [ 'warehouse_id', 'group_id', 'user_id' ], + }, + ], }); return InboxBlock; diff --git a/app/model/inbox_group.js b/app/model/inbox_group.js index 3b5dc47..6a02825 100644 --- a/app/model/inbox_group.js +++ b/app/model/inbox_group.js @@ -67,7 +67,7 @@ module.exports = app => { ai_enabled: { type: TINYINT(1), allowNull: false, - defaultValue: 1, + defaultValue: 0, comment: '是否启用AI自动回复: 0=关闭 1=开启', }, express_interfaces: { diff --git a/app/model/order_stockout.js b/app/model/order_stockout.js index 601f832..4b56eab 100644 --- a/app/model/order_stockout.js +++ b/app/model/order_stockout.js @@ -107,6 +107,31 @@ module.exports = app => { allowNull: true, comment: '备注', }, + express_code: { + type: STRING(50), + allowNull: true, + comment: '快递公司编码(如 SF、STO,用于出站回传 logisticsCode)', + }, + express_name: { + type: STRING(200), + allowNull: true, + comment: '快递公司名称(由 express_code 自动解析,如 顺丰、申通)', + }, + waybill_code: { + type: STRING(50), + allowNull: true, + comment: '运单号', + }, + waybill_codes: { + type: JSON_TYPE, + allowNull: true, + comment: '运单号列表(JSON 数组,支持多包裹场景)', + }, + express_codes: { + type: JSON_TYPE, + allowNull: true, + comment: '@deprecated 运单号列表,请使用 waybill_codes', + }, extend_props: { type: JSON_TYPE, allowNull: true, diff --git a/app/model/warehouse_log.js b/app/model/warehouse_log.js new file mode 100644 index 0000000..7eb67b4 --- /dev/null +++ b/app/model/warehouse_log.js @@ -0,0 +1,111 @@ +// app/model/warehouse_log.js + +'use strict'; + +module.exports = app => { + const { STRING, INTEGER, BIGINT, TEXT, DATE } = app.Sequelize; + + const WarehouseLog = app.model.define('warehouse_log', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + }, + log_id: { + type: STRING(32), + allowNull: false, + unique: true, + field: 'log_id', + comment: '日志唯一ID(WL-{timestamp}-{random})', + }, + app_key: { + type: STRING(64), + allowNull: true, + field: 'app_key', + comment: 'API 应用 AppKey', + }, + method: { + type: STRING(100), + allowNull: true, + comment: '请求方法名(如 inbox.push)', + }, + warehouse_id: { + type: INTEGER(10), + allowNull: true, + field: 'warehouse_id', + comment: '仓库 ID', + }, + url: { + type: TEXT, + allowNull: true, + comment: '请求 URL', + }, + http_status: { + type: INTEGER(5), + allowNull: true, + field: 'http_status', + comment: 'HTTP 状态码', + }, + body: { + type: TEXT('long'), + allowNull: true, + comment: '请求体(最大 65535 字符)', + }, + result: { + type: TEXT('long'), + allowNull: true, + comment: '响应体(最大 65535 字符)', + }, + use_time: { + type: INTEGER(12), + allowNull: true, + field: 'use_time', + comment: '耗时(毫秒)', + }, + created_at: { + type: DATE, + allowNull: true, + field: 'created_at', + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: true, + field: 'updated_at', + comment: '更新时间', + }, + }, { + tableName: 'wms_warehouse_log', + freezeTableName: true, + underscored: true, + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + comment: '仓库开放 API 请求日志表', + indexes: [ + { + name: 'uk_log_id', + unique: true, + fields: [ 'log_id' ], + }, + { + name: 'idx_app_key', + fields: [ 'app_key' ], + }, + { + name: 'idx_method', + fields: [ 'method' ], + }, + { + name: 'idx_warehouse_id', + fields: [ 'warehouse_id' ], + }, + { + name: 'idx_created_at', + fields: [ 'created_at' ], + }, + ], + }); + + return WarehouseLog; +}; diff --git a/app/schedule/consume_warehouse_logs.js b/app/schedule/consume_warehouse_logs.js new file mode 100644 index 0000000..81deece --- /dev/null +++ b/app/schedule/consume_warehouse_logs.js @@ -0,0 +1,56 @@ +'use strict'; + +const path = require('path'); + +/** + * 定时消费仓库 API 日志文件队列,逐条插入数据库。 + * 间隔 30 秒执行,type: worker(仅一个 worker 执行)。 + */ +module.exports = { + schedule: { + interval: '30s', + type: 'worker', + immediate: false, + disable: false, + }, + + async task(ctx) { + if (ctx.app._consumeWarehouseLogsRunning) return; + ctx.app._consumeWarehouseLogsRunning = true; + + const fileWriter = ctx.app.fileWriter; + const mysql = ctx.app.mysql.get('wms'); + const progressFilePath = path.join(fileWriter.baseDir, 'warehouse-logs', '.consume-progress'); + + try { + const result = await fileWriter.consumeFiles({ + businessName: 'warehouse-logs', + progressFilePath, + maxConsumeRecordsPerWindow: 500, + parseJson: true, + onRecord: async record => { + await mysql.insert('wms_warehouse_log', { + log_id: record.log_id || null, + app_key: record.app_key || null, + method: record.method || null, + warehouse_id: record.warehouse_id || null, + url: record.url || null, + http_status: record.http_status || null, + body: record.body || null, + result: record.result || null, + use_time: record.use_time || 0, + created_at: record.created_at ? new Date(record.created_at) : new Date(), + }); + }, + }); + + if (result.processedCount > 0) { + ctx.logger.info(`[consume-warehouse-logs] 消费 ${result.processedCount} 条日志`); + } + } catch (err) { + ctx.logger.error(`[consume-warehouse-logs] 消费失败: ${err.message}`); + } finally { + ctx.app._consumeWarehouseLogsRunning = false; + } + }, +}; diff --git a/app/service/inbox/functions.js b/app/service/inbox/functions.js index 650d65a..6c9ed95 100644 --- a/app/service/inbox/functions.js +++ b/app/service/inbox/functions.js @@ -285,7 +285,7 @@ class InboxFunctionsService extends Service { }); this.register('searchStock', { - description: '搜索仓库商品。按关键词查询当前仓库+货主的商品,返回 stock_store.id、编码、名称、条码、库存总量/锁定/可用 供建单参考', + description: '搜索仓库商品(货主级)。返回商品ID/编码/名称/品牌/单位/毛重/管理标识/库存/图片/关联条码/箱规/违禁品/打包要求', params: { keyword: { type: 'string', required: true, description: '搜索关键词:商品编码(item_code)、条码(barcode)、商品名称(item_name)' }, }, @@ -301,16 +301,28 @@ class InboxFunctionsService extends Service { if (!warehouseId || !storeId) return { success: false, error: '无法获取仓库或货主信息' }; try { - const items = await ctx.model.StockStore.findAll({ - attributes: [ 'id', 'stock_id', 'item_code', 'item_name', 'barcode', 'brand_name', 'stock_unit' ], + // 从 stock_barcodes 找匹配条码的 stock_id + const barcodeMatchIds = await ctx.model.StockBarcode.findAll({ + attributes: [ 'stock_id' ], + where: { barcode: { [Op.like]: `%${keyword}%` } }, + raw: true, + }); + const barcodeStockIds = [ ...new Set(barcodeMatchIds.map(b => b.stock_id)) ]; + + // 直接查 stock_warehouse(按货主过滤,不查 stock_store) + const orConditions = [ + { item_code: { [Op.like]: `%${keyword}%` } }, + { item_name: { [Op.like]: `%${keyword}%` } }, + ]; + if (barcodeStockIds.length > 0) { + orConditions.push({ id: { [Op.in]: barcodeStockIds } }); + } + + const items = await ctx.model.StockWarehouse.findAll({ + attributes: [ 'id', 'item_code', 'item_name', 'brand_name', 'stock_unit', 'gross_weight', 'quantity', 'locked_quantity', 'is_images', 'is_sn_mgmt', 'is_shelf_life_mgmt', 'is_batch_mgmt', 'prohibited_id', 'enable_box_spec', 'box_gross_weight', 'box_net_weight', 'box_length', 'box_width', 'box_height', 'quantity_per_box', 'box_volume', 'packing_requirements' ], where: { - warehouse_id: warehouseId, store_id: storeId, - [Op.or]: [ - { item_code: { [Op.like]: `%${keyword}%` } }, - { item_name: { [Op.like]: `%${keyword}%` } }, - { barcode: { [Op.like]: `%${keyword}%` } }, - ], + [Op.or]: orConditions, }, limit: 10, raw: true, @@ -320,21 +332,56 @@ class InboxFunctionsService extends Service { return { success: true, data: { total: 0, items: [], hint: '未找到匹配商品,请尝试其他关键词' } }; } - // 批量查库存数量 - const stockIds = [ ...new Set(items.map(i => i.stock_id).filter(Boolean)) ]; - const stockQtyMap = {}; - if (stockIds.length > 0) { - const stocks = await ctx.model.StockWarehouse.findAll({ - attributes: [ 'id', 'quantity', 'locked_quantity' ], - where: { id: { [Op.in]: stockIds } }, + // 批查条码 + const itemIds = items.map(i => i.id); + const barcodeMap = {}; + if (itemIds.length > 0) { + const barcodes = await ctx.model.StockBarcode.findAll({ + attributes: [ 'stock_id', 'barcode' ], + where: { stock_id: { [Op.in]: itemIds } }, raw: true, }); - for (const s of stocks) { - stockQtyMap[s.id] = { - quantity: s.quantity || 0, - locked_quantity: s.locked_quantity || 0, - available: Math.max(0, (s.quantity || 0) - (s.locked_quantity || 0)), - }; + for (const b of barcodes) { + if (!barcodeMap[b.stock_id]) barcodeMap[b.stock_id] = []; + barcodeMap[b.stock_id].push(b.barcode); + } + } + + // 批查违禁品 + const prohibitedIds = [ ...new Set(items.map(i => i.prohibited_id).filter(Boolean)) ]; + const prohibitedMap = {}; + if (prohibitedIds.length > 0) { + const pts = await ctx.model.ProhibitedType.findAll({ + attributes: [ 'id', 'type_name' ], + where: { id: { [Op.in]: prohibitedIds } }, + raw: true, + }); + for (const p of pts) prohibitedMap[p.id] = p.type_name || ''; + } + + // 批查商品图片(wms_file_reference + wms_file,与 stock.warehouse.list 一致) + const imageUrlMap = {}; + if (itemIds.length > 0) { + const refs = await ctx.model.FileReference.findAll({ + attributes: [ 'business_id' ], + include: [{ + model: ctx.model.File, + as: 'file', + attributes: [ 'file_url' ], + required: false, + }], + where: { + business_type: 'stock', + business_id: { [Op.in]: itemIds.map(String) }, + }, + order: [[ 'display_order', 'ASC' ]], + raw: true, + }); + for (const r of refs) { + const sid = Number(r.business_id); + if (!imageUrlMap[sid]) imageUrlMap[sid] = []; + const url = (r['file.file_url'] && String(r['file.file_url']).trim()) || ''; + if (url) imageUrlMap[sid].push(url); } } @@ -346,12 +393,26 @@ class InboxFunctionsService extends Service { id: i.id, item_code: i.item_code, item_name: i.item_name, - barcode: i.barcode, + barcode: barcodeMap[i.id]?.[0] || '', brand_name: i.brand_name || '', unit: i.stock_unit || '', - stock_qty: stockQtyMap[i.stock_id]?.quantity || 0, - stock_locked: stockQtyMap[i.stock_id]?.locked_quantity || 0, - stock_available: stockQtyMap[i.stock_id]?.available || 0, + gross_weight: i.gross_weight || 0, + is_sn_mgmt: i.is_sn_mgmt === 'Y', + is_shelf_life_mgmt: i.is_shelf_life_mgmt === 'Y', + is_batch_mgmt: i.is_batch_mgmt === 'Y', + stock_qty: i.quantity || 0, + stock_locked: i.locked_quantity || 0, + stock_available: Math.max(0, (i.quantity || 0) - (i.locked_quantity || 0)), + has_images: i.is_images === 'Y', + image_url: imageUrlMap[i.id] || [], + barcodes: barcodeMap[i.id] || [], + box_spec: i.enable_box_spec ? { + length: i.box_length || 0, width: i.box_width || 0, height: i.box_height || 0, + volume: i.box_volume || 0, gross_weight: i.box_gross_weight || 0, + net_weight: i.box_net_weight || 0, quantity_per_box: i.quantity_per_box || 0, + } : null, + packing_requirements: i.packing_requirements || '', + prohibited_type: prohibitedMap[i.prohibited_id] || '', })), }, }; @@ -361,6 +422,142 @@ class InboxFunctionsService extends Service { }, }); + this.register('searchWarehouseStock', { + description: '搜索仓库商品(仓库级,不限货主)。返回商品ID/货主/编码/名称/条码/品牌/单位/毛重/管理标识/库存/图片/关联条码/箱规/违禁品/打包要求', + params: { + keyword: { type: 'string', required: true, description: '搜索关键词:商品编码(item_code)、条码(barcode)、商品名称(item_name)' }, + }, + groups: [ GROUP.COMMON ], + handler: async (params = {}) => { + const { ctx } = this; + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const keyword = String(params.keyword || '').trim(); + const { Op } = ctx.app.Sequelize; + + if (!keyword) return { success: false, error: '请提供搜索关键词' }; + if (!warehouseId) return { success: false, error: '无法获取仓库信息' }; + + try { + // 从 stock_barcodes 找匹配条码的 stock_id + const barcodeMatchIds = await ctx.model.StockBarcode.findAll({ + attributes: [ 'stock_id' ], + where: { barcode: { [Op.like]: `%${keyword}%` } }, + raw: true, + }); + const barcodeStockIds = [ ...new Set(barcodeMatchIds.map(b => b.stock_id)) ]; + + // 直接查 stock_warehouse + const orConditions = [ + { item_code: { [Op.like]: `%${keyword}%` } }, + { item_name: { [Op.like]: `%${keyword}%` } }, + ]; + if (barcodeStockIds.length > 0) { + orConditions.push({ id: { [Op.in]: barcodeStockIds } }); + } + + const items = await ctx.model.StockWarehouse.findAll({ + attributes: [ 'id', 'store_id', 'item_code', 'item_name', 'brand_name', 'stock_unit', 'gross_weight', 'quantity', 'locked_quantity', 'is_images', 'is_sn_mgmt', 'is_shelf_life_mgmt', 'is_batch_mgmt', 'prohibited_id', 'enable_box_spec', 'box_gross_weight', 'box_net_weight', 'box_length', 'box_width', 'box_height', 'quantity_per_box', 'box_volume', 'packing_requirements' ], + where: { + [Op.or]: orConditions, + }, + limit: 10, + raw: true, + }); + + if (items.length === 0) { + return { success: true, data: { total: 0, items: [], hint: '未找到匹配商品,请尝试其他关键词' } }; + } + + // 批查条码 + const itemIds = items.map(i => i.id); + const barcodeMap = {}; + const barcodes = await ctx.model.StockBarcode.findAll({ + attributes: [ 'stock_id', 'barcode' ], + where: { stock_id: { [Op.in]: itemIds } }, + raw: true, + }); + for (const b of barcodes) { + if (!barcodeMap[b.stock_id]) barcodeMap[b.stock_id] = []; + barcodeMap[b.stock_id].push(b.barcode); + } + + // 批查违禁品 + const prohibitedIds = [ ...new Set(items.map(i => i.prohibited_id).filter(Boolean)) ]; + const prohibitedMap = {}; + if (prohibitedIds.length > 0) { + const pts = await ctx.model.ProhibitedType.findAll({ + attributes: [ 'id', 'type_name' ], + where: { id: { [Op.in]: prohibitedIds } }, + raw: true, + }); + for (const p of pts) prohibitedMap[p.id] = p.type_name || ''; + } + + // 批查商品图片(与 stock.warehouse.list 一致) + const itemIds2 = items.map(i => i.id); + const imageUrlMap2 = {}; + if (itemIds2.length > 0) { + const refs2 = await ctx.model.FileReference.findAll({ + attributes: [ 'business_id' ], + include: [{ + model: ctx.model.File, + as: 'file', + attributes: [ 'file_url' ], + required: false, + }], + where: { + business_type: 'stock', + business_id: { [Op.in]: itemIds2.map(String) }, + }, + order: [[ 'display_order', 'ASC' ]], + raw: true, + }); + for (const r of refs2) { + const sid = Number(r.business_id); + if (!imageUrlMap2[sid]) imageUrlMap2[sid] = []; + const url = (r['file.file_url'] && String(r['file.file_url']).trim()) || ''; + if (url) imageUrlMap2[sid].push(url); + } + } + + return { + success: true, + data: { + total: items.length, + items: items.map(i => ({ + id: i.id, + store_id: i.store_id, + item_code: i.item_code, + item_name: i.item_name, + barcode: barcodeMap[i.id]?.[0] || '', + brand_name: i.brand_name || '', + unit: i.stock_unit || '', + gross_weight: i.gross_weight || 0, + is_sn_mgmt: i.is_sn_mgmt === 'Y', + is_shelf_life_mgmt: i.is_shelf_life_mgmt === 'Y', + is_batch_mgmt: i.is_batch_mgmt === 'Y', + stock_qty: i.quantity || 0, + stock_locked: i.locked_quantity || 0, + stock_available: Math.max(0, (i.quantity || 0) - (i.locked_quantity || 0)), + has_images: i.is_images === 'Y', + image_url: imageUrlMap2[i.id] || [], + barcodes: barcodeMap[i.id] || [], + box_spec: i.enable_box_spec ? { + length: i.box_length || 0, width: i.box_width || 0, height: i.box_height || 0, + volume: i.box_volume || 0, gross_weight: i.box_gross_weight || 0, + net_weight: i.box_net_weight || 0, quantity_per_box: i.quantity_per_box || 0, + } : null, + packing_requirements: i.packing_requirements || '', + prohibited_type: prohibitedMap[i.prohibited_id] || '', + })), + }, + }; + } catch (error) { + return { success: false, error: `仓库商品搜索失败: ${error.message}` }; + } + }, + }); + this.register('recallHistory', { description: '回顾当前群+用户的最近对话历史。当需要上下文但信息不足时调用,获取最近N条消息记录(含AI回复),每条带序号', params: { @@ -378,8 +575,9 @@ class InboxFunctionsService extends Service { data: { total: history.length, messages: history.map(h => ({ - seq: h.seq, role: h.role === 'user' ? '用户' : 'AI', + user: h.user_name || h.user_id || null, + blocked: h.blocked || false, content: h.content || '', })), }, @@ -464,25 +662,32 @@ class InboxFunctionsService extends Service { handler: async (params = {}) => { const { ctx } = this; void params; + const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); + const groupId = String(ctx.inboxContext?.group_id || '').trim(); + const userId = String(ctx.inboxContext?.user_id || '').trim(); const groupName = String(ctx.inboxContext?.group_name || '').trim(); const userName = String(ctx.inboxContext?.user_name || '').trim(); - if (!groupName && !userName) { + if (!warehouseId) { + return { success: false, error: '无法获取仓库信息,屏蔽操作失败' }; + } + + if (!groupId && !userId) { return { success: false, - error: '无法获取群名称或用户名称,屏蔽操作需要明确的群或用户身份', + error: '无法获取群ID或用户ID,屏蔽操作需要明确的群或用户身份', }; } try { const { InboxBlock } = ctx.model; await InboxBlock.create({ - group_name: groupName || null, - user_name: userName || null, + warehouse_id: warehouseId, + group_id: groupId || null, + user_id: userId || null, }); // 失效屏蔽缓存 - const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); await ctx.service.inbox.processor.invalidateBlockCache(warehouseId); const scope = []; @@ -492,7 +697,6 @@ class InboxFunctionsService extends Service { return { success: true, data: { - blocked: groupName || userName, message: `已屏蔽${scope.join('的')},后续将不再处理你的消息。如需解除屏蔽,请联系客服到WMS解除。`, }, }; @@ -825,14 +1029,13 @@ class InboxFunctionsService extends Service { } } - // 智能查询:同一群+用户,最近 maxMessages 条(入站+出站混合) + // 智能查询:同一群,最近 maxMessages 条(入站+出站混合,含所有成员) try { const messages = await InboxMessage.findAll({ - attributes: [ 'id', 'parent_id', 'direction', 'content', 'created_at' ], + attributes: [ 'id', 'parent_id', 'direction', 'content', 'user_id', 'user_name', 'created_at' ], where: { warehouse_id: warehouseId, group_id: groupId, - user_id: userId, direction: { [Op.in]: [ 'inbound', 'outbound' ] }, }, order: [[ 'created_at', 'DESC' ]], @@ -842,11 +1045,20 @@ class InboxFunctionsService extends Service { if (messages.length === 0) return []; - // 升序排列(不再附加序号前缀,防止 AI 输出污染) - return messages.reverse().map(msg => ({ - role: msg.direction === 'inbound' ? 'user' : 'assistant', - content: msg.content || '', - })); + // 升序排列,附加上下文信息供 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 []; @@ -884,10 +1096,17 @@ class InboxFunctionsService extends Service { return { reply: null, functionName: null, functionResult: null }; } + // 拉取群历史(最多 10 条),同时注入 system prompt 和对话上下文 const history = await this.getConversationHistory({ parentId: data.parentId, - maxMessages: 5, + 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 = []; @@ -898,6 +1117,13 @@ class InboxFunctionsService extends Service { const systemPrompt = `你是一个 WMS 仓库管理系统的智能助手,支持多步推理。 已注册函数:\n${functionListText}\n +=== 群最近对话历史 === +${historyContext} +=== + +对话历史中 [已屏蔽] 标记表示该用户已主动要求屏蔽(不想被 AI 打扰)。 +如果 [已屏蔽] 用户发送了表示接手或正在处理的内容(如"我来处理""不用回复""稍等""我看看"),说明真人已接管 → 直接 silent。 + 你需要通过多轮调用来完成用户的复杂请求。每轮返回纯 JSON: 如果还需要调用函数获取信息: @@ -919,18 +1145,27 @@ class InboxFunctionsService extends Service { "action": "silent" } -约束: +真人接管判断规则(优先级最高,先于所有其他规则): +- 如果历史中某条消息 blocked=true 的用户发送了与当前问题相关的内容(如"我来处理""稍等""我看看"等表示接手的话术),说明真人客服已介入处理 → 直接 silent +- 如果 blocked 用户发送的内容与问题无关(如闲聊、询问其他事情),且当前用户仍在提问 → 正常回复当前用户 +- 如果历史中只有当前用户的连续消息,没有其他用户介入 → 正常回复 + +一般约束: - 最多 ${MAX_ROUNDS} 轮函数调用,第 ${MAX_ROUNDS} 轮必须给出最终回复 - 同一函数不要重复调用(除非参数不同) - 如果函数执行失败,换其他方式或直接告知用户 - 回复使用中文纯文本,禁止 Markdown 语法,可用 \\n 换行提升可读性 -- silent 仅用于以下纯社交/确认性语句(用户无提问、无请求):"好的""收到""OK""谢谢""再见""等会再说""手工处理""知道了" -- 以下情况严禁 silent,必须 reply:用户提出疑问、请求查询/建单/操作、函数执行完毕需告知结果、库存为0需说明原因 -- 已调用函数获取了用户请求的数据后,必须 reply 告知结果,绝对不能 silent -- 无法判断是否需要回复时,宁可回复也不要 silent +- 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 回顾对话历史`; @@ -981,9 +1216,10 @@ class InboxFunctionsService extends Service { } if (result.action === 'silent') { - // 已调用过函数 → 必须回复结果,不能 silent - if (executedFunctions.length > 0) { - ctx.logger.info('[inbox functions] 已有函数调用,忽略 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 判定无需回复,跳过回执'); diff --git a/app/service/inbox/message.js b/app/service/inbox/message.js index f572f26..e5cdff0 100644 --- a/app/service/inbox/message.js +++ b/app/service/inbox/message.js @@ -1,6 +1,7 @@ 'use strict'; const Service = require('egg').Service; +const { parseWhereConditions } = require('../../lib/query_condition_parser'); /** * 站内信消息查询/管理服务。 @@ -9,18 +10,25 @@ const Service = require('egg').Service; class InboxMessageService extends Service { /** * 消息列表(多条件筛选,分页)。 + * 支持两种参数风格: + * 1. 扁平风格:{ warehouseId, storeId, keyword, page, pageSize, ... } + * 2. 结构化风格:{ pagination: { page, pageSize }, where: { field: { operator, value } } } * 时间字段使用 app.formatDate 统一格式化输出。 * * @param {Object} params 查询参数。 * @param {number} params.warehouseId 仓库ID(必填,服务端上下文注入)。 - * @param {string|string[]} [params.storeId] 货主ID筛选,支持逗号分隔字符串或数组。 - * @param {string|string[]} [params.groupId] 群ID筛选,支持逗号分隔字符串或数组。 + * @param {Object} [params.pagination] 分页对象(结构化风格)。 + * @param {Object} [params.where] 结构化 where 条件,字段映射同 DB 列名。 + * @param {string|string[]} [params.storeId] 货主ID筛选。 + * @param {string|string[]} [params.groupId] 群ID筛选。 * @param {string} [params.groupName] 群名称模糊搜索。 * @param {string} [params.userName] 用户名模糊搜索。 - * @param {string} [params.content] 正文模糊搜索。 + * @param {string} [params.content] 正文/keyword 模糊搜索。 * @param {string} [params.sourceType] 来源类型:im / api / system。 - * @param {string} [params.direction] 消息方向筛选:inbound / outbound。 - * @param {number} [params.pushStatus] 推送状态筛选:0/1/2/3。 + * @param {string} [params.direction] 消息方向:inbound / outbound。 + * @param {number} [params.pushStatus] 推送状态:0/1/2/3。 + * @param {string} [params.startDate] 开始日期。 + * @param {string} [params.endDate] 结束日期。 * @param {number} [params.page=1] 页码。 * @param {number} [params.pageSize=20] 每页数量。 * @return {Promise<{list: Array, pagination: Object}>} 分页结果。 @@ -35,57 +43,115 @@ class InboxMessageService extends Service { throw new Error('warehouseId 无效'); } - const page = Math.max(1, Number(params.page) || 1); - const pageSize = Math.min(200, Math.max(1, Number(params.pageSize) || 20)); + // 分页:优先取 pagination 对象,兜底扁平参数 + const pag = params.pagination || {}; + const page = Math.max(1, Number(pag.page || params.page) || 1); + const pageSize = Math.min(200, Math.max(1, Number(pag.pageSize || params.pageSize) || 20)); + // 基础条件 const where = { warehouse_id: warehouseId, deleted_at: null, }; - // 货主ID:支持多选(逗号分隔字符串或数组) - const storeIds = this._normalizeIds(params.storeId); - if (storeIds.length > 0) { - where.store_id = { [Op.in]: storeIds }; + // ── 结构化 where(operator 模式)── + if (params.where && typeof params.where === 'object') { + const parsed = parseWhereConditions({ + where: params.where, + app: ctx.app, + specialFieldMap: {}, + }); + + if (!parsed.ok) { + throw new Error(`where 参数解析失败: ${parsed.reason}`); + } + + // 合并解析出的条件 + if (Array.isArray(parsed.result.dynamicConditions)) { + Object.assign(where, ...parsed.result.dynamicConditions); + } + + // 前端约定:store_id = 0 视为无货主消息 → IS NULL + if (where.store_id !== undefined && where.store_id !== null) { + const sid = where.store_id; + // Sequelize 将 [0] 展开为 IN (0),需转为 IS NULL + if (Array.isArray(sid) && sid.length === 1 && sid[0] === 0) { + where.store_id = { [Op.is]: null }; + } else if (sid === 0 || sid === '0') { + where.store_id = { [Op.is]: null }; + } + } } - // 群ID:支持多选(逗号分隔字符串或数组) + // ── 扁平参数(向后兼容,结构化 where 已设置的字段会被覆盖)── + + // 货主ID(-1 = 无货主消息,即 store_id IS NULL) + const rawStoreId = params.storeId; + if (rawStoreId === -1 || rawStoreId === '-1') { + where.store_id = { [Op.is]: null }; + } else { + const storeIds = this._normalizeIds(rawStoreId); + if (storeIds.length > 0) { + where.store_id = { [Op.in]: storeIds }; + } + } + + // 群ID const groupIds = this._normalizeStrings(params.groupId); if (groupIds.length > 0) { where.group_id = { [Op.in]: groupIds }; } - // 群名称模糊搜索 + // 群名称 const groupName = String(params.groupName || '').trim(); if (groupName) { where.group_name = { [Op.like]: `%${groupName}%` }; } - // 用户名模糊搜索 + // 用户名 const userName = String(params.userName || '').trim(); if (userName) { where.user_name = { [Op.like]: `%${userName}%` }; } - // 正文模糊搜索 - const content = String(params.content || '').trim(); - if (content) { - where.content = { [Op.like]: `%${content}%` }; + // 关键词:content + group_name + user_name + const rawKw = params.content || params.keyword; + const keyword = Array.isArray(rawKw) + ? String(rawKw.filter(Boolean)[0] || '').trim() + : String(rawKw || '').trim(); + if (keyword) { + const like = { [Op.like]: `%${keyword}%` }; + where[Op.or] = [ + { content: like }, + { group_name: like }, + { user_name: like }, + ]; } - // 来源类型筛选 + // 来源类型 const VALID_SOURCE_TYPES = [ 'im', 'api', 'system' ]; const sourceType = String(params.sourceType || '').trim(); if (sourceType && VALID_SOURCE_TYPES.includes(sourceType)) { where.source_type = sourceType; } - // 方向筛选 + // 日期范围(扁平参数兜底,结构化 where 已通过 created_at 处理) + if (!where.created_at) { + const startDate = params.startDate || params.start_date; + const endDate = params.endDate || params.end_date; + if (startDate || endDate) { + where.created_at = {}; + if (startDate) where.created_at[Op.gte] = new Date(startDate); + if (endDate) where.created_at[Op.lte] = new Date(endDate); + } + } + + // 方向 if (params.direction && [ 'inbound', 'outbound' ].includes(params.direction)) { where.direction = params.direction; } - // 推送状态筛选 + // 推送状态 if (params.pushStatus !== undefined && params.pushStatus !== null && params.pushStatus !== '') { const status = Number(params.pushStatus); if ([ 0, 1, 2, 3 ].includes(status)) { @@ -103,17 +169,20 @@ class InboxMessageService extends Service { limit: pageSize, }); - // 批量查货主名称 + // 批量查货主备注名称(StoreWarehouse.store_remask) const storeIdsInResult = [ ...new Set(rows.map(r => r.store_id).filter(Boolean)) ]; const storeNameMap = {}; if (storeIdsInResult.length > 0) { - const stores = await ctx.model.Store.findAll({ - attributes: [ 'id', 'company_name' ], - where: { id: { [Op.in]: storeIdsInResult } }, + const contracts = await ctx.model.StoreWarehouse.findAll({ + attributes: [ 'store_id', 'store_remask' ], + where: { + store_id: { [Op.in]: storeIdsInResult }, + warehouse_id: warehouseId, + }, raw: true, }); - for (const s of stores) { - storeNameMap[s.id] = s.company_name || ''; + for (const c of contracts) { + storeNameMap[c.store_id] = c.store_remask || ''; } } diff --git a/app/service/inbox/processor.js b/app/service/inbox/processor.js index c256ea6..bec7f8b 100644 --- a/app/service/inbox/processor.js +++ b/app/service/inbox/processor.js @@ -88,6 +88,8 @@ 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. 处理消息正文,挂载上下文 @@ -104,15 +106,8 @@ class InboxProcessorService extends Service { const bindHandled = await this.tryBindGroup(data); if (bindHandled) return; - // 4. 群未绑定货主则跳过 AI 解析 - const storeId = Number(ctx.inboxContext?.store_id || 0); - if (!storeId) { - ctx.logger.info(`[inbox processor] 群未绑定货主,跳过 AI ext_id=${extId}`); - return; - } - - // 4.1 注入群的 group_type / sub_type / ai_enabled 到上下文 - if (!ctx.inboxContext.group_type || !ctx.inboxContext.sub_type || ctx.inboxContext.ai_enabled === undefined) { + // 4. 加载群的 group_type / sub_type / ai_enabled + if (ctx.inboxContext.ai_enabled === undefined) { try { const groupId = String(ctx.inboxContext.group_id || '').trim(); if (groupId) { @@ -121,27 +116,42 @@ class InboxProcessorService extends Service { where: { group_id: groupId, warehouse_id: warehouseId }, raw: true, }); - if (group) { - ctx.inboxContext.group_type = group.group_type || ''; - ctx.inboxContext.sub_type = group.sub_type || ''; - ctx.inboxContext.ai_enabled = group.ai_enabled; - ctx.logger.info( - `[inbox processor] 注入群分组信息 group_type=${ctx.inboxContext.group_type} sub_type=${ctx.inboxContext.sub_type} ai_enabled=${ctx.inboxContext.ai_enabled}` - ); - } + 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}`); + ctx.inboxContext.ai_enabled = 0; } } - // 4.2 群未启用AI → 跳过 AI 解析(灰度开关) - if (ctx.inboxContext.ai_enabled === 0) { + // 5. 群未启用AI → 跳过(ai_enabled != 1 一律跳过,安全默认) + if (ctx.inboxContext.ai_enabled !== 1) { ctx.logger.info(`[inbox processor] 群未启用AI自动回复,跳过 AI ext_id=${extId}`); return; } - // 5. DeepSeek 两步交互 + // 5.1 加载屏蔽用户列表,注入上下文供 AI 判断真人接管 + if (!ctx.inboxContext._blockedUserIds) { + try { + const { InboxBlock } = ctx.model; + const rows = await InboxBlock.findAll({ + attributes: [ 'user_id' ], + where: { warehouse_id: warehouseId }, + raw: true, + }); + ctx.inboxContext._blockedUserIds = new Set( + rows.map(r => String(r.user_id || '').trim()).filter(Boolean) + ); + } catch (e) { + ctx.inboxContext._blockedUserIds = new Set(); + } + } + + // 6. DeepSeek 两步交互(AI 内部自行判断真人接管) const aiResult = await ctx.service.inbox.functions.processWithAI({ content: data.content || '', ext_data: data.ext_data || null, @@ -152,6 +162,17 @@ class InboxProcessorService extends Service { // AI 显式指示跳过(silent 动作)→ 同上 if (aiResult.skip || (!aiResult.reply && (!aiResult.functionName || aiResult.functionName === 'none'))) { ctx.logger.info(`[inbox processor] 无回复且未匹配函数,跳过回执 ext_id=${extId}`); + // 保存 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}`); + } + } return; } @@ -161,9 +182,10 @@ class InboxProcessorService extends Service { `function=${aiResult.functionName || 'direct'} reply_length=${replyContent.length}` ); - // 6. 写入 outbound 回执记录 - const ackExtId = `sys:ack:${extId}`; + // 7. 写入 outbound 回执记录 + ackExtId = `sys:ack:${extId}`; + let outboundId = null; try { const existAck = await InboxMessage.findOne({ where: { ext_id: ackExtId }, @@ -171,8 +193,10 @@ class InboxProcessorService extends Service { paranoid: false, }); - if (!existAck) { - await InboxMessage.create({ + if (existAck) { + outboundId = existAck.id; + } else { + const created = await InboxMessage.create({ ext_id: ackExtId, warehouse_id: warehouseId, store_id: data.store_id || null, @@ -190,6 +214,7 @@ class InboxProcessorService extends Service { ai_thoughts: aiResult.thoughts || null, flags: {}, }); + outboundId = created.id; ctx.logger.info(`[inbox processor] 回执记录写入成功 parent_id=${parentId}`); } @@ -197,38 +222,142 @@ class InboxProcessorService extends Service { ctx.logger.warn(`[inbox processor] 回执记录写入失败: ${writeError.message}`); } - // 7. 查回调地址并发送 - const callbackUrl = await this.getApiAppCallbackUrl(warehouseId); + // 8. 查回调地址并发送(带 MD5 签名) + callbackConfig = await this.getApiAppCallbackConfig(warehouseId); + const callbackUrl = callbackConfig.url; if (!callbackUrl) { ctx.logger.info(`[inbox processor] 仓库 ${warehouseId} 未配置回调地址,跳过回执 ext_id=${extId}`); return; } - const ackBody = { - content: replyContent, - ext_data: data.ext_data || null, - ext_id: extId || null, + 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(callbackUrl, { + const response = await ctx.curl(urlWithSign, { method: 'POST', dataType: 'json', contentType: 'json', - data: ackBody, + 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 } } + ); + } } 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); + } } } @@ -258,7 +387,7 @@ class InboxProcessorService extends Service { raw: true, }); if (existingGroup && existingGroup.store_id) { - await this.writeOutboundReply(data, '已在绑定状态,无需重复操作'); + await this.writeOutboundReply(data, '已在绑定状态,无需重复操作', 'bind_confirm'); return true; } } catch (e) { @@ -270,7 +399,7 @@ class InboxProcessorService extends Service { try { const cacheValue = await ctx.app.getCacheAsync(cacheKey); if (!cacheValue || !cacheValue.store_id) { - await this.writeOutboundReply(data, '绑群码无效或已过期,请重新生成'); + await this.writeOutboundReply(data, '绑群码无效或已过期,请重新生成', 'bind_confirm'); return true; } @@ -302,7 +431,7 @@ class InboxProcessorService extends Service { `[inbox processor] 绑群成功 group_id=${groupId} store=${storeName}` ); - await this.writeOutboundReply(data, `绑定「${storeName}」成功`); + await this.writeOutboundReply(data, `绑定「${storeName}」成功`, 'bind_confirm'); // 绑定成功后自动查询面单余额 try { @@ -311,7 +440,7 @@ class InboxProcessorService extends Service { ? `面单余额:总量 ${balanceResult.data.print_quantity},已锁定 ${balanceResult.data.print_quantity_locked},可用 ${balanceResult.data.available}` : `面单余额查询失败:${balanceResult?.error || '未知错误'}`; // 使用独立 ext_id 避免与绑定成功回执冲突 - await this.writeOutboundReply({ ...data, ext_id: `${data.ext_id}:balance` }, balanceMsg); + await this.writeOutboundReply({ ...data, ext_id: `${data.ext_id}:balance` }, balanceMsg, 'balance'); } catch (balanceErr) { ctx.logger.warn(`[inbox processor] 绑群后面单余额查询异常: ${balanceErr.message}`); } @@ -334,9 +463,10 @@ 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。 * @return {Promise} */ - async writeOutboundReply(data, replyContent) { + async writeOutboundReply(data, replyContent, source = 'ai_reply') { const { ctx } = this; const { InboxMessage } = ctx.model; @@ -357,13 +487,17 @@ class InboxProcessorService extends Service { ); } + const ackExtId = `sys:ack:${extId}`; + const callbackConfig = await this.getApiAppCallbackConfig(warehouseId); try { - const ackExtId = `sys:ack:${extId}`; + let outboundId = null; const existAck = await InboxMessage.findOne({ where: { ext_id: ackExtId }, attributes: [ 'id' ], paranoid: false, }); - if (!existAck) { - await InboxMessage.create({ + if (existAck) { + outboundId = existAck.id; + } else { + const created = await InboxMessage.create({ ext_id: ackExtId, warehouse_id: warehouseId, store_id: ctx.inboxContext?.store_id || null, direction: 'outbound', parent_id: parentId || null, @@ -376,26 +510,70 @@ class InboxProcessorService extends Service { content: replyContent, ext_data: data.ext_data || null, flags: {}, }); + outboundId = created.id; } - const callbackUrl = await this.getApiAppCallbackUrl(warehouseId); + const callbackUrl = callbackConfig.url; if (callbackUrl) { - const curlResult = await ctx.curl(callbackUrl, { - method: 'POST', dataType: 'json', contentType: 'json', + const crypto = require('crypto'); + const method = 'notify.reply'; + const notifyBody = { + code: 200, data: { + type: source === 'ai_reply' ? 'ai' : source === 'bind_confirm' ? 'bind' : source === 'balance' ? 'balance' : 'error', content: replyContent, ext_data: data.ext_data || null, - ext_id: extId, + ext_id: String(outboundId), group_id: groupId, user_id: userId, group_name: groupName, user_name: userName, + 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 || ''; + + // MD5 签名:MD5(appSecret + timestamp + bodyJson) + 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)}`; + + const curlResult = await ctx.curl(urlWithSign, { + method: 'POST', dataType: 'json', contentType: 'json', + data: notifyBody, headers: { 'Content-Type': 'application/json' }, timeout: 10000, }); - // HTTP 200 → 更新回执消息推送状态为已送达 - if (curlResult && curlResult.status === 200) { + // HTTP 200 且 body.code=200 → 推送成功 + const pushOk = curlResult && curlResult.status === 200 + && (!curlResult.data || curlResult.data.code === undefined || curlResult.data.code === 200); + + // 记录出站通知日志到 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: curlResult ? curlResult.status : null, + body: JSON.stringify(notifyBody).substring(0, 65535), + result: curlResult ? JSON.stringify(curlResult.data || {}).substring(0, 65535) : '', + use_time: Date.now() - timestamp * 1000, + created_at: new Date(), + }); + } catch (logErr) { + ctx.logger.error('[notify-log] 日志写入失败: ' + logErr.message); + } + + if (pushOk) { await InboxMessage.update( { push_status: 2, @@ -415,10 +593,58 @@ class InboxProcessorService extends Service { { where: { id: parentId } } ); } + } else { + // 推送失败:回写状态和原因 + await InboxMessage.update( + { + push_status: 3, + push_response: { + http_status: curlResult ? curlResult.status : null, + body: curlResult ? (curlResult.data || null) : null, + error: curlResult ? '回调返回非200或code非200' : '回调无响应', + }, + }, + { where: { ext_id: ackExtId } } + ); } + } else { + // 未配置回调地址:回写状态 + await InboxMessage.update( + { + push_status: 3, + push_response: { error: '未配置回调地址(wms_api_app.callback_url为空)' }, + }, + { where: { ext_id: ackExtId } } + ); + ctx.logger.info(`[inbox processor] 仓库 ${warehouseId} 未配置回调地址,回写失败状态 ext_id=${extId}`); } } catch (error) { ctx.logger.warn(`[inbox processor] 回执写入失败: ${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); + } + try { + const { WarehouseLog } = ctx.model; + const crypto = require('crypto'); + await WarehouseLog.create({ + log_id: 'WN-' + Date.now() + '-' + crypto.randomBytes(3).toString('hex'), + app_key: (await this.getApiAppCallbackConfig(warehouseId)).appKey || null, + method: 'notify.reply', + warehouse_id: warehouseId || 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); + } } } @@ -430,11 +656,11 @@ class InboxProcessorService extends Service { async isBlocked() { const { ctx } = this; const app = ctx.app; - const groupName = String(ctx.inboxContext?.group_name || '').trim(); - const userName = String(ctx.inboxContext?.user_name || '').trim(); + const groupId = String(ctx.inboxContext?.group_id || '').trim(); + const userId = String(ctx.inboxContext?.user_id || '').trim(); const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); - if (!groupName && !userName) return false; + if (!groupId && !userId) return false; try { // 1. 尝试从缓存读取屏蔽列表 @@ -444,15 +670,19 @@ class InboxProcessorService extends Service { if (!blockedSet || !(blockedSet instanceof Set)) { // 2. 缓存未命中,查库并填入缓存 const { InboxBlock } = ctx.model; - const rows = await InboxBlock.findAll({ attributes: [ 'group_name', 'user_name' ], raw: true }); + const rows = await InboxBlock.findAll({ + attributes: [ 'group_id', 'user_id' ], + where: { warehouse_id: warehouseId }, + raw: true, + }); blockedSet = new Set(); for (const row of rows) { - const g = String(row.group_name || '').trim(); - const u = String(row.user_name || '').trim(); + const g = String(row.group_id || '').trim(); + const u = String(row.user_id || '').trim(); if (g && u) blockedSet.add(`${g}:${u}`); - if (g) blockedSet.add(`${g}:*`); - if (u) blockedSet.add(`*:${u}`); + if (g && !u) blockedSet.add(`${g}:*`); + if (!g && u) blockedSet.add(`*:${u}`); } // TTL 5 分钟 @@ -460,9 +690,9 @@ class InboxProcessorService extends Service { } // 3. 检查当前消息是否命中屏蔽规则 - if (groupName && userName && blockedSet.has(`${groupName}:${userName}`)) return true; - if (groupName && blockedSet.has(`${groupName}:*`)) return true; - if (userName && blockedSet.has(`*:${userName}`)) return true; + if (groupId && userId && blockedSet.has(`${groupId}:${userId}`)) return true; + if (groupId && blockedSet.has(`${groupId}:*`)) return true; + if (userId && blockedSet.has(`*:${userId}`)) return true; return false; } catch (error) { @@ -487,20 +717,20 @@ class InboxProcessorService extends Service { } /** - * 获取仓库 ApiApp 回调地址。 + * 获取仓库 ApiApp 回调配置(URL + 签名凭证)。 * * @param {number} warehouseId 仓库ID。 - * @return {Promise} 回调 URL,未配置时返回 null。 + * @return {Promise<{url: string|null, appKey: string|null, appSecret: string|null}>} */ - async getApiAppCallbackUrl(warehouseId) { + async getApiAppCallbackConfig(warehouseId) { const { ctx } = this; if (!Number.isFinite(warehouseId) || warehouseId <= 0) { - return null; + return { url: null, appKey: null, appSecret: null }; } try { const apiApp = await ctx.model.ApiApp.findOne({ - attributes: [ 'callback_url' ], + attributes: [ 'callback_url', 'self_app_key', 'self_app_secret' ], where: { warehouse_id: warehouseId, interface_type_id: WAREHOUSE_INTERFACE_TYPE_ID, @@ -509,13 +739,27 @@ class InboxProcessorService extends Service { raw: true, }); - return (apiApp && apiApp.callback_url) || null; + return { + url: (apiApp && apiApp.callback_url) || null, + appKey: (apiApp && apiApp.self_app_key) || null, + appSecret: (apiApp && apiApp.self_app_secret) || null, + }; } catch (error) { - ctx.logger.warn(`[inbox processor] 查询回调地址失败: ${error.message}`); - return null; + ctx.logger.warn(`[inbox processor] 查询回调配置失败: ${error.message}`); + return { url: null, appKey: null, appSecret: null }; } } + /** + * 获取仓库 ApiApp 回调地址(兼容旧调用)。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 回调 URL。 + */ + async getApiAppCallbackUrl(warehouseId) { + const config = await this.getApiAppCallbackConfig(warehouseId); + return config.url; + } + /** * 尝试从消息正文中提取仓库ID。 * 子类或业务方可覆盖此方法以实现自定义解析逻辑。 diff --git a/app/service/inbox/receiver.js b/app/service/inbox/receiver.js index b54acc1..4a7e279 100644 --- a/app/service/inbox/receiver.js +++ b/app/service/inbox/receiver.js @@ -146,6 +146,7 @@ class InboxReceiverService extends Service { store_id: storeId || null, source_type: sourceType, source_extra: data.source_extra || null, + ai_enabled: 0, }, }); } catch (groupErr) { diff --git a/app/service/qimenMethods/stockout.js b/app/service/qimenMethods/stockout.js index d7fa424..ff2875a 100644 --- a/app/service/qimenMethods/stockout.js +++ b/app/service/qimenMethods/stockout.js @@ -25,7 +25,7 @@ class stockoutServer extends MainService { * @return {Promise} 返回 success / fail 结果 */ async create(data) { - const { app, ctx, appKey, storeId, warehouseId, warehouseCode } = this; + const { app, ctx, storeId, warehouseId, warehouseCode } = this; const { deliveryOrder, orderLines } = data.request; // 单条 orderLine 转为数组 @@ -106,7 +106,7 @@ class stockoutServer extends MainService { remark: deliveryOrder.remark || null, warehouse_id: warehouseId, store_id: storeId, - qimen_owner_code: appKey, + qimen_owner_code: items[0].ownerCode, qimen_warehouse_code: warehouseCode, source_type: 'QM', created_at: new Date(), diff --git a/app/service/systemMethods/storage/stockout.js b/app/service/systemMethods/storage/stockout.js index c0d4f80..d91bd6f 100644 --- a/app/service/systemMethods/storage/stockout.js +++ b/app/service/systemMethods/storage/stockout.js @@ -4,7 +4,7 @@ const MainService = require('../../main'); /** * 系统方法层:storage.stockout(非订单出库单)。 - * 说明:该实现为最小可用能力,复用订单分表模型读取当前仓库的出库单与明细。 + * 说明:直接读写 wms_order_stockout + wms_order_stockout_items 表。 */ class StorageStockoutService extends MainService { constructor(ctx) { @@ -40,11 +40,11 @@ class StorageStockoutService extends MainService { const page = Math.max(Number(pagination.page) || 1, 1); const pageSize = Math.max(Number(pagination.pageSize) || 20, 1); const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; - const OrderDeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + const OrderStockoutModel = ctx.model.OrderStockout; const andConditions = [ { warehouse_id: warehouseId }, - { delete_at: null }, + { deleted_at: null }, ]; const dynamicConditions = Array.isArray(parsed && parsed.dynamicConditions) ? parsed.dynamicConditions : []; @@ -60,23 +60,20 @@ class StorageStockoutService extends MainService { const keyword = String(quickValue).trim(); andConditions.push({ [Op.or]: [ - { delivery_order_code: { [Op.like]: `%${keyword}%` } }, - { source_order_codes: { [Op.like]: `%${keyword}%` } }, - { buyer_nick: { [Op.like]: `%${keyword}%` } }, - { mobile: { [Op.like]: `%${keyword}%` } }, - { name: { [Op.like]: `%${keyword}%` } }, + { stockout_order_code: { [Op.like]: `%${keyword}%` } }, + { remark: { [Op.like]: `%${keyword}%` } }, ], }); } const validSortFields = [ 'id', - 'delivery_order_code', - 'status', - 'outbound_status', + 'stockout_order_code', + 'order_status', + 'order_type', 'updated_at', - 'create_at', - 'delivery_time', + 'created_at', + 'order_create_time', ]; const sortField = validSortFields.includes(String(sort.sortField || '').trim()) ? String(sort.sortField).trim() @@ -84,7 +81,7 @@ class StorageStockoutService extends MainService { const sortOrder = String(sort.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; const finalWhere = { [Op.and]: andConditions }; - const { count, rows } = await OrderDeliveryModel.findAndCountAll({ + const { count, rows } = await OrderStockoutModel.findAndCountAll({ where: finalWhere, order: [[ sortField, sortOrder ], [ 'id', 'DESC' ]], limit: pageSize, @@ -117,33 +114,34 @@ class StorageStockoutService extends MainService { * 出库单明细查询。 * @param {Object} data 请求体 * @param {number} [data.id] 出库单ID - * @param {string} [data.delivery_order_code] 出库单号 + * @param {string} [data.stockout_order_code] 出库单号 * @return {Promise} 统一成功包装响应 */ async listItems(data = {}) { const { ctx } = this; const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; const id = Number(data.id || 0); - const deliveryOrderCode = String(data.delivery_order_code || '').trim(); + // 兼容 delivery_order_code 旧参数名 + const stockoutOrderCode = String(data.stockout_order_code || data.delivery_order_code || '').trim(); - if (!id && !deliveryOrderCode) { - return this.fail('id 或 delivery_order_code 至少传一个'); + if (!id && !stockoutOrderCode) { + return this.fail('id 或 stockout_order_code 至少传一个'); } - const OrderDeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); - const OrderItemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); + const OrderStockoutModel = ctx.model.OrderStockout; + const OrderStockoutItemsModel = ctx.model.OrderStockoutItems; const where = { warehouse_id: warehouseId, - delete_at: null, + deleted_at: null, }; if (id > 0) { where.id = id; } else { - where.delivery_order_code = deliveryOrderCode; + where.stockout_order_code = stockoutOrderCode; } - const order = await OrderDeliveryModel.findOne({ + const order = await OrderStockoutModel.findOne({ where, raw: true, }); @@ -155,7 +153,7 @@ class StorageStockoutService extends MainService { }); } - const list = await OrderItemsModel.findAll({ + const list = await OrderStockoutItemsModel.findAll({ where: { order_id: order.id, }, @@ -168,6 +166,232 @@ class StorageStockoutService extends MainService { list, }); } + + /** + * 出库单确认(直出)。 + * 不改变内部库存,直接按出库单明细的计划数量确认。 + * 出站同步 taobao.qimen.stockout.confirm 成功后,状态才推进到 COMPLETED。 + * 要求 express_code 已填写,否则拒绝确认。 + * @param {Object} data 请求体 + * @param {number} data.id 出库单ID(必填) + * @return {Promise} 统一成功/失败包装响应 + */ + async confirm(data = {}) { + const { ctx } = this; + const id = Number(data.id || 0); + + if (!id) { + return this.fail('缺少出库单ID'); + } + + const order = await ctx.model.OrderStockout.findByPk(id); + if (!order) { + return this.fail('出库单不存在'); + } + + if (!order.canConfirm || !order.canConfirm()) { + return this.fail(`出库单当前状态(${order.order_status})不允许确认`); + } + + // 校验运单号是否已填写 + if (!order.waybill_code) { + return this.fail('出库单未填写运单号(waybill_code),请先更新运单号后再确认'); + } + + // 第一步:事务内写入明细 actual_qty(暂不改变 order_status) + const transaction = await ctx.model.transaction(); + let items; + try { + items = await ctx.model.OrderStockoutItems.findAll({ + where: { order_id: id }, + transaction, + }); + + for (const item of items) { + await item.update({ + actual_qty: item.plan_qty, + updated_at: new Date(), + }, { transaction }); + } + + await transaction.commit(); + } catch (err) { + await transaction.rollback(); + ctx.logger.error('[stockout.confirm] 明细更新失败:', err); + return this.fail(`确认失败:${err.message}`); + } + + // 第二步:出站通知 ERP(taobao.qimen.stockout.confirm) + const { app } = this; + let qimenSuccess = false; + let qimenMessage = ''; + + if (app.qimenClient && order.qimen_owner_code && order.qimen_warehouse_code) { + try { + const now = app.formatDate(new Date()); + const waybillCodes = Array.isArray(order.waybill_codes) && order.waybill_codes.length > 0 + ? order.waybill_codes + : [ order.waybill_code ].filter(Boolean); + + const outboundData = { + deliveryOrder: { + totalOrderLines: order.total_order_lines, + deliveryOrderCode: order.stockout_order_code, + deliveryOrderId: order.id, + warehouseCode: order.qimen_warehouse_code, + orderType: order.order_type, + status: 'DELIVERED', + outBizCode: order.stockout_order_code, + confirmType: 0, + orderConfirmTime: now, + operatorCode: '', + operatorName: '', + }, + packages: { + package: waybillCodes.map(code => ({ + logisticsCode: order.express_code || 'OTHER', + logisticsName: order.express_name || 'OTHER', + expressCode: code, + packageCode: order.stockout_order_code, + items: items.map(item => ({ + itemCode: item.item_code || '', + itemId: item.item_id || '', + quantity: item.plan_qty || 0, + })), + })), + }, + orderLines: items.map(item => ({ + orderLineNo: item.order_line_no || '', + ownerCode: item.owner_code || order.qimen_owner_code, + itemCode: item.item_code || '', + itemId: item.item_id || '', + itemName: item.item_name || '', + planQty: item.plan_qty || 0, + actualQty: item.plan_qty || 0, + inventoryType: item.inventory_type || 'ZP', + })), + }; + + const sendResult = await app.qimenClient.send( + 'taobao.qimen.stockout.confirm', + order.qimen_owner_code, + outboundData, + { ctx } + ); + + // 解析奇门响应 + const response = (sendResult && sendResult.xmlArray && sendResult.xmlArray.response) + ? (Array.isArray(sendResult.xmlArray.response) ? sendResult.xmlArray.response[0] : sendResult.xmlArray.response) + : {}; + qimenSuccess = String(response.flag || '').trim() === 'success'; + qimenMessage = qimenSuccess ? '' : `${response.code || ''} ${response.message || '未知错误'}`.trim(); + } catch (outboundErr) { + qimenMessage = outboundErr.message || '出站通知异常'; + ctx.logger.error(`[stockout.confirm] 出站通知异常: ${qimenMessage}`); + } + } else { + ctx.logger.warn(`[stockout.confirm] 跳过出站通知: qimenClient=${!!app.qimenClient}, ownerCode=${order.qimen_owner_code}, warehouseCode=${order.qimen_warehouse_code}`); + } + + // 第三步:根据出站结果更新状态 + if (qimenSuccess) { + await ctx.model.OrderStockout.update( + { order_status: 'COMPLETED', sync_status: 'SUCCESS', sync_message: '', updated_at: new Date() }, + { where: { id: order.id } } + ); + ctx.logger.info(`[stockout.confirm] 确认完成: ${order.stockout_order_code}`); + + return this.success('确认成功', { + id: order.id, + stockout_order_code: order.stockout_order_code, + order_status: 'COMPLETED', + logisticsName: 'OTHER', + expressCode: order.express_code, + expressCodes: order.express_codes, + qimenSync: 'success', + }); + } + + // 出站失败:更新 sync_status,order_status 不变 + await ctx.model.OrderStockout.update( + { sync_status: 'FAILED', sync_message: qimenMessage, updated_at: new Date() }, + { where: { id: order.id } } + ); + ctx.logger.error(`[stockout.confirm] 出站同步失败: ${order.stockout_order_code} - ${qimenMessage}`); + + return this.fail(`出站同步失败: ${qimenMessage || '未发起出站通知'}`); + } + + /** + * 更新出库单快递和运单号。 + * 用于在确认前填写 express_code / waybill_code / waybill_codes。 + * express_code 传入后自动从系统快递表解析 express_name。 + * @param {Object} data 请求体 + * @param {number} data.id 出库单ID(必填) + * @param {string} [data.express_code] 快递公司编码(如 SF、STO),传入后自动解析 express_name + * @param {string} [data.waybill_code] 运单号 + * @param {string[]} [data.waybill_codes] 运单号列表 + * @return {Promise} 统一成功/失败包装响应 + */ + async updateExpress(data = {}) { + const { ctx } = this; + const id = Number(data.id || 0); + + if (!id) { + return this.fail('缺少出库单ID'); + } + + const order = await ctx.model.OrderStockout.findByPk(id); + if (!order) { + return this.fail('出库单不存在'); + } + + const updateData = { updated_at: new Date() }; + + // express_code:自动解析 express_name + if (data.express_code !== undefined) { + updateData.express_code = data.express_code || null; + if (data.express_code) { + try { + const expressMap = await ctx.service.systems.setting.express.getSystemExpressMap(); + const info = expressMap.get(String(data.express_code).trim().toUpperCase()); + updateData.express_name = info ? info.name : ''; + } catch (e) { + ctx.logger.warn('[updateExpress] 解析快递名称失败: ' + e.message); + updateData.express_name = ''; + } + } else { + updateData.express_name = null; + } + } + + if (data.waybill_code !== undefined) { + updateData.waybill_code = data.waybill_code || null; + } + if (data.waybill_codes !== undefined) { + const codes = data.waybill_codes; + if (codes !== null && !Array.isArray(codes)) { + return this.fail('waybill_codes 必须是数组或 null'); + } + updateData.waybill_codes = codes; + } + + if (Object.keys(updateData).length <= 1) { + return this.fail('没有需要更新的字段'); + } + + await order.update(updateData); + await order.reload(); + + return this.success('更新成功', { + id: order.id, + stockout_order_code: order.stockout_order_code, + express_code: order.express_code, + express_name: order.express_name, + waybill_code: order.waybill_code, + waybill_codes: order.waybill_codes, + }); + } } module.exports = StorageStockoutService; diff --git a/app/service/systems/apiApp.js b/app/service/systems/apiApp.js index c5b7042..1613a90 100644 --- a/app/service/systems/apiApp.js +++ b/app/service/systems/apiApp.js @@ -149,9 +149,7 @@ class ApiAppService extends Service { self_ip_whitelist: Array.isArray(data.self_ip_whitelist) ? data.self_ip_whitelist : null, callback_url: String(data.callback_url || '').trim() || null, rate_limit: Number(data.rate_limit) || 1000, - sign_method: [ 'md5', 'hmac', 'sha256' ].includes(String(data.sign_method || '').trim()) - ? String(data.sign_method).trim() - : 'md5', + sign_method: 'md5', is_enabled: 1, }; @@ -209,11 +207,7 @@ class ApiAppService extends Service { for (const field of updatableFields) { if (data[field] !== undefined && data[field] !== null) { if (field === 'sign_method') { - const val = String(data[field]).trim(); - if (![ 'md5', 'hmac', 'sha256' ].includes(val)) { - throw new Error('签名方法仅支持 md5/hmac/sha256'); - } - record[field] = val; + throw new Error('签名方法当前仅支持 md5,不允许修改'); } else if (field === 'is_enabled') { record[field] = Number(data[field]); } else if (field === 'rate_limit') { diff --git a/app/service/systems/express_platform.js b/app/service/systems/express_platform.js index a2d3907..cb382d0 100644 --- a/app/service/systems/express_platform.js +++ b/app/service/systems/express_platform.js @@ -704,8 +704,8 @@ class ExpressPlatformService extends MainService { console.log('order', order); const expressListItem = ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code) || {}; let playload = { - object_Id: `${order.warehouse_id}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单唯一标识必须为字符串 - orderno: `${order.warehouse_id}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单号必须为字符串 + object_Id: `${order.warehouse_id.toString(16)}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单唯一标识必须为字符串 + orderno: `${order.warehouse_id.toString(16)}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单号必须为字符串 plattradeno: listByWarehousePlatformCode.platform_code === 'DY' && order.from_key === 23060081 && !!order.pay_no ? order.pay_no : order.source_order_codes || order.delivery_order_code || '', ismultiplepieces: order.package_count > 1 ? 1 : 0, logisticno: allocatedWaybillMap.get(`${Number(order.id) || 0}:${Number(order_tmp.business_key) || 0}`) || '', @@ -1007,7 +1007,8 @@ class ExpressPlatformService extends MainService { switch (listByWarehousePlatformCode.platform_code) { case 'KS': successUpdates = (result.results || []).map(item => { - const [ warehouse_id, order_id, business_key ] = String(item.orderno || '').split('_'); + const [ warehouse_id_hex, order_id, business_key ] = String(item.orderno || '').split('_'); + const warehouse_id = parseInt(warehouse_id_hex, 16); const waybillCode = resolveWaybillCode(item); return { warehouse_id, @@ -1042,7 +1043,9 @@ class ExpressPlatformService extends MainService { break; case 'DY': successUpdates = (result.results || []).map(item => { - const [ warehouse_id, order_id, business_key ] = String(item.orderno || '').split('_'); + const [ warehouse_id_hex, order_id, business_key ] = String(item.orderno || '').split('_'); + const warehouse_id = parseInt(warehouse_id_hex, 16); + const waybillCode = resolveWaybillCode(item); return { warehouse_id, @@ -1142,7 +1145,8 @@ class ExpressPlatformService extends MainService { successUpdates = (batchPrintResult && batchPrintResult.results || []).map(item => { const objectId = String(item && item.orderno || '').trim(); - const [ warehouse_id, order_id, business_key ] = objectId.split('_'); + const [ warehouse_id_hex, order_id, business_key ] = objectId.split('_'); + const warehouse_id = parseInt(warehouse_id_hex, 16); const waybillCode = String(item && (item.logisticno || item.waybill_code) || '').trim(); const rawPrintData = item && Object.prototype.hasOwnProperty.call(item, 'printdata') ? item.printdata @@ -1193,7 +1197,8 @@ class ExpressPlatformService extends MainService { } case 'XHS':{ successUpdates = (result.results || []).map(item => { - const [ warehouse_id, order_id, business_key ] = String(item.orderno || '').split('_'); + const [ warehouse_id_hex, order_id, business_key ] = String(item.orderno || '').split('_'); + const warehouse_id = parseInt(warehouse_id_hex, 16); const waybillCode = resolveWaybillCode(item); const printInfo = item.print_info ?? item.printinfo; return { @@ -1235,7 +1240,8 @@ class ExpressPlatformService extends MainService { if (!objectId || objectIdParts.length < 3) { throw new Error(`视频号取号返回 object_id 无法解析: ${objectId || JSON.stringify(item)}`); } - const [ warehouse_id, order_id, business_key ] = objectIdParts; + const [ warehouse_id_hex, order_id, business_key ] = objectIdParts; + const warehouse_id = parseInt(warehouse_id_hex, 16); const waybillCode = resolveWaybillCode(item); const rawPrintData = item && Object.prototype.hasOwnProperty.call(item, 'raw') ? item.raw diff --git a/app/service/systems/upload.js b/app/service/systems/upload.js index 0dbf547..ba971f6 100644 --- a/app/service/systems/upload.js +++ b/app/service/systems/upload.js @@ -282,8 +282,8 @@ class UploadService extends Service { .replace('{filemd5}', md5) .replace('{.suffix}', ext); - // 添加目录前缀并规范化路径 - const fullPath = path.posix.join(result).replace(/\/\//g, '/'); + // 添加目录前缀并规范化路径,去除前导 / 防止与 CDN 域名拼接时产生 // + const fullPath = path.posix.join(result).replace(/\/\//g, '/').replace(/^\/+/, ''); return fullPath; } @@ -439,7 +439,7 @@ class UploadService extends Service { this.ctx.logger.warn('上传成功通知缺少用户信息,使用默认值'); } - const resolvedFileKey = String(data.url || data.fileKey || ''); + const resolvedFileKey = String(data.url || data.fileKey || '').replace(/^\/+/, ''); const resolvedFileName = String(data.fileName || data.name || path.basename(resolvedFileKey || 'file')); const resolvedFileSize = Number(data.fileSize || data.size || 0); diff --git a/app/service/warehouse.js b/app/service/warehouse.js index 701d20e..0b21fbe 100644 --- a/app/service/warehouse.js +++ b/app/service/warehouse.js @@ -193,6 +193,8 @@ class WarehouseService extends Service { code: 400, message: '参数缺失或错误: method/v/timestamp', data: null, + warehouseId: null, + appKey: String(query.app_key || '').trim() || null, }; } @@ -206,12 +208,18 @@ class WarehouseService extends Service { code: 400, message: `时间戳已过期或无效,服务器时间: ${nowTs}`, data: null, + warehouseId: null, + appKey: String(query.app_key || '').trim() || null, }; } const body = await this.parseJsonBody(); if (body && body.ok === false) { - return body; + return { + ...body, + warehouseId: null, + appKey: String(query.app_key || '').trim() || null, + }; } const { appKey, providedSign } = this.normalizeSignFields(query); @@ -222,6 +230,8 @@ class WarehouseService extends Service { code: 400, message: '参数缺失或错误: app_key', data: null, + warehouseId: null, + appKey: null, }; } @@ -244,6 +254,8 @@ class WarehouseService extends Service { code: 401, message: `签名校验失败: ${verifyResult.message}`, data: null, + warehouseId: null, + appKey, }; } @@ -256,6 +268,8 @@ class WarehouseService extends Service { code: 403, message: 'API 应用未绑定仓库', data: null, + warehouseId: null, + appKey: verifyResult.appKey, }; } @@ -264,10 +278,16 @@ class WarehouseService extends Service { app_key: verifyResult.appKey, }; - return await this.dispatchWarehouseMethod(query.method, body, queryWithAppKey, { + const dispatchResult = await this.dispatchWarehouseMethod(query.method, body, queryWithAppKey, { warehouseId, appKey: verifyResult.appKey, }); + + return { + ...dispatchResult, + warehouseId, + appKey: verifyResult.appKey, + }; } } diff --git a/app/service/warehouseMethods/inbox.js b/app/service/warehouseMethods/inbox.js index 23c7fa9..5de365b 100644 --- a/app/service/warehouseMethods/inbox.js +++ b/app/service/warehouseMethods/inbox.js @@ -38,7 +38,7 @@ class WarehouseInboxService extends MainService { warehouse_id: warehouseId, direction: 'inbound', parent_id: body.parentId || null, - source_type: body.sourceType || 'api', + source_type: 'api', source_extra: String(appKey || ''), target_type: body.targetType || 'im', group_name: body.groupName || null, diff --git a/config/config.default.js b/config/config.default.js index 7e1a222..9561698 100644 --- a/config/config.default.js +++ b/config/config.default.js @@ -52,6 +52,12 @@ module.exports = appInfo => { apiKey: process.env.DEEPSEEK_API_KEY || '', baseUrl: 'https://api.deepseek.com', }; + + // 站内信模块配置 + config.inbox = { + imageBaseUrl: '', // 商品图片域名,为空时用请求 ctx.host + }; + config.tencentCloud = { ...tencentCloudConfig, }; @@ -61,16 +67,16 @@ module.exports = appInfo => { region: 'ap-guangzhou', uploadurl: 'https://ye4s-1255377868.cos.ap-guangzhou.myqcloud.com', cdnurl: 'https://ye4s.file.gzxunren.com', - savekey: '/{warehouseId}/{dir}/{year}{mon}{day}/{filemd5}{.suffix}', + savekey: '{warehouseId}/{dir}/{year}{mon}{day}/{filemd5}{.suffix}', expire: 600, maxsize: '100M', mimetype: 'jpg,png,bmp,jpeg,gif,zip,rar,xls,xlsx,apk', apiupload: 1, dirs: { - image: '/images/', - document: '/documents/', - apk: '/apks/', - temp: '/temp/', // 临时文件目录 + image: 'images/', + document: 'documents/', + apk: 'apks/', + temp: 'temp/', // 临时文件目录 }, }; config.fileWriter = { diff --git a/database/migrations/20260806200000-create-wms-warehouse-log.js b/database/migrations/20260806200000-create-wms-warehouse-log.js new file mode 100644 index 0000000..3d9573e --- /dev/null +++ b/database/migrations/20260806200000-create-wms-warehouse-log.js @@ -0,0 +1,108 @@ +'use strict'; + +/** + * 创建仓库开放 API 请求日志表。 + * 记录 /warehouse 入口的每次请求:app_key、method、warehouse_id、 + * 请求体、响应体、HTTP 状态码、耗时等。 + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + const { STRING, INTEGER, BIGINT, TEXT, DATE } = Sequelize; + + await queryInterface.createTable('wms_warehouse_log', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '自增主键', + }, + log_id: { + type: STRING(32), + allowNull: false, + unique: true, + comment: '日志唯一ID(WL-{timestamp}-{random})', + }, + app_key: { + type: STRING(64), + allowNull: true, + comment: 'API 应用 AppKey', + }, + method: { + type: STRING(100), + allowNull: true, + comment: '请求方法名(如 inbox.push)', + }, + warehouse_id: { + type: INTEGER(10), + allowNull: true, + comment: '仓库 ID', + }, + url: { + type: TEXT, + allowNull: true, + comment: '请求 URL', + }, + http_status: { + type: INTEGER(5), + allowNull: true, + comment: 'HTTP 状态码', + }, + body: { + type: TEXT('long'), + allowNull: true, + comment: '请求体(最大 65535 字符)', + }, + result: { + type: TEXT('long'), + allowNull: true, + comment: '响应体(最大 65535 字符)', + }, + use_time: { + type: INTEGER(12), + allowNull: true, + comment: '耗时(毫秒)', + }, + created_at: { + type: DATE, + allowNull: true, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: true, + comment: '更新时间', + }, + }); + + // 索引 + await queryInterface.addIndex('wms_warehouse_log', { + name: 'uk_log_id', + unique: true, + fields: [ 'log_id' ], + }); + + await queryInterface.addIndex('wms_warehouse_log', { + name: 'idx_app_key', + fields: [ 'app_key' ], + }); + + await queryInterface.addIndex('wms_warehouse_log', { + name: 'idx_method', + fields: [ 'method' ], + }); + + await queryInterface.addIndex('wms_warehouse_log', { + name: 'idx_warehouse_id', + fields: [ 'warehouse_id' ], + }); + + await queryInterface.addIndex('wms_warehouse_log', { + name: 'idx_created_at', + fields: [ 'created_at' ], + }); + }, + + down: async queryInterface => { + await queryInterface.dropTable('wms_warehouse_log'); + }, +}; diff --git a/database/migrations/20260807100000-change-ai-enabled-default-to-0.js b/database/migrations/20260807100000-change-ai-enabled-default-to-0.js new file mode 100644 index 0000000..c5ebcf7 --- /dev/null +++ b/database/migrations/20260807100000-change-ai-enabled-default-to-0.js @@ -0,0 +1,27 @@ +'use strict'; + +const TABLE_NAME = 'wms_inbox_group'; + +/** + * 修改 ai_enabled 默认值从 1 改为 0。 + * 新创建的群默认关闭 AI 自动回复,需管理员手动开启。 + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.changeColumn(TABLE_NAME, 'ai_enabled', { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 0, + comment: '是否启用AI自动回复: 0=关闭 1=开启', + }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.changeColumn(TABLE_NAME, 'ai_enabled', { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 1, + comment: '是否启用AI自动回复: 0=关闭 1=开启', + }); + }, +}; diff --git a/database/migrations/20260807110000-switch-inbox-block-to-ids.js b/database/migrations/20260807110000-switch-inbox-block-to-ids.js new file mode 100644 index 0000000..2033b23 --- /dev/null +++ b/database/migrations/20260807110000-switch-inbox-block-to-ids.js @@ -0,0 +1,83 @@ +'use strict'; + +const TABLE_NAME = 'wms_inbox_block'; + +/** + * 将屏蔽表从 group_name/user_name 切换为 group_id/user_id + warehouse_id。 + * 群名称和用户名可能变更或含特殊字符,改用稳定ID。 + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + // 1. 新增 warehouse_id(不允许为空,给历史数据默认值 0) + const cols = await queryInterface.describeTable(TABLE_NAME); + if (!cols.warehouse_id) { + await queryInterface.addColumn(TABLE_NAME, 'warehouse_id', { + type: Sequelize.INTEGER(10), + allowNull: false, + defaultValue: 0, + comment: '仓库ID', + }); + } + + // 2. 新增 group_id + if (!cols.group_id) { + await queryInterface.addColumn(TABLE_NAME, 'group_id', { + type: Sequelize.STRING(100), + allowNull: true, + comment: '群ID', + }); + } + + // 3. 新增 user_id + if (!cols.user_id) { + await queryInterface.addColumn(TABLE_NAME, 'user_id', { + type: Sequelize.STRING(100), + allowNull: true, + comment: '用户ID', + }); + } + + // 4. 检查是否已有旧列,有则删除 + const colsAfter = await queryInterface.describeTable(TABLE_NAME); + if (colsAfter.group_name) { + await queryInterface.removeColumn(TABLE_NAME, 'group_name'); + } + if (colsAfter.user_name) { + await queryInterface.removeColumn(TABLE_NAME, 'user_name'); + } + + // 5. 添加唯一索引 + await queryInterface.addIndex(TABLE_NAME, { + name: 'uk_warehouse_group_user', + unique: true, + fields: [ 'warehouse_id', 'group_id', 'user_id' ], + }); + }, + + down: async (queryInterface, Sequelize) => { + // 回滚:恢复旧列 + const cols = await queryInterface.describeTable(TABLE_NAME); + if (!cols.group_name) { + await queryInterface.addColumn(TABLE_NAME, 'group_name', { + type: Sequelize.STRING(100), + allowNull: true, + comment: '群名称', + }); + } + if (!cols.user_name) { + await queryInterface.addColumn(TABLE_NAME, 'user_name', { + type: Sequelize.STRING(100), + allowNull: true, + comment: '用户名称', + }); + } + + // 删除新列 + if (cols.group_id) await queryInterface.removeColumn(TABLE_NAME, 'group_id'); + if (cols.user_id) await queryInterface.removeColumn(TABLE_NAME, 'user_id'); + if (cols.warehouse_id) await queryInterface.removeColumn(TABLE_NAME, 'warehouse_id'); + + // 删除唯一索引 + await queryInterface.removeIndex(TABLE_NAME, 'uk_warehouse_group_user'); + }, +}; diff --git a/database/migrations/20260807120000-add-express-code-to-wms-order-stockout.js b/database/migrations/20260807120000-add-express-code-to-wms-order-stockout.js new file mode 100644 index 0000000..bace1e7 --- /dev/null +++ b/database/migrations/20260807120000-add-express-code-to-wms-order-stockout.js @@ -0,0 +1,44 @@ +'use strict'; + +const TABLE = 'wms_order_stockout'; + +/** + * 为出库单主表添加运单号字段。 + * + * - express_code:回传运单号(单个),奇门 stockout.confirm 回传时使用,为空则拒绝确认 + * - express_codes:运单号列表(JSON 数组),支持多包裹场景 + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + const columns = await queryInterface.describeTable(TABLE); + + if (!columns.express_code) { + await queryInterface.addColumn(TABLE, 'express_code', { + type: Sequelize.STRING(50), + allowNull: true, + comment: '回传运单号(奇门 stockout.confirm 回传使用,为空则拒绝确认)', + }); + } + + if (!columns.express_codes) { + await queryInterface.addColumn(TABLE, 'express_codes', { + type: Sequelize.JSON, + allowNull: true, + comment: '运单号列表(JSON 数组,支持多包裹场景)', + }); + } + }, + + down: async (queryInterface) => { + const columns = await queryInterface.describeTable(TABLE); + + if (columns.express_code) { + await queryInterface.removeColumn(TABLE, 'express_code'); + } + + if (columns.express_codes) { + await queryInterface.removeColumn(TABLE, 'express_codes'); + } + }, +}; + diff --git a/database/migrations/20260807130000-add-stockout-api-permissions.js b/database/migrations/20260807130000-add-stockout-api-permissions.js new file mode 100644 index 0000000..1dcb27c --- /dev/null +++ b/database/migrations/20260807130000-add-stockout-api-permissions.js @@ -0,0 +1,84 @@ +'use strict'; + +/** + * 为 storage.stockout.* 添加 API 权限并授权。 + * + * 权限 ID(固定): + * 504 — storage.stockout.list 出库单列表 + * 505 — storage.stockout.listItems 出库单明细 + * 506 — storage.stockout.confirm 出库单确认 + * 507 — storage.stockout.updateExpress 更新运单号 + * + * 授权角色:经理(8)、仓库组-主管(26)、客服组-主管(28)、生产组-主管(29)、客服组-员工(30) + */ +module.exports = { + up: async (queryInterface) => { + // ===== 第一步:写入权限行 ===== + const perms = [ + [504, 'storage.stockout.list', '出库单列表'], + [505, 'storage.stockout.listItems', '出库单明细'], + [506, 'storage.stockout.confirm', '出库单确认'], + [507, 'storage.stockout.updateExpress', '更新运单号'], + ]; + + for (const [id, method, desc] of perms) { + await queryInterface.sequelize.query(` + INSERT INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at) + VALUES (${id}, '${method}', NULL, '${method}', NULL, 'API:${desc}', NULL, 0, 0, NULL, 'api', 0, 1, NOW(), NOW()) + ON DUPLICATE KEY UPDATE path='${method}', meta_title='API:${desc}', type='api' + `); + } + + // ===== 第二步:授权给客服组员工及以上角色 ===== + const roleIds = [8, 26, 28, 29, 30]; // 经理 + 各主管 + 客服组-员工 + const newPermIds = [504, 505, 506, 507]; + + for (const roleId of roleIds) { + for (const permId of newPermIds) { + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = JSON_ARRAY_APPEND(permissions, '$', CAST(${permId} AS UNSIGNED)), + updated_at = NOW() + WHERE id = ${roleId} + AND permissions IS NOT NULL + AND permissions != '*' + AND permissions != '[]' + AND JSON_VALID(permissions) = 1 + AND JSON_CONTAINS(permissions, '${permId}', '$') = 0 + `); + } + } + }, + + down: async (queryInterface) => { + // 移除授权 + const roleIds = [8, 26, 28, 29, 30]; + const permIdStr = '504, 505, 506, 507'; + + for (const roleId of roleIds) { + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = JSON_REMOVE( + JSON_REMOVE( + JSON_REMOVE( + JSON_REMOVE(permissions, JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '504'))), + JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '505')) + ), + JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '506')) + ), + JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '507')) + ), + updated_at = NOW() + WHERE id = ${roleId} + AND permissions IS NOT NULL + AND permissions != '*' + AND permissions != '[]' + `); + } + + // 删除权限行 + await queryInterface.sequelize.query(` + DELETE FROM wms_permission WHERE id IN (504, 505, 506, 507) + `); + }, +}; diff --git a/database/migrations/20260807140000-add-express-name-waybill-to-wms-order-stockout.js b/database/migrations/20260807140000-add-express-name-waybill-to-wms-order-stockout.js new file mode 100644 index 0000000..b9c4912 --- /dev/null +++ b/database/migrations/20260807140000-add-express-name-waybill-to-wms-order-stockout.js @@ -0,0 +1,56 @@ +'use strict'; + +const TABLE = 'wms_order_stockout'; + +/** + * 拆分运单号字段: + * - express_code 保持为快递公司编码(如 SF、STO) + * - 新增 express_name:快递公司名称(如 顺丰、申通) + * - 新增 waybill_code:单个运单号 + * - 新增 waybill_codes:运单号列表(JSON 数组) + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + const columns = await queryInterface.describeTable(TABLE); + + if (!columns.express_name) { + await queryInterface.addColumn(TABLE, 'express_name', { + type: Sequelize.STRING(200), + allowNull: true, + comment: '快递公司名称(由 express_code 自动解析)', + }); + } + + if (!columns.waybill_code) { + await queryInterface.addColumn(TABLE, 'waybill_code', { + type: Sequelize.STRING(50), + allowNull: true, + comment: '运单号', + }); + } + + if (!columns.waybill_codes) { + await queryInterface.addColumn(TABLE, 'waybill_codes', { + type: Sequelize.JSON, + allowNull: true, + comment: '运单号列表(JSON 数组,支持多包裹场景)', + }); + } + }, + + down: async (queryInterface) => { + const columns = await queryInterface.describeTable(TABLE); + + if (columns.express_name) { + await queryInterface.removeColumn(TABLE, 'express_name'); + } + + if (columns.waybill_code) { + await queryInterface.removeColumn(TABLE, 'waybill_code'); + } + + if (columns.waybill_codes) { + await queryInterface.removeColumn(TABLE, 'waybill_codes'); + } + }, +}; diff --git a/methods/changes/qimen.json b/methods/changes/qimen.json index c744a7b..11cfe45 100644 --- a/methods/changes/qimen.json +++ b/methods/changes/qimen.json @@ -53,5 +53,21 @@ "文档与代码实现(qimenMethods/stockout.js query 方法)对齐" ], "type": "updated" + }, + { + "version": "2026.08.07-stockout-confirm-01", + "date": "2026-08-07", + "summary": "stockout.confirm 从入站改为出站:确认后由 WMS 出站调用 taobao.qimen.stockout.confirm 通知 ERP", + "methods": [ + "stockout.confirm" + ], + "notes": [ + "移除 qimenMethods/stockout.js 中错误的入站 confirm 方法(stockout.confirm 是出站而非入站)", + "storage.stockout.confirm 确认后通过 qimenClient.send() 出站调用 taobao.qimen.stockout.confirm", + "出站 payload 包含 deliveryOrder/packages/orderLines,logisticsCode=OTHER", + "qimen.json 移除 stockout.confirm 入站条目" + ], + "type": "changed", + "module": "stockout" } ] diff --git a/methods/changes/system.json b/methods/changes/system.json index 11f208f..6879912 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,54 @@ [ + { + "version": "2026.08.07-stockout-express", + "date": "2026-08-07", + "type": "changed", + "summary": "wms_order_stockout 表新增 express_code / express_codes 字段;storage.stockout.confirm 改为读表字段回传,不再随机生成;新增 storage.stockout.updateExpress 接口。", + "methods": [ + "storage.stockout.confirm", + "storage.stockout.updateExpress" + ], + "notes": [ + "DB 迁移:20260807120000-add-express-code-to-wms-order-stockout.js 添加 express_code VARCHAR(50) 和 express_codes JSON 字段。", + "Model:order_stockout.js 新增 express_code / express_codes 字段定义。", + "storage.stockout.confirm:回传时不再随机生成 expressCode,改为读取表中 express_code / express_codes;express_code 为空则拒绝确认(400)。", + "storage.stockout.updateExpress:新增接口,用于在确认前更新运单号,支持 express_code(单个)和 express_codes(列表)两个字段。", + "qimenMethods/stockout.js confirm 同步调整,透传 expressCodes。" + ], + "module": "storage" + }, + { + "version": "2026.08.07-stockout-confirm", + "date": "2026-08-07", + "type": "added", + "summary": "新增 storage.stockout.confirm 直出确认接口:不改变内部库存,按出库单明细计划数量直接确认,状态推进到 COMPLETED。", + "methods": [ + "storage.stockout.confirm" + ], + "notes": [ + "入参:id(出库单ID,必填)。", + "逻辑:校验 canConfirm (CREATED/PENDING) → 事务内更新 order_status=COMPLETED、actual_qty=plan_qty。", + "返回:id、stockout_order_code、order_status、logisticsName(固定OTHER)、expressCode(随机生成)。", + "对应奇门 stockout.confirm 接口,由 qimenMethods/stockout.js confirm 方法调用。" + ], + "module": "storage" + }, + { + "version": "2026.08.07-stockout-list-fix", + "date": "2026-08-07", + "type": "changed", + "summary": "修复 storage.stockout.list / listItems 读错表:从 OrderDeliveryFactory/OrderItemsFactory 改为直接读取 OrderStockout/OrderStockoutItems 模型(wms_order_stockout 表)。", + "methods": [ + "storage.stockout.list", + "storage.stockout.listItems" + ], + "notes": [ + "list:数据源 OrderDeliveryFactory → OrderStockout;软删字段 delete_at → deleted_at;快速搜索字段适配 stockout_order_code/remark;排序字段适配 order_status/order_type/created_at/order_create_time。", + "listItems:数据源 OrderDeliveryFactory+OrderItemsFactory → OrderStockout+OrderStockoutItems;参数 delivery_order_code → stockout_order_code(兼容旧参数名)。", + "response 字段 items → list,与实际返回一致。" + ], + "module": "storage" + }, { "version": "2026.08.06-inbox-bindCode", "date": "2026-08-06", @@ -5348,5 +5398,22 @@ "task 对象新增 wave_no(string)字段,位于 task_no 之后;查询失败时降级为空字符串。", "数据来源:wms_wave_pick_task_wave INNER JOIN wms_wave_batch ON wave_id。" ] + }, + { + "version": "2026-08-06", + "date": "2026-08-06", + "summary": "sign_method 收紧为仅支持 md5:create 固定为 md5 不可选,update 不允许修改 sign_method,list/detail 响应描述同步更新", + "methods": [ + "apiApp.list", + "apiApp.detail", + "apiApp.create", + "apiApp.update" + ], + "notes": [ + "验证确认 /openapi 和 /warehouse 实际只使用 MD5 签名算法", + "apiApp.create: 删除 sign_method 入参,硬编码为 md5", + "apiApp.update: sign_method 字段改为不可修改,传入即报错", + "apiApp.list / apiApp.detail: sign_method 响应描述更新为「当前仅支持 md5」" + ] } ] diff --git a/methods/changes/warehouse.json b/methods/changes/warehouse.json index 7a8c0f5..59ca781 100644 --- a/methods/changes/warehouse.json +++ b/methods/changes/warehouse.json @@ -1,41 +1,68 @@ [ - { - "version": "2026.08.01-warehouse-01", - "date": "2026-08-01", - "type": "added", - "summary": "新增 /warehouse 仓库开放 API 入口,支持仓库级外部适配器 HMAC-SHA256 签名鉴权调用,首批上线 index.ping 心跳 + store.list 货主列表", - "methods": [ - "index.ping", - "store.list" - ], - "notes": [ - "POST /warehouse 为新增入口,独立于 /openapi(货主级),鉴权使用 interface_type_id=3 的仓库 API 应用(由 apiApp 模块管理)。", - "签名算法与 /openapi 完全一致:query 参数字典序 + body 拼接 → HMAC-SHA256 → hex。", - "时间戳 ±10 分钟有效期,Redis 缓存 API 应用配置 300 秒(缓存前缀 warehouse:api-app)。", - "无需 StoreWarehouse 合约关联,直接通过 api_app.warehouse_id 确定仓库上下文。", - "index.ping:无需 body 参数,返回 warehouse_id / app_key / server_time / status。", - "store.list:分页查询当前仓库下已授权的货主,通过 wms_store_warehouse 关联 wms_store,仅返回 auth_status=2 + store.status=1 + warehouse_use_status=1 的记录。", - "api_sign.js 改造:getApiAppConfigByAppKey 新增 interfaceTypeId 参数(默认 2 保持向后兼容),warehouse 入口传 3,查询增加 interface_type_id 条件并返回 warehouse_id。" - ], - "module": "warehouse" - }, - { - "version": "2026.08.03-warehouse-01", - "date": "2026-08-03", - "type": "added", - "summary": "新增仓库开放 API 站内信模块 inbox.push,支持外部系统将消息推入仓库站内信,WMS 异步转发到目标渠道(IM/API/webhook)", - "methods": [ - "inbox.push" - ], - "notes": [ - "POST /warehouse?method=inbox.push,interface_type_id=3(仓库侧),使用 MD5 签名鉴权", - "warehouse_id 由验签后上下文注入,禁止外部传入(安全边界)", - "ext_id 格式:api:{appKey}:{requestId},用于幂等去重", - "target_url 仅允许 https://,禁止内网 IP(SSRF 防护)", - "推送 body 大小限制 64KB", - "异步推送使用 setImmediate,不阻塞响应;失败指数退避重试(30s→60s→120s,最多3次)", - "路由到 app/service/warehouseMethods/inbox.push → app/service/inbox/receiver.receive" - ], - "module": "inbox" - } + { + "version": "2026.08.01-warehouse-01", + "date": "2026-08-01", + "type": "added", + "summary": "新增 /warehouse 仓库开放 API 入口,支持仓库级外部适配器 HMAC-SHA256 签名鉴权调用,首批上线 index.ping 心跳 + store.list 货主列表", + "methods": [ + "index.ping", + "store.list" + ], + "notes": [ + "POST /warehouse 为新增入口,独立于 /openapi(货主级),鉴权使用 interface_type_id=3 的仓库 API 应用(由 apiApp 模块管理)。", + "签名算法与 /openapi 完全一致:query 参数字典序 + body 拼接 → HMAC-SHA256 → hex。", + "时间戳 ±10 分钟有效期,Redis 缓存 API 应用配置 300 秒(缓存前缀 warehouse:api-app)。", + "无需 StoreWarehouse 合约关联,直接通过 api_app.warehouse_id 确定仓库上下文。", + "index.ping:无需 body 参数,返回 warehouse_id / app_key / server_time / status。", + "store.list:分页查询当前仓库下已授权的货主,通过 wms_store_warehouse 关联 wms_store,仅返回 auth_status=2 + store.status=1 + warehouse_use_status=1 的记录。", + "api_sign.js 改造:getApiAppConfigByAppKey 新增 interfaceTypeId 参数(默认 2 保持向后兼容),warehouse 入口传 3,查询增加 interface_type_id 条件并返回 warehouse_id。" + ], + "module": "warehouse" + }, + { + "version": "2026.08.03-warehouse-01", + "date": "2026-08-03", + "type": "added", + "summary": "新增仓库开放 API 站内信模块 inbox.push,支持外部系统将消息推入仓库站内信,WMS 异步转发到目标渠道(IM/API/webhook)", + "methods": [ + "inbox.push" + ], + "notes": [ + "POST /warehouse?method=inbox.push,interface_type_id=3(仓库侧),使用 MD5 签名鉴权", + "warehouse_id 由验签后上下文注入,禁止外部传入(安全边界)", + "ext_id 格式:api:{appKey}:{requestId},用于幂等去重", + "target_url 仅允许 https://,禁止内网 IP(SSRF 防护)", + "推送 body 大小限制 64KB", + "异步推送使用 setImmediate,不阻塞响应;失败指数退避重试(30s→60s→120s,最多3次)", + "路由到 app/service/warehouseMethods/inbox.push → app/service/inbox/receiver.receive" + ], + "module": "inbox" + }, + { + "version": "2026-08-06", + "date": "2026-08-06", + "summary": "inbox.push 文档同步代码现状:移除废弃参数 sourceChannel/targetChannel/storeId,补齐缺失参数 groupId/groupName/userId/userName/content,更新错误码与描述", + "methods": [ + "inbox.push" + ], + "notes": [ + "移除 sourceChannel / targetChannel / storeId 参数(代码中不存在)", + "补齐 groupId / groupName / userId / userName / content 参数", + "移除 targetChannel/targetUrl 相关错误码", + "新增 parent_id 校验、消息体 64KB 限制错误码", + "ext_id 自动组合为 api:{appKey}:{requestId}" + ] + }, + { + "version": "2026-08-07", + "date": "2026-08-07", + "summary": "inbox.push: source_type 硬编码为 api,移除 sourceType 入参(仓库 API 入站来源固定为 api,无需外部传入)", + "methods": [ + "inbox.push" + ], + "notes": [ + "source_type 从 body.sourceType || 'api' 改为硬编码 'api'", + "文档移除 sourceType 参数,description 补注 source_type 固定为 api" + ] + } ] diff --git a/methods/inbox-callback.json b/methods/inbox-callback.json new file mode 100644 index 0000000..dd745ac --- /dev/null +++ b/methods/inbox-callback.json @@ -0,0 +1,261 @@ +{ + "module": "inbox-callback", + "description": "站内信模块出站回调定义。WMS 处理入站消息后,通过 HTTP POST 将回复推送到仓库 ApiApp 配置的 callback_url(interface_type_id=3),供外部适配器消费并投递到实际聊天通道。回调体统一包裹:{ method, code, data }。", + "version": "1.1.0", + "updatedAt": "2026-08-07", + "http": { + "path": "{ApiApp.callback_url}", + "method": "POST" + }, + "headers": [ + { + "name": "Content-Type", + "type": "string", + "required": true, + "description": "application/json" + } + ], + "methods": { + "groups": [ + { + "groupName": "AI 自动回复", + "module": "ai_reply", + "list": [ + { + "method": "inbox.callback.ai_reply", + "description": "AI 自动回复回调。用户发送消息后,DeepSeek 推理给出回复内容,WMS 推送到外部聊天通道。", + "params": [], + "response": [], + "errors": [], + "notes": [ + "content 为 AI 生成的纯文本(含 \\n 换行,禁止 Markdown)", + "ext_id 与入站消息相同,外部系统可据此关联对话", + "若 AI 判定无需回复(silent),不会触发此回调", + "ai_thoughts 字段记录整个推理链(仅限出站记录查询,不入回调)" + ], + "example": { + "method": "inbox.callback.ai_reply", + "code": 200, + "data": { + "source": "ai_reply", + "content": "条码6900000000016查到2款商品:\n1. 披肩-消退 可用0\n2. 披肩 可用0(总量95已锁定)\n均无可用库存,建议更换商品。", + "ext_id": "api:AK001:req-123", + "ext_data": { + "request_id": "req-123" + }, + "group_id": "wrchat-xxx", + "user_id": "user-001", + "group_name": "售后沟通群", + "user_name": "张三", + "timestamp": 1786100000 + } + } + } + ] + }, + { + "groupName": "绑群确认", + "module": "bind_confirm", + "list": [ + { + "method": "inbox.callback.bind_confirm", + "description": "绑群确认回调。用户发送「授权:CODE」后,WMS 校验成功/失败/已绑定,推送绑群结果。", + "params": [], + "response": [], + "errors": [], + "notes": [ + "成功 content:绑定「{货主备注名}」成功", + "失败 content:绑群码无效或已过期,请重新生成", + "已绑定 content:已在绑定状态,无需重复操作", + "绑定成功后自动追加 inbox.callback.balance 返回面单余额" + ], + "example": { + "method": "inbox.callback.bind_confirm", + "code": 200, + "data": { + "source": "bind_confirm", + "content": "绑定「测试货主1111」成功", + "ext_id": "api:AK001:req-456", + "ext_data": null, + "group_id": "wrchat-xxx", + "user_id": "user-001", + "group_name": "售后沟通群", + "user_name": "张三", + "timestamp": 1786100000 + } + } + } + ] + }, + { + "groupName": "面单余额", + "module": "balance", + "list": [ + { + "method": "inbox.callback.balance", + "description": "面单余额回调。绑群成功后自动查询,或用户主动查询时推送面单余额。", + "params": [], + "response": [], + "errors": [], + "notes": [ + "content 格式:面单余额:总量 {print_quantity},已锁定 {print_quantity_locked},可用 {available}", + "ext_id 为 {原ext_id}:balance 后缀,避免与绑群确认回执冲突", + "余额查询失败时 content:面单余额查询失败:{错误原因}" + ], + "example": { + "method": "inbox.callback.balance", + "code": 200, + "data": { + "source": "balance", + "content": "面单余额:总量 5000,已锁定 200,可用 4800", + "ext_id": "api:AK001:req-456:balance", + "ext_data": null, + "group_id": "wrchat-xxx", + "user_id": "user-001", + "group_name": "售后沟通群", + "user_name": "张三", + "timestamp": 1786100000 + } + } + } + ] + }, + { + "groupName": "异常兜底", + "module": "error", + "list": [ + { + "method": "inbox.callback.error", + "description": "异常兜底回调。AI 5轮推理均失败或系统异常时的兜底回复。", + "params": [], + "response": [], + "errors": [], + "notes": [ + "content 为固定兜底文案:抱歉,暂时无法处理您的请求,请稍后重试", + "出站前仍写入 wms_inbox_message.outbound 记录" + ], + "example": { + "method": "inbox.callback.error", + "code": 200, + "data": { + "source": "error", + "content": "抱歉,暂时无法处理您的请求,请稍后重试", + "ext_id": "api:AK001:req-789", + "ext_data": null, + "group_id": "wrchat-xxx", + "user_id": "user-001", + "group_name": "售后沟通群", + "user_name": "张三", + "timestamp": 1786100000 + } + } + } + ] + }, + { + "groupName": "通用说明", + "module": "common", + "list": [ + { + "method": "inbox.callback.common", + "description": "所有回调类型共有字段说明及路由指引。外部适配器根据 method 字段路由到不同处理逻辑。", + "params": [ + { + "name": "method", + "type": "string", + "required": true, + "source": "body", + "description": "回调方法名,固定格式 inbox.callback.{source},外部适配器据此路由" + }, + { + "name": "code", + "type": "number", + "required": true, + "source": "body", + "description": "状态码,正常回调固定 200" + }, + { + "name": "data.source", + "type": "string", + "required": true, + "source": "body", + "description": "消息来源:ai_reply / bind_confirm / balance / error" + }, + { + "name": "data.content", + "type": "string", + "required": true, + "source": "body", + "description": "回复正文(纯文本,含 \\n 换行)" + }, + { + "name": "data.ext_id", + "type": "string", + "required": true, + "source": "body", + "description": "原始入站消息ID,关联对话链" + }, + { + "name": "data.ext_data", + "type": "object", + "required": false, + "source": "body", + "description": "入站透传数据,原路带回" + }, + { + "name": "data.group_id", + "type": "string", + "required": true, + "source": "body", + "description": "外部群ID" + }, + { + "name": "data.user_id", + "type": "string", + "required": true, + "source": "body", + "description": "外部用户ID" + }, + { + "name": "data.group_name", + "type": "string", + "required": true, + "source": "body", + "description": "群名称" + }, + { + "name": "data.user_name", + "type": "string", + "required": true, + "source": "body", + "description": "用户名称" + }, + { + "name": "data.timestamp", + "type": "number", + "required": true, + "source": "body", + "description": "出站 Unix 时间戳(秒)" + } + ], + "response": [ + { + "name": "http_status", + "type": "number", + "required": true, + "description": "HTTP 200 表示回调成功,WMS 更新 push_status=2" + } + ], + "errors": [], + "notes": [ + "回调由 app/service/inbox/processor.js → writeOutboundReply() / handleApiMessage 发起", + "callback_url 配置:wms_api_app.interface_type_id=3 AND is_enabled=1", + "超时 10 秒,失败不影响消息记录写入", + "HTTP 200 → 更新出站+入站 push_status=2(已送达)" + ] + } + ] + } + ] + } +} \ No newline at end of file diff --git a/methods/system.json b/methods/system.json index 54c497f..4c069d1 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.19", - "updatedAt": "2026-08-05", + "version": "0.3.21", + "updatedAt": "2026-08-06", "headers": [ { "name": "platform", @@ -21792,8 +21792,8 @@ { "method": "storage.stockout.list", "name": "出库单列表", - "description": "非订单出库单能力(对应奇门 stockout.create):用于处理由奇门创建的非订单出库单;主出口为 storage.stockout.*,不再推荐通过 storage.delivery.* 命名使用。storage.delivery.* 仅保留兼容转发。", - "isNeedAuth": false, + "description": "非订单出库单能力(对应奇门 stockout.create):直接读取 wms_order_stockout 表;主出口为 storage.stockout.*,不再推荐通过 storage.delivery.* 命名使用。storage.delivery.* 仅保留兼容转发。", + "isNeedAuth": true, "isNeedLogin": true, "isNeedRight": false, "headers": [ @@ -21817,14 +21817,14 @@ "type": "object", "required": false, "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;常用字段包括 delivery_order_code、status、outbound_status、buyer_nick、mobile 与日期区间字段。" + "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;常用字段包括 stockout_order_code、order_status、order_type、source_type、remark 与日期区间字段。" }, { "name": "sort", "type": "object", "required": false, "source": "body", - "description": "排序参数,支持 sortField/sortOrder,默认按 updated_at DESC、id DESC" + "description": "排序参数,支持 sortField/sortOrder,可选字段:id、stockout_order_code、order_status、order_type、updated_at、created_at、order_create_time,默认按 updated_at DESC、id DESC" } ], "response": [ @@ -21832,7 +21832,7 @@ "name": "list", "type": "array", "required": true, - "description": "出库单列表" + "description": "出库单列表(wms_order_stockout 表记录,含 sync_status/sync_message 出站同步状态字段)" }, { "name": "pagination", @@ -21901,8 +21901,8 @@ { "method": "storage.stockout.listItems", "name": "出库单拉取明细", - "description": "按出库单查询商品明细(用于非订单出库单),底层复用 order.listItems。", - "isNeedAuth": false, + "description": "按出库单查询商品明细(用于非订单出库单),直接读取 wms_order_stockout + wms_order_stockout_items 表。", + "isNeedAuth": true, "isNeedLogin": true, "isNeedRight": false, "headers": [ @@ -21915,25 +21915,18 @@ ], "params": [ { - "name": "delivery_order_code", + "name": "stockout_order_code", "type": "string", "required": false, "source": "body", - "description": "出库单号,可用于定位订单" - }, - { - "name": "order_id", - "type": "number", - "required": false, - "source": "body", - "description": "订单ID,可与 id 兼容用于定位订单" + "description": "出库单号(推荐);兼容 delivery_order_code 旧参数名" }, { "name": "id", "type": "number", "required": false, "source": "body", - "description": "订单ID,可选;与 delivery_order_code / order_id 至少传一个" + "description": "出库单ID,可选;与 stockout_order_code 至少传一个" } ], "response": [ @@ -21941,25 +21934,197 @@ "name": "order", "type": "object", "required": true, - "description": "订单基础信息(含 id、delivery_order_code)" + "description": "出库单基础信息(wms_order_stockout 表记录,含 id、stockout_order_code)" }, { - "name": "items", + "name": "list", "type": "array", "required": true, - "description": "出库单商品明细" + "description": "出库单商品明细(wms_order_stockout_items 表记录)" } ], "errors": [ { "code": "404", - "description": "订单不存在" + "description": "出库单不存在" }, { "code": "500", "description": "缺少定位参数或查询失败" } ] + }, + { + "method": "storage.stockout.confirm", + "name": "出库单确认(直出)", + "description": "直出确认出库单:不改变内部库存,按出库单明细计划数量(plan_qty)直接确认。出站同步 taobao.qimen.stockout.confirm 成功后才将状态推进到 COMPLETED;同步失败则返回错误,order_status 不变,sync_status 标记为 FAILED。要求 express_code 已填写,否则拒绝确认。", + "isNeedAuth": true, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "出库单ID(必填)" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "出库单ID" + }, + { + "name": "stockout_order_code", + "type": "string", + "required": true, + "description": "出库单号" + }, + { + "name": "order_status", + "type": "string", + "required": true, + "description": "确认后状态(COMPLETED)" + }, + { + "name": "logisticsName", + "type": "string", + "required": true, + "description": "物流公司名称(固定为 OTHER)" + }, + { + "name": "expressCode", + "type": "string", + "required": true, + "description": "运单号(取自表中 express_code 字段)" + }, + { + "name": "expressCodes", + "type": "array", + "required": false, + "description": "运单号列表(取自表中 express_codes 字段)" + }, + { + "name": "qimenSync", + "type": "string", + "required": true, + "description": "奇门出站同步结果:success=通知成功,failure=通知失败(确认本身不受影响)" + }, + { + "name": "qimenSyncMessage", + "type": "string", + "required": false, + "description": "奇门出站失败时的错误信息" + } + ], + "errors": [ + { + "code": "400", + "description": "缺少出库单ID" + }, + { + "code": "400", + "description": "出库单不存在" + }, + { + "code": "400", + "description": "出库单当前状态不允许确认(非 CREATED/PENDING)" + }, + { + "code": "400", + "description": "出库单未填写运单号(express_code),请先更新运单号后再确认" + } + ] + }, + { + "method": "storage.stockout.updateExpress", + "name": "更新出库单运单号", + "description": "更新出库单的运单号字段(express_code / express_codes),用于在确认前填写运单信息。", + "isNeedAuth": true, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "出库单ID(必填)" + }, + { + "name": "express_code", + "type": "string", + "required": false, + "source": "body", + "description": "运单号" + }, + { + "name": "express_codes", + "type": "array", + "required": false, + "source": "body", + "description": "运单号列表(JSON 数组)" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "出库单ID" + }, + { + "name": "stockout_order_code", + "type": "string", + "required": true, + "description": "出库单号" + }, + { + "name": "express_code", + "type": "string", + "required": false, + "description": "更新后的运单号" + }, + { + "name": "express_codes", + "type": "array", + "required": false, + "description": "更新后的运单号列表" + } + ], + "errors": [ + { + "code": "400", + "description": "缺少出库单ID" + }, + { + "code": "400", + "description": "出库单不存在" + }, + { + "code": "400", + "description": "express_codes 必须是数组或 null" + } + ] } ] }, @@ -31250,127 +31415,146 @@ "description": "启用状态:1-启用,0-停用" } ], - "response": { - "type": "object", - "properties": [ - { - "name": "list", - "type": "array", - "description": "应用列表", - "children": [ - { - "name": "id", - "type": "number", - "description": "应用 ID" - }, - { - "name": "app_name", - "type": "string", - "description": "应用名称" - }, - { - "name": "warehouse_id", - "type": "number", - "description": "仓库 ID" - }, - { - "name": "interface_type_id", - "type": "number", - "description": "接口类型 ID" - }, - { - "name": "self_app_key", - "type": "string", - "description": "自身 AppKey(对外提供)" - }, - { - "name": "self_app_secret", - "type": "string", - "description": "自身 AppSecret(脱敏,仅显示前8位+****)" - }, - { - "name": "self_ip_whitelist", - "type": "array", - "description": "IP 白名单", - "children": [ - { - "name": "ip", - "type": "string", - "description": "IP 地址或 CIDR" - } - ] - }, - { - "name": "callback_url", - "type": "string", - "description": "回调通知 URL" - }, - { - "name": "rate_limit", - "type": "number", - "description": "速率限制(次/秒)" - }, - { - "name": "sign_method", - "type": "string", - "description": "签名方法:md5/hmac/sha256" - }, - { - "name": "is_enabled", - "type": "number", - "description": "启用状态:1-启用,0-停用" - }, - { - "name": "created_at", - "type": "string", - "description": "创建时间" - }, - { - "name": "updated_at", - "type": "string", - "description": "更新时间" - } - ] - }, - { - "name": "pagination", - "type": "object", - "description": "分页信息", - "children": [ - { - "name": "page", - "type": "number", - "description": "当前页" - }, - { - "name": "pageSize", - "type": "number", - "description": "每页数量" - }, - { - "name": "total", - "type": "number", - "description": "总记录数" - }, - { - "name": "totalPages", - "type": "number", - "description": "总页数" - }, - { - "name": "hasNext", - "type": "boolean", - "description": "是否有下一页" - }, - { - "name": "hasPrevious", - "type": "boolean", - "description": "是否有上一页" - } - ] - } - ] - }, + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "应用列表", + "children": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "应用 ID" + }, + { + "name": "app_name", + "type": "string", + "required": true, + "description": "应用名称" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库 ID" + }, + { + "name": "interface_type_id", + "type": "number", + "required": true, + "description": "接口类型 ID" + }, + { + "name": "self_app_key", + "type": "string", + "required": true, + "description": "自身 AppKey(对外提供)" + }, + { + "name": "self_app_secret", + "type": "string", + "required": true, + "description": "自身 AppSecret(脱敏,仅显示前8位+****)" + }, + { + "name": "self_ip_whitelist", + "type": "array", + "required": false, + "description": "IP 白名单", + "children": [ + { + "name": "ip", + "type": "string", + "required": false, + "description": "IP 地址或 CIDR" + } + ] + }, + { + "name": "callback_url", + "type": "string", + "required": false, + "description": "回调通知 URL" + }, + { + "name": "rate_limit", + "type": "number", + "required": false, + "description": "速率限制(次/秒)" + }, + { + "name": "sign_method", + "type": "string", + "required": false, + "description": "签名方法(当前仅支持 md5)" + }, + { + "name": "is_enabled", + "type": "number", + "required": false, + "description": "启用状态:1-启用,0-停用" + }, + { + "name": "created_at", + "type": "string", + "required": false, + "description": "创建时间" + }, + { + "name": "updated_at", + "type": "string", + "required": false, + "description": "更新时间" + } + ] + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息", + "children": [ + { + "name": "page", + "type": "number", + "required": true, + "description": "当前页" + }, + { + "name": "pageSize", + "type": "number", + "required": true, + "description": "每页数量" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "总记录数" + }, + { + "name": "totalPages", + "type": "number", + "required": true, + "description": "总页数" + }, + { + "name": "hasNext", + "type": "boolean", + "required": true, + "description": "是否有下一页" + }, + { + "name": "hasPrevious", + "type": "boolean", + "required": true, + "description": "是否有上一页" + } + ] + } + ], "errors": [ { "code": "401", @@ -31404,76 +31588,86 @@ "description": "应用 ID" } ], - "response": { - "type": "object", - "properties": [ - { - "name": "id", - "type": "number", - "description": "应用 ID" - }, - { - "name": "app_name", - "type": "string", - "description": "应用名称" - }, - { - "name": "warehouse_id", - "type": "number", - "description": "仓库 ID" - }, - { - "name": "interface_type_id", - "type": "number", - "description": "接口类型 ID" - }, - { - "name": "self_app_key", - "type": "string", - "description": "自身 AppKey" - }, - { - "name": "self_app_secret", - "type": "string", - "description": "自身 AppSecret(脱敏)" - }, - { - "name": "self_ip_whitelist", - "type": "array", - "description": "IP 白名单" - }, - { - "name": "callback_url", - "type": "string", - "description": "回调通知 URL" - }, - { - "name": "rate_limit", - "type": "number", - "description": "速率限制" - }, - { - "name": "sign_method", - "type": "string", - "description": "签名方法" - }, - { - "name": "is_enabled", - "type": "number", - "description": "启用状态" - }, - { - "name": "created_at", - "type": "string", - "description": "创建时间" - }, - { - "name": "updated_at", - "type": "string", - "description": "更新时间" - } - ] - }, + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "应用 ID" + }, + { + "name": "app_name", + "type": "string", + "required": true, + "description": "应用名称" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库 ID" + }, + { + "name": "interface_type_id", + "type": "number", + "required": true, + "description": "接口类型 ID" + }, + { + "name": "self_app_key", + "type": "string", + "required": true, + "description": "自身 AppKey" + }, + { + "name": "self_app_secret", + "type": "string", + "required": true, + "description": "自身 AppSecret(脱敏)" + }, + { + "name": "self_ip_whitelist", + "type": "array", + "required": false, + "description": "IP 白名单" + }, + { + "name": "callback_url", + "type": "string", + "required": false, + "description": "回调通知 URL" + }, + { + "name": "rate_limit", + "type": "number", + "required": false, + "description": "速率限制" + }, + { + "name": "sign_method", + "type": "string", + "required": false, + "description": "签名方法(当前仅支持 md5)" + }, + { + "name": "is_enabled", + "type": "number", + "required": false, + "description": "启用状态" + }, + { + "name": "created_at", + "type": "string", + "required": false, + "description": "创建时间" + }, + { + "name": "updated_at", + "type": "string", + "required": false, + "description": "更新时间" + } + ], "errors": [ { "code": "400", @@ -31495,7 +31689,7 @@ }, { "method": "apiApp.create", - "description": "创建 API 应用,自动生成 AppKey(AK{时间戳}{随机8位hex})和 AppSecret(64位hex)。仅创建时返回完整 Secret", + "description": "创建 API 应用,自动生成 AppKey(AK{时间戳}{随机8位hex})和 AppSecret(64位hex)。仅创建时返回完整 Secret。签名方法固定为 md5", "isNeedAuth": true, "isNeedLogin": true, "headers": [ @@ -31531,6 +31725,7 @@ { "name": "ip", "type": "string", + "required": false, "description": "IP 地址或 CIDR" } ] @@ -31548,70 +31743,70 @@ "required": false, "source": "body", "description": "速率限制(次/秒),默认 1000,范围 1-100000" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "应用 ID" + }, + { + "name": "app_name", + "type": "string", + "required": true, + "description": "应用名称" + }, + { + "name": "self_app_key", + "type": "string", + "required": true, + "description": "自动生成的 AppKey" + }, + { + "name": "self_app_secret", + "type": "string", + "required": true, + "description": "自动生成的 AppSecret(仅创建和重新生成时返回完整值,请妥善保存)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "所属仓库 ID" + }, + { + "name": "interface_type_id", + "type": "number", + "required": true, + "description": "接口类型 ID" + }, + { + "name": "rate_limit", + "type": "number", + "required": false, + "description": "速率限制" }, { "name": "sign_method", "type": "string", "required": false, - "source": "body", - "description": "签名方法:md5/hmac/sha256,默认 md5" + "description": "签名方法(固定为 md5)" + }, + { + "name": "is_enabled", + "type": "number", + "required": false, + "description": "启用状态,创建后默认 1" + }, + { + "name": "created_at", + "type": "string", + "required": false, + "description": "创建时间" } ], - "response": { - "type": "object", - "properties": [ - { - "name": "id", - "type": "number", - "description": "应用 ID" - }, - { - "name": "app_name", - "type": "string", - "description": "应用名称" - }, - { - "name": "self_app_key", - "type": "string", - "description": "自动生成的 AppKey" - }, - { - "name": "self_app_secret", - "type": "string", - "description": "自动生成的 AppSecret(仅创建和重新生成时返回完整值,请妥善保存)" - }, - { - "name": "warehouse_id", - "type": "number", - "description": "所属仓库 ID" - }, - { - "name": "interface_type_id", - "type": "number", - "description": "接口类型 ID" - }, - { - "name": "rate_limit", - "type": "number", - "description": "速率限制" - }, - { - "name": "sign_method", - "type": "string", - "description": "签名方法" - }, - { - "name": "is_enabled", - "type": "number", - "description": "启用状态,创建后默认 1" - }, - { - "name": "created_at", - "type": "string", - "description": "创建时间" - } - ] - }, "errors": [ { "code": "400", @@ -31637,7 +31832,7 @@ }, { "method": "apiApp.update", - "description": "更新 API 应用(名称、白名单、回调地址、限流、签名方法、启用状态),不可变字段:app_key、interface_type_id", + "description": "更新 API 应用(名称、白名单、回调地址、限流、启用状态),不可变字段:app_key、interface_type_id、sign_method(固定为 md5,不允许修改)", "isNeedAuth": true, "isNeedLogin": true, "headers": [ @@ -31684,13 +31879,6 @@ "source": "body", "description": "速率限制,范围 1-100000" }, - { - "name": "sign_method", - "type": "string", - "required": false, - "source": "body", - "description": "签名方法:md5/hmac/sha256" - }, { "name": "is_enabled", "type": "number", @@ -31699,41 +31887,44 @@ "description": "启用状态:1-启用,0-停用" } ], - "response": { - "type": "object", - "properties": [ - { - "name": "id", - "type": "number", - "description": "应用 ID" - }, - { - "name": "app_name", - "type": "string", - "description": "应用名称" - }, - { - "name": "self_app_key", - "type": "string", - "description": "AppKey(不可变)" - }, - { - "name": "self_app_secret", - "type": "string", - "description": "AppSecret(脱敏)" - }, - { - "name": "is_enabled", - "type": "number", - "description": "启用状态" - }, - { - "name": "updated_at", - "type": "string", - "description": "更新时间" - } - ] - }, + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "应用 ID" + }, + { + "name": "app_name", + "type": "string", + "required": true, + "description": "应用名称" + }, + { + "name": "self_app_key", + "type": "string", + "required": true, + "description": "AppKey(不可变)" + }, + { + "name": "self_app_secret", + "type": "string", + "required": true, + "description": "AppSecret(脱敏)" + }, + { + "name": "is_enabled", + "type": "number", + "required": false, + "description": "启用状态" + }, + { + "name": "updated_at", + "type": "string", + "required": false, + "description": "更新时间" + } + ], "errors": [ { "code": "400", @@ -31745,7 +31936,7 @@ }, { "code": "400", - "message": "签名方法仅支持 md5/hmac/sha256" + "message": "签名方法当前仅支持 md5,不允许修改" }, { "code": "401", @@ -31948,6 +32139,20 @@ "source": "body", "description": "推送状态筛选:0=待推送 1=推送中 2=已送达 3=失败" }, + { + "name": "startDate", + "type": "string", + "required": false, + "source": "body", + "description": "开始日期(created_at >=),格式 YYYY-MM-DD 或 YYYY-MM-DD HH:mm:ss" + }, + { + "name": "endDate", + "type": "string", + "required": false, + "source": "body", + "description": "结束日期(created_at <=),格式 YYYY-MM-DD 或 YYYY-MM-DD HH:mm:ss" + }, { "name": "page", "type": "number", diff --git a/methods/warehouse.json b/methods/warehouse.json index 8389202..f94bd06 100644 --- a/methods/warehouse.json +++ b/methods/warehouse.json @@ -1,8 +1,8 @@ { "module": "warehouse", - "description": "仓库开放 API 统一入口,供仓库级外部适配器(企微/钉钉/飞书/IM 等)调用,HTTP POST /warehouse,使用 MD5 签名鉴权(interface_type_id=3)", - "version": "1.0.0", - "updatedAt": "2026-08-03", + "description": "仓库开放 API 统一入口(入站方向:外部 → WMS),供仓库级外部适配器(企微/钉钉/飞书/IM 等)调用,HTTP POST /warehouse,使用 MD5 签名鉴权(interface_type_id=3)。出站通知请参阅 warehouse_notify.json。", + "version": "1.2.0", + "updatedAt": "2026-08-07", "http": { "path": "/warehouse", "method": "POST" @@ -204,25 +204,11 @@ "list": [ { "method": "inbox.push", - "description": "外部系统将消息推入仓库站内信,WMS 异步转发到目标渠道。warehouse_id 由验签后上下文注入,禁止外部传入。", + "description": "外部系统将消息推入仓库站内信。warehouse_id 由验签后上下文注入,禁止外部传入。ext_id 由 appKey + requestId 自动组合,幂等去重。source_type 固定为 api,禁止外部传入。", "isNeedAuth": false, "isNeedLogin": false, "headers": [], "params": [ - { - "name": "sourceType", - "type": "string", - "required": false, - "source": "body", - "description": "来源类型:im / api,默认 api" - }, - { - "name": "sourceChannel", - "type": "string", - "required": false, - "source": "body", - "description": "来源渠道标识(IM 平台名称 / API 标识),将写入 source_extra" - }, { "name": "requestId", "type": "string", @@ -230,6 +216,48 @@ "source": "body", "description": "来源请求唯一 ID,与 appKey 组合为 ext_id(api:{appKey}:{requestId}),用于幂等去重" }, + { + "name": "content", + "type": "string", + "required": false, + "source": "body", + "description": "消息正文/摘要" + }, + { + "name": "groupId", + "type": "string", + "required": false, + "source": "body", + "description": "外部群 ID,用于关联群及自动查询货主路由" + }, + { + "name": "groupName", + "type": "string", + "required": false, + "source": "body", + "description": "群名称(展示用)" + }, + { + "name": "userId", + "type": "string", + "required": false, + "source": "body", + "description": "外部用户 ID" + }, + { + "name": "userName", + "type": "string", + "required": false, + "source": "body", + "description": "用户名称(展示用)" + }, + { + "name": "parentId", + "type": "number", + "required": false, + "source": "body", + "description": "关联消息 ID(回信时指向原消息,形成对话链)" + }, { "name": "targetType", "type": "string", @@ -237,13 +265,6 @@ "source": "body", "description": "目标类型:im / api / webhook,默认 im" }, - { - "name": "targetChannel", - "type": "string", - "required": true, - "source": "body", - "description": "目标渠道:wecom / dingtalk / feishu / warehouse_api / webhook" - }, { "name": "extData", "type": "object", @@ -256,21 +277,7 @@ "type": "object", "required": false, "source": "body", - "description": "处理标记,可选:skip_ai_parse(跳过智能解析)、skip_auto_reply(跳过自动回复)、skip_forward(仅存档不转发)" - }, - { - "name": "storeId", - "type": "number", - "required": false, - "source": "body", - "description": "关联货主 ID" - }, - { - "name": "parentId", - "type": "number", - "required": false, - "source": "body", - "description": "关联消息 ID(回信时指向原消息,形成对话链)" + "description": "处理标记(预留,当前未消费)" } ], "response": [ @@ -290,7 +297,7 @@ "name": "ext_id", "type": "string", "required": true, - "description": "外部唯一消息主键" + "description": "外部唯一消息主键(api:{appKey}:{requestId})" } ], "errors": [ @@ -298,25 +305,17 @@ "code": "400", "message": "requestId 不能为空" }, - { - "code": "400", - "message": "targetChannel 不能为空" - }, - { - "code": "400", - "message": "targetUrl 不能为空" - }, { "code": "400", "message": "缺少仓库信息" }, { "code": "400", - "message": "target_url 仅允许 https:// 协议" + "message": "parent_id=XX 对应的消息不存在" }, { "code": "400", - "message": "target_url 不允许指向内网地址" + "message": "消息体超过 64KB 限制" }, { "code": "500", diff --git a/methods/warehouse_notify.json b/methods/warehouse_notify.json new file mode 100644 index 0000000..0b29b96 --- /dev/null +++ b/methods/warehouse_notify.json @@ -0,0 +1,181 @@ +{ + "module": "warehouse_notify", + "description": "仓库开放通知 API 定义(出站方向:WMS → 外部系统)。WMS 处理消息后,通过 HTTP POST 主动推送到外部系统配置的 notify_url,使用 MD5 签名鉴权。method 通过 query 参数传递,body 为 { code, data }。外部系统返回 {\"code\":200} 或 HTTP 非 200 视为推送失败。", + "version": "1.0.0", + "updatedAt": "2026-08-07", + "http": { + "path": "{wms_api_app.callback_url}", + "method": "POST" + }, + "auth": { + "type": "MD5", + "description": "签名算法:sign = MD5(app_secret + timestamp + body_json)。外部系统用预先分配的 AppSecret 验证。method / app_key / timestamp / sign 通过 query 参数传递。", + "params": [ + { + "name": "app_key", + "type": "string", + "required": true, + "source": "query", + "description": "WMS 的 AppKey" + }, + { + "name": "method", + "type": "string", + "required": true, + "source": "query", + "description": "notify.ping / notify.reply" + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "source": "query", + "description": "Unix 时间戳(秒),±10分钟有效" + }, + { + "name": "sign", + "type": "string", + "required": true, + "source": "query", + "description": "MD5(appSecret + timestamp + bodyJson)" + } + ] + }, + "headers": [ + { + "name": "Content-Type", + "type": "string", + "required": true, + "description": "application/json" + } + ], + "methods": { + "groups": [ + { + "groupName": "心跳", + "module": "ping", + "list": [ + { + "method": "notify.ping", + "description": "连通性测试。WMS 配置 notify_url 后可发送 ping 通知验证外部系统可达。", + "isNeedAuth": true, + "isNeedLogin": false, + "example": { + "query": "?app_key=AK20260807001×tamp=1786100000&sign=abc123", + "method": "notify.ping", + "code": 200, + "data": { + "content": "ping", + "timestamp": 1786100000 + } + } + } + ] + }, + { + "groupName": "消息回复", + "module": "reply", + "list": [ + { + "method": "notify.reply", + "description": "消息回复通知。WMS 处理入站消息后,将 AI 回复/绑群结果/面单余额等内容推送到外部系统。外部系统根据 data.type 区分消息类别。", + "isNeedAuth": true, + "isNeedLogin": false, + "params": [ + { + "name": "data.type", + "type": "string", + "required": true, + "source": "body", + "description": "ai=AI回复 / bind=绑群结果 / balance=面单余额 / error=异常兜底" + }, + { + "name": "data.content", + "type": "string", + "required": true, + "source": "body", + "description": "回复正文(纯文本)" + }, + { + "name": "data.ext_id", + "type": "string", + "required": true, + "source": "body", + "description": "通知唯一 ID(wms_inbox_message.id 主键),用于幂等判断。网络波动时可能重推,接收方应据此去重" + }, + { + "name": "data.ext_data", + "type": "object", + "required": false, + "source": "body", + "description": "入站透传数据,原路带回" + }, + { + "name": "data.group_id", + "type": "string", + "required": true, + "source": "body", + "description": "群ID" + }, + { + "name": "data.user_id", + "type": "string", + "required": true, + "source": "body", + "description": "用户ID" + }, + { + "name": "data.group_name", + "type": "string", + "required": true, + "source": "body", + "description": "群名称" + }, + { + "name": "data.user_name", + "type": "string", + "required": true, + "source": "body", + "description": "用户名称" + }, + { + "name": "data.timestamp", + "type": "number", + "required": true, + "source": "body", + "description": "Unix 秒" + } + ], + "notes": [ + "对应入站:/warehouse inbox.push", + "type=ai:用户消息触发 AI 推理回复", + "type=bind:用户发送「授权:CODE」绑群", + "type=balance:绑群成功后自动推送面单余额", + "type=error:AI 无法处理时的兜底回复", + "AI silent(无需回复)时不推送", + "ext_id 为 wms_inbox_message.id 主键,接收方应以 ext_id 做幂等去重,网络波动可能重推" + ], + "example": { + "query": "?app_key=AK001×tamp=1786100000&sign=abc", + "method": "notify.reply", + "code": 200, + "data": { + "type": "ai", + "content": "条码6900000000016查到2款商品:\n1. 披肩-消退 可用0\n2. 披肩 可用0(总量95已锁定)", + "ext_id": "188", + "ext_data": { + "request_id": "req-123" + }, + "group_id": "wrchat-xxx", + "user_id": "user-001", + "group_name": "售后沟通群", + "user_name": "张三", + "timestamp": 1786100000 + } + } + } + ] + } + ] + } +} \ No newline at end of file