From 9af7dcf8fb01e8323e7b88b838ae97995ff81f68 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 14 Nov 2026 17:13:57 +0800 Subject: [PATCH] =?UTF-8?q?feat(storeWarehouse):=20=E7=AD=BE=E7=BA=A6?= =?UTF-8?q?=E5=85=B3=E7=B3=BB=E6=8E=A5=E5=8F=A3=E9=85=8D=E7=BD=AE=E6=8C=89?= =?UTF-8?q?=E8=B4=A7=E4=B8=BB=E5=BC=80=E6=94=BE=E6=8E=A5=E5=8F=A3=E8=90=BD?= =?UTF-8?q?=E5=BA=93=E4=B8=94=E5=9B=9E=E8=B0=83=E5=9C=B0=E5=9D=80=E7=BB=9F?= =?UTF-8?q?=E4=B8=80=E5=8F=96=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - storeWarehouse.store.saveApiConfig:新增 resolveContractApiInterfaceType, interface_type_id=3(OPEN_API_WAREHOUSE 仓库开放接口)自动映射为 2(OPEN_API 货主开放接口)落库, 不再要求当前主体为仓库(货主可维护自身签约关系下的接口配置) - callback_url 不再取入参(含 callbackUrl 别名),统一写入 config.openapi.defaultCallbackUrl(新增配置项,默认空) - storeWarehouse.store.listApiConfig:interface_type_id 过滤同步映射(传 3 按 2 查询) - 文档:methods/system.json 升级 0.3.350、methods/changes/system.json 变更记录、docs/openapi-callback-events.md 回调地址来源说明 - 测试:saveApiConfig 新增 4 条用例(3→2 落库、忽略入参回调地址、默认值未配置、货主主体可保存、缺失类型 404),listApiConfig 新增 1 条过滤映射用例 同时提交工作区其余在制品改动: - waybill:移除 wms_order_express_trace 模型并新增 drop 迁移,轨迹查询/取号/打印链路调整 - order:订单 SN 编码(order_item_sn / order_item_sn_log / sn_code_rule、has_sn_item 回填迁移),pendingOrder/recheckOrder/wave/base 调整 - express_platform、order_async、order_export、order_storage_allocation、storage.report、stock_store 配套修复 - lib:新增 jd_client,调整 qimen_client、callback_functions 及配套测试 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- app/lib/callback_functions.js | 5 +- app/lib/jd_client.js | 522 +++++++++++++ app/lib/qimen_client.js | 41 +- app/model/order_delivery.js | 6 + app/model/order_express_trace.js | 95 --- app/model/order_item_sn.js | 120 +++ app/model/order_item_sn_log.js | 113 +++ app/model/picking_strategy.js | 2 +- app/model/stock_warehouse.js | 8 +- app/service/systemMethods/order/base.js | 193 ++++- .../systemMethods/order/pendingOrder.js | 100 ++- .../systemMethods/order/recheckOrder.js | 260 ++++++- app/service/systemMethods/order/wave.js | 477 ++++++++---- app/service/systemMethods/stock/warehouse.js | 4 + .../systemMethods/waybill/warehouse.js | 317 ++------ app/service/systems/delivery_order.js | 33 +- app/service/systems/express_platform.js | 72 +- app/service/systems/order_async.js | 146 +++- app/service/systems/order_export.js | 143 +++- app/service/systems/order_item_sn.js | 713 ++++++++++++++++++ .../systems/order_storage_allocation.js | 101 ++- app/service/systems/sn_code_rule.js | 235 ++++++ app/service/systems/stock_store.js | 20 +- app/service/systems/storage/report.js | 154 +++- app/service/systems/store_warehouse.js | 88 ++- app/service/systems/waybill.js | 555 ++++++-------- config/config.default.js | 7 + database/designs/waybill-module-design.md | 121 +-- ...1111205500-drop-wms-order-express-trace.js | 74 ++ ...50000-add-has-sn-item-to-order-delivery.js | 102 +++ ...261113151000-backfill-order-has-sn-item.js | 194 +++++ ...261113160000-enlarge-order-item-sn-code.js | 71 ++ ...00-add-sn-code-rules-to-stock-warehouse.js | 68 ++ ...d-store-id-and-indexes-to-order-item-sn.js | 160 ++++ docs/openapi-callback-events.md | 25 +- docs/report-config-guide.md | 4 +- methods/changes/system.json | 396 ++++++++++ methods/system.json | 564 +++++--------- test/app/lib/qimen_client.test.js | 77 +- .../order/wave.singleFetchByIds.test.js | 38 + .../order/wave.waveStrategyList.test.js | 128 ++++ .../systems/express_platform.cainiao.test.js | 25 + .../express_platform.pdd.ext_data.test.js | 25 + .../systems/express_platform.polyapi.test.js | 25 + .../systems/order_async.syncOrderIds.test.js | 201 ++++- .../systems/storage_report_export.test.js | 80 +- .../store_warehouse.listApiConfig.test.js | 27 +- .../store_warehouse.saveApiConfig.test.js | 126 +++- test/support/order_service_test_helper.js | 9 + 49 files changed, 5664 insertions(+), 1406 deletions(-) create mode 100644 app/lib/jd_client.js delete mode 100644 app/model/order_express_trace.js create mode 100644 app/model/order_item_sn.js create mode 100644 app/model/order_item_sn_log.js create mode 100644 app/service/systems/order_item_sn.js create mode 100644 app/service/systems/sn_code_rule.js create mode 100644 database/migrations/20261111205500-drop-wms-order-express-trace.js create mode 100644 database/migrations/20261113150000-add-has-sn-item-to-order-delivery.js create mode 100644 database/migrations/20261113151000-backfill-order-has-sn-item.js create mode 100644 database/migrations/20261113160000-enlarge-order-item-sn-code.js create mode 100644 database/migrations/20261113203000-add-sn-code-rules-to-stock-warehouse.js create mode 100644 database/migrations/20261113233000-add-store-id-and-indexes-to-order-item-sn.js diff --git a/app/lib/callback_functions.js b/app/lib/callback_functions.js index 0dcdf9f..4a4f507 100644 --- a/app/lib/callback_functions.js +++ b/app/lib/callback_functions.js @@ -24,9 +24,8 @@ const CALLBACK_FUNCTIONS = [ { method: 'waybill.getTrace', name: '运单物流轨迹查询', - description: '按运单号批量查询物流轨迹:请求 { waybill_codes: [...] },' - + '外部返回 [{ waybillNo, trace: { opTime, outBizCode, memo, opOrgCityName, weight, scanType } }],' - + '落库 wms_order_express_trace(按 express_id + op_time + scan_type 幂等)', + description: '按运单号查询物流轨迹(实时回源,不落库):请求 { waybill_codes: [运单号] },' + + '外部返回 [{ waybillNo, trace: { opTime, outBizCode, memo, opOrgCityName, weight, scanType } }]', }, ]; diff --git a/app/lib/jd_client.js b/app/lib/jd_client.js new file mode 100644 index 0000000..8878b9c --- /dev/null +++ b/app/lib/jd_client.js @@ -0,0 +1,522 @@ +'use strict'; + +const crypto = require('node:crypto'); +const http = require('node:http'); +const https = require('node:https'); + +/** 京东物流开放平台默认网关 */ +const DEFAULT_BASE_URI = 'https://api.jdl.com'; + +/** 京东物流开放平台协议版本 */ +const DEFAULT_VERSION = '2.0'; + +/** 默认签名算法(md5(content) 小写十六进制) */ +const DEFAULT_ALGORITHM = 'md5-salt'; + +/** 单次请求默认超时时间(毫秒) */ +const DEFAULT_TIMEOUT = 15000; + +/** 标识调用方 HTTP 客户端(与京东示例一致,仅作统计用途) */ +const DEFAULT_USER_AGENT = 'lop-http/nodejs'; + +/** HMac 系列算法名 → node:crypto 摘要名 */ +const HMAC_ALGORITHMS = { + HMacMD5: 'md5', + HMacSHA1: 'sha1', + HMacSHA256: 'sha256', + HMacSHA512: 'sha512', +}; + +/** 只能在 request() 传入的请求级参数(init 里传会被忽略,因此显式报错) */ +const REQUEST_ONLY_KEYS = [ 'path', 'method', 'body', 'query', 'headers', 'timestamp', 'now', 'raw' ]; + +/** + * 判断输入是否为普通对象。 + * @param {*} value 任意输入值。 + * @return {boolean} 是否为普通对象。 + */ +function isPlainObject(value) { + return Object.prototype.toString.call(value) === '[object Object]'; +} + +/** + * 按京东开放平台规则生成签名。 + * @param {string} algorithm 算法名:md5-salt / HMacMD5 / HMacSHA1 / HMacSHA256 / HMacSHA512。 + * @param {string} data 待签名原文(见 buildSignContent)。 + * @param {string} [secret] 密钥(仅 HMac 系列使用)。 + * @return {string} 签名值:md5-salt 为小写十六进制,HMac 系列为 base64。 + * @throws {Error} 算法不支持时抛出。 + */ +function sign(algorithm, data, secret) { + const name = String(algorithm || DEFAULT_ALGORITHM); + const text = String(data === undefined || data === null ? '' : data); + + if (name === 'md5-salt') { + return crypto.createHash('md5').update(text, 'utf8').digest('hex'); + } + + const hmacName = HMAC_ALGORITHMS[name]; + if (!hmacName) { + throw new Error(`Algorithm ${name} not supported yet`); + } + + return crypto.createHmac(hmacName, String(secret === undefined || secret === null ? '' : secret)) + .update(text, 'utf8') + .digest('base64'); +} + +/** + * 格式化签名为 `YYYY-MM-DD HH:mm:ss`(服务器本地时区,与京东 PHP 示例 date() 口径一致)。 + * @param {Date} [date] 时间对象,默认当前时间。 + * @return {string} 格式化后的时间戳。 + */ +function formatTimestamp(date = new Date()) { + const pad = num => String(num).padStart(2, '0'); + return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` + + `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`; +} + +/** + * 格式化当前时区相对 UTC 的小时数,用于 lop-tz 请求头(东八区为 '8')。 + * @param {Date} [date] 时间对象,默认当前时间。 + * @return {string} 时区小时数(如 '8'、'5.5'、'-5')。 + */ +function formatTimezoneOffset(date = new Date()) { + return String(-date.getTimezoneOffset() / 60); +} + +/** + * 拼接签名原文。 + * + * 与京东 PHP 示例完全一致: + * `secret + 'access_token' + token + 'app_key' + key + 'method' + path + + * 'param_json' + body + 'timestamp' + ts + 'v' + version + secret` + * + * @param {Object} options 签名要素。 + * @param {string} options.appSecret 应用密钥。 + * @param {string} [options.accessToken] 访问令牌。 + * @param {string} options.appKey 应用 AppKey。 + * @param {string} options.method 接口路径(京东协议中 method 即 path)。 + * @param {string} [options.paramJson] 业务报文原文。 + * @param {string} options.timestamp 请求时间戳。 + * @param {string} options.version 协议版本。 + * @return {string} 签名原文。 + */ +function buildSignContent({ appSecret, accessToken, appKey, method, paramJson, timestamp, version }) { + const toString = value => String(value === undefined || value === null ? '' : value); + return [ + toString(appSecret), + 'access_token', toString(accessToken), + 'app_key', toString(appKey), + 'method', toString(method), + 'param_json', toString(paramJson), + 'timestamp', toString(timestamp), + 'v', toString(version), + toString(appSecret), + ].join(''); +} + +/** + * 京东物流开放平台客户端(api.jdl.com)。 + * + * 使用方式: + * ```js + * const jdClient = require('./jd_client'); + * jdClient.init(appKey, appSecret, { accessToken }); + * const res = await jdClient.request({ + * path: '/jd/tracking/query', + * domain: 'Tracking_JD', + * body: [{ referenceNumber: 'JDAP20626092313', referenceType: '20000', phone: '7068' }], + * }); + * ``` + */ +class JdClient { + /** + * @param {Object} [options={}] 默认配置。 + */ + constructor(options = {}) { + this.options = { + baseUri: DEFAULT_BASE_URI, + version: DEFAULT_VERSION, + algorithm: DEFAULT_ALGORITHM, + timeout: DEFAULT_TIMEOUT, + userAgent: DEFAULT_USER_AGENT, + appKey: '', + appSecret: '', + accessToken: '', + domain: '', + logger: null, + ...options, + }; + } + + /** + * 初始化凭据与默认配置(可重复调用覆盖)。 + * + * 只能传「请求之间不变」的配置;`path` / `body` / `method` / `query` / `headers` / + * `timestamp` 等请求级参数请传给 request(),误传到这里会直接报错。 + * + * @param {string} appKey 应用 AppKey。 + * @param {string} appSecret 应用 AppSecret。 + * @param {Object} [options={}] 可选默认配置。 + * @param {string} [options.accessToken] 访问令牌,也可后续用 setAccessToken 设置。 + * @param {string} [options.domain] 接口域(LOP-DN),如 Tracking_JD。 + * @param {string} [options.baseUri] 网关地址,默认 https://api.jdl.com。 + * @param {string} [options.version] 协议版本,默认 2.0。 + * @param {string} [options.algorithm] 签名算法,默认 md5-salt。 + * @param {number} [options.timeout] 超时毫秒数,默认 15000。 + * @param {string} [options.userAgent] UA,默认 lop-http/nodejs。 + * @param {Object} [options.logger] 可选日志器(需实现 warn)。 + * @return {JdClient} 当前实例(便于链式调用)。 + * @throws {Error} options 里出现请求级参数时抛出。 + */ + init(appKey, appSecret, options = {}) { + const safeOptions = isPlainObject(options) ? options : {}; + const invalidKeys = Object.keys(safeOptions).filter(key => REQUEST_ONLY_KEYS.includes(key)); + if (invalidKeys.length > 0) { + throw new Error( + `init 不支持请求级参数:${invalidKeys.join(', ')},请在 request() 中传入` + ); + } + + this.options = { + ...this.options, + ...safeOptions, + appKey: String(appKey || '').trim(), + appSecret: String(appSecret || '').trim(), + }; + return this; + } + + /** + * 更新访问令牌。 + * @param {string} accessToken 访问令牌。 + * @return {JdClient} 当前实例。 + */ + setAccessToken(accessToken) { + this.options.accessToken = String(accessToken || '').trim(); + return this; + } + + /** + * 解析本次请求的凭据与配置(请求级参数优先于 init 默认值)。 + * @param {Object} [options={}] 请求参数。 + * @return {Object} 解析后的配置。 + */ + resolveOptions(options = {}) { + const source = isPlainObject(options) ? options : {}; + const pick = key => (source[key] === undefined || source[key] === null + ? this.options[key] + : source[key]); + + const appKey = String(pick('appKey') || '').trim(); + const appSecret = String(pick('appSecret') || '').trim(); + if (!appKey || !appSecret) { + throw new Error('京东开放平台 appKey / appSecret 未配置'); + } + + return { + appKey, + appSecret, + accessToken: String(pick('accessToken') || '').trim(), + domain: String(pick('domain') || '').trim(), + baseUri: String(pick('baseUri') || DEFAULT_BASE_URI).replace(/\/+$/, ''), + version: String(pick('version') || DEFAULT_VERSION), + algorithm: String(pick('algorithm') || DEFAULT_ALGORITHM), + timeout: Number(pick('timeout')) || DEFAULT_TIMEOUT, + userAgent: String(pick('userAgent') || DEFAULT_USER_AGENT), + logger: pick('logger') || null, + }; + } + + /** + * 序列化业务报文:字符串原样使用(签名与发送必须完全一致),其余按 JSON 序列化。 + * @param {*} body 业务报文。 + * @return {string} param_json 原文。 + */ + normalizeParamJson(body) { + if (body === undefined || body === null) return ''; + if (typeof body === 'string') return body; + return JSON.stringify(body); + } + + /** + * 构建已签名的请求参数(不发请求,便于日志与单测)。 + * @param {Object} [options={}] 请求参数。 + * @param {string} options.path 接口路径(如 /jd/tracking/query),京东协议中同时作为签名 method。 + * @param {string} [options.method='POST'] HTTP 方法。 + * @param {*} [options.body] 业务报文(对象/数组/字符串),序列化后作为 param_json。 + * @param {Object} [options.query={}] 额外查询参数(如京东要求的业务 query 参数)。 + * @param {Object} [options.headers={}] 额外请求头。 + * @param {string} [options.timestamp] 指定时间戳(默认当前本地时间),便于复现。 + * @param {Date} [options.now] 指定当前时间对象(影响时间戳与 lop-tz)。 + * @return {Object} { url, method, headers, body, paramJson, sign, timestamp, content, query }。 + */ + buildRequestOptions(options = {}) { + const { + path: apiPath, + method = 'POST', + body, + query: extraQuery = {}, + headers: extraHeaders = {}, + timestamp, + now, + } = options; + + const config = this.resolveOptions(options); + const path = String(apiPath || '').trim(); + if (!path) { + throw new Error('京东接口 path 不能为空'); + } + + const httpMethod = String(method || 'POST').toUpperCase(); + const paramJson = this.normalizeParamJson(body); + const nowDate = now instanceof Date ? now : new Date(); + const requestTimestamp = timestamp ? String(timestamp) : formatTimestamp(nowDate); + + const content = buildSignContent({ + appSecret: config.appSecret, + accessToken: config.accessToken, + appKey: config.appKey, + method: path, + paramJson, + timestamp: requestTimestamp, + version: config.version, + }); + const signValue = sign(config.algorithm, content, config.appSecret); + + const queryPairs = []; + if (config.domain) queryPairs.push([ 'LOP-DN', config.domain ]); + queryPairs.push([ 'app_key', config.appKey ]); + queryPairs.push([ 'access_token', config.accessToken ]); + queryPairs.push([ 'timestamp', requestTimestamp ]); + queryPairs.push([ 'v', config.version ]); + queryPairs.push([ 'sign', signValue ]); + queryPairs.push([ 'algorithm', config.algorithm ]); + if (httpMethod === 'GET' && paramJson) { + queryPairs.push([ 'param_json', paramJson ]); + } + for (const [ key, value ] of Object.entries(isPlainObject(extraQuery) ? extraQuery : {})) { + if (value === undefined || value === null) continue; + queryPairs.push([ key, String(value) ]); + } + + const search = new URLSearchParams(); + for (const [ key, value ] of queryPairs) { + search.append(key, value); + } + + const url = `${config.baseUri}${path}${search.toString() ? `?${search.toString()}` : ''}`; + const headers = { + 'content-type': 'application/json;charset=utf-8', + 'lop-tz': formatTimezoneOffset(nowDate), + 'user-agent': config.userAgent, + ...(isPlainObject(extraHeaders) ? extraHeaders : {}), + }; + const requestBody = httpMethod === 'GET' ? null : paramJson; + if (requestBody !== null && headers['content-length'] === undefined) { + headers['content-length'] = String(Buffer.byteLength(requestBody, 'utf8')); + } + + return { + url, + method: httpMethod, + headers, + body: requestBody, + paramJson, + sign: signValue, + timestamp: requestTimestamp, + content, + query: Object.fromEntries(queryPairs), + timeout: config.timeout, + }; + } + + /** + * 调用京东开放平台接口。 + * @param {Object} [options={}] 请求参数,见 buildRequestOptions。 + * @param {boolean} [options.raw=false] 为 true 时返回 { status, headers, text } 原始响应。 + * @return {Promise} 默认返回 { success, status, headers, data, text, url }。 + */ + async request(options = {}) { + const prepared = this.buildRequestOptions(options); + const response = await this.send(prepared); + const text = response.text; + let data = null; + try { + data = text ? JSON.parse(text) : null; + } catch (_e) { + data = text; + } + + const result = { + success: response.status >= 200 && response.status < 300, + status: response.status, + headers: response.headers, + data, + text, + url: prepared.url, + }; + + if (options && options.raw === true) { + return { status: response.status, headers: response.headers, text, url: prepared.url }; + } + return result; + } + + /** + * 发送 HTTP 请求(内置 http/https,不依赖第三方请求库)。 + * @param {Object} prepared buildRequestOptions 的返回值。 + * @return {Promise<{status: number, headers: Object, text: string}>} 响应。 + */ + send(prepared) { + return new Promise((resolve, reject) => { + const target = new URL(prepared.url); + const transport = target.protocol === 'http:' ? http : https; + const req = transport.request({ + protocol: target.protocol, + hostname: target.hostname, + port: target.port || (target.protocol === 'http:' ? 80 : 443), + path: `${target.pathname}${target.search}`, + method: prepared.method, + headers: prepared.headers, + timeout: prepared.timeout, + }, res => { + const chunks = []; + res.on('data', chunk => chunks.push(chunk)); + res.on('end', () => { + resolve({ + status: Number(res.statusCode) || 0, + headers: res.headers, + text: Buffer.concat(chunks).toString('utf8'), + }); + }); + res.on('error', reject); + }); + + req.on('timeout', () => { + req.destroy(new Error(`京东接口请求超时(${prepared.timeout}ms)`)); + }); + req.on('error', reject); + if (prepared.body !== null && prepared.body !== undefined) { + req.write(prepared.body); + } + req.end(); + }); + } + + /** + * 驱动式调用:兼容 `execute({ url, body })` 写法(与其它快递驱动保持一致)。 + * + * - `url` 可传完整地址(自动拆成 baseUri + path + query),也可只传 path; + * - `body` 为对象/数组时自动 JSON.stringify,字符串原样使用(签名与发送同一份); + * - 返回类 fetch 响应对象,支持 `await res.text()` / `await res.json()`。 + * + * @param {Object} [request={}] 请求参数。 + * @param {string} request.url 接口地址(完整 URL 或 path)。 + * @param {*} [request.body] 业务报文。 + * @param {string} [request.method='POST'] HTTP 方法。 + * @param {Object} [request.query] 额外 query 参数。 + * @param {Object} [request.headers] 额外请求头。 + * @param {string} [request.domain] 接口域(LOP-DN)。 + * @param {string} [request.accessToken] 覆盖默认 access_token。 + * @return {Promise} { ok, status, statusText, headers, url, data, text(), json() }。 + */ + async execute(request = {}) { + const safeRequest = isPlainObject(request) ? request : {}; + const targetUrl = String(safeRequest.url || '').trim(); + if (!targetUrl) { + throw new Error('京东接口 url 不能为空'); + } + + const isAbsolute = /^https?:\/\//i.test(targetUrl); + const parsed = isAbsolute ? new URL(targetUrl) : null; + const urlQuery = {}; + if (parsed) { + for (const [ key, value ] of parsed.searchParams.entries()) { + urlQuery[key] = value; + } + } + + const result = await this.request({ + ...safeRequest, + baseUri: parsed ? `${parsed.protocol}//${parsed.host}` : safeRequest.baseUri, + path: parsed ? parsed.pathname : targetUrl, + query: { ...urlQuery, ...(isPlainObject(safeRequest.query) ? safeRequest.query : {}) }, + }); + + const text = result.text === undefined || result.text === null ? '' : String(result.text); + return { + ok: result.success, + status: result.status, + statusText: result.success ? 'OK' : 'ERROR', + headers: result.headers || {}, + url: result.url, + data: result.data, + text: async () => text, + json: async () => { + if (text) return JSON.parse(text); + return null; + }, + }; + } +} + +const defaultClient = new JdClient(); + +module.exports = { + JdClient, + buildSignContent, + formatTimestamp, + formatTimezoneOffset, + sign, + /** + * 初始化默认客户端。 + * @param {string} appKey 应用 AppKey。 + * @param {string} appSecret 应用 AppSecret。 + * @param {Object} [options={}] 默认配置。 + * @return {JdClient} 默认客户端实例。 + */ + init(appKey, appSecret, options) { + return defaultClient.init(appKey, appSecret, options); + }, + /** + * 更新默认客户端的访问令牌。 + * @param {string} accessToken 访问令牌。 + * @return {JdClient} 默认客户端实例。 + */ + setAccessToken(accessToken) { + return defaultClient.setAccessToken(accessToken); + }, + /** + * 用默认客户端构建签名请求参数。 + * @param {Object} [options={}] 请求参数。 + * @return {Object} 已签名请求参数。 + */ + buildRequestOptions(options) { + return defaultClient.buildRequestOptions(options); + }, + /** + * 用默认客户端调用接口。 + * @param {Object} [options={}] 请求参数。 + * @return {Promise} 响应。 + */ + request(options) { + return defaultClient.request(options); + }, + /** + * 用默认客户端做驱动式调用(兼容 execute({ url, body }))。 + * @param {Object} [request={}] 请求参数。 + * @return {Promise} 类 fetch 响应(支持 text() / json())。 + */ + execute(request) { + return defaultClient.execute(request); + }, + /** + * 默认客户端实例。 + * @return {JdClient} 实例。 + */ + get client() { + return defaultClient; + }, +}; diff --git a/app/lib/qimen_client.js b/app/lib/qimen_client.js index bfd14fa..1bf62f9 100644 --- a/app/lib/qimen_client.js +++ b/app/lib/qimen_client.js @@ -66,23 +66,48 @@ class QimenClient { .replace(selfClosingRegex, (match, attributes = '') => `<${newTag}${attributes}/>`); } + replaceDeliveryConfirmSnListTags(xmlString) { + const snListBlockRegex = /<\s*snList(\s+[^>]*)?>[\s\S]*?<\s*\/\s*snList\s*>/gi; + + return String(xmlString || '').replace(snListBlockRegex, block => { + // 奇门 deliveryorder.confirm 要求 snList 下为 子节点,而 buildXmlNode 对标量数组统一输出 + return this.replaceXmlTagsWithString(block, 'item', 'sn'); + }); + } + replaceDeliveryConfirmOrderLineTags(xmlString) { const orderLinesBlockRegex = /<\s*orderLines(\s+[^>]*)?>[\s\S]*?<\s*\/\s*orderLines\s*>/gi; return String(xmlString || '').replace(orderLinesBlockRegex, block => { - return this.replaceXmlTagsWithString(block, 'item', 'orderLine'); + // 先修正 snList 内的 ,否则会被下面的 item→orderLine 替换误伤 + const withSnList = this.replaceDeliveryConfirmSnListTags(block); + return this.replaceXmlTagsWithString(withSnList, 'item', 'orderLine'); }); } replaceDeliveryConfirmPackageTags(xmlString) { - const packagesBlockRegex = /<\s*packages(\s+[^>]*)?>[\s\S]*?<\s*\/\s*packages\s*>/gi; + const packagesBlockRegex = /<\s*packages(\s+[^>]*)?>([\s\S]*?)<\s*\/\s*packages\s*>/gi; - return String(xmlString || '').replace(packagesBlockRegex, block => { - return block - // 去掉 buildXmlNode 为数组元素添加的 包装器: → - .replace(/<\s*package\s*>\s*<\s*item\s*>/gi, '') - // 去掉对应的 包装器闭合,输出标准格式 XML(不再做交错标签变换) - .replace(/<\s*\/\s*item\s*>\s*<\s*\/\s*package\s*>/gi, ''); + return String(xmlString || '').replace(packagesBlockRegex, (match, attributes = '', inner = '') => { + // buildXmlNode 把 packages.package 数组序列化成 …, + // 奇门要求 …:去掉数组容器,再把每个 改名为 , + // 否则一单多运单号(多个包裹)时标签会错位成 / + const withoutContainer = String(inner) + .replace(/^\s*<\s*package\s*>/, '') + .replace(/<\s*\/\s*package\s*>\s*$/, ''); + + // 下的 是包裹内商品明细,必须保留原名;先占位保护,改名后再还原 + const innerItemsBlocks = []; + const protectedInner = withoutContainer.replace(/<\s*items(\s+[^>]*)?>[\s\S]*?<\s*\/\s*items\s*>/gi, block => { + innerItemsBlocks.push(block); + return `@@PACKAGE_ITEMS_${innerItemsBlocks.length - 1}@@`; + }); + + const renamed = this.replaceXmlTagsWithString(protectedInner, 'item', 'package'); + const restored = renamed.replace(/@@PACKAGE_ITEMS_(\d+)@@/g, + (placeholder, index) => innerItemsBlocks[Number(index)] || placeholder); + + return `${restored}`; }); } diff --git a/app/model/order_delivery.js b/app/model/order_delivery.js index 7ad2bbb..c391349 100644 --- a/app/model/order_delivery.js +++ b/app/model/order_delivery.js @@ -288,6 +288,12 @@ module.exports = app => { defaultValue: 'N', comment: '是否B2B:Y是 N否', }, + has_sn_item: { + type: ENUM('Y', 'N'), + allowNull: true, + defaultValue: 'N', + comment: '是否含序列号管理商品:Y是 N否(按订单明细 stock_warehouse.is_sn_mgmt 聚合)', + }, invoice_flag: { type: ENUM(...StatusEnum.INVOICE), allowNull: true, diff --git a/app/model/order_express_trace.js b/app/model/order_express_trace.js deleted file mode 100644 index a9ba532..0000000 --- a/app/model/order_express_trace.js +++ /dev/null @@ -1,95 +0,0 @@ -'use strict'; - -/** - * 运单物流轨迹模型。 - * 一个运单(express_id)对应多条轨迹,由外部快递/轨迹接口回传。 - * @param {import('egg').Application} app Egg 应用实例。 - * @return {import('sequelize').ModelCtor} Sequelize 模型。 - */ -module.exports = app => { - const { BIGINT, STRING, DECIMAL, DATE, JSON: JSON_TYPE } = app.Sequelize; - - const OrderExpressTrace = app.model.define('order_express_trace', { - id: { - type: BIGINT(20).UNSIGNED, - primaryKey: true, - autoIncrement: true, - allowNull: false, - comment: '主键ID', - }, - express_id: { - type: BIGINT(20).UNSIGNED, - allowNull: false, - comment: '运单ID(wms_order_express.id)', - }, - waybill_code: { - type: STRING(50), - allowNull: false, - comment: '运单号(冗余,便于按运单号直查)', - }, - order_id: { - type: BIGINT(20).UNSIGNED, - allowNull: true, - comment: '订单ID(冗余,便于按订单查轨迹)', - }, - warehouse_id: { - type: BIGINT(20).UNSIGNED, - allowNull: false, - comment: '仓库ID(数据隔离维度)', - }, - op_time: { - type: DATE, - allowNull: true, - comment: '操作时间(opTime)', - }, - out_biz_code: { - type: STRING(191), - allowNull: true, - comment: '外部业务码(outBizCode)', - }, - memo: { - type: STRING(500), - allowNull: true, - comment: '轨迹描述(memo)', - }, - op_org_city_name: { - type: STRING(100), - allowNull: true, - comment: '操作机构所在城市(opOrgCityName)', - }, - weight: { - type: DECIMAL(10, 3), - allowNull: true, - defaultValue: 0, - comment: '重量(weight,来源原值,支持小数如 0.99)', - }, - scan_type: { - type: STRING(50), - allowNull: true, - comment: '扫描类型(scanType),如 发件/到件/派件/签收', - }, - raw_data: { - type: JSON_TYPE, - allowNull: true, - comment: '原始轨迹报文(未落库字段的兜底存储)', - }, - }, { - tableName: 'wms_order_express_trace', - freezeTableName: true, - underscored: true, - timestamps: true, - createdAt: 'created_at', - updatedAt: 'updated_at', - deletedAt: 'deleted_at', - paranoid: true, - comment: '运单物流轨迹表(1 运单 : N 轨迹)', - indexes: [ - { name: 'uk_express_op_scan', unique: true, fields: [ 'express_id', 'op_time', 'scan_type' ] }, - { name: 'idx_waybill_code', fields: [ 'waybill_code', 'op_time' ] }, - { name: 'idx_order_id', fields: [ 'order_id' ] }, - { name: 'idx_warehouse_op_time', fields: [ 'warehouse_id', 'op_time' ] }, - ], - }); - - return OrderExpressTrace; -}; diff --git a/app/model/order_item_sn.js b/app/model/order_item_sn.js new file mode 100644 index 0000000..9c298f7 --- /dev/null +++ b/app/model/order_item_sn.js @@ -0,0 +1,120 @@ +// app/model/order_item_sn.js +'use strict'; + +module.exports = app => { + const { BIGINT, STRING, INTEGER, DATE } = app.Sequelize; + + const OrderItemSn = app.model.define('wms_order_item_sn', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '货主ID(复核落库时从订单冗余,便于按货主隔离查询)', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '订单ID,逻辑关联分仓订单主表,不做物理外键', + }, + order_item_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '订单明细ID,逻辑关联分仓订单明细表,不做物理外键', + }, + sn_code: { + type: STRING(512), + allowNull: false, + comment: 'SN编码(支持链接/二维码内容,最长512字符)', + }, + sn_status: { + type: STRING(32), + allowNull: false, + defaultValue: 'BOUND', + comment: 'SN状态:BOUND/VERIFIED/RETURNED/REISSUED/INVALID', + }, + verify_status: { + type: STRING(32), + allowNull: false, + defaultValue: 'UNVERIFIED', + comment: '核验状态:UNVERIFIED/PASS/FAIL', + }, + bound_at: { + type: DATE, + allowNull: true, + comment: '绑定时间', + }, + verified_at: { + type: DATE, + allowNull: true, + comment: '核验时间', + }, + returned_at: { + type: DATE, + allowNull: true, + comment: '退回时间', + }, + reissued_at: { + type: DATE, + allowNull: true, + comment: '重发时间', + }, + version: { + type: INTEGER.UNSIGNED, + allowNull: false, + defaultValue: 1, + comment: '版本号', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }, { + tableName: 'wms_order_item_sn', + timestamps: false, + comment: '订单明细SN当前关系与状态表', + indexes: [ + { + name: 'uk_wms_order_item_sn_warehouse_sn_code', + unique: true, + fields: [ 'warehouse_id', 'sn_code' ], + }, + { + name: 'idx_wms_order_item_sn_order_id', + fields: [ 'order_id' ], + }, + { + name: 'idx_wms_order_item_sn_order_item_id', + fields: [ 'order_item_id' ], + }, + { + name: 'idx_wms_order_item_sn_sn_code', + fields: [ 'sn_code' ], + }, + { + name: 'idx_wms_order_item_sn_store_id', + fields: [ 'store_id' ], + }, + ], + }); + + return OrderItemSn; +}; diff --git a/app/model/order_item_sn_log.js b/app/model/order_item_sn_log.js new file mode 100644 index 0000000..506e4bb --- /dev/null +++ b/app/model/order_item_sn_log.js @@ -0,0 +1,113 @@ +// app/model/order_item_sn_log.js +'use strict'; + +module.exports = app => { + const { BIGINT, STRING, DATE } = app.Sequelize; + + const OrderItemSnLog = app.model.define('wms_order_item_sn_log', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + sn_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联 wms_order_item_sn.id,不做物理外键', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '订单ID,逻辑关联分仓订单主表,不做物理外键', + }, + order_item_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '订单明细ID,逻辑关联分仓订单明细表,不做物理外键', + }, + sn_code: { + type: STRING(512), + allowNull: false, + comment: 'SN编码(支持链接/二维码内容,最长512字符)', + }, + from_sn_status: { + type: STRING(32), + allowNull: true, + comment: '变更前SN状态', + }, + to_sn_status: { + type: STRING(32), + allowNull: false, + comment: '变更后SN状态', + }, + verify_status: { + type: STRING(32), + allowNull: true, + comment: '本次状态变更后的核验状态', + }, + action_type: { + type: STRING(32), + allowNull: false, + comment: '动作类型:BIND/VERIFY/RETURN/REISSUE/UNBIND', + }, + remark: { + type: STRING(255), + allowNull: true, + comment: '备注', + }, + operator_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '操作人ID', + }, + operated_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '操作时间', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }, { + tableName: 'wms_order_item_sn_log', + timestamps: false, + comment: '订单明细SN状态变更流水表', + indexes: [ + { + name: 'idx_wms_order_item_sn_log_sn_id', + fields: [ 'sn_id' ], + }, + { + name: 'idx_wms_order_item_sn_log_sn_code', + fields: [ 'sn_code' ], + }, + { + name: 'idx_wms_order_item_sn_log_order_id', + fields: [ 'order_id' ], + }, + { + name: 'idx_wms_order_item_sn_log_order_item_id', + fields: [ 'order_item_id' ], + }, + ], + }); + + return OrderItemSnLog; +}; diff --git a/app/model/picking_strategy.js b/app/model/picking_strategy.js index 4115436..bf9b067 100644 --- a/app/model/picking_strategy.js +++ b/app/model/picking_strategy.js @@ -30,7 +30,7 @@ module.exports = app => { strategy_type: { type: TINYINT, allowNull: false, - comment: '策略类型:1-散单 2-团购', + comment: '策略类型:1-散单 2-团购 3-SN(序列号管理,固定先拣后分)', }, status: { type: TINYINT, diff --git a/app/model/stock_warehouse.js b/app/model/stock_warehouse.js index f73edcd..a43a97a 100644 --- a/app/model/stock_warehouse.js +++ b/app/model/stock_warehouse.js @@ -1,7 +1,7 @@ 'use strict'; module.exports = app => { - const { STRING, BIGINT, DECIMAL, TEXT, DATE, CHAR, INTEGER, ENUM, TINYINT } = app.Sequelize; + const { STRING, BIGINT, DECIMAL, TEXT, DATE, CHAR, INTEGER, ENUM, TINYINT, JSON } = app.Sequelize; const StockWarehouse = app.model.define('stock_warehouse', { id: { @@ -115,6 +115,12 @@ module.exports = app => { defaultValue: 'N', comment: '是否序列号管理', }, + sn_code_rules: { + type: JSON, + allowNull: true, + defaultValue: null, + comment: 'SN码规则(JSON数组):match_type=prefix|suffix、match_value=前缀/后缀、keep_mode=full|strip', + }, is_shelf_life_mgmt: { type: CHAR(1), defaultValue: 'N', diff --git a/app/service/systemMethods/order/base.js b/app/service/systemMethods/order/base.js index 832fe6f..49fde3f 100644 --- a/app/service/systemMethods/order/base.js +++ b/app/service/systemMethods/order/base.js @@ -40,6 +40,7 @@ const ORDER_LIST_BASE_ATTRIBUTES = [ 'id_type', 'id_number', 'sync_status', 'items', 'items_count', 'items_total', 'items_weight', 'packages_weight', + 'has_sn_item', 'wave_id', 'wave_no', 'wave_strategy_version', @@ -609,6 +610,7 @@ class OrderBaseService extends MainService { wave_scan_result: this.normalizeWaveScanResult(order.wave_scan_result), create_channel: this.formatCreateChannelLabel(order.create_channel), lock_status: this.normalizeLockStatusFlag(order.lock_status), + is_sn_order: String(order.has_sn_item || '').trim().toUpperCase() === 'Y' ? 'Y' : 'N', }; } @@ -1234,6 +1236,183 @@ class OrderBaseService extends MainService { }; } + /** + * 提取 is_sn_order(是否序列号订单)虚拟筛选条件。 + * + * 订单表已冗余 has_sn_item 字段(建单时按明细 stock_warehouse.is_sn_mgmt 聚合), + * 因此这里仅做参数归一化,后续直接生成订单表字段条件,无需反查明细。 + * 原始列 has_sn_item 仍走通用 where 解析,可继续按标准操作符(eq/ne/in 等)使用。 + * + * 取值兼容:Y/N、1/0、true/false、是/否,以及 { value } 标准结构。 + * + * @param {Object} whereInput 标准化后的 where 条件。 + * @return {{ where: Object, isSnOrder: boolean|null }} 清洗后的 where 与序列号订单筛选值。 + */ + extractSnOrderVirtualFilter(whereInput = {}) { + const normalizedWhere = this.isPlainObject(whereInput) + ? { ...whereInput } + : {}; + const snCondition = normalizedWhere.is_sn_order + ?? normalizedWhere.isSnOrder; + + delete normalizedWhere.is_sn_order; + delete normalizedWhere.isSnOrder; + + if (snCondition === undefined || snCondition === null || snCondition === '') { + return { where: normalizedWhere, isSnOrder: null }; + } + + const rawValue = this.isPlainObject(snCondition) + && Object.prototype.hasOwnProperty.call(snCondition, 'value') + ? snCondition.value + : snCondition; + + if (rawValue === undefined || rawValue === null || rawValue === '') { + return { where: normalizedWhere, isSnOrder: null }; + } + + const normalizedValue = typeof rawValue === 'string' + ? rawValue.trim().toLowerCase() + : rawValue; + + if (normalizedValue === true || normalizedValue === 1 + || [ 'y', 'yes', 'true', '1', '是' ].includes(normalizedValue)) { + return { where: normalizedWhere, isSnOrder: true }; + } + + if (normalizedValue === false || normalizedValue === 0 + || [ 'n', 'no', 'false', '0', '否' ].includes(normalizedValue)) { + return { where: normalizedWhere, isSnOrder: false }; + } + + throw new Error('is_sn_order 参数不合法,仅支持 Y/N(或 true/false、1/0)'); + } + + /** + * 构建 is_sn_order(是否序列号订单)筛选条件。 + * + * has_sn_item='Y' 视为序列号订单;N 条件兼容历史 NULL 行(未回填前按非序列号订单处理)。 + * + * @param {boolean|null} isSnOrder true=仅序列号订单,false=仅非序列号订单,null=不过滤。 + * @return {Object|null} Sequelize 条件,无效值返回 null。 + */ + buildSnOrderFilterCondition(isSnOrder) { + if (typeof isSnOrder !== 'boolean') { + return null; + } + + const { Op } = this.app.Sequelize; + + if (isSnOrder) { + return { + has_sn_item: { [Op.eq]: 'Y' }, + }; + } + + return { + [Op.or]: [ + { has_sn_item: { [Op.is]: null } }, + { has_sn_item: { [Op.ne]: 'Y' } }, + ], + }; + } + + /** + * 提取 sn_code(按 SN 码反查订单)虚拟筛选条件。 + * + * 兼容 sn_code / snCode / sn_codes / snCodes 四种写法,值支持单个字符串 + * (逗号/空格/分号分隔多个)、字符串数组,以及 { value } 标准结构。 + * 取值仅做 trim 与去重,不做模糊匹配(扫码得到的是完整 SN 码)。 + * + * @param {Object} whereInput 标准化后的 where 条件。 + * @return {{ where: Object, snCodes: string[] }} 清洗后的 where 与 SN 码列表。 + */ + extractSnCodeVirtualFilter(whereInput = {}) { + const normalizedWhere = this.isPlainObject(whereInput) + ? { ...whereInput } + : {}; + + const rawCondition = normalizedWhere.sn_code + ?? normalizedWhere.snCode + ?? normalizedWhere.sn_codes + ?? normalizedWhere.snCodes; + + delete normalizedWhere.sn_code; + delete normalizedWhere.snCode; + delete normalizedWhere.sn_codes; + delete normalizedWhere.snCodes; + + const value = this.isPlainObject(rawCondition) + && Object.prototype.hasOwnProperty.call(rawCondition, 'value') + ? rawCondition.value + : rawCondition; + + const candidates = Array.isArray(value) ? value : [ value ]; + const snCodes = Array.from(new Set( + candidates + .flatMap(item => String(item === undefined || item === null ? '' : item).split(/[\s,;]+/)) + .map(code => code.trim()) + .filter(Boolean) + )); + + return { + where: normalizedWhere, + snCodes, + }; + } + + /** + * 根据 SN 码查询 wms_order_item_sn 命中的订单ID。 + * + * 订单表结构不变,仅用 SN 码表反查 order_id 后回填到订单列表条件中; + * 查询走 (warehouse_id, sn_code) 唯一键或 idx_wms_order_item_sn_sn_code。 + * + * @param {string[]} snCodes SN 码列表。 + * @param {number|string} [warehouseId] 仓库ID(必须与当前上下文一致)。 + * @return {Promise} 命中的订单ID列表。 + */ + async findOrderIdsBySnCodes(snCodes = [], warehouseId = this.getWarehouseId()) { + const contextWarehouseId = this.getWarehouseId(); + + if (contextWarehouseId === null || contextWarehouseId === undefined || contextWarehouseId === '') { + throw new Error('缺少当前用户仓库上下文 store_id'); + } + + if (warehouseId !== null && warehouseId !== undefined && warehouseId !== '' + && String(warehouseId) !== String(contextWarehouseId)) { + throw new Error('订单工作台仓库ID必须来自当前用户上下文 store_id,禁止传入外部仓库ID。'); + } + + const normalizedSnCodes = Array.from(new Set( + (Array.isArray(snCodes) ? snCodes : []) + .map(code => String(code || '').trim()) + .filter(Boolean) + )); + + if (normalizedSnCodes.length === 0) { + return []; + } + + const orderItemSnModel = this.ctx.model && this.ctx.model.OrderItemSn; + if (!orderItemSnModel || typeof orderItemSnModel.findAll !== 'function') { + return []; + } + + const { Op } = this.app.Sequelize; + const rows = await orderItemSnModel.findAll({ + where: { + warehouse_id: contextWarehouseId, + sn_code: { [Op.in]: normalizedSnCodes }, + }, + attributes: [ 'order_id' ], + raw: true, + }); + + return Array.from(new Set((Array.isArray(rows) ? rows : []) + .map(row => Number(row && row.order_id)) + .filter(orderId => Number.isFinite(orderId) && orderId > 0))); + } + /** * 根据 wave_index 筛选条件查询 wms_order_wave_index 命中的订单ID。 * @param {Object} waveIndexCondition 序号筛选条件(含 operator/value)。 @@ -1728,7 +1907,9 @@ class OrderBaseService extends MainService { const { where: whereAfterStockQuery, stockQuery } = this.extractStockQueryVirtualFilter(whereAfterBuyerMessage); const { where: whereAfterWaveIndex, waveIndexCondition } = this.extractWaveIndexVirtualFilter(whereAfterStockQuery); const { where: whereAfterWaveScope, waveScope } = this.extractWaveScopeVirtualFilter(whereAfterWaveIndex); - const mergedWhere = this.mergeWhereObjects(this.getDefaultWhere(moduleName), whereAfterWaveScope); + const { where: whereAfterSnOrder, isSnOrder } = this.extractSnOrderVirtualFilter(whereAfterWaveScope); + const { where: whereAfterSnCode, snCodes } = this.extractSnCodeVirtualFilter(whereAfterSnOrder); + const mergedWhere = this.mergeWhereObjects(this.getDefaultWhere(moduleName), whereAfterSnCode); let queryWhere = this.buildWhere(mergedWhere, contextWarehouseId, { specialFieldMap: { quickWhere: { @@ -1762,6 +1943,16 @@ class OrderBaseService extends MainService { queryWhere = this.appendConditionToWhere(queryWhere, waveScopeCondition); } + if (isSnOrder !== null) { + const snOrderCondition = this.buildSnOrderFilterCondition(isSnOrder); + queryWhere = this.appendConditionToWhere(queryWhere, snOrderCondition); + } + + if (snCodes.length > 0) { + const snOrderIds = await this.findOrderIdsBySnCodes(snCodes, contextWarehouseId); + queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, snOrderIds); + } + const model = await this.getOrderModel(moduleName, contextWarehouseId); const order = this.buildListOrder(requestData.sort, moduleName); const offset = (page - 1) * pageSize; diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index 0c0f77a..a0f1110 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -2077,6 +2077,87 @@ class PendingOrderService extends OrderBaseService { } } + /** + * 自动同步回传前置过滤:静默剔除 SN(序列号管理)订单。 + * + * auto_sync_back 由运单分配、手工运单等链路自动触发,此时 SN 订单尚未复核、 + * SN 明细也尚未写入,回传链路会拦截并置为待处理异常(sn_batch_forbidden), + * 因此自动触发场景直接跳过,不改变订单状态、不写 sync_message,仅在日志中记录被跳过的订单。 + * SN 订单的自动回传改由复核完成(order.recheckOrder.confirmRecheck)后触发。 + * + * @param {Object} params 过滤参数。 + * @param {Array|number|string} [params.orderIds] 待同步订单ID集合。 + * @param {number|string} [params.warehouseId] 仓库ID(后台链路 ctx.user 为空时必须显式传入)。 + * @param {string} [params.source] 触发来源(仅用于日志定位)。 + * @return {Promise<{ orderIds: number[], skippedSnOrderIds: number[] }>} 过滤后的订单ID与被跳过的SN订单ID。 + */ + async filterAutoSyncSnOrderIds(params = {}) { + const { ctx } = this; + const logger = ctx.logger && typeof ctx.logger === 'object' + ? ctx.logger + : { info() {}, warn() {} }; + const requestData = this.isPlainObject(params) ? params : {}; + const orderIds = this.normalizeOrderIds({ ids: requestData.orderIds }); + if (orderIds.length === 0) { + return { orderIds: [], skippedSnOrderIds: [] }; + } + + const source = String(requestData.source || '').trim() || 'unknown'; + const warehouseId = Number(requestData.warehouseId || this.getWarehouseId() || 0); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + return { orderIds, skippedSnOrderIds: [] }; + } + + try { + const factory = ctx.model && ctx.model.OrderDeliveryFactory; + const orderModel = factory && typeof factory.getCurrentModel === 'function' + ? await factory.getCurrentModel(warehouseId) + : null; + if (!orderModel || typeof orderModel.findAll !== 'function') { + return { orderIds, skippedSnOrderIds: [] }; + } + + const { Op } = this.app.Sequelize; + const rows = await orderModel.findAll({ + where: { + id: { [Op.in]: orderIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'has_sn_item' ], + raw: true, + }); + + const snOrderIdSet = new Set((Array.isArray(rows) ? rows : []) + .filter(row => String(row && row.has_sn_item || '').trim().toUpperCase() === 'Y') + .map(row => Number(row && row.id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0)); + + if (snOrderIdSet.size === 0) { + return { orderIds, skippedSnOrderIds: [] }; + } + + const skippedSnOrderIds = orderIds.filter(orderId => snOrderIdSet.has(orderId)); + const keptOrderIds = orderIds.filter(orderId => !snOrderIdSet.has(orderId)); + + logger.info('[auto_sync_back] 静默跳过SN订单', { + warehouseId, + source, + skippedSnOrderIds, + keptOrderIds, + }); + + return { orderIds: keptOrderIds, skippedSnOrderIds }; + } catch (error) { + logger.warn('[auto_sync_back] SN订单过滤失败,按原订单集合继续', { + warehouseId, + source, + orderCount: orderIds.length, + error: error && error.message ? error.message : `${error}`, + }); + return { orderIds, skippedSnOrderIds: [] }; + } + } + /** * 同步待处理订单(异步模式)。 * @@ -2189,7 +2270,7 @@ class PendingOrderService extends OrderBaseService { } const skipReasonMap = { not_found: '订单不存在', already_synced: '已同步' }; - const failReasonMap = { express_unallocated: '快递未分配', sn_batch_forbidden: 'SN订单不支持批量' }; + const failReasonMap = { express_unallocated: '快递未分配', sn_batch_forbidden: 'SN明细未齐套或未复核' }; const dispatchChannels = (resultData.dispatch_results || []) .map(r => r.create_channel).filter(Boolean).join('/') || 'unknown'; @@ -3793,6 +3874,7 @@ class PendingOrderService extends OrderBaseService { 'country_code', 'province', 'city', 'area', 'town', 'detail_address', 'id_type', 'id_number', 'oaid', 'extend_props', 'items', 'items_count', 'items_total', 'items_weight', 'items_hash', 'items_crc', + 'has_sn_item', ]; const newOrderData = { ...RESET_FIELDS }; @@ -6910,11 +6992,19 @@ class PendingOrderService extends OrderBaseService { && contractConfig.policy_config && contractConfig.policy_config.auto_sync_back === 1 ) { - this.syncOrderIds({ orderIds: [ orderId ] }).catch(err => { - this.ctx.logger.error( - `[auto_sync_back] manualWaybill 自动同步失败: ${err.message}` - ); + // SN 订单自动回传会被拦截并置异常,自动触发场景静默跳过 + const autoSyncFilter = await this.filterAutoSyncSnOrderIds({ + orderIds: [ orderId ], + warehouseId: Number(order.warehouse_id) || warehouseId, + source: 'manualWaybill', }); + if (autoSyncFilter.orderIds.length > 0) { + this.syncOrderIds({ orderIds: autoSyncFilter.orderIds }).catch(err => { + this.ctx.logger.error( + `[auto_sync_back] manualWaybill 自动同步失败: ${err.message}` + ); + }); + } } } } catch (err) { diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index 109cd60..cdfd851 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -866,6 +866,10 @@ class RecheckOrderService extends OrderBaseService { images: Array.isArray(item.images) ? [ ...item.images ] : [], has_shared_barcode: Boolean(item.has_shared_barcode), need_recheck: String(item.need_recheck || 'Y').trim(), + need_sn: String(item.need_sn || 'N').trim().toUpperCase() === 'Y' ? 'Y' : 'N', + sn_code_rules: Array.isArray(item.sn_code_rules) + ? item.sn_code_rules.map(rule => ({ ...rule })) + : [], plan_qty: Number(item.plan_qty || 0), store_id: item.store_id != null ? Number(item.store_id) : 0, owner_code: String(item.owner_code || '').trim(), @@ -1418,6 +1422,35 @@ class RecheckOrderService extends OrderBaseService { } } + // 3.1 批量查询序列号管理商品(is_sn_mgmt='Y')与其 SN 码规则,用于标记商品行是否需要采集 SN 码 + // 并下发 sn_code_rules 供前端扫码校验/加工 + const snStockIdSet = new Set(); + const snCodeRulesMap = new Map(); + if (stockIds.length > 0 && this.ctx && this.ctx.model && this.ctx.model.StockWarehouse) { + const snRows = await this.ctx.model.StockWarehouse.findAll({ + where: { + id: { [this.app.Sequelize.Op.in]: stockIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'is_sn_mgmt', 'sn_code_rules' ], + raw: true, + paranoid: false, + }); + for (const snRow of (Array.isArray(snRows) ? snRows : [])) { + const sid = Number(snRow && snRow.id || 0); + if (sid <= 0) { + continue; + } + if (String(snRow.is_sn_mgmt || '').trim().toUpperCase() === 'Y') { + snStockIdSet.add(sid); + } + const rules = this.ctx.service.systems.snCodeRule.toRuleList(snRow.sn_code_rules); + if (rules.length > 0) { + snCodeRulesMap.set(sid, rules); + } + } + } + // 4. 批量查询货主备注名(wms_store_warehouse.store_remask),按 store_id 映射 const storeRemarkMapByStock = new Map(); if (stockMap.size > 0 && this.ctx.model && this.ctx.model.StoreWarehouse) { @@ -1547,6 +1580,8 @@ class RecheckOrderService extends OrderBaseService { images, has_shared_barcode: hasSharedBarcode, need_recheck: String(stockInfo.need_recheck || 'Y').trim(), + need_sn: snStockIdSet.has(sid) ? 'Y' : 'N', + sn_code_rules: snCodeRulesMap.get(sid) || [], plan_qty: Number(item.plan_qty || 0), store_id: stockInfo.store_id != null ? Number(stockInfo.store_id) : 0, owner_code: String(item.owner_code || '').trim(), @@ -1702,21 +1737,50 @@ class RecheckOrderService extends OrderBaseService { const waybillNo = String(expresses?.[0]?.waybill_code || '').trim(); const now = new Date(); + const operator = this.getOrderLogOperator(); const updateValues = { recheck_status: 'fin', recheck_time: now, updated_at: now, }; - const updateResult = await orderModel.update(updateValues, { - where: orderWhere, - }); - const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0); - if (affectedRows <= 0) { - throw new Error('未找到对应订单'); + // SN(序列号管理)订单必须随复核提交 SN 码:SN 落库与复核状态更新同事务,任一失败整体回滚 + const needSnVerify = this.isSnOrderRow(order) || this.hasRecheckSnPayload(requestData); + const transaction = needSnVerify ? await ctx.model.transaction() : null; + let snSummary = { sn_count: 0, sn_item_count: 0, sn_created_count: 0, sn_reused_count: 0 }; + + try { + if (transaction) { + snSummary = await this.verifyRecheckSnForOrder({ + order, + warehouseId, + requestData, + operator, + now, + transaction, + }); + } + + const updateResult = await orderModel.update(updateValues, { + where: orderWhere, + ...(transaction ? { transaction } : {}), + }); + const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0); + + if (affectedRows <= 0) { + throw new Error('未找到对应订单'); + } + + if (transaction) { + await transaction.commit(); + } + } catch (error) { + if (transaction) { + await transaction.rollback(); + } + throw error; } - const operator = this.getOrderLogOperator(); const reviewNo = this.buildRecheckReviewNo(orderId, now); const orderNo = String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(); const operatorNo = String(operator.id || '').trim(); @@ -1797,15 +1861,180 @@ class RecheckOrderService extends OrderBaseService { // 通知仓库面板刷新(大屏增量更新,失败不影响主流程) await this.service.systems.warehousePanel.touchLastChangeAt(Number(warehouseId)); + // SN 订单此前被自动回传链路跳过(未复核 + SN 未齐套),复核通过后 SN 明细已齐套, + // 按货主-仓库签约策略 auto_sync_back 异步回传一次,失败不影响复核结果 + await this._tryAutoSyncBackAfterRecheck({ order, warehouseId, source: 'confirmRecheck' }); + return { order_id: orderId, waybill_no: waybillNo, recheck_status: 'fin', recheck_time: now, review_no: reviewNo, + has_sn_item: this.isSnOrderRow(order) ? 'Y' : 'N', + sn_count: snSummary.sn_count || 0, + sn_item_count: snSummary.sn_item_count || 0, }; } + /** + * 判断订单是否为 SN(序列号管理)订单。 + * @param {Object} order 订单主表行。 + * @return {boolean} 是否 SN 订单。 + */ + isSnOrderRow(order = {}) { + return String((order && order.has_sn_item) || '').trim().toUpperCase() === 'Y'; + } + + /** + * 复核通过后对 SN 订单异步触发一次回传。 + * + * SN 订单在运单分配阶段被 auto_sync_back 前置过滤跳过(此时未复核、SN 明细未写入), + * 复核通过后 SN 明细已齐套,需要补一次回传。仅处理 SN 订单,且受货主-仓库签约策略 + * policy_config.auto_sync_back 控制;任何异常只写日志,不影响复核结果。 + * + * @param {Object} params 参数。 + * @param {Object} params.order 订单主表行(需含 id / store_id / has_sn_item / sync_status)。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {string} [params.source] 触发来源(仅用于日志定位)。 + * @return {Promise} 无返回值。 + */ + async _tryAutoSyncBackAfterRecheck({ order = {}, warehouseId, source = 'confirmRecheck' }) { + const { ctx } = this; + + try { + if (!this.isSnOrderRow(order)) { + return; + } + + const orderId = Number(order.id); + if (!Number.isInteger(orderId) || orderId <= 0) { + return; + } + + if (String(order.sync_status || '').trim() === 'fin') { + return; + } + + const storeId = Number(order.store_id) || 0; + if (storeId <= 0) { + ctx.logger.warn('[auto_sync_back] SN订单缺少货主 store_id,跳过复核后自动回传', { + warehouseId, + orderId, + source, + }); + return; + } + + const contractWarehouseId = Number(order.warehouse_id) || Number(warehouseId); + + const storeWarehouseService = this.service.systems && this.service.systems.storeWarehouse; + if (!storeWarehouseService || typeof storeWarehouseService.getContractConfig !== 'function') { + ctx.logger.warn('[auto_sync_back] 签约策略服务不可用,跳过复核后自动回传', { + warehouseId, + orderId, + source, + }); + return; + } + + const contractConfig = await storeWarehouseService.getContractConfig(contractWarehouseId, storeId); + const policyConfig = contractConfig && contractConfig.policy_config ? contractConfig.policy_config : {}; + if (policyConfig.auto_sync_back !== 1) { + ctx.logger.info('[auto_sync_back] 未开启自动同步回传,跳过复核后自动回传', { + warehouseId: contractWarehouseId, + orderId, + storeId, + source, + }); + return; + } + + const pendingOrderService = ctx.service + && ctx.service.systemMethods + && ctx.service.systemMethods.order + && ctx.service.systemMethods.order.pendingOrder; + if (!pendingOrderService || typeof pendingOrderService.syncOrderIds !== 'function') { + ctx.logger.warn('[auto_sync_back] 待处理订单服务不可用,跳过复核后自动回传', { + warehouseId: contractWarehouseId, + orderId, + source, + }); + return; + } + + ctx.logger.info('[auto_sync_back] 复核完成,触发SN订单自动回传', { + warehouseId: contractWarehouseId, + orderId, + storeId, + source, + }); + + pendingOrderService.syncOrderIds({ + orderIds: [ orderId ], + warehouse_id: contractWarehouseId, + }).catch(err => { + ctx.logger.error( + `[auto_sync_back] ${source} 复核后自动回传失败: ${err && err.message ? err.message : err}` + ); + }); + } catch (error) { + ctx.logger.error( + `[auto_sync_back] ${source} 复核后自动回传异常: ${error && error.message ? error.message : error}` + ); + } + } + + /** + * 判断复核入参是否提交了 SN 码内容(唯一格式:sn_map = { stock_id: [sn_code] })。 + * @param {Object} payload 复核请求体。 + * @return {boolean} 是否提交了 SN 码。 + */ + hasRecheckSnPayload(payload = {}) { + const requestData = this.isPlainObject(payload) ? payload : {}; + const snMap = requestData.sn_map ?? requestData.snMap; + if (!this.isPlainObject(snMap)) { + return false; + } + + return Object.values(snMap).some(value => { + if (Array.isArray(value)) { + return value.some(code => String(code === undefined || code === null ? '' : code).trim() !== ''); + } + return String(value === undefined || value === null ? '' : value).trim() !== ''; + }); + } + + /** + * 复核提交时校验并写入 SN 码,具体规则由 systems.orderItemSn 承担。 + * @param {Object} params 参数。 + * @param {Object} params.order 订单主表行。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {Object} params.requestData 复核请求体。 + * @param {Object} params.operator 操作人。 + * @param {Date} params.now 复核时间。 + * @param {Object} params.transaction Sequelize 事务。 + * @return {Promise} SN 提交汇总。 + */ + async verifyRecheckSnForOrder({ order, warehouseId, requestData, operator, now, transaction }) { + const snService = this.service && this.service.systems + ? (this.service.systems.orderItemSn || this.service.systems.order_item_sn) + : null; + + if (!snService || typeof snService.verifyRecheckSnList !== 'function') { + throw new Error('SN码校验服务不可用,无法提交复核'); + } + + return await snService.verifyRecheckSnList({ + order, + warehouseId, + payload: requestData, + operator, + now, + transaction, + }); + } + /** * 团购波次批量复核:将波次下所有非拦截订单标记为已复核,并更新波次批次状态为复核完成。 * @param {number} waveId 波次ID。 @@ -1862,6 +2091,7 @@ class RecheckOrderService extends OrderBaseService { 'intercept_status', 'pick_status', 'recheck_status', + 'has_sn_item', ], raw: true, }); @@ -1898,6 +2128,11 @@ class RecheckOrderService extends OrderBaseService { this.assertOrderCanRecheck(order); } + // SN 订单必须逐单提交 SN 码,团购波次批量复核没有 SN 采集入口,直接拒绝 + if (normalOrders.some(order => this.isSnOrderRow(order))) { + throw new Error('SN订单不支持团购波次复核,请使用单订单复核并提交SN码'); + } + const now = new Date(); const normalOrderIds = normalOrders .map(o => Number(o.id)) @@ -3608,6 +3843,7 @@ class RecheckOrderService extends OrderBaseService { o.status, o.create_at, o.recheck_time, + o.has_sn_item, wi.wave_index, (SELECT oe.waybill_code FROM wms_order_express oe WHERE oe.order_id = o.id AND oe.warehouse_id = o.warehouse_id AND oe.delete_at IS NULL LIMIT 1) AS waybill_code FROM ${orderTableName} o${waveIndexJoin} @@ -3658,6 +3894,7 @@ class RecheckOrderService extends OrderBaseService { status: Number(row?.status || 0), create_at: row?.create_at || null, recheck_time: row?.recheck_time || null, + has_sn_item: String(row?.has_sn_item || '').trim().toUpperCase() === 'Y' ? 'Y' : 'N', })); return this.success('ok', { @@ -4157,7 +4394,7 @@ class RecheckOrderService extends OrderBaseService { attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code', 'storage_status', 'post_status', 'sync_status', 'status', 'intercept_status', - 'pick_status', 'recheck_status', 'wave_id', 'wave_no', + 'pick_status', 'recheck_status', 'wave_id', 'wave_no', 'has_sn_item', ], raw: true, }); @@ -4335,7 +4572,7 @@ class RecheckOrderService extends OrderBaseService { attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code', 'storage_status', 'post_status', 'sync_status', 'status', 'intercept_status', - 'pick_status', 'recheck_status', 'wave_id', 'wave_no', + 'pick_status', 'recheck_status', 'wave_id', 'wave_no', 'has_sn_item', ], raw: true, }); @@ -4756,6 +4993,11 @@ class RecheckOrderService extends OrderBaseService { // 校验订单是否允许复核(拣货已完成且未被拦截) this.assertOrderCanRecheck(order); + // SN 订单必须逐单提交 SN 码,快捷复核没有 SN 采集入口,直接拒绝避免绕过 SN 校验 + if (this.isSnOrderRow(order)) { + throw new Error('SN订单需在单订单复核中提交SN码,不支持快捷复核'); + } + const now = new Date(); // 更新订单复核状态 diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index 94d6f5c..cfdf9bc 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -972,13 +972,43 @@ class WaveService extends OrderBaseService { }; } + /** + * 构建「排除 SN(序列号管理)订单」筛选条件。 + * + * has_sn_item='Y' 为序列号订单;NULL 视为非 SN(兼容未回填的存量行)。 + * + * @return {Object} Sequelize 条件。 + */ + buildExcludeSnOrderCondition() { + return { + [Op.or]: [ + { has_sn_item: { [Op.is]: null } }, + { has_sn_item: { [Op.ne]: 'Y' } }, + ], + }; + } + + /** + * 过滤候选订单中的 SN(序列号管理)订单。 + * + * @param {Array} rows 候选订单行(需含 has_sn_item)。 + * @return {Array} 非 SN 订单行。 + */ + filterNonSnCandidateRows(rows = []) { + return (Array.isArray(rows) ? rows : []) + .filter(row => String(row && row.has_sn_item || '').trim().toUpperCase() !== 'Y'); + } + /** * 构建抓取候选订单筛选条件。 * * @param {Object} structure 结构化请求。 + * @param {Object} [options={}] 附加选项。 + * @param {boolean} [options.excludeSnOrders=false] 是否排除 SN(序列号管理)订单。 * @return {Object} Sequelize where 条件。 */ - buildFetchWhere(structure = {}) { + buildFetchWhere(structure = {}, options = {}) { + const normalizedOptions = this.isPlainObject(options) ? options : {}; const where = { step: { [Op.in]: [ 1, 2, 3 ] }, status: { [Op.ne]: 'cancel' }, @@ -990,6 +1020,10 @@ class WaveService extends OrderBaseService { is_b2b: { [Op.or]: [{ [Op.is]: null }, 'N' ] }, }; + if (normalizedOptions.excludeSnOrders === true) { + where[Op.and] = [ this.buildExcludeSnOrderCondition() ]; + } + const itemPartType = String(structure.item_part_type || '').trim(); const itemPart = String(structure.item_part || '').trim(); if (itemPartType === 'items_hash') { @@ -1018,6 +1052,7 @@ class WaveService extends OrderBaseService { * @param {number} [minGroupOrderFetchQuantity=13] 最小团购抓取数量。 * @param {Object} [options={}] 额外抓取选项。 * @param {number} [options.maxFetchQuantity=0] 本结构最大抓取订单数上限,0 表示不限制。 + * @param {boolean} [options.excludeSnOrders=false] 是否排除 SN(序列号管理)订单(团购抓取固定 true)。 * @param {number|string} [options.source=0] 波次来源:0-普通波次 1-管理后台策略任务 2-PDA策略任务。 * @return {Promise} 单结构抓取结果。 */ @@ -1030,9 +1065,9 @@ class WaveService extends OrderBaseService { options = {} ) { const { ctx } = this; - const where = this.buildFetchWhere(structure); - const requestedQuantity = Number(structure.quantity || 0); const normalizedOptions = this.isPlainObject(options) ? options : {}; + const where = this.buildFetchWhere(structure, normalizedOptions); + const requestedQuantity = Number(structure.quantity || 0); const normalizedMaxFetchQuantity = Number.isInteger(Number(normalizedOptions.maxFetchQuantity)) && Number(normalizedOptions.maxFetchQuantity) > 0 ? Number(normalizedOptions.maxFetchQuantity) @@ -1395,6 +1430,38 @@ class WaveService extends OrderBaseService { return [ ...new Set(statusList) ]; } + /** + * 规范化波次策略类型筛选值,兼容单值与数组写法(1 散单 / 2 团购 / 3 SN)。 + * + * 数组中的空值(undefined/null/空字符串)会被忽略,重复值去重; + * 任一元组不合法时抛出统一错误提示。 + * + * @param {number|string|Array} value 策略类型筛选值。 + * @return {Array} 规范化后的策略类型数组,未传时返回空数组。 + */ + normalizeWaveStrategyTypeList(value) { + if (value === undefined || value === null) { + return []; + } + + const sourceList = Array.isArray(value) ? value : [ value ]; + const typeList = []; + sourceList.forEach(item => { + if (item === undefined || item === null || `${item}`.trim() === '') { + return; + } + + const normalized = Number(item); + if (!Number.isInteger(normalized) || ![ 1, 2, 3 ].includes(normalized)) { + throw new Error('strategy_type 仅支持 1(散单)、2(团购) 或 3(SN),数组写法如 [1, 3]'); + } + + typeList.push(normalized); + }); + + return [ ...new Set(typeList) ]; + } + /** * 规范化波次列表库位分配状态筛选值。 * @@ -2917,6 +2984,8 @@ class WaveService extends OrderBaseService { wave_id: 0, // 波次抓取不抓取 B2B 订单(NULL 视为非 B2B,兼容存量行) is_b2b: { [Op.or]: [{ [Op.is]: null }, 'N' ] }, + // 团购抓取排除 SN(序列号管理)订单 + [Op.and]: [ this.buildExcludeSnOrderCondition() ], }; if (storeId > 0) { @@ -3173,6 +3242,8 @@ class WaveService extends OrderBaseService { wave_id: 0, // 波次抓取不抓取 B2B 订单(NULL 视为非 B2B,兼容存量行) is_b2b: { [Op.or]: [{ [Op.is]: null }, 'N' ] }, + // 散单抓取同样排除 SN(序列号管理)订单 + [Op.and]: [ this.buildExcludeSnOrderCondition() ], }; if (storeId > 0) { @@ -3439,6 +3510,8 @@ class WaveService extends OrderBaseService { wave_id: 0, // 波次抓取不抓取 B2B 订单(NULL 视为非 B2B,兼容存量行) is_b2b: { [Op.or]: [{ [Op.is]: null }, 'N' ] }, + // 团购抓取排除 SN(序列号管理)订单 + [Op.and]: [ this.buildExcludeSnOrderCondition() ], }; if (storeId > 0) { @@ -3531,18 +3604,14 @@ class WaveService extends OrderBaseService { * * @param {Object} [data={}] 请求参数。 * @param {Object} [data.pagination] 分页参数。 + * @param {number|string|Array} [data.strategy_type] 策略类型过滤,支持单值与数组:1 散单 / 2 团购 / 3 SN。 + * @param {Object} [data.where] 过滤条件,支持 where.strategy_type(单值或数组)。 * @return {Promise} 波次策略列表及分页信息。 */ async waveStrategyList(data = {}) { const requestData = this.isPlainObject(data) ? data : {}; const rawType = requestData.strategy_type ?? requestData?.where?.strategy_type; - let normalizedStrategyType; - if (rawType !== undefined && rawType !== null && `${rawType}` !== '') { - normalizedStrategyType = Number(rawType); - if (![ 1, 2 ].includes(normalizedStrategyType)) { - throw new Error('strategy_type 仅支持 1(散单) 或 2(团购)'); - } - } + const strategyTypeList = this.normalizeWaveStrategyTypeList(rawType); const calculateNextFetchOrderCount = Number( requestData.calculate_next_fetch_order_count ?? requestData.calculateNextFetchOrderCount ?? 0 ) === 1; @@ -3562,8 +3631,10 @@ class WaveService extends OrderBaseService { const where = { warehouse_id: contextWarehouseId, }; - if (normalizedStrategyType !== undefined) { - where.strategy_type = normalizedStrategyType; + if (strategyTypeList.length === 1) { + where.strategy_type = strategyTypeList[0]; + } else if (strategyTypeList.length > 1) { + where.strategy_type = { [Op.in]: strategyTypeList }; } const queryResult = await strategyModel.findAndCountAll({ @@ -3578,16 +3649,43 @@ class WaveService extends OrderBaseService { }); const list = Array.isArray(queryResult && queryResult.rows) ? queryResult.rows : []; - const matchedOrderCountMap = await this.getWaveStrategyMatchedOrderCountFilteredMap( - contextWarehouseId, - list - ); - const nextFetchOrderCountMap = calculateNextFetchOrderCount - ? await this.getWaveStrategyNextFetchOrderCountMap(contextWarehouseId, list) - : new Map(); - const debugFetchOrderListMap = debugEnabled - ? await this.getWaveStrategyDebugFetchOrderListMap(contextWarehouseId, list) - : new Map(); + // 统计失败(如目标库尚未执行 has_sn_item 迁移)时降级为 0,避免整张策略列表返回失败 + let matchedOrderCountMap = new Map(); + try { + matchedOrderCountMap = await this.getWaveStrategyMatchedOrderCountFilteredMap( + contextWarehouseId, + list + ); + } catch (error) { + this.ctx.logger.warn('[wave.waveStrategyList] 统计策略命中订单数失败,降级为 0', { + warehouse_id: contextWarehouseId, + error: error && error.message ? error.message : `${error}`, + }); + } + + let nextFetchOrderCountMap = new Map(); + if (calculateNextFetchOrderCount) { + try { + nextFetchOrderCountMap = await this.getWaveStrategyNextFetchOrderCountMap(contextWarehouseId, list); + } catch (error) { + this.ctx.logger.warn('[wave.waveStrategyList] 预演下一抓取订单数失败,降级为 0', { + warehouse_id: contextWarehouseId, + error: error && error.message ? error.message : `${error}`, + }); + } + } + + let debugFetchOrderListMap = new Map(); + if (debugEnabled) { + try { + debugFetchOrderListMap = await this.getWaveStrategyDebugFetchOrderListMap(contextWarehouseId, list); + } catch (error) { + this.ctx.logger.warn('[wave.waveStrategyList] 预演抓取订单清单失败,降级为空', { + warehouse_id: contextWarehouseId, + error: error && error.message ? error.message : `${error}`, + }); + } + } const mergedList = list.map(item => { const strategyId = Number(item && item.id || 0); const debugRow = debugEnabled ? (debugFetchOrderListMap.get(strategyId) || null) : null; @@ -3615,12 +3713,12 @@ class WaveService extends OrderBaseService { try { matchedOrderCountTotal = await this.getWaveStrategyMatchedOrderCountTotal( contextWarehouseId, - { strategyType: normalizedStrategyType } + { strategyType: strategyTypeList } ); } catch (error) { this.ctx.logger.warn('[wave.waveStrategyList] 统计全部命中订单总数失败,降级为 0', { warehouse_id: contextWarehouseId, - strategy_type: normalizedStrategyType, + strategy_type: strategyTypeList, error: error && error.message ? error.message : `${error}`, }); } @@ -3835,7 +3933,7 @@ class WaveService extends OrderBaseService { } const strategyType = Number(strategyRow.strategy_type || 0); - if (![ 1, 2 ].includes(strategyType)) { + if (![ 1, 2, 3 ].includes(strategyType)) { return 0; } @@ -3845,6 +3943,7 @@ class WaveService extends OrderBaseService { minSameStructure: strategyRow.min_same_structure, maxSameStructure: strategyRow.max_same_structure, requireSameExpress: Number(strategyRow.require_same_express || 0), + strategyType, }); if (candidateRows.length <= 0) { return 0; @@ -3923,12 +4022,12 @@ class WaveService extends OrderBaseService { * 1) 仅统计未在波次订单(wave_id = 0); * 2) 仅统计 step != 0 的订单; * 3) 仅统计状态有效订单(status != cancel 且 outbound_status != padding); - * 4) 同结构数量需落在策略 min_same_structure/max_same_structure 区间内; - * 当 require_same_express = 1 时按「结构(items_hash) + 快递」分组计数, - * 否则仅按结构(items_hash)分组计数。 + * 4) 散单/团购策略的同结构数量需落在 min_same_structure/max_same_structure 区间内 + * (require_same_express = 1 时按「结构 + 快递」分组计数); + * SN 策略(strategy_type=3)忽略同结构区间,仅统计 SN 订单。 * * @param {number|string} warehouseId 仓库ID。 - * @param {Array} strategyRows 当前页策略行数组(含 require_same_express)。 + * @param {Array} strategyRows 当前页策略行数组(含 require_same_express / strategy_type)。 * @return {Promise>} strategy_id 到过滤后命中订单数的映射。 */ async getWaveStrategyMatchedOrderCountFilteredMap(warehouseId, strategyRows = []) { @@ -3946,6 +4045,7 @@ class WaveService extends OrderBaseService { return [ strategyId, { id: strategyId, + strategyType: Number(item && item.strategy_type || 0), requireSameExpress: Number(item && item.require_same_express || 0) === 1, }]; }) @@ -3957,50 +4057,65 @@ class WaveService extends OrderBaseService { const orderModel = await this.getOrderModel('pendingOrder', normalizedWarehouseId); const orderTableName = this.getModelTableSqlName(orderModel); const expressExpr = alias => `COALESCE(NULLIF(TRIM(COALESCE(${alias}.sys_logistics_code, '')), ''), NULLIF(TRIM(COALESCE(${alias}.logistics_code, '')), ''), TRIM(COALESCE(${alias}.logistics_name, '')))`; + const orderPoolConditionSql = alias => ` + AND ${alias}.warehouse_id = :warehouseId + AND ${alias}.wave_id = 0 + AND ${alias}.step != 0 + AND ${alias}.post_status = 'fin' + AND ${alias}.storage_status = 'fin' + AND ${alias}.print_status != 'fin' + AND ${alias}.status != 'cancel' + AND ${alias}.outbound_status != 'padding' + AND ${alias}.intercept_status = 'none' + AND ${alias}.lock_status = 'none' + AND (${alias}.is_b2b IS NULL OR ${alias}.is_b2b = 'N')`; const matchedMap = new Map(); - const runCountQuery = async (strategyGroup, requireSameExpress) => { + const runCountQuery = async (strategyGroup, options = {}) => { const strategyIds = strategyGroup.map(item => item.id); if (strategyIds.length === 0) { return; } - const groupKeyExtra = requireSameExpress ? `, ${expressExpr('src')} AS express_key` : ''; - const joinKeyExtra = requireSameExpress ? ` AND same_structure.express_key = ${expressExpr('o')}` : ''; - const querySql = ` + const isSnStrategy = options.isSn === true; + const requireSameExpress = options.requireSameExpress === true; + const snCondition = isSnStrategy + ? "AND o.has_sn_item = 'Y'" + : "AND (o.has_sn_item IS NULL OR o.has_sn_item <> 'Y')"; + let querySql; + + if (isSnStrategy) { + // SN 策略忽略同结构区间,直接按策略命中明细统计 SN 订单 + querySql = ` SELECT m.strategy_id, COUNT(DISTINCT m.order_id) AS matched_order_count_filtered FROM wms_order_wave_strategy_match m INNER JOIN ${orderTableName} o - ON o.id = m.order_id - AND o.warehouse_id = :warehouseId - AND o.wave_id = 0 - AND o.step != 0 - AND o.post_status = 'fin' - AND o.storage_status = 'fin' - AND o.print_status != 'fin' - AND o.status != 'cancel' - AND o.outbound_status != 'padding' - AND o.intercept_status = 'none' - AND o.lock_status = 'none' - AND (o.is_b2b IS NULL OR o.is_b2b = 'N') + ON o.id = m.order_id${orderPoolConditionSql('o')} + ${snCondition} + WHERE m.warehouse_id = :warehouseId + AND m.strategy_id IN (:strategyIds) + GROUP BY m.strategy_id + `; + } else { + const groupKeyExtra = requireSameExpress ? `, ${expressExpr('src')} AS express_key` : ''; + const joinKeyExtra = requireSameExpress ? ` AND same_structure.express_key = ${expressExpr('o')}` : ''; + querySql = ` + SELECT + m.strategy_id, + COUNT(DISTINCT m.order_id) AS matched_order_count_filtered + FROM wms_order_wave_strategy_match m + INNER JOIN ${orderTableName} o + ON o.id = m.order_id${orderPoolConditionSql('o')} + ${snCondition} INNER JOIN ( SELECT src.items_hash AS structure_key${groupKeyExtra}, COUNT(1) AS same_structure_count FROM ${orderTableName} src - WHERE src.warehouse_id = :warehouseId - AND src.wave_id = 0 - AND src.step != 0 - AND src.post_status = 'fin' - AND src.storage_status = 'fin' - AND src.print_status != 'fin' - AND src.status != 'cancel' - AND src.outbound_status != 'padding' - AND src.intercept_status = 'none' - AND src.lock_status = 'none' - AND (src.is_b2b IS NULL OR src.is_b2b = 'N') + WHERE 1 = 1${orderPoolConditionSql('src')} + AND (src.has_sn_item IS NULL OR src.has_sn_item <> 'Y') GROUP BY src.items_hash${requireSameExpress ? `, ${expressExpr('src')}` : ''} ) same_structure ON same_structure.structure_key = o.items_hash${joinKeyExtra} @@ -4013,6 +4128,7 @@ class WaveService extends OrderBaseService { AND (s.max_same_structure IS NULL OR s.max_same_structure <= 0 OR same_structure.same_structure_count <= s.max_same_structure) GROUP BY m.strategy_id `; + } const queryRows = await this.ctx.model.query(querySql, { replacements: { @@ -4033,9 +4149,13 @@ class WaveService extends OrderBaseService { }); }; + const snStrategies = normalizedStrategies.filter(item => item.strategyType === 3); + const nonSnStrategies = normalizedStrategies.filter(item => item.strategyType !== 3); + await Promise.all([ - runCountQuery(normalizedStrategies.filter(item => item.requireSameExpress), true), - runCountQuery(normalizedStrategies.filter(item => !item.requireSameExpress), false), + runCountQuery(snStrategies, { isSn: true }), + runCountQuery(nonSnStrategies.filter(item => item.requireSameExpress), { requireSameExpress: true }), + runCountQuery(nonSnStrategies.filter(item => !item.requireSameExpress), { requireSameExpress: false }), ]); return matchedMap; @@ -4044,14 +4164,14 @@ class WaveService extends OrderBaseService { /** * 统计仓库内全部策略命中的去重订单总数。 * - * 口径与 getWaveStrategyMatchedOrderCountFilteredMap 完全一致(订单池过滤、同结构 - * 数量区间、require_same_express 分组方式),但不再按策略分组统计,而是汇总 - * 查询条件下(仓库 + 可选策略类型)全部策略命中的订单并去重: + * 口径与 getWaveStrategyMatchedOrderCountFilteredMap 完全一致(订单池过滤、 + * 散单/团购的同结构数量区间、require_same_express 分组方式;SN 策略忽略同结构区间), + * 但不再按策略分组统计,而是汇总查询条件下(仓库 + 可选策略类型)全部策略命中的订单并去重: * 同一订单命中多个策略仅计一次。 * * @param {number|string} warehouseId 仓库ID。 * @param {Object} [options={}] 统计选项。 - * @param {number|string|null} [options.strategyType=null] 策略类型过滤(1 散单 / 2 团购),为 null 时不限制。 + * @param {number|string|Array|null} [options.strategyType=null] 策略类型过滤(1 散单 / 2 团购 / 3 SN),支持数组;为空数组或 null 时不限制。 * @return {Promise} 全部策略命中的去重订单总数。 */ async getWaveStrategyMatchedOrderCountTotal(warehouseId, options = {}) { @@ -4061,14 +4181,41 @@ class WaveService extends OrderBaseService { } const normalizedOptions = this.isPlainObject(options) ? options : {}; - const strategyTypeRaw = Number(normalizedOptions.strategyType); - const strategyType = Number.isInteger(strategyTypeRaw) && [ 1, 2 ].includes(strategyTypeRaw) - ? strategyTypeRaw - : null; + const strategyTypes = this.normalizeWaveStrategyTypeList(normalizedOptions.strategyType); + const strategyTypeFilterSql = strategyTypes.length > 0 + ? `AND s.strategy_type IN (${strategyTypes.join(', ')})` + : ''; const orderModel = await this.getOrderModel('pendingOrder', normalizedWarehouseId); const orderTableName = this.getModelTableSqlName(orderModel); const expressExpr = alias => `COALESCE(NULLIF(TRIM(COALESCE(${alias}.sys_logistics_code, '')), ''), NULLIF(TRIM(COALESCE(${alias}.logistics_code, '')), ''), TRIM(COALESCE(${alias}.logistics_name, '')))`; + const orderPoolConditionSql = alias => ` + AND ${alias}.warehouse_id = :warehouseId + AND ${alias}.wave_id = 0 + AND ${alias}.step != 0 + AND ${alias}.post_status = 'fin' + AND ${alias}.storage_status = 'fin' + AND ${alias}.print_status != 'fin' + AND ${alias}.status != 'cancel' + AND ${alias}.outbound_status != 'padding' + AND ${alias}.intercept_status = 'none' + AND ${alias}.lock_status = 'none' + AND (${alias}.is_b2b IS NULL OR ${alias}.is_b2b = 'N')`; + + // SN 策略命中明细:忽略同结构区间,仅统计 SN 订单 + const buildSnMatchedOrderIdSql = () => ` + SELECT m.order_id AS order_id + FROM wms_order_wave_strategy_match m + INNER JOIN ${orderTableName} o + ON o.id = m.order_id${orderPoolConditionSql('o')} + AND o.has_sn_item = 'Y' + INNER JOIN wms_wave_strategy s + ON s.id = m.strategy_id + AND s.warehouse_id = :warehouseId + AND s.strategy_type = 3 + ${strategyTypeFilterSql} + WHERE m.warehouse_id = :warehouseId + `; const buildMatchedOrderIdSql = requireSameExpress => { const groupKeyExtra = requireSameExpress ? `, ${expressExpr('src')} AS express_key` : ''; @@ -4077,34 +4224,15 @@ class WaveService extends OrderBaseService { SELECT m.order_id AS order_id FROM wms_order_wave_strategy_match m INNER JOIN ${orderTableName} o - ON o.id = m.order_id - AND o.warehouse_id = :warehouseId - AND o.wave_id = 0 - AND o.step != 0 - AND o.post_status = 'fin' - AND o.storage_status = 'fin' - AND o.print_status != 'fin' - AND o.status != 'cancel' - AND o.outbound_status != 'padding' - AND o.intercept_status = 'none' - AND o.lock_status = 'none' - AND (o.is_b2b IS NULL OR o.is_b2b = 'N') + ON o.id = m.order_id${orderPoolConditionSql('o')} + AND (o.has_sn_item IS NULL OR o.has_sn_item <> 'Y') INNER JOIN ( SELECT src.items_hash AS structure_key${groupKeyExtra}, COUNT(1) AS same_structure_count FROM ${orderTableName} src - WHERE src.warehouse_id = :warehouseId - AND src.wave_id = 0 - AND src.step != 0 - AND src.post_status = 'fin' - AND src.storage_status = 'fin' - AND src.print_status != 'fin' - AND src.status != 'cancel' - AND src.outbound_status != 'padding' - AND src.intercept_status = 'none' - AND src.lock_status = 'none' - AND (src.is_b2b IS NULL OR src.is_b2b = 'N') + WHERE 1 = 1${orderPoolConditionSql('src')} + AND (src.has_sn_item IS NULL OR src.has_sn_item <> 'Y') GROUP BY src.items_hash${requireSameExpress ? `, ${expressExpr('src')}` : ''} ) same_structure ON same_structure.structure_key = o.items_hash${joinKeyExtra} @@ -4112,7 +4240,8 @@ class WaveService extends OrderBaseService { ON s.id = m.strategy_id AND s.warehouse_id = :warehouseId AND COALESCE(s.require_same_express, 0) = ${requireSameExpress ? 1 : 0} - AND (:strategyType IS NULL OR s.strategy_type = :strategyType) + AND s.strategy_type <> 3 + ${strategyTypeFilterSql} WHERE m.warehouse_id = :warehouseId AND same_structure.same_structure_count >= COALESCE(NULLIF(s.min_same_structure, 0), 0) AND (s.max_same_structure IS NULL OR s.max_same_structure <= 0 OR same_structure.same_structure_count <= s.max_same_structure) @@ -4122,6 +4251,8 @@ class WaveService extends OrderBaseService { const countRows = await this.ctx.model.query(` SELECT COUNT(DISTINCT matched.order_id) AS order_count FROM ( + ${buildSnMatchedOrderIdSql()} + UNION ALL ${buildMatchedOrderIdSql(true)} UNION ALL ${buildMatchedOrderIdSql(false)} @@ -4129,7 +4260,6 @@ class WaveService extends OrderBaseService { `, { replacements: { warehouseId: normalizedWarehouseId, - strategyType, }, type: this.ctx.model.QueryTypes.SELECT, }); @@ -4447,7 +4577,13 @@ class WaveService extends OrderBaseService { payload.wave_prefix = wavePrefix || null; } payload.strategy_type = this.normalizeRequiredPositiveInteger(requestData.strategy_type, 'strategy_type'); - if (Object.prototype.hasOwnProperty.call(requestData, 'batch_mode')) { + if (![ 1, 2, 3 ].includes(payload.strategy_type)) { + throw new Error('strategy_type 仅支持 1(散单)、2(团购) 或 3(SN)'); + } + if (payload.strategy_type === 3) { + // SN 策略固定批次模式:先拣后分(batch_mode=2) + payload.batch_mode = 2; + } else if (Object.prototype.hasOwnProperty.call(requestData, 'batch_mode')) { payload.batch_mode = this.normalizePositiveInteger(requestData.batch_mode, 'batch_mode'); } else if (payload.strategy_type === 2) { payload.batch_mode = 0; @@ -4468,8 +4604,14 @@ class WaveService extends OrderBaseService { } if (Object.prototype.hasOwnProperty.call(requestData, 'strategy_type')) { payload.strategy_type = this.normalizeRequiredPositiveInteger(requestData.strategy_type, 'strategy_type'); + if (![ 1, 2, 3 ].includes(payload.strategy_type)) { + throw new Error('strategy_type 仅支持 1(散单)、2(团购) 或 3(SN)'); + } } - if (Object.prototype.hasOwnProperty.call(requestData, 'batch_mode')) { + if (payload.strategy_type === 3) { + // SN 策略固定批次模式:先拣后分(batch_mode=2) + payload.batch_mode = 2; + } else if (Object.prototype.hasOwnProperty.call(requestData, 'batch_mode')) { payload.batch_mode = this.normalizePositiveInteger(requestData.batch_mode, 'batch_mode'); } else if (payload.strategy_type === 2) { payload.batch_mode = 0; @@ -4506,6 +4648,10 @@ class WaveService extends OrderBaseService { if (resolvedStrategyType === 2) { payload.batch_max_orders = 0; } + if (resolvedStrategyType === 3) { + // SN 策略固定批次模式:先拣后分(batch_mode=2) + payload.batch_mode = 2; + } const resolvedBatchMode = Object.prototype.hasOwnProperty.call(payload, 'batch_mode') ? payload.batch_mode : Object.prototype.hasOwnProperty.call(requestData, 'batch_mode') @@ -4632,7 +4778,7 @@ class WaveService extends OrderBaseService { * * @param {Object} params 解析参数。 * @param {number|string} params.warehouseId 仓库ID。 - * @param {number|string} params.strategyType 策略类型(1-散单,2-团购)。 + * @param {number|string} params.strategyType 策略类型(1-散单,2-团购,3-SN)。 * @param {Object} [params.strategyRow={}] 策略行。 * @return {Promise<{ wavePrefix: string, source: string }>} 前缀及来源。 */ @@ -7278,6 +7424,7 @@ class WaveService extends OrderBaseService { 'province', 'sys_platform_code', 'source_platform_code', + 'has_sn_item', ], where: this.buildWaveStrategyQuickScanOrderWhere(warehouseId, strategyVersion, orderIds, forceRescan), raw: true, @@ -7820,6 +7967,7 @@ class WaveService extends OrderBaseService { const strategyId = Number(normalizedRow.strategy_id || normalizedRow.strategyId || normalizedRow.id || 0); return { strategy_id: Number.isInteger(strategyId) && strategyId > 0 ? strategyId : null, + strategy_type: Number(normalizedRow.strategy_type || 0) || 0, order_min_sku: this.normalizeWaveStrategyQuickScanNumberOrNull(normalizedRow.order_min_sku), order_max_sku: this.normalizeWaveStrategyQuickScanNumberOrNull(normalizedRow.order_max_sku), order_min_qty: this.normalizeWaveStrategyQuickScanNumberOrNull(normalizedRow.order_min_qty), @@ -8058,6 +8206,13 @@ class WaveService extends OrderBaseService { return false; } + // 策略类型与订单 SN 属性互斥:SN 策略(3)只命中 SN 订单;散单/团购策略(1/2)不命中 SN 订单 + const strategyType = Number(normalizedStrategy.strategy_type || 0); + const isSnOrder = String(normalizedOrder.has_sn_item || '').trim().toUpperCase() === 'Y'; + if (strategyType === 3 ? !isSnOrder : isSnOrder) { + return false; + } + const storeId = String(normalizedOrder.store_id || '').trim().toLowerCase(); if (normalizedStrategy.allow_cross_owner === false) { @@ -8257,8 +8412,9 @@ class WaveService extends OrderBaseService { * 1. 仅处理当前仓库上下文订单; * 2. 传入 ids 中已存在波次(wave_id>0)的订单会被排除; * 3. 不区分快递,所有可抓取订单统一写入同一个新波次; - * 4. 除已在波次中的订单外,其余传入且存在的订单均可抓取; - * 5. 成功抓取后批量写入订单操作日志。 + * 4. 除已在波次中的订单外,其余传入且存在的订单均可抓取; + * 5. SN(序列号管理)订单允许按订单ID显式抓取散单(不在散单/团购策略候选中出现,但手工按订单抓取不受限); + * 6. 成功抓取后批量写订单操作日志。 * * @param {Object} data 请求参数。 * @param {Array|number|string} data.ids 订单ID集合(优先)。 @@ -8329,6 +8485,10 @@ class WaveService extends OrderBaseService { .map(row => Number(row && row.id || 0)) .filter(id => Number.isInteger(id) && id > 0)) ] .sort((a, b) => a - b); + // SN(序列号管理)订单允许按订单ID显式抓取散单:SN 策略只是「不自动出现在散单策略候选」, + // 手工按订单抓取时不受限(manual_ids 波次在拣货侧固定走先拣后分 pick_mode=3,与 SN 策略一致), + // 因此这里不再排除 SN 订单,excluded_sn_order_ids 保留在响应中但恒为空数组。 + const excludedSnOrderIds = []; const fetchableRows = normalizedOrderRows.filter(row => { const orderId = Number(row && row.id || 0); @@ -8379,6 +8539,7 @@ class WaveService extends OrderBaseService { excluded_intercepted_order_ids: excludedInterceptedOrderIds, excluded_locked_order_ids: excludedLockedOrderIds, excluded_b2b_order_ids: excludedB2bOrderIds, + excluded_sn_order_ids: excludedSnOrderIds, skipped_order_ids: skippedOrderIds, not_found_order_ids: notFoundOrderIds, }); @@ -8445,6 +8606,7 @@ class WaveService extends OrderBaseService { fetched_order_ids: [], fetched_order_count: 0, excluded_existing_wave_order_ids: excludedExistingWaveOrderIds, + excluded_sn_order_ids: excludedSnOrderIds, skipped_order_ids: skippedOrderIds, not_found_order_ids: notFoundOrderIds, }); @@ -8498,6 +8660,7 @@ class WaveService extends OrderBaseService { excluded_intercepted_order_ids: excludedInterceptedOrderIds, excluded_locked_order_ids: excludedLockedOrderIds, excluded_b2b_order_ids: excludedB2bOrderIds, + excluded_sn_order_ids: excludedSnOrderIds, skipped_order_ids: skippedOrderIds, not_found_order_ids: notFoundOrderIds, }); @@ -11313,6 +11476,8 @@ class WaveService extends OrderBaseService { normalizedFetchMode === 'single' ? 1 : minGroupOrderFetchQuantity, { maxFetchQuantity: remainingFetchQuantity, + // 波次抓取(团购/散单)统一排除 SN 订单 + excludeSnOrders: true, } ); results.push(result); @@ -11513,12 +11678,17 @@ class WaveService extends OrderBaseService { ? options.strategyRow : {}; + const strategyType = Number(strategyRow.strategy_type || 0); + // SN 策略固定先拣后分,忽略显式 pick_mode 入参 + if (strategyType === 3) { + return 3; + } + const explicitPickMode = Number(requestData.pick_mode ?? requestData.pickMode); if (Number.isInteger(explicitPickMode) && explicitPickMode >= 1 && explicitPickMode <= 5) { return explicitPickMode; } - const strategyType = Number(strategyRow.strategy_type || 0); const batchMode = Number(strategyRow.batch_mode || 0); const groupBatchMaxOrders = Number(strategyRow.group_batch_max_orders || 0); @@ -11834,16 +12004,19 @@ class WaveService extends OrderBaseService { /** * 查询策略自动分流候选订单(命中策略且未分配波次)。 * - * 过滤口径:step != 0、wave_id = 0、status != cancel、outbound_status != padding, - * 并按同结构数量命中 min_same_structure/max_same_structure。 + * 过滤口径:step != 0、wave_id = 0、status != cancel、outbound_status != padding; + * 散单/团购策略还需按同结构数量命中 min_same_structure/max_same_structure, + * SN 策略(strategy_type=3)忽略同结构数量区间(SN 订单只能由 SN 策略抓取)。 * * @param {Object} params 查询参数。 * @param {number|string} params.warehouseId 仓库ID。 * @param {number|string} params.strategyId 策略ID。 - * @param {number|string|null} [params.minSameStructure=0] 最小同结构数量。 - * @param {number|string|null} [params.maxSameStructure=null] 最大同结构数量。 + * @param {number|string|null} [params.minSameStructure=0] 最小同结构数量(SN 策略忽略)。 + * @param {number|string|null} [params.maxSameStructure=null] 最大同结构数量(SN 策略忽略)。 * @param {Date|string|null} [params.createdBefore=null] 创建时间上限(不含), * 仅命中创建时间早于该值的订单,用于分割第一/第二订单池;为 null 时不限制。 + * @param {number|string} [params.strategyType=0] 策略类型:1-散单 2-团购 3-SN; + * 1/2 排除 SN 订单,3 仅取 SN 订单。 * @return {Promise>} 候选订单数组(按 order_id 升序)。 */ async getWaveStrategyFetchCandidateOrders(params = {}) { @@ -11859,6 +12032,14 @@ class WaveService extends OrderBaseService { : null; const requireSameExpress = Number(params.requireSameExpress ?? 0) === 1; const createdBefore = this.normalizeWaveStrategyFetchCreatedBefore(params.createdBefore); + const strategyType = Number(params.strategyType ?? 0); + const isSnStrategy = strategyType === 3; + const snOuterCondition = isSnStrategy + ? "AND o.has_sn_item = 'Y'" + : "AND (o.has_sn_item IS NULL OR o.has_sn_item <> 'Y')"; + const snSourceCondition = isSnStrategy + ? "AND src.has_sn_item = 'Y'" + : "AND (src.has_sn_item IS NULL OR src.has_sn_item <> 'Y')"; const orderModel = await this.getOrderModel('pendingOrder', warehouseId); const orderTableName = this.getModelTableSqlName(orderModel); @@ -11866,31 +12047,11 @@ class WaveService extends OrderBaseService { const expressExpr = alias => `COALESCE(NULLIF(TRIM(COALESCE(${alias}.sys_logistics_code, '')), ''), NULLIF(TRIM(COALESCE(${alias}.logistics_code, '')), ''), TRIM(COALESCE(${alias}.logistics_name, '')))`; const groupKeyExtra = requireSameExpress ? `, ${expressExpr('src')}` : ''; const joinKeyExtra = requireSameExpress ? ` AND same_structure.express_key = ${expressExpr('o')}` : ''; - const rows = await this.ctx.model.query(` - SELECT - o.id, - o.items_hash, - o.items, - o.logistics_name, - o.sys_logistics_code, - o.logistics_code, - o.items_count, - o.items_total - FROM wms_order_wave_strategy_match m - INNER JOIN ${orderTableName} o - ON o.id = m.order_id - AND o.warehouse_id = :warehouseId - AND o.wave_id = 0 - AND o.step != 0 - AND o.post_status = 'fin' - AND o.storage_status = 'fin' - AND o.print_status != 'fin' - AND o.status != 'cancel' - AND o.outbound_status != 'padding' - AND o.intercept_status = 'none' - AND o.lock_status = 'none' - AND (o.is_b2b IS NULL OR o.is_b2b = 'N') - AND (:createdBefore IS NULL OR o.create_at < :createdBefore) + // SN 策略(strategy_type=3)忽略同结构最小/最大数量限制:SN 订单只能由 SN 策略抓取, + // 若按散单的同结构区间过滤,单个/少量 SN 订单会永远匹配不到,故直接跳过同结构统计与过滤。 + const sameStructureJoinSql = isSnStrategy + ? '' + : ` INNER JOIN ( SELECT ${structureExpr('src')} AS structure_key${requireSameExpress ? `, ${expressExpr('src')} AS express_key` : ''}, @@ -11907,13 +12068,45 @@ class WaveService extends OrderBaseService { AND src.intercept_status = 'none' AND src.lock_status = 'none' AND (src.is_b2b IS NULL OR src.is_b2b = 'N') + ${snSourceCondition} GROUP BY ${structureExpr('src')}${groupKeyExtra} ) same_structure - ON same_structure.structure_key = ${structureExpr('o')}${joinKeyExtra} - WHERE m.warehouse_id = :warehouseId - AND m.strategy_id = :strategyId + ON same_structure.structure_key = ${structureExpr('o')}${joinKeyExtra}`; + const sameStructureWhereSql = isSnStrategy + ? '' + : ` AND same_structure.same_structure_count >= :minSameStructure - AND (:maxSameStructure IS NULL OR same_structure.same_structure_count <= :maxSameStructure) + AND (:maxSameStructure IS NULL OR same_structure.same_structure_count <= :maxSameStructure)`; + const rows = await this.ctx.model.query(` + SELECT + o.id, + o.items_hash, + o.items, + o.logistics_name, + o.sys_logistics_code, + o.logistics_code, + o.items_count, + o.items_total, + o.has_sn_item + FROM wms_order_wave_strategy_match m + INNER JOIN ${orderTableName} o + ON o.id = m.order_id + AND o.warehouse_id = :warehouseId + AND o.wave_id = 0 + AND o.step != 0 + AND o.post_status = 'fin' + AND o.storage_status = 'fin' + AND o.print_status != 'fin' + AND o.status != 'cancel' + AND o.outbound_status != 'padding' + AND o.intercept_status = 'none' + AND o.lock_status = 'none' + AND (o.is_b2b IS NULL OR o.is_b2b = 'N') + ${snOuterCondition} + AND (:createdBefore IS NULL OR o.create_at < :createdBefore) + ${sameStructureJoinSql} + WHERE m.warehouse_id = :warehouseId + AND m.strategy_id = :strategyId${sameStructureWhereSql} ORDER BY o.id ASC `, { replacements: { @@ -11936,6 +12129,7 @@ class WaveService extends OrderBaseService { logistics_code: String(row && row.logistics_code || '').trim(), items_count: Number(row && row.items_count || 0), items_total: Number(row && row.items_total || 0), + has_sn_item: String(row && row.has_sn_item || '').trim(), })) .filter(row => Number.isInteger(row.id) && row.id > 0) .sort((a, b) => a.id - b.id); @@ -12438,6 +12632,7 @@ class WaveService extends OrderBaseService { AND o.intercept_status = 'none' AND o.lock_status = 'none' AND (o.is_b2b IS NULL OR o.is_b2b = 'N') + AND (o.has_sn_item IS NULL OR o.has_sn_item <> 'Y') AND ${structureExpr('o')} IN (:structureKeys)${expressCondition} ORDER BY o.id ASC `, { @@ -12528,6 +12723,7 @@ class WaveService extends OrderBaseService { minSameStructure: strategyRow.min_same_structure, maxSameStructure: strategyRow.max_same_structure, requireSameExpress: Number(strategyRow.require_same_express || 0), + strategyType, }; // 订单池分割:第一订单池 = 创建时间早于今日 0 点(前一天及更早订单), @@ -12635,7 +12831,7 @@ class WaveService extends OrderBaseService { if (result.selected_wave_ids.length <= 0) { throw new Error('团购策略创建波次失败:无有效波次生成'); } - } else if (strategyType === 1) { + } else if (strategyType === 1 || strategyType === 3) { const effectiveCandidateRows = Number(strategyRow.require_same_express || 0) === 1 ? this.filterCandidateOrdersByRequireSameExpress(candidateRows) : candidateRows; @@ -12649,7 +12845,7 @@ class WaveService extends OrderBaseService { .filter(id => Number.isInteger(id) && id > 0)) ] .sort((a, b) => a - b); if (mergedOrderIds.length === 0) { - throw new Error('散单策略无可用候选订单'); + throw new Error('散单/SN 策略无可用候选订单'); } const orderLimitRaw = Number(plan.order_limit || strategyRow.batch_max_orders || 0); @@ -12673,18 +12869,18 @@ class WaveService extends OrderBaseService { } else if (pickMode === 4 || pickMode === 2) { selectedOrderIds = mergedOrderIds; } else { - throw new Error(`散单策略不支持的 pick_mode: ${pickMode}`); + throw new Error(`散单/SN 策略不支持的 pick_mode: ${pickMode}`); } if (selectedOrderIds.length <= 0) { - throw new Error('散单策略筛选后无可用订单(候选可能已被剔除)'); + throw new Error('散单/SN 策略筛选后无可用订单(候选可能已被剔除)'); } const limitedOrderIds = orderLimit > 0 ? selectedOrderIds.slice(0, orderLimit) : selectedOrderIds; if (limitedOrderIds.length <= 0) { - throw new Error('散单策略筛选后无可用订单(batch_max_orders 限制导致为空)'); + throw new Error('散单/SN 策略筛选后无可用订单(batch_max_orders 限制导致为空)'); } const createdWave = await this.createWaveBatchByOrderIdsInTransaction({ @@ -12702,7 +12898,7 @@ class WaveService extends OrderBaseService { result.selected_wave_ids.push(createdWave.waveId); result.selected_order_ids.push(...createdWave.selectedOrderIds); if (result.selected_wave_ids.length <= 0) { - throw new Error('散单策略创建波次失败:无有效波次生成'); + throw new Error('散单/SN 策略创建波次失败:无有效波次生成'); } } else { throw new Error(`不支持的策略类型: ${strategyType}`); @@ -12736,7 +12932,8 @@ class WaveService extends OrderBaseService { * * 在一个事务内完成候选查询、分组与建波: * - 团购策略(strategy_type=2):每个结构分组创建一个波次; - * - 散单策略(strategy_type=1):合并全部候选订单后创建一个散单波次。 + * - 散单策略(strategy_type=1):合并全部候选订单后创建一个散单波次; + * - SN 策略(strategy_type=3):只抓 SN 订单,与散单同形态建波并固定 pick_mode=3(先拣后分)。 * * @param {Object} params 执行参数。 * @param {Object} params.plan 预处理计划。 @@ -12771,7 +12968,9 @@ class WaveService extends OrderBaseService { minSameStructure: strategyRow.min_same_structure, maxSameStructure: strategyRow.max_same_structure, requireSameExpress: Number(strategyRow.require_same_express || 0), + strategyType, }); + // getWaveStrategyFetchCandidateOrders 已按策略类型过滤 SN 订单(3 只取 SN,1/2 排除 SN) const candidateCount = candidateRows.length; if (candidateCount <= 0) { throw new Error('未找到符合策略且未分配波次的候选订单'); @@ -12813,7 +13012,7 @@ class WaveService extends OrderBaseService { createdWaveNos.push(created.waveNo); createdOrderIds.push(...created.selectedOrderIds); } - } else if (strategyType === 1) { + } else if (strategyType === 1 || strategyType === 3) { const effectiveCandidateRows = Number(strategyRow.require_same_express || 0) === 1 ? this.filterCandidateOrdersByRequireSameExpress(candidateRows) : candidateRows; @@ -12827,7 +13026,7 @@ class WaveService extends OrderBaseService { .filter(id => Number.isInteger(id) && id > 0)) ] .sort((a, b) => a - b); if (mergedOrderIds.length <= 0) { - throw new Error('散单策略无可用候选订单'); + throw new Error('散单/SN 策略无可用候选订单'); } const createdWave = await this.createWaveBatchByOrderIdsInTransaction({ diff --git a/app/service/systemMethods/stock/warehouse.js b/app/service/systemMethods/stock/warehouse.js index b677710..a808798 100644 --- a/app/service/systemMethods/stock/warehouse.js +++ b/app/service/systemMethods/stock/warehouse.js @@ -562,6 +562,8 @@ class WarehouseService extends MainService { outbound_min_days, remaining_threshold_days, warning_quantity, + sn_code_rules, + snCodeRules, } = data || {}; try { const result = await service.systems.stockStore.saveWarehouseStock({ @@ -609,6 +611,8 @@ class WarehouseService extends MainService { outbound_min_days, remaining_threshold_days, warning_quantity, + sn_code_rules, + snCodeRules, }); return this.success('ok', { data: result, code: 200 }); } catch (error) { diff --git a/app/service/systemMethods/waybill/warehouse.js b/app/service/systemMethods/waybill/warehouse.js index 11e5abc..237df27 100644 --- a/app/service/systemMethods/waybill/warehouse.js +++ b/app/service/systemMethods/waybill/warehouse.js @@ -4,12 +4,11 @@ const MainService = require('../../main'); const WAYBILL_EXPORT_TASK_CACHE_KEY_PREFIX = 'waybill_export_task_'; const WAYBILL_RECEIVE_TASK_CACHE_KEY_PREFIX = 'waybill_receive_task_'; -const WAYBILL_TRACE_TASK_CACHE_KEY_PREFIX = 'waybill_trace_task_'; -/** 物流轨迹查询所依赖的出站回调 method */ +/** 轨迹查询所依赖的出站回调 method */ const WAYBILL_TRACE_EVENT = 'waybill.getTrace'; -/** 仓库未配置轨迹查询外部接口时的失败提示(直接失败,不进入任务流程) */ +/** 轨迹查询外部接口未配置时的失败提示 */ const WAYBILL_TRACE_NOT_CONFIGURED_MESSAGE = - '如需更新运单物流轨迹信息,到【设置】->【基础设置】->【API开放接口】配置相应的外部访问接口'; + '如需查询运单物流轨迹,到【设置】->【基础设置】->【API开放接口】配置相应的外部访问接口'; /** 揽收状态查询所依赖的出站回调 method */ const WAYBILL_RECEIVE_EVENT = 'waybill.getreceive'; /** 仓库未配置外部接口时的失败提示(直接失败,不进入任务流程) */ @@ -29,9 +28,9 @@ class WaybillWarehouseService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,detail,export,exportTaskProgress,updateReceive,updateReceiveTaskProgress,updateTrace,updateTraceTaskProgress,getTrace'; + const _noNeedRight = 'list,detail,export,exportTaskProgress,updateReceive,updateReceiveTaskProgress,getTrace'; const _noNeedLog = ''; - const _noNeedAuth = 'list,detail,export,exportTaskProgress,updateReceive,updateReceiveTaskProgress,updateTrace,updateTraceTaskProgress,getTrace'; + const _noNeedAuth = 'list,detail,export,exportTaskProgress,updateReceive,updateReceiveTaskProgress,getTrace'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -489,6 +488,26 @@ class WaybillWarehouseService extends MainService { return String(first && first.appKey || '').trim(); } + /** + * 解析仓库承接 waybill.getTrace 的 API 应用 AppKey(按 id 升序取首个)。 + * 返回空字符串表示仓库未配置轨迹查询外部接口。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 目标应用 AppKey。 + */ + async resolveTraceAppKey(warehouseId) { + const warehouseNotify = this.service.systems && this.service.systems.warehouseNotify; + if (!warehouseNotify || typeof warehouseNotify.listCallbackConfigs !== 'function') { + return ''; + } + + const candidates = await warehouseNotify.listCallbackConfigs( + Number(warehouseId) || 0, + WAYBILL_TRACE_EVENT + ); + const first = Array.isArray(candidates) ? candidates[0] : null; + return String(first && first.appKey || '').trim(); + } + /** * 规范导出任务ID。 * @param {Object} data 请求体。 @@ -599,265 +618,16 @@ class WaybillWarehouseService extends MainService { return await this.getTaskProgress(taskId, WAYBILL_RECEIVE_TASK_CACHE_KEY_PREFIX); } - /** - * 批量更新运单物流轨迹(仓库侧)。 - * - * 链路走 OpenAPI 出站回调 `waybill.getTrace`(单批最多 10 单,自动切批), - * 请求与 `waybill.getreceive` 一致(`{ request: { waybill_codes: [...] } }`), - * 查询结果按 (express_id, op_time, scan_type) 幂等落库到 `wms_order_express_trace`。 - * 异步任务模式:提交后通过 `updateTraceTaskProgress` 查询进度。 - * 仓库未配置承接该 method 的 API 应用时直接失败(不创建任务)。 - * - * 入参二选一: - * - `waybillCodes`:显式运单号列表(优先); - * - `where`:与 `waybill.warehouse.list` 完全一致的筛选条件(不含分页/排序)。 - * - * @param {Object} data 请求参数。 - * @param {string[]} [data.waybillCodes] 运单号列表(兼容 waybill_codes)。 - * @param {Object} [data.where] 筛选条件(同 waybill.warehouse.list 的 where)。 - * @return {Promise} 任务提交结果,含 task_id。 - */ - async updateTrace(data = {}) { - try { - const safeData = this.isPlainObject(data) ? data : {}; - let waybillCodes = this.normalizeReceiveWaybillCodes(safeData.waybillCodes || safeData.waybill_codes); - const rawWhere = this.isPlainObject(safeData.where) ? safeData.where : null; - - if (waybillCodes.length === 0 && !rawWhere) { - return this.fail('运单号不能为空,或传入 where 筛选条件'); - } - - const warehouseId = Number(this.ctx?.user?.store_id || 0); - if (!warehouseId) { - return this.fail('无法获取当前仓库ID'); - } - - // 未配置外部访问接口:直接失败,不进入任务流程 - const appKey = await this.resolveTraceAppKey(warehouseId); - if (!appKey) { - return this.fail(WAYBILL_TRACE_NOT_CONFIGURED_MESSAGE); - } - - if (waybillCodes.length === 0) { - const resolved = await this.service.systems.waybill.resolveWaybillCodesByWhere({ - where: rawWhere, - warehouseId, - limit: WAYBILL_RECEIVE_MAX_CODES, - }); - if (resolved.exceeded) { - return this.fail( - `符合条件的运单超过 ${WAYBILL_RECEIVE_MAX_CODES} 条,请缩小筛选范围或直接传 waybillCodes` - ); - } - waybillCodes = this.normalizeReceiveWaybillCodes(resolved.codes); - if (waybillCodes.length === 0) { - return this.fail('未匹配到符合条件的运单'); - } - } - - const taskId = this.generateTraceTaskId(); - const taskPayload = { - task_id: taskId, - status: 'submitted', - progress: 0, - current_count: 0, - total_count: waybillCodes.length, - message: '更新物流轨迹任务已提交', - result: null, - error: '', - }; - await this.setTraceTaskProgress(taskId, taskPayload); - - setImmediate(async () => { - try { - await this.setTraceTaskProgress(taskId, { - task_id: taskId, - status: 'running', - progress: 0, - current_count: 0, - total_count: waybillCodes.length, - message: '正在查询运单物流轨迹', - result: null, - error: '', - }); - - const result = await this.service.systems.waybill.queryTraces({ - warehouseId, - waybillCodes, - appKey, - onProgress: async progress => { - const safeProgress = this.isPlainObject(progress) ? progress : {}; - await this.setTraceTaskProgress(taskId, { - task_id: taskId, - status: 'running', - progress: safeProgress.progress || 0, - current_count: safeProgress.currentCount || 0, - total_count: safeProgress.totalCount || waybillCodes.length, - message: safeProgress.message || '正在查询运单物流轨迹', - result: null, - error: '', - }); - }, - }); - - if (!result || result.success !== true) { - await this.setTraceTaskProgress(taskId, { - task_id: taskId, - status: 'failed', - progress: 100, - current_count: 0, - total_count: waybillCodes.length, - message: '更新物流轨迹失败', - result: null, - error: String(result && result.reason || '运单物流轨迹查询失败'), - }); - return; - } - - const failedList = Array.isArray(result.failed) ? result.failed : []; - const emptyList = Array.isArray(result.empty) ? result.empty : []; - await this.setTraceTaskProgress(taskId, { - task_id: taskId, - status: 'success', - progress: 100, - current_count: waybillCodes.length, - total_count: waybillCodes.length, - message: `更新完成:新增 ${result.inserted} 条轨迹,更新 ${result.updated} 条` - + `,无轨迹 ${emptyList.length} 单,失败 ${failedList.length} 单`, - result: { - total: result.total, - matched: result.matched, - inserted: result.inserted, - updated: result.updated, - empty: emptyList, - not_found: Array.isArray(result.not_found) ? result.not_found : [], - failed: failedList, - }, - error: '', - }); - } catch (error) { - const errorMessage = error && error.message ? error.message : `${error}`; - await this.setTraceTaskProgress(taskId, { - task_id: taskId, - status: 'failed', - progress: 100, - message: '更新物流轨迹失败', - result: null, - error: errorMessage, - }); - } - }); - - return this.success('ok', { - ...taskPayload, - update_time: Date.now(), - }); - } catch (e) { - return this.fail(e.message); - } - } - - /** - * 查询运单物流轨迹更新任务进度。 - * - * @param {Object} data 请求参数。 - * @param {string} [data.task_id] 任务ID(下划线写法)。 - * @param {string} [data.taskId] 任务ID(驼峰写法)。 - * @return {Promise} 任务进度信息。 - */ - async updateTraceTaskProgress(data = {}) { - try { - const safeData = this.isPlainObject(data) ? data : {}; - const taskId = String(safeData.task_id || safeData.taskId || '').trim(); - const notFoundPayload = { - task_id: taskId, - status: 'not_found', - progress: 0, - current_count: 0, - total_count: 0, - message: '任务不存在', - result: null, - error: '', - update_time: Date.now(), - }; - - if (!taskId) { - return this.success('ok', notFoundPayload); - } - - const cachedTask = await this.getTraceTaskProgress(taskId); - if (!cachedTask) { - return this.success('ok', notFoundPayload); - } - - return this.success('ok', { - task_id: taskId, - ...cachedTask, - update_time: Date.now(), - }); - } catch (e) { - return this.fail(e.message); - } - } - - /** - * 生成运单物流轨迹更新任务ID。 - * @return {string} 任务ID。 - */ - generateTraceTaskId() { - const warehouseId = this.ctx?.user?.store_id || 'unknown'; - const timestamp = Date.now(); - const randomToken = Math.random().toString(36).slice(2, 10); - return `waybill_trace_${warehouseId}_${timestamp}_${randomToken}`; - } - - /** - * 解析仓库承接 waybill.getTrace 的 API 应用 AppKey(按 id 升序取首个)。 - * @param {number} warehouseId 仓库ID。 - * @return {Promise} 目标应用 AppKey,未配置时返回空字符串。 - */ - async resolveTraceAppKey(warehouseId) { - const warehouseNotify = this.service.systems && this.service.systems.warehouseNotify; - if (!warehouseNotify || typeof warehouseNotify.listCallbackConfigs !== 'function') { - return ''; - } - - const candidates = await warehouseNotify.listCallbackConfigs( - Number(warehouseId) || 0, - WAYBILL_TRACE_EVENT - ); - const first = Array.isArray(candidates) ? candidates[0] : null; - return String(first && first.appKey || '').trim(); - } - - /** - * 写入运单物流轨迹任务进度缓存。 - * @param {string} taskId 任务ID。 - * @param {Object} payload 任务状态。 - * @return {Promise} 无返回值。 - */ - async setTraceTaskProgress(taskId = '', payload = {}) { - await this.setTaskProgress(taskId, payload, WAYBILL_TRACE_TASK_CACHE_KEY_PREFIX); - } - - /** - * 读取运单物流轨迹任务进度缓存。 - * @param {string} taskId 任务ID。 - * @return {Promise} 任务状态对象或 null。 - */ - async getTraceTaskProgress(taskId = '') { - return await this.getTaskProgress(taskId, WAYBILL_TRACE_TASK_CACHE_KEY_PREFIX); - } - /** * 查询单个运单的全部物流轨迹(仓库侧)。 * + * 全部回源:实时调用外部访问接口 `waybill.getTrace` 查询,不做本地存储。 * 一次返回该运单号下的所有轨迹(不分页),按操作时间倒序排列(最新的在前)。 - * 仅查当前仓库的数据(warehouse_id 隔离);运单号不存在或该仓库无轨迹时返回空列表。 + * 命中轨迹(非空)时顺带把该运单 `is_galaxy_receive` 置为 Y(只升不降)。 * * @param {Object} data 请求参数。 * @param {string} [data.waybillCode] 运单号(兼容 waybill_code)。 - * @return {Promise} { waybill_code, total, list }。 + * @return {Promise} { waybill_code, total, list, received_updated }。 */ async getTrace(data = {}) { try { @@ -872,12 +642,37 @@ class WaybillWarehouseService extends MainService { return this.fail('无法获取当前仓库ID'); } - const result = await this.service.systems.waybill.listTracesByWaybill({ - waybillCode, + const appKey = await this.resolveTraceAppKey(warehouseId); + if (!appKey) { + return this.fail(WAYBILL_TRACE_NOT_CONFIGURED_MESSAGE); + } + + const fetched = await this.service.systems.waybill.fetchTracesByWaybill({ warehouseId, + waybillCode, + appKey, }); - return this.success('获取成功', result); + if (!fetched.success) { + const reason = fetched.reason || fetched.error || '运单轨迹查询失败'; + return this.fail(`运单轨迹查询失败: ${reason}`); + } + + // 有轨迹即视为已揽收(只升不降);失败不阻断查询 + let receivedUpdated = 0; + if (!fetched.empty) { + receivedUpdated = await this.service.systems.waybill.markReceiveByTraces({ + warehouseId, + waybillCodes: [ waybillCode ], + }); + } + + return this.success('获取成功', { + waybill_code: waybillCode, + total: fetched.traces.length, + list: fetched.traces, + received_updated: receivedUpdated, + }); } catch (e) { return this.fail(e.message); } diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index b7d57fd..1ef6d71 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -1115,6 +1115,8 @@ class DeliveryOrderService extends Service { items_hash: this.generateItemsHash(itemsInfo), // 哈希值 items_crc: this.calculateCRC32(itemsInfo.items_str || ''), // CRC校验 source_order_codes: ((itemsInfo.stats && itemsInfo.stats.source_order_codes) || []).filter(code => code).join(',') || deliveryOrder.deliveryOrderCode, + // 是否含序列号管理商品:建单时按 stock_warehouse.is_sn_mgmt 聚合,随 INSERT 一次写入 + has_sn_item: itemsInfo.has_sn_item ? 'Y' : 'N', // 主表 timestamps:false,updated_at 需显式写入(原先由统计列 UPDATE 顺带更新) updated_at: new Date(), }; @@ -1694,18 +1696,22 @@ class DeliveryOrderService extends Service { // ===== Sort: 按 stockId 升序排序,保证所有事务加锁顺序一致,从根本上消除死锁 ===== resolvedItems.sort((a, b) => a.stockId - b.stockId); - // ===== 批量查询 wms_stock_warehouse 获取仓库侧称重毛重 & 违禁品类型 ===== + // ===== 批量查询 wms_stock_warehouse 获取仓库侧称重毛重 & 违禁品类型 & 序列号管理标记 ===== const stockIds = [ ...new Set(resolvedItems.map(item => item.stockId).filter(Boolean)) ]; const warehouseWeightMap = new Map(); const stockProhibitedMap = new Map(); // stock_id -> 违禁品类型ID + let hasSnItem = false; // 订单是否包含序列号管理商品(任一明细 is_sn_mgmt='Y') if (stockIds.length > 0) { const warehouseRecords = await app.model.StockWarehouse.findAll({ where: { id: stockIds }, - attributes: [ 'id', 'gross_weight', 'prohibited_id' ], + attributes: [ 'id', 'gross_weight', 'prohibited_id', 'is_sn_mgmt' ], transaction, raw: true, }); for (const record of warehouseRecords) { + if (String(record.is_sn_mgmt || '').trim().toUpperCase() === 'Y') { + hasSnItem = true; + } const gw = parseFloat(record.gross_weight) || 0; if (gw > 0) { warehouseWeightMap.set(record.id, gw); @@ -1858,6 +1864,7 @@ class DeliveryOrderService extends Service { stock_weight_map: Object.fromEntries(stockWeightMap), // stock_id -> 单件重量 line_data: lineData, // 创建的明细数据 prohibited_type_ids: [ ...new Set(stockProhibitedMap.values()) ], // 违禁品类型ID去重数组(快递策略匹配用) + has_sn_item: hasSnItem, // 是否含序列号管理商品 stats: { // 统计信息汇总 unique_items: stock_count, total_items: item_total_count, @@ -2346,7 +2353,7 @@ class DeliveryOrderService extends Service { id: orderId, warehouse_id: warehouseId, }, - attributes: [ 'id', 'wave_id', 'step', 'status', 'outbound_status', 'lock_status' ], + attributes: [ 'id', 'wave_id', 'step', 'status', 'outbound_status', 'lock_status', 'has_sn_item' ], transaction, lock: transaction.LOCK.UPDATE, }); @@ -2361,6 +2368,12 @@ class DeliveryOrderService extends Service { return false; } + // SN(序列号管理)订单不参与团购,自动加团时静默跳过 + if (String(orderRow.has_sn_item || '').trim().toUpperCase() === 'Y') { + await transaction.commit(); + return false; + } + const currentWaveId = Number(orderRow.wave_id || 0); if (currentWaveId === normalizedWaveId) { await transaction.commit(); @@ -2484,15 +2497,21 @@ class DeliveryOrderService extends Service { */ async countCandidateGroupOrders(context, structure) { const { ctx } = this; + const { Op } = ctx.app.Sequelize; const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(context.warehouseId); const where = { warehouse_id: context.warehouseId, wave_id: 0, - step: { [ctx.app.Sequelize.Op.in]: [ 1, 2, 3 ] }, - status: { [ctx.app.Sequelize.Op.ne]: 'cancel' }, - outbound_status: { [ctx.app.Sequelize.Op.ne]: 'padding' }, + step: { [Op.in]: [ 1, 2, 3 ] }, + status: { [Op.ne]: 'cancel' }, + outbound_status: { [Op.ne]: 'padding' }, lock_status: 'none', sys_logistics_code: structure.logisticsName, + // 团购排除 SN(序列号管理)订单 + [Op.or]: [ + { has_sn_item: { [Op.is]: null } }, + { has_sn_item: { [Op.ne]: 'Y' } }, + ], }; where[structure.itemPartType] = structure.itemPart; @@ -2534,7 +2553,7 @@ class DeliveryOrderService extends Service { context.warehouseId, 'B', minGroupOrderFetchQuantity, - { maxFetchQuantity: maxWaveQuantity } + { maxFetchQuantity: maxWaveQuantity, excludeSnOrders: true } ); }); } diff --git a/app/service/systems/express_platform.js b/app/service/systems/express_platform.js index 11db834..74b6676 100644 --- a/app/service/systems/express_platform.js +++ b/app/service/systems/express_platform.js @@ -1885,17 +1885,25 @@ class ExpressPlatformService extends MainService { .filter(Boolean); if (syncedOrderIds.length > 0) { - // 异步调用,不阻塞主流程 - // 显式传仓库上下文:Qimen 创建订单等链路 ctx.user 为空, - // 不传会导致 syncOrderIds 因"缺少仓库上下文"静默失败 - this.ctx.service.systemMethods.order.pendingOrder.syncOrderIds({ + // SN 订单自动回传会被拦截并置异常,自动触发场景静默跳过 + const autoSyncFilter = await this.ctx.service.systemMethods.order.pendingOrder.filterAutoSyncSnOrderIds({ orderIds: syncedOrderIds, warehouseId, - }).catch(err => { - this.ctx.logger.error( - `[auto_sync_back] polyapi 自动同步失败: ${err.message}` - ); + source: 'polyapi', }); + if (autoSyncFilter.orderIds.length > 0) { + // 异步调用,不阻塞主流程 + // 显式传仓库上下文:Qimen 创建订单等链路 ctx.user 为空, + // 不传会导致 syncOrderIds 因"缺少仓库上下文"静默失败 + this.ctx.service.systemMethods.order.pendingOrder.syncOrderIds({ + orderIds: autoSyncFilter.orderIds, + warehouseId, + }).catch(err => { + this.ctx.logger.error( + `[auto_sync_back] polyapi 自动同步失败: ${err.message}` + ); + }); + } } } } @@ -2252,17 +2260,25 @@ class ExpressPlatformService extends MainService { .filter(Boolean); if (syncedOrderIds.length > 0) { - // 异步调用,不阻塞主流程 - // 显式传仓库上下文:Qimen 创建订单等链路 ctx.user 为空, - // 不传会导致 syncOrderIds 因"缺少仓库上下文"静默失败 - this.ctx.service.systemMethods.order.pendingOrder.syncOrderIds({ + // SN 订单自动回传会被拦截并置异常,自动触发场景静默跳过 + const autoSyncFilter = await this.ctx.service.systemMethods.order.pendingOrder.filterAutoSyncSnOrderIds({ orderIds: syncedOrderIds, warehouseId, - }).catch(err => { - this.ctx.logger.error( - `[auto_sync_back] cainiao 自动同步失败: ${err.message}` - ); + source: 'cainiao', }); + if (autoSyncFilter.orderIds.length > 0) { + // 异步调用,不阻塞主流程 + // 显式传仓库上下文:Qimen 创建订单等链路 ctx.user 为空, + // 不传会导致 syncOrderIds 因"缺少仓库上下文"静默失败 + this.ctx.service.systemMethods.order.pendingOrder.syncOrderIds({ + orderIds: autoSyncFilter.orderIds, + warehouseId, + }).catch(err => { + this.ctx.logger.error( + `[auto_sync_back] cainiao 自动同步失败: ${err.message}` + ); + }); + } } } } @@ -2912,17 +2928,25 @@ class ExpressPlatformService extends MainService { .filter(Boolean); if (syncedOrderIds.length > 0) { - // 异步调用,不阻塞主流程 - // 显式传仓库上下文:Qimen 创建订单等链路 ctx.user 为空, - // 不传会导致 syncOrderIds 因"缺少仓库上下文"静默失败 - this.ctx.service.systemMethods.order.pendingOrder.syncOrderIds({ + // SN 订单自动回传会被拦截并置异常,自动触发场景静默跳过 + const autoSyncFilter = await this.ctx.service.systemMethods.order.pendingOrder.filterAutoSyncSnOrderIds({ orderIds: syncedOrderIds, warehouseId, - }).catch(err => { - this.ctx.logger.error( - `[auto_sync_back] pdd 自动同步失败: ${err.message}` - ); + source: 'pdd', }); + if (autoSyncFilter.orderIds.length > 0) { + // 异步调用,不阻塞主流程 + // 显式传仓库上下文:Qimen 创建订单等链路 ctx.user 为空, + // 不传会导致 syncOrderIds 因"缺少仓库上下文"静默失败 + this.ctx.service.systemMethods.order.pendingOrder.syncOrderIds({ + orderIds: autoSyncFilter.orderIds, + warehouseId, + }).catch(err => { + this.ctx.logger.error( + `[auto_sync_back] pdd 自动同步失败: ${err.message}` + ); + }); + } } } } diff --git a/app/service/systems/order_async.js b/app/service/systems/order_async.js index d0d50de..6d462f5 100644 --- a/app/service/systems/order_async.js +++ b/app/service/systems/order_async.js @@ -11,6 +11,8 @@ const TRANSACTION_LOCK_RETRY_MAX_ATTEMPTS = 3; const TRANSACTION_LOCK_RETRY_BASE_DELAY_MS = 50; const DISPATCH_BATCH_SIZE = 20; const SYNC_ORDER_IDS_PROGRESS_CACHE_TTL = 7200; +/** SN 状态中代表「已随订单发出」的集合(复核提交后写入 VERIFIED),回传平台时只带这些 SN */ +const SHIPPED_SN_STATUS_LIST = [ 'VERIFIED', 'REISSUED' ]; // 订单同步通知合并去抖:最后一次同步后等待 3 分钟无新同步,再统一推送一条消息 const ORDER_SYNC_NOTICE_DEBOUNCE_MS = 3 * 60 * 1000; @@ -194,6 +196,138 @@ async function buildOrderWaybillCodeMapInternal(service, orderIds = [], warehous return waybillCodeMap; } +/** + * 解析单个订单明细回传用的 snList:优先使用明细上已有的 sn_list,其次用 SN 表数据。 + * + * @param {Object} orderItem 订单明细记录。 + * @param {Map} snListMap 明细ID -> SN 列表。 + * @return {string[]} SN 列表。 + */ +function resolveOrderLineSnListInternal(orderItem = {}, snListMap = new Map()) { + if (Array.isArray(orderItem.sn_list) && orderItem.sn_list.length > 0) { + return orderItem.sn_list + .map(code => String(code || '').trim()) + .filter(code => !!code); + } + + const itemId = Number(orderItem.id ?? orderItem.order_item_id); + if (!Number.isFinite(itemId) || itemId <= 0) { + return []; + } + + return snListMap.get(itemId) || []; +} + +/** + * 奇门 deliveryorder.confirm 的 orderLine.sn 限长(见接口规范 string(50))。 + */ +const QIMEN_SN_CODE_MAX_LENGTH = 50; + +/** + * 按奇门规范拆分单行 SN:不超过长度上限的放 snList;超长的(二维码/链接型 SN)改放 orderLine.qrCode, + * 多个之间用分号拼接,并与明细自带 qr_code 合并去重。未指定上限时(如 API/JSON 渠道)全部保留在 snList。 + * + * @param {string[]} snCodes 已发出的 SN 列表。 + * @param {string} qrCode 明细自带的二维码。 + * @param {number} [maxSnCodeLength] snList 单值长度上限,缺省或非正数表示不限制。 + * @return {{ snList: string[], qrCode: string }} 奇门 orderLine 的 snList 与 qrCode。 + */ +function splitOrderLineSnCodesInternal(snCodes = [], qrCode = '', maxSnCodeLength) { + const limit = Number(maxSnCodeLength); + const hasLimit = Number.isFinite(limit) && limit > 0; + const shortCodes = []; + const longCodes = []; + + for (const code of Array.isArray(snCodes) ? snCodes : []) { + const normalizedCode = String(code || '').trim(); + if (!normalizedCode) { + continue; + } + if (!hasLimit || normalizedCode.length <= limit) { + shortCodes.push(normalizedCode); + } else { + longCodes.push(normalizedCode); + } + } + + const qrCodes = [ String(qrCode || '').trim(), ...longCodes ].filter((code, index, list) => !!code && list.indexOf(code) === index); + + return { + snList: shortCodes, + qrCode: qrCodes.join(';'), + }; +} + +/** + * 构建订单明细 -> 已发出 SN 列表映射(用于回传报文 orderLines[].snList)。 + * + * 只取已随订单发出(VERIFIED/REISSUED)的 SN,避免把退回/作废的 SN 回传平台; + * 查询失败仅告警并返回空映射,不阻断回传主流程。 + * + * @param {Object} service 订单异步服务实例。 + * @param {Object} orderRow 订单主表记录(需含 id、warehouse_id)。 + * @param {Array} orderItems 订单明细记录。 + * @return {Promise>} order_item_id 到 SN 列表的映射。 + */ +async function buildOrderItemSnListMapInternal(service, orderRow = {}, orderItems = []) { + const snListMap = new Map(); + const orderItemSnModel = service.ctx.model && service.ctx.model.OrderItemSn; + const orderId = Number(orderRow && orderRow.id); + + if (!orderItemSnModel || typeof orderItemSnModel.findAll !== 'function') { + return snListMap; + } + if (!Number.isFinite(orderId) || orderId <= 0) { + return snListMap; + } + + const itemIds = [ ...new Set((Array.isArray(orderItems) ? orderItems : []) + .map(item => Number(item && (item.id ?? item.order_item_id))) + .filter(itemId => Number.isFinite(itemId) && itemId > 0)) ]; + if (itemIds.length === 0) { + return snListMap; + } + + const { Op } = service.app.Sequelize; + const where = { + order_id: orderId, + order_item_id: { [Op.in]: itemIds }, + sn_status: { [Op.in]: SHIPPED_SN_STATUS_LIST }, + }; + const warehouseId = Number(orderRow && orderRow.warehouse_id); + if (Number.isFinite(warehouseId) && warehouseId > 0) { + where.warehouse_id = warehouseId; + } + + try { + const snRows = await orderItemSnModel.findAll({ + where, + attributes: [ 'order_item_id', 'sn_code' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + for (const row of Array.isArray(snRows) ? snRows : []) { + const itemId = Number(row && row.order_item_id); + const snCode = String(row && row.sn_code || '').trim(); + if (!Number.isFinite(itemId) || itemId <= 0 || !snCode) { + continue; + } + if (!snListMap.has(itemId)) { + snListMap.set(itemId, []); + } + snListMap.get(itemId).push(snCode); + } + } catch (error) { + service.ctx.logger.warn('[order_async] 读取订单SN明细失败,回传报文将不带 snList', { + orderId, + message: error && error.message, + }); + } + + return snListMap; +} + async function buildQimenDeliveryOrderConfirmDataInternal(service, orderRow, orderItems, requestContext = {}) { const app = service.app; const now = app.formatDate(new Date()); @@ -257,6 +391,7 @@ async function buildQimenDeliveryOrderConfirmDataInternal(service, orderRow, ord const packageCode = String(orderRow.package_code || '').trim() || deliveryOrderCode; const invoiceNo = String(orderRow.invoice_no || '').trim(); const orderConfirmTime = now; + const snListMap = await buildOrderItemSnListMapInternal(service, orderRow, orderItems); const orderLines = []; for (const orderItem of Array.isArray(orderItems) ? orderItems : []) { @@ -265,6 +400,12 @@ async function buildQimenDeliveryOrderConfirmDataInternal(service, orderRow, ord continue; } + const snPayload = splitOrderLineSnCodesInternal( + resolveOrderLineSnListInternal(orderItem, snListMap), + orderItem.qr_code, + requestContext.snCodeMaxLength + ); + orderLines.push({ orderLineNo: String(orderItem.order_line_no || '').trim() || orderLines.length + 1, orderSourceCode: String(orderItem.source_order_code || '').trim(), @@ -280,8 +421,8 @@ async function buildQimenDeliveryOrderConfirmDataInternal(service, orderRow, ord actualPrice: Number(orderItem.actual_price) || 0, discountAmount: String(orderItem.discount_amount || '').trim(), inventoryType: String(orderItem.inventory_type || '').trim(), - snList: Array.isArray(orderItem.sn_list) ? orderItem.sn_list.slice() : [], - qrCode: String(orderItem.qr_code || '').trim(), + snList: snPayload.snList, + qrCode: snPayload.qrCode, }); } @@ -2519,6 +2660,7 @@ async function processQmOrderInternal(service, orderModel, orderItemsModel, qime ...context, packageExpressCode: Array.isArray(waybillCode) ? waybillCode[0] : (waybillCode || orderRow.express_code || ''), packageExpressCodes: Array.isArray(waybillCode) ? waybillCode : [], + snCodeMaxLength: QIMEN_SN_CODE_MAX_LENGTH, }); if (!requestData.ownerCode) { await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, '发货单缺少奇门货主编码'); diff --git a/app/service/systems/order_export.js b/app/service/systems/order_export.js index 73c17c6..3412adf 100644 --- a/app/service/systems/order_export.js +++ b/app/service/systems/order_export.js @@ -14,6 +14,8 @@ const ORDER_EXPORT_MAX_ROWS_PER_SHEET = 1000000; const ORDER_EXPORT_UPLOAD_MAX_SIZE_BYTES = 1024 * 1024 * 1024; // 订单导出上传文件上限 1GB const ORDER_EXPORT_WORKSHEET_NAME = '订单导出'; const ORDER_EXPORT_ALLOWED_TABLE_TYPES = new Set([ 'current', 'history', 'dispatch', 'outsourced' ]); +/** 订单导出中可见的 SN 状态(已登记/已核验/已重发),排除退回/作废 */ +const ORDER_EXPORT_VISIBLE_SN_STATUS_LIST = Object.freeze([ 'BOUND', 'VERIFIED', 'REISSUED' ]); const ORDER_EXPORT_MODULE_MAP = Object.freeze({ order: 'order', revieworder: 'reviewOrder', @@ -55,6 +57,8 @@ const ORDER_EXPORT_COLUMNS = Object.freeze([ { header: '分配时间', key: 'waybill_allocated_at', width: 20 }, { header: '订单商品总类数', key: 'items_count', width: 16 }, { header: '订单商品总数', key: 'items_total', width: 16 }, + { header: 'SN码数量', key: 'sn_quantity', width: 12 }, + { header: 'SN码汇总', key: 'sn_codes_summary', width: 60 }, { header: '商品重量', key: 'items_weight', width: 12 }, { header: '称重重量(g)', key: 'weighing_weight', width: 14 }, { header: '订单金额', key: 'total_amount', width: 14 }, @@ -108,6 +112,8 @@ const ORDER_EXPORT_ITEM_COLUMNS = Object.freeze([ { header: '分配时间', key: 'waybill_allocated_at', width: 20 }, { header: '订单商品总类数', key: 'items_count', width: 16 }, { header: '订单商品总数', key: 'items_total', width: 16 }, + { header: 'SN码数量', key: 'sn_quantity', width: 12 }, + { header: 'SN码', key: 'sn_codes', width: 60 }, { header: '商品重量', key: 'items_weight', width: 12 }, { header: '称重重量(g)', key: 'weighing_weight', width: 14 }, { header: '订单金额', key: 'total_amount', width: 14 }, @@ -394,12 +400,26 @@ class OrderExportService extends OrderBaseService { * @param {Map} [context.imageUrlMap] stockId → 商品图片URL的映射。 * @param {Map>} [context.expressMap] 订单ID → 运单行列表的映射。 * @param {Map} [context.packageMaterialMap] package_material_id → 包材编码的映射。 + * @param {Set} [context.snStockIdSet] 启用序列号管理的 stockId 集合(用于统计 SN 码数量)。 + * @param {Map} [context.snCodesByOrderMap] 订单ID → 已登记 SN 码列表(订单级汇总)。 + * @param {Map>} [context.snCodesByItemMap] 订单ID → (明细ID → 已登记 SN 码列表)。 * @param {string} [mode='waybill'] 导出模式:'waybill' 或 'item'。 * @return {Array} 导出行数组。 */ mapOrderExportRow(orderRow = {}, context = {}, mode = 'waybill') { const safeOrderRow = this.isPlainObject(orderRow) ? orderRow : {}; - const { itemsMap, storeRemarkMap, stockNameMap, barcodeMap, imageUrlMap, expressMap, packageMaterialMap } = context; + const { + itemsMap, + storeRemarkMap, + stockNameMap, + barcodeMap, + imageUrlMap, + expressMap, + packageMaterialMap, + snStockIdSet, + snCodesByOrderMap, + snCodesByItemMap, + } = context; const safeItemsMap = itemsMap instanceof Map ? itemsMap : new Map(); const safeStoreRemarkMap = storeRemarkMap instanceof Map ? storeRemarkMap : new Map(); const safeExpressMap = expressMap instanceof Map ? expressMap : new Map(); @@ -441,6 +461,35 @@ class OrderExportService extends OrderBaseService { const safeStockNameMap = stockNameMap instanceof Map ? stockNameMap : new Map(); const safeBarcodeMap = barcodeMap instanceof Map ? barcodeMap : new Map(); const safeImageUrlMap = imageUrlMap instanceof Map ? imageUrlMap : new Map(); + const safeSnStockIdSet = snStockIdSet instanceof Set ? snStockIdSet : new Set(); + + /** + * 计算单个明细的 SN 码数量(仅序列号管理商品计入,取 plan_qty)。 + * @param {Object} item 订单明细。 + * @return {number} SN 码数量。 + */ + const resolveItemSnQuantity = item => { + const stockId = Number(item && item.stock_id || 0); + if (!safeSnStockIdSet.has(stockId)) { + return 0; + } + const planQty = Number(item && item.plan_qty); + return Number.isFinite(planQty) && planQty > 0 ? planQty : 0; + }; + + // 订单级 SN 码数量:明细中所有序列号管理商品的 plan_qty 合计(用于账单核对) + const orderSnQuantity = (Array.isArray(items) ? items : []) + .reduce((sum, item) => sum + resolveItemSnQuantity(item), 0); + + // 复核时登记的 SN 码(订单级汇总 + 明细级列表) + const safeSnCodesByOrderMap = snCodesByOrderMap instanceof Map ? snCodesByOrderMap : new Map(); + const safeSnCodesByItemMap = snCodesByItemMap instanceof Map ? snCodesByItemMap : new Map(); + const orderSnCodes = safeSnCodesByOrderMap.get(orderId) || []; + const itemSnCodesMap = safeSnCodesByItemMap.get(orderId) instanceof Map + ? safeSnCodesByItemMap.get(orderId) + : new Map(); + const joinSnCodes = codes => (Array.isArray(codes) ? codes.join(', ') : ''); + const itemsDetail = Array.isArray(items) && items.length > 0 ? items.map(item => { const stockId = Number(item.stock_id || 0); @@ -473,6 +522,8 @@ class OrderExportService extends OrderBaseService { logistics_name: this.normalizeExportCellValue(safeOrderRow.logistics_name), items_count: this.normalizeExportCellValue(safeOrderRow.items_count), items_total: this.normalizeExportCellValue(safeOrderRow.items_total), + sn_quantity: this.normalizeExportCellValue(orderSnQuantity), + sn_codes_summary: this.normalizeExportCellValue(joinSnCodes(orderSnCodes)), items_weight: this.normalizeExportCellValue(safeOrderRow.items_weight), total_amount: this.normalizeExportCellValue(safeOrderRow.total_amount), got_amount: this.normalizeExportCellValue(safeOrderRow.got_amount), @@ -513,6 +564,7 @@ class OrderExportService extends OrderBaseService { item_barcode: '', item_image: '', item_quantity: '', + sn_codes: '', business_type: businessType, logistics_interface_name: this.normalizeExportCellValue(interfaceName), package_material_id: materialId, @@ -532,6 +584,8 @@ class OrderExportService extends OrderBaseService { item_barcode: sid > 0 ? (safeBarcodeMap.get(sid) || '') : '', item_image: sid > 0 ? (safeImageUrlMap.get(sid) || '') : '', item_quantity: item.plan_qty || 1, + sn_quantity: resolveItemSnQuantity(item), + sn_codes: joinSnCodes(itemSnCodesMap.get(Number(item.id || 0)) || []), business_type: businessType, logistics_interface_name: this.normalizeExportCellValue(interfaceName), package_material_id: materialId, @@ -571,6 +625,8 @@ class OrderExportService extends OrderBaseService { // 商品总类数/商品总数为订单级数据,仅主单号行体现;子单号行置 0,避免与主单号重复 items_count: isMainWaybill ? commonFields.items_count : 0, items_total: isMainWaybill ? commonFields.items_total : 0, + sn_quantity: isMainWaybill ? commonFields.sn_quantity : 0, + sn_codes_summary: isMainWaybill ? commonFields.sn_codes_summary : '', waybill_code: exp.waybill_code || '', business_type: isMainWaybill ? '主单号' : '子单号', logistics_interface_name: this.normalizeExportCellValue(exp.logistics_interface_name), @@ -701,7 +757,7 @@ class OrderExportService extends OrderBaseService { const itemsModel = await this.getOrderItemsModelByTableType(target.tableType, warehouseId); const itemsRows = await itemsModel.findAll({ where: { order_id: { [this.app.Sequelize.Op.in]: orderIds } }, - attributes: [ 'order_id', 'item_name', 'plan_qty', 'stock_id' ], + attributes: [ 'id', 'order_id', 'item_name', 'plan_qty', 'stock_id' ], order: [[ 'id', 'ASC' ]], raw: true, }); @@ -719,6 +775,87 @@ class OrderExportService extends OrderBaseService { } } + // 批量查询序列号管理商品(用于导出 SN码数量:明细中 is_sn_mgmt='Y' 商品的 plan_qty 合计) + const snStockIdSet = new Set(); + if (itemsMap.size > 0 && this.ctx && this.ctx.model && this.ctx.model.StockWarehouse) { + try { + const snStockIds = [ + ...new Set( + [ ...itemsMap.values() ] + .flat() + .map(item => Number(item.stock_id || 0)) + .filter(id => id > 0) + ), + ]; + if (snStockIds.length > 0) { + const snRows = await this.ctx.model.StockWarehouse.findAll({ + where: { + id: { [this.app.Sequelize.Op.in]: snStockIds }, + warehouse_id: warehouseId, + is_sn_mgmt: 'Y', + }, + attributes: [ 'id' ], + raw: true, + paranoid: false, + }); + for (const snRow of (Array.isArray(snRows) ? snRows : [])) { + const sid = Number(snRow.id || 0); + if (sid > 0) { + snStockIdSet.add(sid); + } + } + } + } catch (err) { + this.app.logger.warn(`[order_export] 批量查询序列号管理商品失败: ${err.message}`); + } + } + + // 批量查询复核时登记的 SN 码(wms_order_item_sn),用于导出 SN 码汇总 / 商品行 SN 码列表 + const snCodesByOrderMap = new Map(); + const snCodesByItemMap = new Map(); + if (orderIds.length > 0 && this.ctx && this.ctx.model && this.ctx.model.OrderItemSn) { + try { + const { Op } = this.app.Sequelize; + const snRows = await this.ctx.model.OrderItemSn.findAll({ + where: { + warehouse_id: warehouseId, + order_id: { [Op.in]: orderIds }, + sn_status: { [Op.in]: ORDER_EXPORT_VISIBLE_SN_STATUS_LIST }, + }, + attributes: [ 'order_id', 'order_item_id', 'sn_code' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + for (const snRow of (Array.isArray(snRows) ? snRows : [])) { + const snOrderId = Number(snRow.order_id || 0); + const snItemId = Number(snRow.order_item_id || 0); + const snCode = String(snRow.sn_code || '').trim(); + if (snOrderId <= 0 || !snCode) { + continue; + } + + if (!snCodesByOrderMap.has(snOrderId)) { + snCodesByOrderMap.set(snOrderId, []); + } + snCodesByOrderMap.get(snOrderId).push(snCode); + + if (snItemId > 0) { + if (!snCodesByItemMap.has(snOrderId)) { + snCodesByItemMap.set(snOrderId, new Map()); + } + const itemSnMap = snCodesByItemMap.get(snOrderId); + if (!itemSnMap.has(snItemId)) { + itemSnMap.set(snItemId, []); + } + itemSnMap.get(snItemId).push(snCode); + } + } + } catch (err) { + this.app.logger.warn(`[order_export] 批量查询订单SN码失败: ${err.message}`); + } + } + // 批量查询仓库商品名称、条码与图片(复用 getStockDetails 缓存) const stockNameMap = new Map(); const barcodeMap = new Map(); @@ -850,7 +987,7 @@ class OrderExportService extends OrderBaseService { } } - const exportContext = { itemsMap, storeRemarkMap, stockNameMap, barcodeMap, imageUrlMap, expressMap, packageMaterialMap }; + const exportContext = { itemsMap, storeRemarkMap, stockNameMap, barcodeMap, imageUrlMap, expressMap, packageMaterialMap, snStockIdSet, snCodesByOrderMap, snCodesByItemMap }; const exportRows = []; for (const row of rowsWithWaveIndex) { diff --git a/app/service/systems/order_item_sn.js b/app/service/systems/order_item_sn.js new file mode 100644 index 0000000..fd205a1 --- /dev/null +++ b/app/service/systems/order_item_sn.js @@ -0,0 +1,713 @@ +'use strict'; + +const OrderBaseService = require('../systemMethods/order/base'); + +/** SN 主表状态:复核提交即视为已核验并已随订单发出 */ +const SN_STATUS_VERIFIED = 'VERIFIED'; +/** SN 主表状态:已绑定待核验(可被复核提交升级为 VERIFIED) */ +const SN_STATUS_BOUND = 'BOUND'; +/** 核验通过 */ +const VERIFY_STATUS_PASS = 'PASS'; +/** 流水表中代表「已随订单发出」的变更后状态,用于判断 SN 是否已经发过 */ +const SHIPPED_SN_STATUS_LIST = [ 'VERIFIED', 'REISSUED' ]; +/** 复核提交写入的流水动作类型 */ +const RECHECK_LOG_ACTION = 'VERIFY'; +/** SN 码最大长度(与 wms_order_item_sn.sn_code VARCHAR(512) 保持一致,支持链接/二维码内容) */ +const MAX_SN_CODE_LENGTH = 512; + +/** + * 订单明细 SN 服务。 + * 负责复核提交环节的 SN 入参归一化、数量与占用校验,以及 SN 主表/流水表落库。 + */ +class OrderItemSnService extends OrderBaseService { + /** + * 归一化复核入参中的 SN 提交内容。 + * + * 统一只有一种格式:sn_map = { stock_id: [ sn_code, ... ] }(值也兼容逗号/换行分隔的字符串), + * 即「商品(仓库商品ID)→ SN 码列表」一一对应,不再按订单明细ID提交。 + * 单个 SN 码最长 512 字符(支持链接/二维码内容)。 + * + * @param {Object} payload 复核请求体。 + * @return {Map} 仓库商品ID键 -> SN 码列表。 + */ + normalizeRecheckSnPayload(payload = {}) { + const requestData = this.isPlainObject(payload) ? payload : {}; + const codesByStock = new Map(); + const snMap = requestData.sn_map ?? requestData.snMap; + if (!this.isPlainObject(snMap)) { + return codesByStock; + } + + for (const [ rawStockKey, rawCodes ] of Object.entries(snMap)) { + const stockKey = this.normalizeSnStockKey(rawStockKey); + if (!stockKey) { + continue; + } + const codeList = Array.isArray(rawCodes) ? rawCodes : this.splitSnCodeText(rawCodes); + const codes = codeList + .map(code => this.normalizeSnCode(code)) + .filter(code => !!code); + for (const code of codes) { + if (code.length > MAX_SN_CODE_LENGTH) { + throw new Error( + `SN码长度不能超过${MAX_SN_CODE_LENGTH}个字符:${code.slice(0, 32)}…(共${code.length}字符)` + ); + } + } + if (codes.length === 0) { + continue; + } + if (!codesByStock.has(stockKey)) { + codesByStock.set(stockKey, []); + } + codesByStock.get(stockKey).push(...codes); + } + + return codesByStock; + } + + /** + * 判断请求体是否提交了 SN 码内容(非空才算提交)。 + * @param {Object} payload 复核请求体。 + * @return {boolean} 是否提交了 SN 码。 + */ + hasRecheckSnPayload(payload = {}) { + const codesByStock = this.normalizeRecheckSnPayload(payload); + for (const codes of codesByStock.values()) { + if (codes.length > 0) { + return true; + } + } + return false; + } + + /** + * 复核提交时校验并写入 SN 码。 + * 校验规则: + * 1. SN 订单必须提交 SN 码,且每个序列号管理商品(stock_id)的 SN 数量必须等于该商品在订单内的 plan_qty 合计; + * 2. 非序列号管理商品不允许提交 SN 码;提交的 stock_id 必须属于当前订单; + * 3. 同一批提交内 SN 不可重复; + * 4. SN 若已绑定其它订单/明细,或流水显示已随其它订单发出,则判定为已发过,直接失败; + * 5. 同一订单同一明细重复提交视为幂等,不重复写入。 + * @param {Object} params 参数。 + * @param {Object} params.order 订单主表行(需包含 id 与 has_sn_item)。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {Object} params.payload 复核请求体,含 sn_map(stock_id -> SN 列表)。 + * @param {Object} [params.operator] 操作人。 + * @param {Date} [params.now] 复核时间。 + * @param {Object} [params.transaction] Sequelize 事务,与复核状态更新共用。 + * @return {Promise<{ sn_count: number, sn_item_count: number, sn_created_count: number, sn_reused_count: number }>} + * SN 提交汇总:SN 总数、涉及明细数、新增写入数、幂等复用数。 + */ + async verifyRecheckSnList({ order = {}, warehouseId, payload = {}, operator = {}, now = new Date(), transaction }) { + const orderId = Number(order && order.id); + const normalizedWarehouseId = Number(warehouseId); + const storeId = Number(order && order.store_id) || 0; + + if (!Number.isInteger(orderId) || orderId <= 0) { + throw new Error('订单ID不合法,无法校验SN码'); + } + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw new Error('仓库ID不合法,无法校验SN码'); + } + + const codesByStock = this.normalizeRecheckSnPayload(payload); + const isSnOrder = this.isSnOrderRow(order); + const submittedCodeCount = this.countSnCodes(codesByStock); + + if (submittedCodeCount === 0) { + if (isSnOrder) { + throw new Error('订单包含序列号管理商品,提交复核时必须上传全部SN码'); + } + return { sn_count: 0, sn_item_count: 0, sn_created_count: 0, sn_reused_count: 0 }; + } + + const items = await this.loadOrderItemsForSn(orderId, normalizedWarehouseId, transaction); + const snStockIdSet = await this.loadSnStockIdSet(items, normalizedWarehouseId); + const stockItemMap = this.buildSnStockItemMap(items, snStockIdSet); + + if (isSnOrder && stockItemMap.size === 0) { + throw new Error('订单序列号商品信息缺失,无法校验SN码,请检查商品是否启用序列号管理'); + } + + this.assertSnStockCodesMatched({ stockItemMap, codesByStock }); + const codesByItem = this.mapStockCodesToOrderItems({ stockItemMap, codesByStock }); + + const allCodes = []; + for (const codes of codesByItem.values()) { + allCodes.push(...codes); + } + this.assertSnCodesUnique(allCodes); + + const writeResult = await this.persistRecheckSn({ + orderId, + warehouseId: normalizedWarehouseId, + storeId, + codesByItem, + allCodes, + operator, + now, + transaction, + }); + + return { + sn_count: allCodes.length, + sn_item_count: codesByItem.size, + sn_created_count: writeResult.createdCount, + sn_reused_count: writeResult.reusedCount, + }; + } + + /** + * 判断订单是否含序列号管理商品。 + * @param {Object} order 订单主表行。 + * @return {boolean} 是否 SN 订单。 + */ + isSnOrderRow(order = {}) { + return String(order && order.has_sn_item || '').trim().toUpperCase() === 'Y'; + } + + /** + * 清洗单个 SN 码。 + * @param {*} rawCode 原始 SN 码。 + * @return {string} 清洗后的 SN 码,空值返回空串。 + */ + normalizeSnCode(rawCode) { + if (rawCode === undefined || rawCode === null) { + return ''; + } + return String(rawCode).trim(); + } + + /** + * 把 SN 文本按换行/逗号/分号/空格拆分为 SN 数组。 + * @param {*} rawText 原始文本。 + * @return {string[]} SN 数组。 + */ + splitSnCodeText(rawText) { + if (rawText === undefined || rawText === null) { + return []; + } + if (Array.isArray(rawText)) { + return rawText.map(code => this.normalizeSnCode(code)).filter(Boolean); + } + return String(rawText) + .split(/[\s,;]+/) + .map(code => this.normalizeSnCode(code)) + .filter(Boolean); + } + + /** + * 归一化订单明细主键,统一为字符串键,避免数字/字符串混用导致分组错乱。 + * @param {*} rawItemKey 明细ID原始值。 + * @return {string} 明细ID键,非法返回空串。 + */ + normalizeSnItemKey(rawItemKey) { + return this.normalizeSnStockKey(rawItemKey); + } + + /** + * 归一化仓库商品ID(stock_id)键,统一为字符串键。 + * @param {*} rawStockKey 仓库商品ID原始值。 + * @return {string} 仓库商品ID键,非法返回空串。 + */ + normalizeSnStockKey(rawStockKey) { + if (rawStockKey === undefined || rawStockKey === null) { + return ''; + } + const stockKey = String(rawStockKey).trim(); + if (!stockKey) { + return ''; + } + return /^\d+$/.test(stockKey) ? String(Number(stockKey)) : stockKey; + } + + /** + * 统计按明细分组的 SN 总数。 + * @param {Map} codesByItem 按明细分组的 SN。 + * @return {number} SN 总数。 + */ + countSnCodes(codesByItem) { + let total = 0; + for (const codes of codesByItem.values()) { + total += codes.length; + } + return total; + } + + /** + * 读取订单明细。 + * @param {number} orderId 订单ID。 + * @param {number} warehouseId 仓库ID。 + * @param {Object} [transaction] Sequelize 事务。 + * @return {Promise} 订单明细列表。 + */ + async loadOrderItemsForSn(orderId, warehouseId, transaction) { + const orderItemsModel = await this.getOrderItemsModelByTableType('current', warehouseId); + const rows = await orderItemsModel.findAll({ + where: { order_id: orderId }, + attributes: [ 'id', 'stock_id', 'item_code', 'item_name', 'plan_qty' ], + order: [[ 'id', 'ASC' ]], + raw: true, + transaction, + }); + + return Array.isArray(rows) ? rows : []; + } + + /** + * 读取明细对应商品的序列号管理标记,返回序列号管理商品ID集合。 + * @param {Object[]} items 订单明细。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 启用了序列号管理的仓库商品ID集合。 + */ + async loadSnStockIdSet(items, warehouseId) { + const { ctx } = this; + const snStockIdSet = new Set(); + const stockIds = [ ...new Set( + (items || []).map(item => Number(item.stock_id)).filter(id => Number.isInteger(id) && id > 0) + ) ]; + + if (stockIds.length === 0) { + return snStockIdSet; + } + + const stockModel = ctx.model && ctx.model.StockWarehouse; + if (!stockModel) { + throw new Error('商品仓库模型不存在,无法校验SN码'); + } + + const { Op } = this.app.Sequelize; + // paranoid:false 保证商品被软删后仍能读到 is_sn_mgmt,避免历史订单无法校验 SN + const stockRows = await stockModel.findAll({ + where: { + id: { [Op.in]: stockIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'is_sn_mgmt' ], + raw: true, + paranoid: false, + }); + + for (const row of (stockRows || [])) { + if (String(row.is_sn_mgmt || '').trim().toUpperCase() !== 'Y') { + continue; + } + const stockId = Number(row.id); + if (Number.isInteger(stockId) && stockId > 0) { + snStockIdSet.add(stockId); + } + } + + return snStockIdSet; + } + + /** + * 按序列号管理商品(stock_id)聚合订单明细。 + * @param {Object[]} items 订单明细。 + * @param {Set} snStockIdSet 序列号管理商品ID集合。 + * @return {Map} 仓库商品ID键 -> 该商品的订单明细(按明细ID升序)。 + */ + buildSnStockItemMap(items, snStockIdSet) { + const stockItemMap = new Map(); + const sortedItems = (Array.isArray(items) ? items : []) + .slice() + .sort((a, b) => Number(a && a.id || 0) - Number(b && b.id || 0)); + + for (const item of sortedItems) { + if (!snStockIdSet || !snStockIdSet.has(Number(item && item.stock_id))) { + continue; + } + const stockKey = this.normalizeSnStockKey(item.stock_id); + if (!stockKey) { + continue; + } + if (!stockItemMap.has(stockKey)) { + stockItemMap.set(stockKey, []); + } + stockItemMap.get(stockKey).push(item); + } + + return stockItemMap; + } + + /** + * 校验提交的 SN 是否按商品齐套。 + * @param {Object} params 参数。 + * @param {Map} params.stockItemMap 序列号管理商品 -> 明细。 + * @param {Map} params.codesByStock 提交的 SN(商品ID -> SN 列表)。 + */ + assertSnStockCodesMatched({ stockItemMap, codesByStock }) { + for (const [ stockKey, codes ] of codesByStock.entries()) { + const items = stockItemMap.get(stockKey); + if (!items || items.length === 0) { + throw new Error(`提交的SN码对应商品不在订单中或未启用序列号管理:stock_id=${stockKey}`); + } + const label = this.buildSnItemLabel(items[0]); + const requiredQty = this.sumSnItemPlanQty(items); + if (requiredQty <= 0) { + throw new Error(`商品[${label}]数量异常,无法校验SN码`); + } + if (codes.length !== requiredQty) { + throw new Error(`商品[${label}]需提交${requiredQty}个SN码,实际提交${codes.length}个`); + } + } + + for (const [ stockKey, items ] of stockItemMap.entries()) { + if (codesByStock.has(stockKey)) { + continue; + } + const requiredQty = this.sumSnItemPlanQty(items); + // 数量为 0 的序列号商品不需要提交 SN,避免历史脏数据阻塞复核 + if (requiredQty <= 0) { + continue; + } + throw new Error( + `商品[${this.buildSnItemLabel(items[0])}]需提交${requiredQty}个SN码,实际提交0个` + ); + } + } + + /** + * 汇总同一商品下所有明细的 plan_qty(仅统计合法正整数)。 + * @param {Object[]} items 同一商品的订单明细。 + * @return {number} 需要的 SN 总数。 + */ + sumSnItemPlanQty(items) { + let total = 0; + for (const item of (Array.isArray(items) ? items : [])) { + const planQty = Number(item && item.plan_qty); + if (Number.isInteger(planQty) && planQty > 0) { + total += planQty; + } + } + return total; + } + + /** + * 把「商品 -> SN 列表」按明细 plan_qty 顺序拆分到具体订单明细,供落库使用。 + * @param {Object} params 参数。 + * @param {Map} params.stockItemMap 序列号管理商品 -> 明细。 + * @param {Map} params.codesByStock 提交的 SN(商品ID -> SN 列表)。 + * @return {Map} 订单明细ID键 -> SN 列表。 + */ + mapStockCodesToOrderItems({ stockItemMap, codesByStock }) { + const codesByItem = new Map(); + + for (const [ stockKey, codes ] of codesByStock.entries()) { + const items = stockItemMap.get(stockKey) || []; + let cursor = 0; + + for (const item of items) { + const planQty = Number(item && item.plan_qty); + if (!Number.isInteger(planQty) || planQty <= 0) { + continue; + } + const itemCodes = codes.slice(cursor, cursor + planQty); + cursor += planQty; + if (itemCodes.length === 0) { + continue; + } + const itemKey = this.normalizeSnItemKey(item.id); + if (!itemKey) { + continue; + } + codesByItem.set(itemKey, itemCodes); + } + + if (cursor < codes.length) { + const tailItem = items[items.length - 1]; + const tailKey = tailItem ? this.normalizeSnItemKey(tailItem.id) : ''; + if (tailKey) { + const merged = (codesByItem.get(tailKey) || []).concat(codes.slice(cursor)); + codesByItem.set(tailKey, merged); + } + } + } + + return codesByItem; + } + + /** + * 校验同一批提交内 SN 不重复。 + * @param {string[]} allCodes 全部 SN。 + */ + assertSnCodesUnique(allCodes) { + const seen = new Set(); + const duplicated = new Set(); + for (const code of allCodes) { + if (seen.has(code)) { + duplicated.add(code); + } + seen.add(code); + } + if (duplicated.size > 0) { + const sample = Array.from(duplicated).slice(0, 5).join('、'); + throw new Error(`SN码重复提交:${sample}`); + } + } + + /** + * 生成明细展示文案,优先商品编码 + 名称。 + * @param {Object} item 订单明细。 + * @return {string} 展示文案。 + */ + buildSnItemLabel(item = {}) { + const code = String(item.item_code || '').trim(); + const name = String(item.item_name || '').trim(); + if (code && name) { + return `${code} ${name}`; + } + return code || name || String(item.id || ''); + } + + /** + * 校验 SN 是否已发过并写入 SN 主表与流水表。 + * @param {Object} params 参数。 + * @param {number} params.orderId 订单ID。 + * @param {number} params.warehouseId 仓库ID。 + * @param {number} [params.storeId] 货主ID(从订单冗余写入,便于按货主隔离查询)。 + * @param {Map} params.codesByItem 按明细分组的 SN。 + * @param {string[]} params.allCodes 全部 SN。 + * @param {Object} [params.operator] 操作人。 + * @param {Date} params.now 复核时间。 + * @param {Object} [params.transaction] Sequelize 事务。 + * @return {Promise<{ createdCount: number, reusedCount: number }>} 新增写入数与此前已绑定同明细的幂等复用数。 + */ + async persistRecheckSn({ orderId, warehouseId, storeId = 0, codesByItem, allCodes, operator = {}, now = new Date(), transaction }) { + const { ctx } = this; + const { Op } = this.app.Sequelize; + const orderItemSnModel = ctx.model && ctx.model.OrderItemSn; + const orderItemSnLogModel = ctx.model && ctx.model.OrderItemSnLog; + + if (!orderItemSnModel || !orderItemSnLogModel) { + throw new Error('订单SN模型不存在,无法写入SN码'); + } + + const itemIdByCode = new Map(); + for (const [ itemKey, codes ] of codesByItem.entries()) { + for (const code of codes) { + itemIdByCode.set(code, Number(itemKey)); + } + } + + const lockOption = transaction && transaction.LOCK ? { lock: transaction.LOCK.UPDATE } : {}; + const existingRows = await orderItemSnModel.findAll({ + where: { + warehouse_id: warehouseId, + sn_code: { [Op.in]: allCodes }, + }, + attributes: [ 'id', 'order_id', 'order_item_id', 'sn_code', 'sn_status' ], + raw: true, + ...lockOption, + transaction, + }); + + const existingByCode = new Map(); + for (const row of existingRows || []) { + existingByCode.set(String(row.sn_code), row); + } + + const createRows = []; + const upgradeRows = []; + let reusedCount = 0; + + for (const code of allCodes) { + const existing = existingByCode.get(code); + if (!existing) { + createRows.push(code); + continue; + } + + const sameOrder = Number(existing.order_id) === orderId; + const sameItem = Number(existing.order_item_id) === Number(itemIdByCode.get(code)); + const existingStatus = String(existing.sn_status || '').trim().toUpperCase(); + + if (!sameOrder || !sameItem) { + throw new Error(`SN码[${code}]已被其他订单占用,不可重复使用`); + } + if (existingStatus === SN_STATUS_VERIFIED) { + reusedCount += 1; + continue; + } + if (existingStatus === SN_STATUS_BOUND) { + upgradeRows.push(existing); + continue; + } + throw new Error(`SN码[${code}]状态为${existingStatus || 'UNKNOWN'},不可用于当前订单复核`); + } + + const createCodeSet = new Set(createRows); + await this.assertSnCodesNotShipped({ + warehouseId, + allCodes: allCodes.filter(code => createCodeSet.has(code)), + orderId, + transaction, + }); + + const normalizedStoreId = Number(storeId) > 0 ? Number(storeId) : null; + const createdRows = []; + if (createRows.length > 0) { + const payload = createRows.map(code => ({ + warehouse_id: warehouseId, + store_id: normalizedStoreId, + order_id: orderId, + order_item_id: itemIdByCode.get(code), + sn_code: code, + sn_status: SN_STATUS_VERIFIED, + verify_status: VERIFY_STATUS_PASS, + bound_at: now, + verified_at: now, + version: 1, + created_at: now, + updated_at: now, + })); + + let instances; + try { + instances = await orderItemSnModel.bulkCreate(payload, { transaction }); + } catch (error) { + if (this.isDuplicateKeyError(error)) { + throw new Error('SN码已被占用,请核对后重新提交'); + } + throw error; + } + + for (const instance of instances || []) { + createdRows.push({ + sn_id: instance.id, + order_item_id: Number(instance.order_item_id), + sn_code: String(instance.sn_code), + }); + } + } + + if (upgradeRows.length > 0) { + await orderItemSnModel.update({ + sn_status: SN_STATUS_VERIFIED, + verify_status: VERIFY_STATUS_PASS, + verified_at: now, + updated_at: now, + version: this.app.Sequelize.literal('version + 1'), + ...(normalizedStoreId !== null && { store_id: normalizedStoreId }), + }, { + where: { id: { [Op.in]: upgradeRows.map(row => row.id) } }, + transaction, + }); + } + + const operatorId = this.normalizeSnOperatorId(operator); + const logRows = [ + ...createdRows.map(row => ({ + warehouse_id: warehouseId, + sn_id: row.sn_id, + order_id: orderId, + order_item_id: row.order_item_id, + sn_code: row.sn_code, + from_sn_status: null, + to_sn_status: SN_STATUS_VERIFIED, + verify_status: VERIFY_STATUS_PASS, + action_type: RECHECK_LOG_ACTION, + remark: '复核提交SN核验', + operator_id: operatorId, + operated_at: now, + created_at: now, + updated_at: now, + })), + ...upgradeRows.map(row => ({ + warehouse_id: warehouseId, + sn_id: row.id, + order_id: orderId, + order_item_id: Number(row.order_item_id), + sn_code: String(row.sn_code), + from_sn_status: SN_STATUS_BOUND, + to_sn_status: SN_STATUS_VERIFIED, + verify_status: VERIFY_STATUS_PASS, + action_type: RECHECK_LOG_ACTION, + remark: '复核提交SN核验', + operator_id: operatorId, + operated_at: now, + created_at: now, + updated_at: now, + })), + ]; + + if (logRows.length > 0) { + await orderItemSnLogModel.bulkCreate(logRows, { transaction }); + } + + return { createdCount: createdRows.length, reusedCount }; + } + + /** + * 校验 SN 是否已经随其它订单发出(流水存在 VERIFIED/REISSUED 记录)。 + * @param {Object} params 参数。 + * @param {number} params.warehouseId 仓库ID。 + * @param {string[]} params.allCodes 待校验 SN。 + * @param {number} params.orderId 当前订单ID。 + * @param {Object} [params.transaction] Sequelize 事务。 + * @return {Promise} 无返回值,命中已发货 SN 时抛错。 + */ + async assertSnCodesNotShipped({ warehouseId, allCodes, orderId, transaction }) { + if (!Array.isArray(allCodes) || allCodes.length === 0) { + return; + } + + const { ctx } = this; + const { Op } = this.app.Sequelize; + const orderItemSnLogModel = ctx.model && ctx.model.OrderItemSnLog; + if (!orderItemSnLogModel) { + throw new Error('订单SN流水模型不存在,无法校验SN码'); + } + + const shippedLogs = await orderItemSnLogModel.findAll({ + where: { + warehouse_id: warehouseId, + sn_code: { [Op.in]: allCodes }, + to_sn_status: { [Op.in]: SHIPPED_SN_STATUS_LIST }, + order_id: { [Op.ne]: orderId }, + }, + attributes: [ 'sn_code', 'order_id', 'to_sn_status' ], + raw: true, + transaction, + }); + + if (Array.isArray(shippedLogs) && shippedLogs.length > 0) { + const first = shippedLogs[0]; + throw new Error( + `SN码[${first.sn_code}]已随订单[${first.order_id}]发货,不可重复使用` + ); + } + } + + /** + * 归一化操作人ID,非数字操作人(如 system)落空,避免 BIGINT 写入失败。 + * @param {Object} operator 操作人。 + * @return {number|null} 操作人ID。 + */ + normalizeSnOperatorId(operator = {}) { + const rawId = String(operator && operator.id || '').trim(); + if (!/^\d+$/.test(rawId)) { + return null; + } + const parsed = Number(rawId); + return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null; + } + + /** + * 判断是否唯一键冲突错误。 + * @param {Object} error 错误对象。 + * @return {boolean} 是否唯一键冲突。 + */ + isDuplicateKeyError(error) { + if (!error) { + return false; + } + if (error.name === 'SequelizeUniqueConstraintError') { + return true; + } + return Boolean(error.parent && error.parent.code === 'ER_DUP_ENTRY'); + } +} + +module.exports = OrderItemSnService; diff --git a/app/service/systems/order_storage_allocation.js b/app/service/systems/order_storage_allocation.js index b40988f..b40734c 100644 --- a/app/service/systems/order_storage_allocation.js +++ b/app/service/systems/order_storage_allocation.js @@ -10,6 +10,8 @@ const STORAGE_STATUS_ERROR = 'error'; const ORDER_STATUS_CANCEL = 'cancel'; const ORDER_STEP_EXCEPTION = 3; const ALLOCATION_LOG_SAMPLE_LIMIT = 20; +/** SN 状态中代表「已随订单发出」的集合(复核提交后写入 VERIFIED) */ +const SN_SHIPPED_STATUS_SET = new Set([ 'VERIFIED', 'REISSUED' ]); /** * 规范化块状日志的输出值。 @@ -1659,6 +1661,10 @@ class OrderStorageAllocationService extends MainService { * `orderAsync.syncQmOrders`、`orderAsync.syncManualOrders`、`orderAsync.syncApiOrders`、 * `orderAsync.syncStockoutOrders` 四个处理入口。 * + * SN(序列号管理)订单不做无差别拦截:仅当「SN 明细未齐套(每个序列号明细的已发出 SN 数量 + * 少于 plan_qty)」或「订单未复核完成」时才拦截(failed_reason=sn_batch_forbidden); + * 齐套且已复核的 SN 订单与普通订单一样参与回传。 + * * @param {Object} data 请求体。 * @return {Promise} 同步结果。 */ @@ -1666,7 +1672,7 @@ class OrderStorageAllocationService extends MainService { const { ctx } = this; const unallocatedPostStatus = 'none'; const fastFailReason = '快递状态未分配,禁止同步'; - const snBatchForbiddenReason = 'SN订单不支持批量回传,请改用单订单回传'; + const snBatchForbiddenReason = 'SN订单SN明细未齐套或未复核完成,不允许回传'; const requestData = data && typeof data === 'object' ? data : {}; const normalizeNumber = (value, defaultValue = 0) => { const numericValue = Number(value); @@ -1825,13 +1831,17 @@ class OrderStorageAllocationService extends MainService { orderMap.set(Number(plainOrder.id), plainOrder); } - // SN 管理订单不允许走批量回传:通过订单明细 stock_id 反查 stock_warehouse.is_sn_mgmt。 + // SN(序列号管理)订单回传前置校验:通过订单明细 stock_id 反查 stock_warehouse.is_sn_mgmt, + // 只有「每个序列号明细的 SN 数量齐套」且「订单已复核」时才允许回传; + // 齐套但未复核、或已复核但 SN 未齐套,一律标记快速失败,避免把缺 SN 的发货单回传平台。 const snOrderIdSet = new Set(); + const snBlockedOrderIdSet = new Set(); const existingOrderIds = Array.from(orderMap.keys()); if (existingOrderIds.length > 0) { try { const orderItemModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); const stockModel = ctx.model.StockWarehouse; + const orderItemSnModel = ctx.model.OrderItemSn; if (orderItemModel && typeof orderItemModel.findAll === 'function' && stockModel && typeof stockModel.findAll === 'function') { const orderItemRows = await orderItemModel.findAll({ @@ -1840,7 +1850,7 @@ class OrderStorageAllocationService extends MainService { [ctx.app.Sequelize.Op.in]: existingOrderIds, }, }, - attributes: [ 'order_id', 'stock_id' ], + attributes: [ 'id', 'order_id', 'stock_id', 'plan_qty' ], raw: true, }); @@ -1865,11 +1875,88 @@ class OrderStorageAllocationService extends MainService { .map(row => Number(row && row.id || 0)) .filter(stockId => Number.isFinite(stockId) && stockId > 0)); + // 订单 -> 序列号明细(order_item_id + plan_qty) + const snItemsByOrderId = new Map(); for (const row of (Array.isArray(orderItemRows) ? orderItemRows : [])) { const orderId = Number(row && row.order_id || 0); const stockId = Number(row && row.stock_id || 0); - if (snStockIdSet.has(stockId) && orderId > 0) { - snOrderIdSet.add(orderId); + if (!snStockIdSet.has(stockId) || orderId <= 0) { + continue; + } + + snOrderIdSet.add(orderId); + if (!snItemsByOrderId.has(orderId)) { + snItemsByOrderId.set(orderId, []); + } + snItemsByOrderId.get(orderId).push({ + order_item_id: Number(row && row.id || 0), + plan_qty: Number(row && row.plan_qty || 0), + }); + } + + if (snOrderIdSet.size > 0) { + const snModelAvailable = Boolean(orderItemSnModel) + && typeof orderItemSnModel.findAll === 'function'; + + // 明细 -> 已发出的 SN 编码集合(去重,避免重复录入被重复计数) + const shippedSnCodeMap = new Map(); + if (snModelAvailable) { + const snRows = await orderItemSnModel.findAll({ + where: { + warehouse_id: warehouseId, + order_id: { + [ctx.app.Sequelize.Op.in]: Array.from(snOrderIdSet), + }, + }, + attributes: [ 'order_id', 'order_item_id', 'sn_code', 'sn_status' ], + raw: true, + }); + + for (const row of (Array.isArray(snRows) ? snRows : [])) { + const snStatus = String(row && row.sn_status || '').trim().toUpperCase(); + if (!SN_SHIPPED_STATUS_SET.has(snStatus)) { + continue; + } + const itemKey = `${Number(row && row.order_id || 0)}:${Number(row && row.order_item_id || 0)}`; + if (!shippedSnCodeMap.has(itemKey)) { + shippedSnCodeMap.set(itemKey, new Set()); + } + const snCode = String(row && row.sn_code || '').trim(); + if (snCode) { + shippedSnCodeMap.get(itemKey).add(snCode); + } + } + } else { + ctx.logger.warn('[OrderStorageAllocationService.syncOrderIds] 订单SN模型不可用,SN订单将全部拦截', { + warehouseId, + snOrderIds: Array.from(snOrderIdSet), + }); + } + + for (const orderId of snOrderIdSet) { + const orderRow = orderMap.get(orderId) || {}; + const rechecked = String(orderRow.recheck_status || '').trim() === 'fin'; + const snItems = snItemsByOrderId.get(orderId) || []; + let snCompleted = snModelAvailable; + + if (snCompleted) { + for (const item of snItems) { + // plan_qty 非正整数(脏数据/赠品 0 数量)不参与齐套判定 + if (!Number.isInteger(item.plan_qty) || item.plan_qty <= 0) { + continue; + } + const codes = shippedSnCodeMap.get(`${orderId}:${item.order_item_id}`); + const codeCount = codes ? codes.size : 0; + if (codeCount < item.plan_qty) { + snCompleted = false; + break; + } + } + } + + if (!rechecked || !snCompleted) { + snBlockedOrderIdSet.add(orderId); + } } } } @@ -1910,8 +1997,8 @@ class OrderStorageAllocationService extends MainService { continue; } - // SN 管理订单不允许走批量回传,标记为跳过,不阻断其他订单 - if (snOrderIdSet.has(orderId)) { + // SN 订单仅在「SN 明细未齐套」或「未复核完成」时拦截,齐套且已复核允许回传 + if (snBlockedOrderIdSet.has(orderId)) { fastFailedOrders.push({ order_id: orderId, status: 'failed', diff --git a/app/service/systems/sn_code_rule.js b/app/service/systems/sn_code_rule.js new file mode 100644 index 0000000..750bd0a --- /dev/null +++ b/app/service/systems/sn_code_rule.js @@ -0,0 +1,235 @@ +'use strict'; + +const Service = require('egg').Service; + +/** 单条 SN 码规则的匹配位置:前缀 */ +const MATCH_TYPE_PREFIX = 'prefix'; +/** 单条 SN 码规则的匹配位置:后缀 */ +const MATCH_TYPE_SUFFIX = 'suffix'; +/** 单条 SN 码规则的处理方式:整个扫码内容作为 SN 码 */ +const KEEP_MODE_FULL = 'full'; +/** 单条 SN 码规则的处理方式:去掉匹配到的前缀/后缀后作为 SN 码 */ +const KEEP_MODE_STRIP = 'strip'; + +const MATCH_TYPE_SET = new Set([ MATCH_TYPE_PREFIX, MATCH_TYPE_SUFFIX ]); +const KEEP_MODE_SET = new Set([ KEEP_MODE_FULL, KEEP_MODE_STRIP ]); +/** 单个商品最多可配置的 SN 码规则条数 */ +const MAX_RULE_COUNT = 20; +/** 前缀/后缀字符串最大长度 */ +const MAX_MATCH_VALUE_LENGTH = 64; +/** 扫码内容(用于匹配校验)最大长度,与 wms_order_item_sn.sn_code 的 VARCHAR(512) 对齐 */ +const MAX_SN_CODE_LENGTH = 512; + +/** + * 商品 SN 码规则服务。 + * + * 规则用于把「扫到的码」加工成真正入库的 SN 码,一条规则三步: + * 1. match_type:匹配位置,prefix=前缀 / suffix=后缀; + * 2. match_value:要匹配的前缀或后缀字符串; + * 3. keep_mode:full=整个扫码内容作为 SN 码 / strip=去掉匹配到的前缀或后缀后再作为 SN 码。 + * + * 存储形如: + * [{ "match_type": "prefix", "match_value": "YGP", "keep_mode": "strip" }] + * 多条规则按数组顺序匹配,命中第一条即生效。 + */ +class SnCodeRuleService extends Service { + /** + * 推断单条规则字段在其它调用处的可用性(供外部判断常量使用)。 + * @return {Object} 规则常量。 + */ + getConstants() { + return { + matchTypes: [ MATCH_TYPE_PREFIX, MATCH_TYPE_SUFFIX ], + keepModes: [ KEEP_MODE_FULL, KEEP_MODE_STRIP ], + maxRuleCount: MAX_RULE_COUNT, + maxMatchValueLength: MAX_MATCH_VALUE_LENGTH, + }; + } + + /** + * 把任意来源的规则内容解析为数组(不做元素合法性校验)。 + * 兼容 JSON 字符串、数组、null/undefined;其它类型抛错。 + * + * @param {*} rawRules 原始规则内容。 + * @return {Object[]} 规则数组(未逐条校验)。 + */ + parseRules(rawRules) { + if (rawRules === undefined || rawRules === null) { + return []; + } + if (Array.isArray(rawRules)) { + return rawRules; + } + if (typeof rawRules === 'string') { + const text = rawRules.trim(); + if (!text) { + return []; + } + let parsed; + try { + parsed = JSON.parse(text); + } catch { + throw new Error('SN码规则格式不正确,必须是合法的 JSON 数组'); + } + if (!Array.isArray(parsed)) { + throw new Error('SN码规则格式不正确,必须是数组'); + } + return parsed; + } + throw new Error('SN码规则格式不正确,必须是数组'); + } + + /** + * 读取并校验规则;非法内容返回空数组,用于查询回显(不抛错)。 + * + * @param {*} rawRules 原始规则内容(数据库列值)。 + * @return {Object[]} 规范化后的规则数组。 + */ + toRuleList(rawRules) { + try { + return this.normalizeRules(rawRules); + } catch { + return []; + } + } + + /** + * 校验并规范化保存入参中的 SN 码规则。 + * + * @param {*} rawRules 前端传入的规则(数组或 JSON 字符串),支持 match_type/matchType 等写法。 + * @return {Object[]} 规范化后的规则数组:{ match_type, match_value, keep_mode }。 + */ + normalizeRules(rawRules) { + const parsed = this.parseRules(rawRules); + if (parsed.length > MAX_RULE_COUNT) { + throw new Error(`SN码规则最多配置${MAX_RULE_COUNT}条`); + } + + const normalized = []; + const seenKeys = new Set(); + + parsed.forEach((rawRule, index) => { + const position = index + 1; + const rule = this.isPlainObject(rawRule) ? rawRule : null; + if (!rule) { + throw new Error(`第${position}条SN码规则格式不正确,必须是对象`); + } + + const matchType = this.normalizeMatchType(rule.match_type ?? rule.matchType ?? rule.type); + if (!matchType) { + throw new Error(`第${position}条SN码规则的匹配位置(match_type)只能是 prefix(前缀)或 suffix(后缀)`); + } + + const matchValue = this.normalizeMatchValue(rule.match_value ?? rule.matchValue ?? rule.value); + if (!matchValue) { + throw new Error(`第${position}条SN码规则的匹配内容(match_value)不能为空`); + } + if (matchValue.length > MAX_MATCH_VALUE_LENGTH) { + throw new Error(`第${position}条SN码规则的匹配内容(match_value)长度不能超过${MAX_MATCH_VALUE_LENGTH}个字符`); + } + + const keepMode = this.normalizeKeepMode(rule.keep_mode ?? rule.keepMode ?? rule.mode); + if (!keepMode) { + throw new Error(`第${position}条SN码规则的处理方式(keep_mode)只能是 full(全码)或 strip(去掉前缀/后缀)`); + } + + const uniqueKey = `${matchType}|${matchValue}|${keepMode}`; + if (seenKeys.has(uniqueKey)) { + throw new Error(`第${position}条SN码规则与前面的规则重复:${matchType}「${matchValue}」${keepMode}`); + } + seenKeys.add(uniqueKey); + + normalized.push({ + match_type: matchType, + match_value: matchValue, + keep_mode: keepMode, + }); + }); + + return normalized; + } + + /** + * 按规则把扫码内容加工成 SN 码;未命中任何规则时返回原码。 + * + * @param {string} rawCode 扫码内容。 + * @param {Object[]} rules 已规范化的规则数组。 + * @return {{ matched: boolean, rule: Object|null, sn_code: string, reason?: string }} 匹配结果。 + */ + matchSnCode(rawCode, rules = []) { + const code = String(rawCode === undefined || rawCode === null ? '' : rawCode).trim(); + if (!code) { + return { matched: false, rule: null, sn_code: '', reason: 'empty_code' }; + } + if (code.length > MAX_SN_CODE_LENGTH) { + return { matched: false, rule: null, sn_code: code, reason: 'code_too_long' }; + } + + const ruleList = this.toRuleList(rules); + for (const rule of ruleList) { + if (rule.match_type === MATCH_TYPE_PREFIX && !code.startsWith(rule.match_value)) { + continue; + } + if (rule.match_type === MATCH_TYPE_SUFFIX && !code.endsWith(rule.match_value)) { + continue; + } + + let snCode = code; + if (rule.keep_mode === KEEP_MODE_STRIP) { + const start = rule.match_type === MATCH_TYPE_PREFIX ? rule.match_value.length : 0; + const end = rule.match_type === MATCH_TYPE_SUFFIX ? code.length - rule.match_value.length : code.length; + snCode = code.slice(start, end); + } + + if (!snCode) { + return { matched: true, rule, sn_code: '', reason: 'empty_after_strip' }; + } + return { matched: true, rule, sn_code: snCode }; + } + + return { matched: false, rule: null, sn_code: code }; + } + + /** + * 规范化匹配位置。 + * @param {*} rawValue 原始值。 + * @return {string} 'prefix' / 'suffix',非法返回空串。 + */ + normalizeMatchType(rawValue) { + const value = String(rawValue === undefined || rawValue === null ? '' : rawValue).trim().toLowerCase(); + return MATCH_TYPE_SET.has(value) ? value : ''; + } + + /** + * 规范化处理方式。 + * @param {*} rawValue 原始值。 + * @return {string} 'full' / 'strip',非法返回空串。 + */ + normalizeKeepMode(rawValue) { + const value = String(rawValue === undefined || rawValue === null ? '' : rawValue).trim().toLowerCase(); + return KEEP_MODE_SET.has(value) ? value : ''; + } + + /** + * 清洗前缀/后缀字符串:去首尾空白,把 undefined/null 转空串。 + * @param {*} rawValue 原始值。 + * @return {string} 清洗后的字符串。 + */ + normalizeMatchValue(rawValue) { + if (rawValue === undefined || rawValue === null) { + return ''; + } + return String(rawValue).trim(); + } + + /** + * 判断是否普通对象。 + * @param {*} value 待判断值。 + * @return {boolean} 是否普通对象。 + */ + isPlainObject(value) { + return Object.prototype.toString.call(value) === '[object Object]'; + } +} + +module.exports = SnCodeRuleService; diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index ad8c5c1..09c2880 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -3086,7 +3086,7 @@ class stockStoreService extends Service { */ async getInfo(data) { const { - ctx, + ctx, service, } = this; const { id, @@ -3106,6 +3106,7 @@ class stockStoreService extends Service { 'is_batch_mgmt', 'is_shelf_life_mgmt', 'is_sn_mgmt', + 'sn_code_rules', 'need_recheck', 'goods_code', 'item_code', @@ -3142,6 +3143,8 @@ class stockStoreService extends Service { raw: true, }); stock.enable_box_spec = !!stock.enable_box_spec; + // SN 码规则统一输出为数组(兼容数据库 JSON 列返回字符串的情况) + stock.sn_code_rules = service.systems.snCodeRule.toRuleList(stock.sn_code_rules); // 要求合并开关归一化(默认合并);合并时拣货/复核要求统一用打包要求覆盖输出 stock.packing_requirements = stock.packing_requirements || ''; stock.merge_requirements = stock.merge_requirements || 'Y'; @@ -3176,6 +3179,7 @@ class stockStoreService extends Service { shelf_life_days, inbound_min_days, outbound_min_days, remaining_threshold_days, need_recheck, warning_quantity, + sn_code_rules, snCodeRules, } = data; const normalizedVolume = volume ?? volume_cm3 ?? volumeCm3; const normalizedBoxVolume = box_volume ?? box_volume_m3 ?? boxVolumeM3; @@ -3183,6 +3187,12 @@ class stockStoreService extends Service { // 1. 参数验证 this.validateSaveParams(data); + // SN 码规则:仅当入参显式带了字段时才更新(支持传 [] 清空),格式非法直接报错 + const rawSnCodeRules = sn_code_rules !== undefined ? sn_code_rules : snCodeRules; + const normalizedSnCodeRules = rawSnCodeRules === undefined + ? undefined + : service.systems.snCodeRule.normalizeRules(rawSnCodeRules); + if (is_shelf_life_mgmt === 'Y') { const shelfLifeFields = [ [ 'shelf_life_days', shelf_life_days ], @@ -3270,6 +3280,7 @@ class stockStoreService extends Service { outbound_min_days, remaining_threshold_days, warning_quantity, + ...(normalizedSnCodeRules !== undefined && { sn_code_rules: normalizedSnCodeRules }), updated_at: new Date(), }; // 5. 清除空值 @@ -3346,10 +3357,16 @@ class stockStoreService extends Service { box_width, box_height, box_volume, box_remark, need_recheck, warning_quantity, + sn_code_rules, snCodeRules, } = data; // 1. 参数验证 this.validateSaveParams(data, false); + // SN 码规则:创建时未传则存空数组 + const rawSnCodeRules = sn_code_rules !== undefined ? sn_code_rules : snCodeRules; + const normalizedSnCodeRules = rawSnCodeRules === undefined + ? [] + : service.systems.snCodeRule.normalizeRules(rawSnCodeRules); let checkItemCodeUnique = {}; try { checkItemCodeUnique = await this.checkItemCodeUnique(null, item_code, store_id, warehouseId); @@ -3400,6 +3417,7 @@ class stockStoreService extends Service { box_height, box_volume, box_remark, + sn_code_rules: normalizedSnCodeRules, updated_at: new Date(), }; const transaction = await ctx.model.transaction(); diff --git a/app/service/systems/storage/report.js b/app/service/systems/storage/report.js index 333e83e..12abc58 100644 --- a/app/service/systems/storage/report.js +++ b/app/service/systems/storage/report.js @@ -6,6 +6,10 @@ const path = require('path'); const Service = require('egg').Service; const ExcelJS = require('exceljs'); +// 发货单分表表位顺序(兜底扫描用)与物理表名白名单:wms_order_delivery_{warehouseId}[_dispatch|_history|_outsourced] +const DELIVERY_SHARD_TABLE_TYPES = [ 'current', 'dispatch', 'history', 'outsourced' ]; +const SHARD_DELIVERY_TABLE_PATTERN = /^wms_order_delivery_\d+(_dispatch|_history|_outsourced)?$/; + /** * 将输入转换为时间戳。 * @param {string|Date|number|null|undefined} value 时间值 @@ -473,15 +477,7 @@ class StorageReportService extends Service { } ) : [], - normalizedOrderIds.length > 0 - ? ctx.model.query( - 'SELECT id, source_order_codes FROM wms_order_delivery WHERE id IN (:ids)', - { - replacements: { ids: normalizedOrderIds }, - type: app.Sequelize.QueryTypes.SELECT, - } - ) - : [], + this.loadOrderDeliveryRows(normalizedOrderIds, warehouseId, orderWarehouseMap), normalizedOrderIds.length > 0 ? (async () => { // 强制同仓校验:读取 wms_order_express 必须同时带订单ID与仓库ID, @@ -579,30 +575,155 @@ class StorageReportService extends Service { }; } + /** + * 读取发货单(配送)基础字段:delivery_order_code / source_order_codes。 + * 发货单按仓库分表,单体表 wms_order_delivery 在分表环境下为空;因此先按仓库查询 + * 订单位置索引表 wms_order_id_location_{仓库} 取得 location(current/dispatch/history/outsourced), + * 直达对应分表取值;索引缺失(存量未回填)或指针失效时,退回逐表位扫描。 + * @param {number[]} orderIds 订单ID列表 + * @param {number|null} warehouseId 仓库ID(仓库模式为当前仓库;货主模式为 null,按订单所属仓库分组) + * @param {Map|null} orderWarehouseMap 订单ID → 所属仓库ID(货主模式) + * @return {Promise>} 命中的发货单记录 + */ + async loadOrderDeliveryRows(orderIds = [], warehouseId = null, orderWarehouseMap = null) { + const { ctx, app } = this; + const normalizedOrderIds = [ ...new Set((orderIds || []).map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)) ]; + if (normalizedOrderIds.length === 0) { + return []; + } + + const factory = ctx.model && ctx.model.OrderDeliveryFactory; + const defaultWarehouseId = Number(warehouseId) > 0 ? Number(warehouseId) : 0; + + // 按仓库分组:货主模式优先用行所属仓库,缺失时回落仓库模式仓库ID + const idsByWarehouse = new Map(); + for (const orderId of normalizedOrderIds) { + const rowWarehouseId = orderWarehouseMap && typeof orderWarehouseMap.get === 'function' + ? Number(orderWarehouseMap.get(orderId)) + : 0; + const shardWarehouseId = rowWarehouseId > 0 ? rowWarehouseId : defaultWarehouseId; + if (shardWarehouseId <= 0) { + continue; + } + if (!idsByWarehouse.has(shardWarehouseId)) { + idsByWarehouse.set(shardWarehouseId, []); + } + idsByWarehouse.get(shardWarehouseId).push(orderId); + } + + /** + * 查询单个仓库分表,返回命中行与未命中的订单ID。 + * @param {number} shardWarehouseId 仓库ID + * @param {string} tableType 表位类型 + * @param {number[]} ids 订单ID列表 + * @return {Promise<{rows: Array, unresolvedIds: number[]}>} 查询结果 + */ + const queryShardTable = async (shardWarehouseId, tableType, ids) => { + const tableName = factory && typeof factory.generateTableName === 'function' + ? factory.generateTableName(shardWarehouseId, tableType) + : ''; + if (ids.length === 0 || !SHARD_DELIVERY_TABLE_PATTERN.test(String(tableName))) { + return { rows: [], unresolvedIds: ids }; + } + try { + const shardRows = await ctx.model.query( + `SELECT id, delivery_order_code, source_order_codes FROM ${tableName} WHERE id IN (:ids)`, + { + replacements: { ids }, + type: app.Sequelize.QueryTypes.SELECT, + } + ); + const safeRows = Array.isArray(shardRows) ? shardRows : []; + const foundIdSet = new Set(safeRows.map(row => Number(row.id))); + return { rows: safeRows, unresolvedIds: ids.filter(id => !foundIdSet.has(id)) }; + } catch (error) { + // 分表可能尚未创建:命中“表不存在”时静默跳过(回退流水单据号),其余异常告警后继续 + const isMissingTable = /ER_NO_SUCH_TABLE|doesn't exist|does not exist/i.test(String(error && error.message)); + if (!isMissingTable) { + ctx.logger.warn(`[loadOrderDeliveryRows] 查询 ${tableName} 失败,跳过该表位: ${error.message}`); + } + return { rows: [], unresolvedIds: ids }; + } + }; + + const rows = []; + for (const [ shardWarehouseId, warehouseOrderIds ] of idsByWarehouse) { + // 1) 位置索引表:orderId → location,命中时直达对应分表 + let locationMap = new Map(); + if (factory && typeof factory.getOrderLocations === 'function') { + try { + const resolvedLocations = await factory.getOrderLocations(warehouseOrderIds, shardWarehouseId); + if (resolvedLocations instanceof Map) { + locationMap = resolvedLocations; + } + } catch (error) { + ctx.logger.warn(`[loadOrderDeliveryRows] 查询订单位置索引失败,退回逐表位扫描: ${error.message}`); + } + } + + const idsByLocation = new Map(); + let unresolvedIds = []; + for (const orderId of warehouseOrderIds) { + const location = String(locationMap.get(orderId) || '').trim(); + if (DELIVERY_SHARD_TABLE_TYPES.includes(location)) { + if (!idsByLocation.has(location)) { + idsByLocation.set(location, []); + } + idsByLocation.get(location).push(orderId); + } else { + // 无位置记录(存量订单未回填索引) + unresolvedIds.push(orderId); + } + } + + for (const [ tableType, locationOrderIds ] of idsByLocation) { + const located = await queryShardTable(shardWarehouseId, tableType, locationOrderIds); + rows.push(...located.rows); + // 位置指针可能过期(订单已迁移但指针未更新),未命中的订单继续兜底 + unresolvedIds.push(...located.unresolvedIds); + } + + // 2) 兜底:无位置记录或指针失效时逐表位扫描 + for (const tableType of DELIVERY_SHARD_TABLE_TYPES) { + if (unresolvedIds.length === 0) { + break; + } + const scanned = await queryShardTable(shardWarehouseId, tableType, unresolvedIds); + rows.push(...scanned.rows); + unresolvedIds = scanned.unresolvedIds; + } + } + + return rows; + } + /** * 构建库存报表导出文件名。 * @param {string|Date|null|undefined} startTime 开始时间 * @param {string|Date|null|undefined} endTime 结束时间 + * @param {string|number} [uniqueToken=''] 唯一后缀:重复导出同一时间范围时避免同名对象覆盖、CDN 命中旧文件 * @return {string} 导出文件名 */ - buildExportFilename(startTime, endTime) { + buildExportFilename(startTime, endTime, uniqueToken = '') { const startToken = formatDateToken(startTime); const endToken = formatDateToken(endTime); const todayToken = formatDateToken(new Date()); + const normalizedToken = String(uniqueToken ?? '').trim(); + const suffix = normalizedToken ? `_${normalizedToken}` : ''; if (startToken && endToken) { - return `库存报表_${startToken}_${endToken}.xlsx`; + return `库存报表_${startToken}_${endToken}${suffix}.xlsx`; } if (startToken) { - return `库存报表_${startToken}.xlsx`; + return `库存报表_${startToken}${suffix}.xlsx`; } if (endToken) { - return `库存报表_${endToken}.xlsx`; + return `库存报表_${endToken}${suffix}.xlsx`; } - return `库存报表_${todayToken}.xlsx`; + return `库存报表_${todayToken}${suffix}.xlsx`; } /** @@ -799,7 +920,8 @@ class StorageReportService extends Service { // 明细游标分页:按主键 id 升序分批拉取(id 自增序≈插入序), // 流式写入 ExcelJS stream,避免一次性把全部明细与单元格留在内存。 const detailBatchSize = 5000; - const filename = this.buildExportFilename(startTime, endTime); + // 文件名带时间戳:同一时间范围重复导出会覆盖同名对象,CDN/浏览器会继续命中旧文件 + const filename = this.buildExportFilename(startTime, endTime, Date.now()); let tempDir = null; let workbook = null; let currentCount = 0; @@ -998,7 +1120,7 @@ class StorageReportService extends Service { batch_no: item.batch_no || '', inventory_type: item.inventory_type || '', order_type: item.order_type || '', - order_no: item.order_no || '', + order_no: String(orderDelivery.delivery_order_code || item.order_no || '').trim(), order_id: orderId, receiving_id: toNumber(item.receiving_id), entry_order_id: entryOrderId, diff --git a/app/service/systems/store_warehouse.js b/app/service/systems/store_warehouse.js index 59e0896..562a256 100644 --- a/app/service/systems/store_warehouse.js +++ b/app/service/systems/store_warehouse.js @@ -10,6 +10,10 @@ const Service = require('egg').Service; const { Op } = require('sequelize'); const SIGN_TEMP_EXPIRE_SECONDS = 600; +// 签约关系级接口配置统一按货主开放接口维护,仓库开放接口仅用于仓库级应用(apiApp 模块) +const CONTRACT_OPEN_API_CODE = 'OPEN_API'; +const WAREHOUSE_OPEN_API_CODE = 'OPEN_API_WAREHOUSE'; +const DEFAULT_CALLBACK_URL_MAX_LENGTH = 500; const AUTH_STATUS_LABELS = Object.freeze({ 1: '申请中', 2: '已通过', @@ -1102,6 +1106,74 @@ class SettingStoreWarehouseService extends Service { return this.getApiInterfaceType(data, options); } + /** + * 解析签约关系级接口类型。 + * + * 签约关系上的接口配置统一按货主开放接口(OPEN_API)落库: + * 传入仓库开放接口(OPEN_API_WAREHOUSE)时映射为货主开放接口,避免货主侧创建仓库接口。 + * + * @param {Object} [data={}] 请求参数。 + * @param {Object} [options={}] 选项。 + * @param {boolean} [options.allowDisabled=false] 是否允许禁用接口类型(查询过滤时可放宽)。 + * @param {Object|null} [options.transaction=null] 事务对象。 + * @return {Promise} 接口类型对象。 + * @throws {Error} 接口类型不存在(400/404)或缺失货主开放接口类型(404)时抛出。 + */ + async resolveContractApiInterfaceType(data = {}, options = {}) { + const { ctx } = this; + const { transaction = null, allowDisabled = false } = options; + const interfaceType = await this.getApiInterfaceType(data, { transaction, requireId: true, allowDisabled }); + if (interfaceType.interface_code !== WAREHOUSE_OPEN_API_CODE) { + return interfaceType; + } + + const storeInterfaceType = await ctx.model.InterfaceType.findOne({ + where: { + interface_code: CONTRACT_OPEN_API_CODE, + ...(allowDisabled ? {} : { is_enabled: 1 }), + }, + attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'is_enabled' ], + transaction, + }); + if (!storeInterfaceType) { + throw this.createError('未配置可用的货主开放接口类型', 404); + } + + ctx.logger.warn( + '[storeWarehouse.saveApiConfig] interface_type_id=%s 为仓库开放接口,签约关系级配置按货主开放接口(id=%s)落库', + interfaceType.id, + storeInterfaceType.id + ); + return storeInterfaceType; + } + + /** + * 获取签约关系级接口配置的默认回调地址。 + * + * 回调地址不由调用方传入,统一取 config.openapi.defaultCallbackUrl。 + * + * @return {string|null} 默认回调地址;未配置或超出长度限制时返回 null。 + */ + getDefaultApiCallbackUrl() { + const openApiConfig = this.app && this.app.config ? this.app.config.openapi : null; + const rawValue = openApiConfig ? openApiConfig.defaultCallbackUrl : ''; + if (rawValue === undefined || rawValue === null) { + return null; + } + const normalized = String(rawValue).trim(); + if (!normalized) { + return null; + } + if (normalized.length > DEFAULT_CALLBACK_URL_MAX_LENGTH) { + this.ctx.logger.warn( + '[storeWarehouse.saveApiConfig] config.openapi.defaultCallbackUrl 长度超过 %s,已忽略', + DEFAULT_CALLBACK_URL_MAX_LENGTH + ); + return null; + } + return normalized; + } + /** * 根据奇门 AppKey 解析客户标识。 * @@ -2751,9 +2823,11 @@ class SettingStoreWarehouseService extends Service { contract_id: Number(relation.id || 0), }; if (interfaceTypeId) { - const interfaceType = await this.getApiInterfaceType({ interface_type_id: interfaceTypeId }, { - allowDisabled: true, - }); + // 签约关系级配置没有仓库开放接口,传 3 时按货主开放接口过滤 + const interfaceType = await this.resolveContractApiInterfaceType( + { interface_type_id: interfaceTypeId }, + { allowDisabled: true } + ); where.interface_type_id = Number(interfaceType.id || 0); } @@ -2814,6 +2888,9 @@ class SettingStoreWarehouseService extends Service { /** * 保存接口配置。 * + * 签约关系级配置统一按货主开放接口维护:传入仓库开放接口(interface_type_id=3)时按货主开放接口落库, + * 回调地址不再取入参,统一使用 config.openapi.defaultCallbackUrl。 + * * @param {Object} [data={}] 请求参数。 * @return {Promise} 接口响应对象。 */ @@ -2824,8 +2901,7 @@ class SettingStoreWarehouseService extends Service { try { const currentSubject = await this.getCurrentSubject(); const relation = await this.findScopedRelation(data, currentSubject, transaction); - this.ensureWarehouseSubject(currentSubject, '接口配置'); - const interfaceType = await this.getApiInterfaceType(data, { transaction, requireId: true }); + const interfaceType = await this.resolveContractApiInterfaceType(data, { transaction }); const isOpenApi = interfaceType.interface_category === 'OPEN_API'; const isQimenWms = interfaceType.interface_category === 'QM_WMS'; @@ -2944,7 +3020,7 @@ class SettingStoreWarehouseService extends Service { contact_person: contactPerson || null, contact_phone: contactPhone || null, email, - callback_url: this.normalizeText(data.callback_url || data.callbackUrl, 'callback_url', 500) || null, + callback_url: this.getDefaultApiCallbackUrl(), is_enabled: isEnabled, }; diff --git a/app/service/systems/waybill.js b/app/service/systems/waybill.js index be53427..1c9ceb8 100644 --- a/app/service/systems/waybill.js +++ b/app/service/systems/waybill.js @@ -22,12 +22,9 @@ const WAYBILL_RECEIVE_FLAGS = [ 'Y', 'N' ]; */ const WAYBILL_RECEIVE_SIGN_MODE = 'simple'; -/** 出站回调 method:批量查询运单物流轨迹 */ +/** 出站回调 method:查询运单物流轨迹 */ const WAYBILL_TRACE_EVENT = 'waybill.getTrace'; -/** 单次轨迹回调最多携带的运单号数量(与揽收查询一致,按 10 单切批) */ -const WAYBILL_TRACE_MAX_BATCH = 10; - /** 轨迹查询回调签名模式:与揽收查询一致(仓库通知协议) */ const WAYBILL_TRACE_SIGN_MODE = WAYBILL_RECEIVE_SIGN_MODE; @@ -1261,6 +1258,7 @@ class WaybillService extends MainService { * * 业务报文:`{ waybill_codes: [...] }`,经 `openapi.callback.sendByAppKey` 统一 * 包装为 `{ request: { waybill_codes: [...] } }` 发送(与其它出站回调一致)。 + * 运单号会按 `buildWaybillQueryCodeMap` 规则补寄件电话后四位(`运单号|后四位`)。 * 外部返回 `[{ waybill_code, is_galaxy_receive: 1|0 }]`,兼容 `{ code, data: [...] }` 包装 * 与 `'Y'/'N'` 字符串取值;命中结果按 waybill_code + warehouse_id 回写 * `wms_order_express.is_galaxy_receive`。 @@ -1315,13 +1313,17 @@ class WaybillService extends MainService { const statusMap = new Map(); const failed = []; + const queryCodeMap = await this.buildWaybillQueryCodeMap({ + warehouseId: normalizedWarehouseId, + waybillCodes: codes, + }); let processedCount = 0; for (let offset = 0; offset < codes.length; offset += WAYBILL_RECEIVE_MAX_BATCH) { const batch = codes.slice(offset, offset + WAYBILL_RECEIVE_MAX_BATCH); const result = await callbackService.sendByAppKey({ appKey: targetAppKey, event: WAYBILL_RECEIVE_EVENT, - request: { waybill_codes: batch }, + request: { waybill_codes: batch.map(code => queryCodeMap.get(code) || code) }, signMode: WAYBILL_RECEIVE_SIGN_MODE, }); @@ -1350,7 +1352,7 @@ class WaybillService extends MainService { } } else { for (const row of this.extractReceiveRows(result.response)) { - const code = String(row && (row.waybill_code || row.waybillCode) || '').trim(); + const code = this.stripWaybillCodeSuffix(String(row && (row.waybill_code || row.waybillCode) || '').trim()); if (!code) continue; const flag = this.normalizeReceiveFlag(row.is_galaxy_receive); if (!flag) { @@ -1474,6 +1476,108 @@ class WaybillService extends MainService { return [ ...new Set(waybillCodes.map(code => String(code || '').trim()).filter(Boolean)) ]; } + /** + * 去掉运单号上的 `|电话后四位` 查询后缀,还原成纯运单号。 + * @param {string} code 运单号(可能带后缀)。 + * @return {string} 纯运单号。 + */ + stripWaybillCodeSuffix(code) { + const text = String(code === undefined || code === null ? '' : code).trim(); + const index = text.indexOf('|'); + return index === -1 ? text : text.slice(0, index).trim(); + } + + /** + * 取寄件电话的后四位(非数字字符先剔除)。 + * @param {string} tel 寄件电话。 + * @return {string} 后四位数字,位数不足时返回空字符串。 + */ + extractSenderTelLast4(tel) { + const digits = String(tel === undefined || tel === null ? '' : tel).replace(/\D/g, ''); + return digits.length >= 4 ? digits.slice(-4) : ''; + } + + /** + * 构建出站查询的运单号映射(原始运单号 → 出站查询值)。 + * + * 外部快递接口(中通轨迹/揽收查询)要求 `运单号|收寄件人手机号后四位` 才能查询: + * 按 warehouse_id 命中 `wms_order_express` 后,用 `logistics_interface_id` 取 + * `wms_express_interface.sender_tel` 的后四位拼接。未命中运单、未关联物流接口 + * 或接口未配置电话时,保持原始运单号发送。 + * + * @param {Object} options 参数。 + * @param {number} options.warehouseId 仓库 ID。 + * @param {Array} options.waybillCodes 原始运单号列表。 + * @return {Promise>} 原始运单号 → 出站查询运单号。 + */ + async buildWaybillQueryCodeMap({ warehouseId, waybillCodes = [] } = {}) { + const { ctx } = this; + const codes = this.normalizeWaybillCodes(waybillCodes); + const map = new Map(codes.map(code => [ code, code ])); + if (codes.length === 0) return map; + + const OrderExpress = ctx.model && ctx.model.OrderExpress; + const ExpressInterface = ctx.model && ctx.model.ExpressInterface; + if (!OrderExpress || !ExpressInterface) return map; + + const { Op } = this.app.Sequelize; + const normalizedWarehouseId = Number(warehouseId) || 0; + const expressWhere = { waybill_code: { [Op.in]: codes } }; + if (normalizedWarehouseId) { + expressWhere.warehouse_id = normalizedWarehouseId; + } + + let expressRows = []; + try { + expressRows = await OrderExpress.findAll({ + attributes: [ 'waybill_code', 'logistics_interface_id' ], + where: expressWhere, + raw: true, + }); + } catch (e) { + ctx.logger.warn('[WaybillService.buildWaybillQueryCodeMap] 查询运单快递信息失败', { + warehouseId: normalizedWarehouseId, + error: e && e.message ? e.message : `${e}`, + }); + return map; + } + + const interfaceIdByCode = new Map(); + for (const row of expressRows || []) { + const code = this.stripWaybillCodeSuffix(String(row && row.waybill_code || '').trim()); + const interfaceId = Number(row && row.logistics_interface_id) || 0; + if (!code || !interfaceId || interfaceIdByCode.has(code)) continue; + interfaceIdByCode.set(code, interfaceId); + } + if (interfaceIdByCode.size === 0) return map; + + let interfaceRows = []; + try { + interfaceRows = await ExpressInterface.findAll({ + attributes: [ 'id', 'sender_tel' ], + where: { id: { [Op.in]: [ ...new Set(interfaceIdByCode.values()) ] } }, + raw: true, + }); + } catch (e) { + ctx.logger.warn('[WaybillService.buildWaybillQueryCodeMap] 查询快递接口配置失败', { + warehouseId: normalizedWarehouseId, + error: e && e.message ? e.message : `${e}`, + }); + return map; + } + + const telById = new Map( + (interfaceRows || []).map(row => [ Number(row && row.id) || 0, row && row.sender_tel ]) + ); + for (const [ code, interfaceId ] of interfaceIdByCode.entries()) { + const last4 = this.extractSenderTelLast4(telById.get(interfaceId)); + if (last4) { + map.set(code, `${code}|${last4}`); + } + } + return map; + } + /** * 解析揽收查询的目标应用:取仓库下勾选了 waybill.getreceive 的首个应用(按 id 升序)。 * @param {number} warehouseId 仓库 ID。 @@ -1541,174 +1645,141 @@ class WaybillService extends MainService { } /** - * 批量查询运单物流轨迹(出站回调 waybill.getTrace)并落库 wms_order_express_trace。 + * 实时查询单个运单的物流轨迹(出站回调 waybill.getTrace)。 * - * 请求与 `waybill.getreceive` 一致:`{ request: { waybill_codes: [...] } }`,单批最多 10 单。 - * 外部返回: - * ``` - * [{ "waybillNo": "770358128188071", - * "trace": { "opTime": "2026-11-10 06:15:53", "outBizCode": "...", - * "memo": "【广州市】快件已发往 山东济南转运中心", - * "opOrgCityName": "广州市", "weight": 0, "scanType": "发件" } }] - * ``` - * 兼容 `trace` 为数组、`traces` 数组、以及 `{ code, data: [...] }` 包装。 - * 落库按 (express_id, op_time, scan_type) 幂等:已存在则更新轨迹文案等字段,不产生重复行。 + * 纯回源:不落库、不读本地表;请求与 `waybill.getreceive` 一致 + * (`{ request: { waybill_codes: [waybillCode] } }`,运单号同样会补寄件电话后四位 + * `运单号|后四位`),响应兼容 + * `[{ waybillNo, trace }]` / `{ waybillNo, trace }` / `{ code, data: [...] }`。 * * @param {Object} options 查询参数。 - * @param {number} options.warehouseId 仓库 ID(回写隔离)。 - * @param {Array} options.waybillCodes 运单号列表。 + * @param {number} options.warehouseId 仓库 ID(仅用于日志与揽收联动)。 + * @param {string} options.waybillCode 运单号。 * @param {string} [options.appKey] 指定目标应用 AppKey,不传则按仓库订阅关系解析。 - * @param {Function} [options.onProgress] 进度回调(每批完成后触发)。 - * @return {Promise} 结果 { success, event, app_key, total, matched, inserted, updated, not_found, failed, reason }。 + * @return {Promise<{success: boolean, traces: Array, app_key: string, empty: boolean, reason?: string, error?: string}>} 轨迹列表。 */ - async queryTraces({ warehouseId, waybillCodes, appKey = '', onProgress = null } = {}) { + async fetchTracesByWaybill({ warehouseId, waybillCode, appKey = '' } = {}) { const { ctx } = this; const normalizedWarehouseId = Number(warehouseId) || 0; - const codes = this.normalizeWaybillCodes(waybillCodes); - const base = { - success: false, - event: WAYBILL_TRACE_EVENT, - app_key: String(appKey || '').trim(), - total: codes.length, - matched: 0, - inserted: 0, - updated: 0, - empty: [], - not_found: [], - failed: [], - }; + const normalizedCode = String(waybillCode || '').trim(); - if (codes.length === 0) { - return { ...base, reason: '运单号不能为空' }; + if (!normalizedCode) { + return { success: false, traces: [], app_key: '', empty: false, reason: '运单号不能为空' }; } if (!normalizedWarehouseId) { - return { ...base, reason: '缺少仓库ID' }; + return { success: false, traces: [], app_key: '', empty: false, reason: '缺少仓库ID' }; } - const targetAppKey = base.app_key + const targetAppKey = String(appKey || '').trim() || await this.resolveTraceQueryAppKey(normalizedWarehouseId); if (!targetAppKey) { return { - ...base, - skipped: true, + success: false, + traces: [], + app_key: '', + empty: false, reason: '无应用承接该回调 method(callback_functions 未勾选或应用未启用)', }; } const callbackService = ctx.service.openapi && ctx.service.openapi.callback; if (!callbackService || typeof callbackService.sendByAppKey !== 'function') { - return { ...base, app_key: targetAppKey, reason: 'OpenAPI 回调服务不可用' }; + return { success: false, traces: [], app_key: targetAppKey, empty: false, reason: 'OpenAPI 回调服务不可用' }; } - const traceGroups = []; - const emptyWaybills = []; - const failed = []; - let processedCount = 0; - - for (let offset = 0; offset < codes.length; offset += WAYBILL_TRACE_MAX_BATCH) { - const batch = codes.slice(offset, offset + WAYBILL_TRACE_MAX_BATCH); - const result = await callbackService.sendByAppKey({ - appKey: targetAppKey, - event: WAYBILL_TRACE_EVENT, - request: { waybill_codes: batch }, - signMode: WAYBILL_TRACE_SIGN_MODE, - }); - - if (!result || result.success !== true) { - const error = String(result && result.error || '未知错误'); - ctx.logger.warn('[WaybillService.queryTraces] 轨迹查询回调失败', { - warehouseId: normalizedWarehouseId, - appKey: targetAppKey, - batchSize: batch.length, - error, - }); - for (const code of batch) { - failed.push({ waybill_code: code, reason: `回调失败: ${error}` }); - } - } else { - const businessError = this.extractReceiveError(result.response); - if (businessError) { - ctx.logger.warn('[WaybillService.queryTraces] 外部接口返回业务失败', { - warehouseId: normalizedWarehouseId, - appKey: targetAppKey, - batchSize: batch.length, - error: businessError, - }); - for (const code of batch) { - failed.push({ waybill_code: code, reason: `外部接口返回失败: ${businessError}` }); - } - } else { - const rows = this.extractTraceRows(result.response); - for (const row of rows) { - const waybillNo = String(row.waybillNo || row.waybill_no || row.waybillCode || '').trim(); - if (!waybillNo) continue; - const traceList = this.normalizeTraceList(row); - if (traceList.length === 0) { - // 外部对「暂无轨迹」的运单返回 trace: [],属正常业务状态(如刚下单尚未揽收), - // 只计入 empty,不当作失败,避免整单任务被判失败 - emptyWaybills.push(waybillNo); - continue; - } - traceGroups.push({ waybillNo, traces: traceList }); - } - } - } - - processedCount += batch.length; - await this.reportReceiveProgress(onProgress, { - processedCount, - totalCount: codes.length, - failedCount: failed.length, - }); - } - - const empty = [ ...new Set(emptyWaybills) ]; - if (traceGroups.length === 0) { - // 全部为「暂无轨迹」或失败:无数据可落库,但只要没有硬失败(回调/业务码异常)就算执行成功 - return { - ...base, - success: failed.length === 0, - app_key: targetAppKey, - empty, - not_found: [ ...new Set(failed.map(item => item.waybill_code)) ], - failed, - ...(failed.length === 0 && empty.length === 0 ? { reason: '未返回可用轨迹' } : {}), - }; - } - - const saveResult = await this.saveTraces({ + const queryCodeMap = await this.buildWaybillQueryCodeMap({ warehouseId: normalizedWarehouseId, - traceGroups, + waybillCodes: [ normalizedCode ], }); - const notFound = [ ...saveResult.notFound, ...failed.map(item => item.waybill_code) ] - .filter((code, index, arr) => arr.indexOf(code) === index); - - ctx.logger.info('[WaybillService.queryTraces] 轨迹同步完成', { - warehouseId: normalizedWarehouseId, + const result = await callbackService.sendByAppKey({ appKey: targetAppKey, - total: codes.length, - matched: saveResult.matched, - inserted: saveResult.inserted, - updated: saveResult.updated, - empty: empty.length, - notFound: saveResult.notFound.length, - failed: failed.length, + event: WAYBILL_TRACE_EVENT, + request: { waybill_codes: [ queryCodeMap.get(normalizedCode) || normalizedCode ] }, + signMode: WAYBILL_TRACE_SIGN_MODE, }); + if (!result || result.success !== true) { + const error = String(result && result.error || '未知错误'); + ctx.logger.warn('[WaybillService.fetchTracesByWaybill] 轨迹查询回调失败', { + warehouseId: normalizedWarehouseId, + appKey: targetAppKey, + waybillCode: normalizedCode, + error, + }); + return { success: false, traces: [], app_key: targetAppKey, empty: false, error }; + } + + const businessError = this.extractReceiveError(result.response); + if (businessError) { + ctx.logger.warn('[WaybillService.fetchTracesByWaybill] 外部接口返回业务失败', { + warehouseId: normalizedWarehouseId, + appKey: targetAppKey, + waybillCode: normalizedCode, + error: businessError, + }); + return { success: false, traces: [], app_key: targetAppKey, empty: false, error: businessError }; + } + + const rows = this.extractTraceRows(result.response); + const matched = rows.find(row => { + const code = this.stripWaybillCodeSuffix( + String(row && (row.waybillNo || row.waybill_no || row.waybillCode) || '').trim() + ); + return code === normalizedCode; + }) || rows[0] || null; + + const traces = this.normalizeTraceList(matched) + .map(trace => this.normalizeTraceItem(trace)) + .sort((a, b) => { + const timeA = a.op_time_raw ? a.op_time_raw.getTime() : 0; + const timeB = b.op_time_raw ? b.op_time_raw.getTime() : 0; + return timeB - timeA; + }) + .map(item => { + const output = { ...item }; + delete output.op_time_raw; + return output; + }); + return { - ...base, - success: !failed.length || saveResult.inserted + saveResult.updated > 0, + success: true, + traces, app_key: targetAppKey, - matched: saveResult.matched, - inserted: saveResult.inserted, - updated: saveResult.updated, - empty, - not_found: notFound, - failed, + empty: traces.length === 0, }; } + /** + * 归一单条轨迹字段(外部字段名 → 接口输出字段名)。 + * @param {Object} trace 外部轨迹对象。 + * @return {Object} 归一后的轨迹(含内部排序用 op_time_raw)。 + */ + normalizeTraceItem(trace = {}) { + const opTime = this.parseTraceTime(trace.opTime || trace.op_time); + return { + op_time: opTime ? this.formatTimestamp(opTime) : '', + op_time_raw: opTime, + out_biz_code: String(trace.outBizCode || trace.out_biz_code || '').trim(), + memo: String(trace.memo || '').trim(), + op_org_city_name: String(trace.opOrgCityName || trace.op_org_city_name || '').trim(), + weight: this.parseTraceWeight(trace.weight), + scan_type: String(trace.scanType || trace.scan_type || '').trim(), + raw_data: trace, + }; + } + + /** + * 把时间格式化为 'YYYY-MM-DD HH:mm:ss'(本地时间)。 + * @param {Date} date 时间对象。 + * @return {string} 格式化后的时间字符串。 + */ + formatTimestamp(date) { + const pad = num => String(num).padStart(2, '0'); + return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` + + `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`; + } + /** * 解析轨迹查询的目标应用:取仓库下勾选了 waybill.getTrace 的首个应用(按 id 升序)。 * @param {number} warehouseId 仓库 ID。 @@ -1729,7 +1800,7 @@ class WaybillService extends MainService { } /** - * 从回调响应中提取轨迹行,兼容裸数组与 { code, data: [...] } 包装。 + * 从回调响应中提取轨迹行,兼容裸数组、单个对象与 { code, data: [...] } 包装。 * @param {*} response 回调响应体。 * @return {Array} 轨迹行列表(每行含 waybillNo + trace)。 */ @@ -1740,6 +1811,8 @@ class WaybillService extends MainService { if (Array.isArray(response.traces)) return response.traces; if (response.data && Array.isArray(response.data.traces)) return response.data.traces; if (response.data && Array.isArray(response.data.results)) return response.data.results; + if (response.data && typeof response.data === 'object') return [ response.data ]; + if (response.waybillNo || response.waybill_no || response.trace || response.traces) return [ response ]; return []; } @@ -1788,182 +1861,48 @@ class WaybillService extends MainService { } /** - * 轨迹落库:按 (express_id, op_time, scan_type) 幂等 upsert 到 wms_order_express_trace。 - * 仅处理当前仓库下能匹配到运单的轨迹,其余计入 notFound。 + * 按轨迹把运单标记为已揽收(is_galaxy_receive='Y')。 + * 仅把非 Y(含 NULL)的行升级为 Y,已为 Y 的不重复更新;按仓库隔离。 * - * @param {Object} options 落库参数。 + * @param {Object} options 参数。 * @param {number} options.warehouseId 仓库 ID。 - * @param {Array<{waybillNo: string, traces: Array}>} options.traceGroups 轨迹分组。 - * @return {Promise<{matched: number, inserted: number, updated: number, notFound: Array}>} 落库统计。 + * @param {Array} options.waybillCodes 有轨迹的运单号。 + * @return {Promise} 实际更新行数。 */ - async saveTraces({ warehouseId, traceGroups = [] } = {}) { + async markReceiveByTraces({ warehouseId, waybillCodes = [] } = {}) { const { ctx } = this; const { Op } = this.app.Sequelize; - const waybillCodes = [ ...new Set(traceGroups.map(item => item.waybillNo).filter(Boolean)) ]; - if (waybillCodes.length === 0) { - return { matched: 0, inserted: 0, updated: 0, notFound: [] }; - } + const codes = [ ...new Set((waybillCodes || []).map(code => String(code || '').trim()).filter(Boolean)) ]; + if (codes.length === 0) return 0; - const expressRows = await ctx.model.OrderExpress.findAll({ - attributes: [ 'id', 'waybill_code', 'order_id' ], - where: { - waybill_code: { [Op.in]: waybillCodes }, - warehouse_id: Number(warehouseId) || 0, - }, - raw: true, - }); - - const expressMap = new Map(); - for (const row of expressRows) { - const code = String(row.waybill_code || '').trim(); - // 同一运单号可能有多条子单记录,取 id 最小的一条作为轨迹归属 - if (!code) continue; - const current = expressMap.get(code); - if (!current || Number(row.id) < Number(current.id)) { - expressMap.set(code, row); - } - } - - const notFound = waybillCodes.filter(code => !expressMap.has(code)); - const rows = []; - for (const group of traceGroups) { - const express = expressMap.get(group.waybillNo); - if (!express) continue; - for (const trace of group.traces) { - rows.push({ - express_id: Number(express.id), - waybill_code: group.waybillNo, - order_id: express.order_id ? Number(express.order_id) : null, - warehouse_id: Number(warehouseId) || 0, - op_time: this.parseTraceTime(trace.opTime || trace.op_time), - out_biz_code: String(trace.outBizCode || trace.out_biz_code || '').trim() || null, - memo: String(trace.memo || '').trim().slice(0, 500) || null, - op_org_city_name: String(trace.opOrgCityName || trace.op_org_city_name || '').trim() || null, - weight: this.parseTraceWeight(trace.weight), - scan_type: String(trace.scanType || trace.scan_type || '').trim() || null, - raw_data: trace, + try { + const [ affected ] = await ctx.model.OrderExpress.update( + { is_galaxy_receive: 'Y' }, + { + where: { + waybill_code: { [Op.in]: codes }, + warehouse_id: Number(warehouseId) || 0, + [Op.or]: [ + { is_galaxy_receive: { [Op.ne]: 'Y' } }, + { is_galaxy_receive: { [Op.is]: null } }, + ], + }, + } + ); + const count = Number(affected) || 0; + if (count > 0) { + ctx.logger.info('[WaybillService.markReceiveByTraces] 轨迹命中,揽收状态已置 Y', { + warehouseId, + waybills: codes.length, + updated: count, }); } + return count; + } catch (error) { + // 揽收状态是轨迹查询的附带收益,失败只记日志,不影响轨迹返回 + ctx.logger.warn(`[WaybillService.markReceiveByTraces] 更新揽收状态失败: ${error.message}`); + return 0; } - - if (rows.length === 0) { - return { matched: waybillCodes.length - notFound.length, inserted: 0, updated: 0, notFound }; - } - - // 预判已存在的轨迹(用于区分新增/更新统计) - const expressIds = [ ...new Set(rows.map(row => row.express_id)) ]; - const existed = await ctx.model.OrderExpressTrace.findAll({ - attributes: [ 'express_id', 'op_time', 'scan_type' ], - where: { express_id: { [Op.in]: expressIds } }, - raw: true, - }); - const existedKeys = new Set(existed.map(row => this.buildTraceKey( - row.express_id, - row.op_time, - row.scan_type - ))); - - let inserted = 0; - let updated = 0; - for (const row of rows) { - if (existedKeys.has(this.buildTraceKey(row.express_id, row.op_time, row.scan_type))) { - updated++; - } else { - inserted++; - } - } - - const TraceModel = ctx.model.OrderExpressTrace; - if (TraceModel && typeof TraceModel.bulkCreate === 'function') { - await TraceModel.bulkCreate(rows, { - updateOnDuplicate: [ 'out_biz_code', 'memo', 'op_org_city_name', 'weight', 'raw_data', 'updated_at' ], - }); - } - - return { matched: waybillCodes.length - notFound.length, inserted, updated, notFound }; - } - - /** - * 构造轨迹去重键(与表唯一索引 uk_express_op_scan 口径一致)。 - * @param {*} expressId 运单ID。 - * @param {*} opTime 操作时间。 - * @param {*} scanType 扫描类型。 - * @return {string} 去重键。 - */ - buildTraceKey(expressId, opTime, scanType) { - const time = opTime instanceof Date - ? opTime.toISOString() - : String(opTime || ''); - return `${Number(expressId) || 0}|${time}|${String(scanType || '')}`; - } - - /** - * 查询单个运单的全部物流轨迹(不分页),按操作时间倒序返回。 - * 仅查当前仓库数据(warehouse_id 隔离)。 - * - * @param {Object} options 查询参数。 - * @param {string} options.waybillCode 运单号。 - * @param {number} options.warehouseId 仓库 ID。 - * @return {Promise<{waybill_code: string, total: number, list: Array}>} 轨迹列表。 - */ - async listTracesByWaybill({ waybillCode, warehouseId } = {}) { - const { ctx } = this; - const normalizedCode = String(waybillCode || '').trim(); - const normalizedWarehouseId = Number(warehouseId) || 0; - - if (!normalizedCode) { - throw new Error('运单号不能为空'); - } - if (!normalizedWarehouseId) { - throw new Error('缺少仓库ID'); - } - - const rows = await ctx.model.OrderExpressTrace.findAll({ - attributes: [ - 'id', 'express_id', 'order_id', 'op_time', 'out_biz_code', - 'memo', 'op_org_city_name', 'weight', 'scan_type', 'raw_data', 'created_at', - ], - where: { - waybill_code: normalizedCode, - warehouse_id: normalizedWarehouseId, - }, - order: [[ 'op_time', 'DESC' ], [ 'id', 'DESC' ]], - raw: true, - }); - - const list = (rows || []).map(row => ({ - id: Number(row.id) || 0, - express_id: Number(row.express_id) || 0, - order_id: row.order_id ? Number(row.order_id) : null, - op_time: this.formatTraceTime(row.op_time), - out_biz_code: row.out_biz_code || '', - memo: row.memo || '', - op_org_city_name: row.op_org_city_name || '', - weight: this.parseTraceWeight(row.weight), - scan_type: row.scan_type || '', - raw_data: row.raw_data || null, - })); - - return { - waybill_code: normalizedCode, - total: list.length, - list, - }; - } - - /** - * 把轨迹时间格式化为 'YYYY-MM-DD HH:mm:ss'(本地时间),空值返回空字符串。 - * @param {*} value 数据库返回值。 - * @return {string} 格式化后的时间字符串。 - */ - formatTraceTime(value) { - if (!value) return ''; - const date = value instanceof Date ? value : new Date(value); - if (Number.isNaN(date.getTime())) return String(value); - - const pad = num => String(num).padStart(2, '0'); - return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` - + `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`; } } diff --git a/config/config.default.js b/config/config.default.js index 1926960..685f0fd 100644 --- a/config/config.default.js +++ b/config/config.default.js @@ -64,6 +64,13 @@ module.exports = appInfo => { baseUrl: 'https://api.deepseek.com', }; + // 开放接口(OpenAPI)配置 + config.openapi = { + // 签约关系级接口配置的默认回调地址:不再由接口配置入参维护,保存时统一写入该值。 + // 为空时不写入 callback_url(回调通知需在 config.local.js / config.prod.js 等环境配置中补齐) + defaultCallbackUrl: '', + }; + // 站内信模块配置 config.inbox = { imageBaseUrl: '', // 商品图片域名,为空时用请求 ctx.host diff --git a/database/designs/waybill-module-design.md b/database/designs/waybill-module-design.md index 7ba3009..d3baadf 100644 --- a/database/designs/waybill-module-design.md +++ b/database/designs/waybill-module-design.md @@ -75,29 +75,8 @@ | `express_print_record` | `express_no` ↔ `waybill_code` | 打印记录(打印时间、打印机、模板) | | `pack_task` | `waybill_code` | 打包任务(打包状态、打包人、打包时间) | | `package_material` | `package_material_id` ↔ `id` | 包材详情 | -| `wms_order_express_trace` | `express_id` ↔ `id`(另冗余 `waybill_code` / `order_id`) | 运单物流轨迹(1 运单 : N 轨迹,外部快递接口回传) | -### 2.2.1 `wms_order_express_trace`(运单物流轨迹,2026-11-11 新增) - -一个运单对应多条轨迹,外部返回的轨迹行字段同名转下划线落库,未建模字段存 `raw_data` 兜底。 - -| 列 | 类型 | 对应外部字段 | 说明 | -|---|---|---|---| -| `express_id` | BIGINT UNSIGNED NOT NULL | — | 关联 `wms_order_express.id`(弱引用,不建物理外键) | -| `waybill_code` | VARCHAR(50) NOT NULL | — | 运单号(冗余,便于直查) | -| `order_id` | BIGINT UNSIGNED NULL | — | 订单ID(冗余,便于按订单查) | -| `warehouse_id` | BIGINT UNSIGNED NOT NULL | — | 仓库隔离维度 | -| `op_time` | DATETIME NULL | `opTime` | 操作时间 | -| `out_biz_code` | VARCHAR(191) NULL | `outBizCode` | 外部业务码 | -| `memo` | VARCHAR(500) NULL | `memo` | 轨迹描述 | -| `op_org_city_name` | VARCHAR(100) NULL | `opOrgCityName` | 操作机构城市 | -| `weight` | DECIMAL(10,3) NULL DEFAULT 0 | `weight` | 重量(来源原值,支持小数如 `"0.99"`) | -| `scan_type` | VARCHAR(50) NULL | `scanType` | 扫描类型(发件/到件/派件/签收) | -| `raw_data` | JSON NULL | — | 原始轨迹报文兜底 | - -索引:`uk_express_op_scan (express_id, op_time, scan_type)` 幂等去重、`idx_waybill_code (waybill_code, op_time)`、`idx_order_id`、`idx_warehouse_op_time (warehouse_id, op_time)`。 - -模型:`app/model/order_express_trace.js`(`paranoid`,`deleted_at` 软删除)。表字符集与主表一致(`utf8mb4_general_ci`)。 +> **轨迹不落库(2026-11-11 调整)**:物流轨迹改为**全部实时回源**,`wms_order_express_trace` 表与模型已删除(迁移 `20261111205500-drop-wms-order-express-trace.js`)。轨迹查询不再有本地表,也不再存在 1:N 关联。 ### 2.3 索引评估 @@ -235,17 +214,15 @@ POST /system { method: "waybill.warehouse.list", ... } | 4 | `waybill.warehouse.exportTaskProgress` | 运单导出任务进度查询 | ✓ | ✗ | | 5 | `waybill.warehouse.updateReceive` | 批量更新运单是否揽收(走出站回调 `waybill.getreceive`,异步任务) | ✓ | ✗ | | 6 | `waybill.warehouse.updateReceiveTaskProgress` | 揽收状态更新任务进度查询 | ✓ | ✗ | -| 7 | `waybill.warehouse.updateTrace` | 批量更新运单物流轨迹(走出站回调 `waybill.getTrace`,异步任务) | ✓ | ✗ | -| 8 | `waybill.warehouse.updateTraceTaskProgress` | 物流轨迹更新任务进度查询 | ✓ | ✗ | -| 9 | `waybill.warehouse.getTrace` | 查询单个运单的全部物流轨迹(不分页) | ✓ | ✗ | +| 7 | `waybill.warehouse.getTrace` | 查询单个运单的全部物流轨迹(实时回源,不分页) | ✓ | ✗ | > **预留接口(本期不实现)**: > > | # | method | 描述 | > |---|--------|------| -> | 10 | `waybill.store.list` | 运单列表-货主侧(按 store_id 隔离) | -> | 11 | `waybill.store.detail` | 运单详情-货主侧 | -> | 12 | `waybill.store.export` | 运单导出-货主侧 | +> | 8 | `waybill.store.list` | 运单列表-货主侧(按 store_id 隔离) | +> | 9 | `waybill.store.detail` | 运单详情-货主侧 | +> | 10 | `waybill.store.export` | 运单导出-货主侧 | --- @@ -608,67 +585,24 @@ waybill.warehouse.updateReceive(入口层:参数校验 + 接口配置预检 --- -### 3.9 `waybill.warehouse.updateTrace` / `waybill.warehouse.updateTraceTaskProgress` — 批量更新物流轨迹(仓库侧) +### 3.9 `waybill.warehouse.getTrace` — 查询运单物流轨迹(仓库侧,实时回源) -**功能说明**:按运单号(或 `where` 条件圈选)调用外部访问接口查询物流轨迹,落库到 `wms_order_express_trace`。入参与 `waybill.warehouse.updateReceive` **完全一致**。 +**功能说明**:按运单号**实时**调用外部访问接口 `waybill.getTrace` 查询轨迹,一次返回全部轨迹(不分页),按 `op_time` 倒序。 + +- **不做本地存储**:`wms_order_express_trace` 表与模型已删除(迁移 `20261111205500-drop-wms-order-express-trace.js`),每次查询都回源 +- **揽收联动**:轨迹非空时把该运单 `wms_order_express.is_galaxy_receive` 置为 `Y`(只升不降,失败只记日志不阻断查询) +- **失败口径**:未配置承接应用或外部接口异常时直接返回失败(无本地兜底);`trace: []` 属于正常结果(`success` + `total=0`) #### 调用链路 ``` -waybill.warehouse.updateTrace(入口层:参数校验 + 接口配置预检 + 建任务) - → systems/waybill.js#queryTraces(每批 ≤10 单) +waybill.warehouse.getTrace(入口层:参数校验 + 接口配置预检) + → systems/waybill.js#fetchTracesByWaybill(单运单实时查询 + 归一排序) → openapi/callback.js#sendByAppKey(event = waybill.getTrace,signMode=simple) - → systems/waybill.js#saveTraces(按 express_id + op_time + scan_type 幂等 upsert) + → systems/waybill.js#markReceiveByTraces(命中轨迹则置 is_galaxy_receive=Y) ``` -#### 请求参数 - -```json -{ "method": "waybill.warehouse.updateTrace", "waybillCodes": ["770358128188071"] } -``` -```json -{ "method": "waybill.warehouse.updateTrace", "where": { "isGalaxyReceive": "Y", "logisticsCode": "YTO" } } -``` - -参数、优先级、5000 条上限与 `updateReceive` 相同(`waybillCodes` > `where`)。 - -#### 外部接口约定(`waybill.getTrace`) - -- 请求体:`{ "request": { "waybill_codes": [...] } }`,单批最多 10 单;签名同 `waybill.getreceive`(`MD5(appSecret + timestamp + bodyJson)`) -- 响应: - -```json -[{ - "waybillNo": "770358128188071", - "trace": { - "opTime": "2026-11-10 06:15:53", - "outBizCode": "770358128188071_510180_1794262553000_210", - "memo": "【广州市】快件已发往 山东济南转运中心", - "opOrgCityName": "广州市", - "weight": 0, - "scanType": "发件" - } -}] -``` - -- 兼容:`trace` 可为数组(一个运单多条轨迹)、`traces`/`traceList` 数组、`{ code, data: [...] }` 包装 -- **暂无轨迹**:外部对未产生轨迹的运单返回 `"trace": []`,只计入任务 `result.empty`,不落库、不计失败,任务仍为 `success` -- **重量**:外部可能返回字符串小数(如 `"0.99"`),`parseTraceWeight` 统一转数字并保留 3 位小数(列类型 `DECIMAL(10,3)`) -- 落库映射:`opTime→op_time`、`outBizCode→out_biz_code`、`memo→memo`、`opOrgCityName→op_org_city_name`、`weight→weight`、`scanType→scan_type`,原始报文存 `raw_data` -- 幂等:唯一键 `(express_id, op_time, scan_type)`,重复回传只更新 `memo` / `op_org_city_name` / `weight` / `raw_data` -- 匹配不到运单的轨迹不落库,运单号写入任务 `result.not_found` - -#### 任务进度 - -`task_id` 前缀 `waybill_trace_`,缓存键前缀 `waybill_trace_task_`(与 `waybill_export_`、`waybill_receive_` 隔离),`result` 返回 `{ total, matched, inserted, updated, empty, not_found, failed }`;提示语形如「更新完成:新增 X 条轨迹,更新 Y 条,无轨迹 Z 单,失败 N 单」。 - -```json -{ "method": "waybill.warehouse.updateTraceTaskProgress", "task_id": "waybill_trace_1000028_1731190000000_ab12cd34" } -``` - -#### 查询单个运单轨迹(`waybill.warehouse.getTrace`) - -只读接口:按运单号一次返回该运单下**全部**轨迹(不分页),按 `op_time DESC, id DESC` 排序;不调用外部接口、不落库。 +#### 请求 / 响应 ```json { "method": "waybill.warehouse.getTrace", "waybillCode": "770358128188071" } @@ -677,27 +611,28 @@ waybill.warehouse.updateTrace(入口层:参数校验 + 接口配置预检 + ```json { "waybill_code": "770358128188071", - "total": 1, + "total": 2, + "received_updated": 1, "list": [ { - "id": 1, - "express_id": 123, - "order_id": 456, - "op_time": "2026-11-10 06:15:53", - "out_biz_code": "770358128188071_510180_1794262553000_210", + "op_time": "2026-11-11 10:43:00", + "out_biz_code": "770358128188071_510902_1794255999000_120", "memo": "【广州市】快件已发往 山东济南转运中心", "op_org_city_name": "广州市", - "weight": 0, - "scan_type": "发件", - "raw_data": { "opTime": "2026-11-10 06:15:53" } + "weight": 0.99, + "scan_type": "收件", + "raw_data": { "opTime": "2026-11-11 10:43:00" } } ] } ``` -- 仓库隔离:查询固定带 `warehouse_id = ctx.user.store_id` -- 运单号不存在或该仓库无轨迹 → `success` + `total=0` + `list=[]`(不报错) -- 同一运单号存在主单/子单多条运单记录时,按 `waybill_code` 聚合返回 +#### 外部接口约定(`waybill.getTrace`) + +- 请求体:`{ "request": { "waybill_codes": ["770358128188071"] } }`(单运单);签名同 `waybill.getreceive`(`MD5(appSecret + timestamp + bodyJson)`) +- 响应:`[{ "waybillNo": "...", "trace": [ { "opTime", "outBizCode", "memo", "opOrgCityName", "weight", "scanType" } ] }]`,`trace` 可为对象或数组,另兼容 `{ code, data: [...] }` 与单个对象返回 +- `trace: []` 表示暂无轨迹;`weight` 支持字符串小数(`"0.99"`) +- 目标应用:该仓库 `callback_functions` 勾选 `waybill.getTrace` 的首个启用应用(按 `id` 升序) --- diff --git a/database/migrations/20261111205500-drop-wms-order-express-trace.js b/database/migrations/20261111205500-drop-wms-order-express-trace.js new file mode 100644 index 0000000..2844fe3 --- /dev/null +++ b/database/migrations/20261111205500-drop-wms-order-express-trace.js @@ -0,0 +1,74 @@ +'use strict'; + +/** + * 下线运单物流轨迹本地存储:删除 wms_order_express_trace。 + * + * 背景(2026-11-11 业务调整): + * - 轨迹查询改为「全部回源」,`waybill.warehouse.getTrace` 实时调用外部 waybill.getTrace 返回, + * 不再落库;批量同步方法 `waybill.warehouse.updateTrace` / `updateTraceTaskProgress` 一并下线; + * - 因此轨迹表不再需要,删除以免产生无用数据与维护成本。 + * - 揽收联动保留:查询命中轨迹时仍会把 wms_order_express.is_galaxy_receive 置为 Y。 + * + * 说明:本迁移不可逆(数据不再保留),down 仅重建空表结构以便回滚版本时可启动。 + */ + +const TABLE_NAME = 'wms_order_express_trace'; + +module.exports = { + async up(queryInterface) { + const tables = await queryInterface.showAllTables(); + const exists = (tables || []).some(t => { + const name = typeof t === 'string' ? t : (t && (t.tableName || t.name)) || ''; + return String(name).toLowerCase() === TABLE_NAME; + }); + + if (!exists) { + console.log(`[${TABLE_NAME}] skip: 表不存在`); + return; + } + + await queryInterface.dropTable(TABLE_NAME); + console.log(`[${TABLE_NAME}] dropped`); + }, + + async down(queryInterface, Sequelize) { + const { BIGINT, STRING, DATE, JSON: JSON_TYPE, DECIMAL } = Sequelize; + const tables = await queryInterface.showAllTables(); + const exists = (tables || []).some(t => { + const name = typeof t === 'string' ? t : (t && (t.tableName || t.name)) || ''; + return String(name).toLowerCase() === TABLE_NAME; + }); + if (exists) { + console.log(`[${TABLE_NAME}] skip: 表已存在`); + return; + } + + await queryInterface.createTable(TABLE_NAME, { + id: { type: BIGINT(20).UNSIGNED, primaryKey: true, autoIncrement: true, allowNull: false, comment: '主键ID' }, + express_id: { type: BIGINT(20).UNSIGNED, allowNull: false, comment: '运单ID(wms_order_express.id)' }, + waybill_code: { type: STRING(50), allowNull: false, comment: '运单号' }, + order_id: { type: BIGINT(20).UNSIGNED, allowNull: true, comment: '订单ID' }, + warehouse_id: { type: BIGINT(20).UNSIGNED, allowNull: false, comment: '仓库ID' }, + op_time: { type: DATE, allowNull: true, comment: '操作时间' }, + out_biz_code: { type: STRING(191), allowNull: true, comment: '外部业务码' }, + memo: { type: STRING(500), allowNull: true, comment: '轨迹描述' }, + op_org_city_name: { type: STRING(100), allowNull: true, comment: '操作机构城市' }, + weight: { type: DECIMAL(10, 3), allowNull: true, defaultValue: 0, comment: '重量(来源原值)' }, + scan_type: { type: STRING(50), allowNull: true, comment: '扫描类型' }, + raw_data: { type: JSON_TYPE, allowNull: true, comment: '原始轨迹报文' }, + created_at: { type: DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), comment: '创建时间' }, + updated_at: { type: DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), comment: '更新时间' }, + deleted_at: { type: DATE, allowNull: true, comment: '软删除时间' }, + }, { + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '运单物流轨迹表(已下线本地存储)', + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'express_id', 'op_time', 'scan_type' ], { unique: true, name: 'uk_express_op_scan' }); + await queryInterface.addIndex(TABLE_NAME, [ 'waybill_code', 'op_time' ], { name: 'idx_waybill_code' }); + await queryInterface.addIndex(TABLE_NAME, [ 'order_id' ], { name: 'idx_order_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'op_time' ], { name: 'idx_warehouse_op_time' }); + console.log(`[${TABLE_NAME}] recreated (empty)`); + }, +}; diff --git a/database/migrations/20261113150000-add-has-sn-item-to-order-delivery.js b/database/migrations/20261113150000-add-has-sn-item-to-order-delivery.js new file mode 100644 index 0000000..dd85f48 --- /dev/null +++ b/database/migrations/20261113150000-add-has-sn-item-to-order-delivery.js @@ -0,0 +1,102 @@ +'use strict'; + +/** + * 订单表增加 has_sn_item(是否含序列号管理商品)字段。 + * + * 取值:Y=订单任一明细的 stock_warehouse.is_sn_mgmt='Y',N=否。默认 N。 + * 用途:订单工作台「是否序列号订单」筛选(is_sn_order),并为后续 SN 波次策略提供订单级标记。 + * + * 覆盖范围: + * - 基表 wms_order_delivery; + * - 全部仓库分表 wms_order_delivery_{wh}(current)及 + * _{wh}_history / _{wh}_dispatch / _{wh}_outsourced。 + * + * 幂等:列已存在则跳过。分表模型由 app/model/order_delivery_factory.js + * 运行时 drift 同步兜底,本迁移提前补齐避免运行时 ALTER。 + */ + +const BASE_TABLE = 'wms_order_delivery'; + +const SHARD_PATTERN = /^wms_order_delivery_(\d+)(?:_(history|dispatch|outsourced))?$/; + +const COLUMN_NAME = 'has_sn_item'; + +/** + * 列举库内全部订单分表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 分表名列表。 + */ +async function listOrderShards(queryInterface) { + const [ rows ] = await queryInterface.sequelize.query( + 'SELECT TABLE_NAME AS tableName FROM INFORMATION_SCHEMA.TABLES ' + + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE \'wms_order_delivery\\_%\' ' + + 'ORDER BY TABLE_NAME' + ); + return (rows || []) + .map(row => String(row.tableName || row.TABLE_NAME || '')) + .filter(name => SHARD_PATTERN.test(name)); +} + +/** + * 判断列是否已存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} columnName 列名。 + * @return {Promise} 是否存在。 + */ +async function columnExists(queryInterface, tableName, columnName) { + const described = await queryInterface.describeTable(tableName); + return Boolean(described && described[columnName]); +} + +module.exports = { + /** + * 执行迁移:为基表与全部分表增加 has_sn_item 列。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 构造器。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ]; + const results = []; + + for (const tableName of tables) { + if (await columnExists(queryInterface, tableName, COLUMN_NAME)) { + results.push({ tableName, action: 'skip', reason: 'exists' }); + continue; + } + + await queryInterface.addColumn(tableName, COLUMN_NAME, { + type: Sequelize.ENUM('Y', 'N'), + allowNull: true, + defaultValue: 'N', + comment: '是否含序列号管理商品:Y是 N否', + }); + results.push({ tableName, action: 'added' }); + } + + console.log('[20261113150000-add-has-sn-item-to-order-delivery] up results:', JSON.stringify(results)); + }, + + /** + * 回滚迁移:移除 base 与全部分表的 has_sn_item 列。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ]; + const results = []; + + for (const tableName of tables) { + if (!await columnExists(queryInterface, tableName, COLUMN_NAME)) { + results.push({ tableName, action: 'skip', reason: 'missing' }); + continue; + } + + await queryInterface.removeColumn(tableName, COLUMN_NAME); + results.push({ tableName, action: 'removed' }); + } + + console.log('[20261113150000-add-has-sn-item-to-order-delivery] down results:', JSON.stringify(results)); + }, +}; diff --git a/database/migrations/20261113151000-backfill-order-has-sn-item.js b/database/migrations/20261113151000-backfill-order-has-sn-item.js new file mode 100644 index 0000000..eee60df --- /dev/null +++ b/database/migrations/20261113151000-backfill-order-has-sn-item.js @@ -0,0 +1,194 @@ +'use strict'; + +/** + * 存量订单回填 has_sn_item(是否含序列号管理商品)。 + * + * 口径:订单任一明细的 stock_warehouse.is_sn_mgmt='Y' → has_sn_item='Y',否则保持 'N'。 + * + * 覆盖范围:基表 wms_order_delivery 与全部仓库分表,按分表后缀关联对应订单明细表: + * - wms_order_delivery_{wh} → wms_order_items_{wh} + * - wms_order_delivery_{wh}_history → wms_order_items_{wh}_history + * - wms_order_delivery_{wh}_dispatch → wms_order_items_{wh}_dispatch + * - wms_order_delivery_{wh}_outsourced → wms_order_items_{wh}(外仓明细与常用表共用) + * + * 幂等:先把 Y 重置为 N,再按明细回填 Y,重复执行结果一致。 + */ + +const BASE_TABLE = 'wms_order_delivery'; + +const SHARD_PATTERN = /^wms_order_delivery_(\d+)(?:_(history|dispatch|outsourced))?$/; + +/** + * 列举库内全部订单分表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 分表名列表。 + */ +async function listOrderShards(queryInterface) { + const [ rows ] = await queryInterface.sequelize.query( + 'SELECT TABLE_NAME AS tableName FROM INFORMATION_SCHEMA.TABLES ' + + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE \'wms_order_delivery\\_%\' ' + + 'ORDER BY TABLE_NAME' + ); + return (rows || []) + .map(row => String(row.tableName || row.TABLE_NAME || '')) + .filter(name => SHARD_PATTERN.test(name)); +} + +/** + * 判断表是否存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @return {Promise} 是否存在。 + */ +async function tableExists(queryInterface, tableName) { + const [ rows ] = await queryInterface.sequelize.query( + 'SELECT TABLE_NAME AS tableName FROM INFORMATION_SCHEMA.TABLES ' + + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = :tableName LIMIT 1', + { replacements: { tableName } } + ); + return Boolean(rows && rows.length > 0); +} + +/** + * 判断表是否包含指定列。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} columnName 列名。 + * @return {Promise} 是否存在。 + */ +async function columnExists(queryInterface, tableName, columnName) { + const [ rows ] = await queryInterface.sequelize.query( + 'SELECT COLUMN_NAME AS columnName FROM INFORMATION_SCHEMA.COLUMNS ' + + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = :tableName AND COLUMN_NAME = :columnName LIMIT 1', + { replacements: { tableName, columnName } } + ); + return Boolean(rows && rows.length > 0); +} + +/** + * 由订单表名推导对应订单明细表名。 + * @param {string} orderTable 订单表名。 + * @return {string|null} 明细表名,无法推导时返回 null。 + */ +function resolveItemsTable(orderTable) { + if (orderTable === BASE_TABLE) { + return 'wms_order_items'; + } + + const matched = SHARD_PATTERN.exec(orderTable); + if (!matched) { + return null; + } + + const warehouseId = matched[1]; + const suffix = matched[2] || ''; + if (suffix === 'history') { + return `wms_order_items_${warehouseId}_history`; + } + if (suffix === 'dispatch') { + return `wms_order_items_${warehouseId}_dispatch`; + } + + return `wms_order_items_${warehouseId}`; +} + +/** + * 提取受影响行数。 + * @param {*} updateResult query 返回结果。 + * @return {number} 受影响行数。 + */ +function extractAffectedRows(updateResult) { + if (Array.isArray(updateResult)) { + const meta = updateResult[1]; + return Number(meta && (meta.affectedRows || meta.affectedCount || meta.rowCount) || 0); + } + if (updateResult && typeof updateResult === 'object') { + return Number(updateResult.affectedRows || updateResult.affectedCount || updateResult.rowCount || 0); + } + return 0; +} + +module.exports = { + /** + * 执行迁移:按订单明细回填 has_sn_item。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface) { + const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ]; + const results = []; + + for (const tableName of tables) { + if (!await tableExists(queryInterface, tableName)) { + results.push({ tableName, action: 'skip', reason: 'order-table-missing' }); + continue; + } + + const itemsTable = resolveItemsTable(tableName); + if (!itemsTable || !await tableExists(queryInterface, itemsTable)) { + results.push({ tableName, action: 'skip', reason: `items-table-missing:${itemsTable || ''}` }); + continue; + } + + // 兼容旧版基表:wms_order_items(无 stock_id / order_id 的历史结构)无法参与回填 + if (!await columnExists(queryInterface, itemsTable, 'order_id') + || !await columnExists(queryInterface, itemsTable, 'stock_id')) { + results.push({ tableName, action: 'skip', reason: `items-table-unsupported:${itemsTable}` }); + continue; + } + + const resetResult = await queryInterface.sequelize.query(` + UPDATE \`${tableName}\` + SET has_sn_item = 'N' + WHERE has_sn_item = 'Y' + `); + + const updateResult = await queryInterface.sequelize.query(` + UPDATE \`${tableName}\` o + INNER JOIN ( + SELECT DISTINCT oi.order_id + FROM \`${itemsTable}\` oi + INNER JOIN wms_stock_warehouse sw + ON sw.id = oi.stock_id + AND sw.is_sn_mgmt = 'Y' + ) t ON t.order_id = o.id + SET o.has_sn_item = 'Y' + `); + + results.push({ + tableName, + itemsTable, + resetRows: extractAffectedRows(resetResult), + affectedRows: extractAffectedRows(updateResult), + }); + } + + console.log('[20261113151000-backfill-order-has-sn-item] up results:', JSON.stringify(results)); + }, + + /** + * 回滚迁移:全部置回 'N'。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ]; + const results = []; + + for (const tableName of tables) { + if (!await tableExists(queryInterface, tableName)) { + results.push({ tableName, action: 'skip', reason: 'order-table-missing' }); + continue; + } + + const updateResult = await queryInterface.sequelize.query(` + UPDATE \`${tableName}\` + SET has_sn_item = 'N' + WHERE has_sn_item = 'Y' + `); + results.push({ tableName, affectedRows: extractAffectedRows(updateResult) }); + } + + console.log('[20261113151000-backfill-order-has-sn-item] down results:', JSON.stringify(results)); + }, +}; diff --git a/database/migrations/20261113160000-enlarge-order-item-sn-code.js b/database/migrations/20261113160000-enlarge-order-item-sn-code.js new file mode 100644 index 0000000..54714b8 --- /dev/null +++ b/database/migrations/20261113160000-enlarge-order-item-sn-code.js @@ -0,0 +1,71 @@ +'use strict'; + +const ORDER_ITEM_SN_TABLE = 'wms_order_item_sn'; +const ORDER_ITEM_SN_LOG_TABLE = 'wms_order_item_sn_log'; +/** SN 编码目标长度:支持以链接/二维码内容作为 SN,同时保证 (warehouse_id, sn_code) 唯一索引不超过 3072 字节 */ +const TARGET_SN_CODE_LENGTH = 512; + +/** + * 读取列当前定义的字符长度。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} columnName 列名。 + * @return {Promise} 当前字符长度,取不到时返回 0。 + */ +const getColumnLength = async (queryInterface, tableName, columnName) => { + const tableDefinition = await queryInterface.describeTable(tableName); + const column = tableDefinition[columnName]; + if (!column) { + return 0; + } + + const length = Number(column.character_maximum_length || column.maxLength || 0); + return Number.isFinite(length) ? length : 0; +}; + +module.exports = { + /** + * 把 SN 编码列扩充到 512 字符(支持链接/二维码内容作为 SN 码)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const existingTables = new Set((await queryInterface.showAllTables()).map(table => ( + typeof table === 'string' ? table : (table.tableName || table.name || '') + ).toLowerCase())); + + for (const tableName of [ ORDER_ITEM_SN_TABLE, ORDER_ITEM_SN_LOG_TABLE ]) { + if (!existingTables.has(tableName)) { + continue; + } + + const currentLength = await getColumnLength(queryInterface, tableName, 'sn_code'); + if (currentLength >= TARGET_SN_CODE_LENGTH) { + continue; + } + + await queryInterface.changeColumn(tableName, 'sn_code', { + type: Sequelize.STRING(TARGET_SN_CODE_LENGTH), + allowNull: false, + comment: 'SN编码(支持链接/二维码内容,最长512字符)', + }); + } + }, + + /** + * 回滚为 128 字符(超长数据会失败,需先清理)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface, Sequelize) { + for (const tableName of [ ORDER_ITEM_SN_TABLE, ORDER_ITEM_SN_LOG_TABLE ]) { + await queryInterface.changeColumn(tableName, 'sn_code', { + type: Sequelize.STRING(128), + allowNull: false, + comment: 'SN编码', + }); + } + }, +}; diff --git a/database/migrations/20261113203000-add-sn-code-rules-to-stock-warehouse.js b/database/migrations/20261113203000-add-sn-code-rules-to-stock-warehouse.js new file mode 100644 index 0000000..14a3200 --- /dev/null +++ b/database/migrations/20261113203000-add-sn-code-rules-to-stock-warehouse.js @@ -0,0 +1,68 @@ +'use strict'; + +/** + * 仓库商品表新增 sn_code_rules(SN 码规则)字段。 + * + * 存储结构(JSON 数组,多条规则按顺序匹配,命中第一条生效): + * [{ "match_type": "prefix|suffix", "match_value": "YGP", "keep_mode": "full|strip" }] + * - match_type:匹配前缀还是后缀; + * - match_value:要匹配的前缀/后缀字符串; + * - keep_mode:full=整个扫码内容作为 SN 码,strip=去掉匹配到的前缀/后缀后再作为 SN 码。 + * + * 用途:复核扫描(order.recheckOrder.scanOrder)把规则下发给 PDA,前端据此校验/加工扫码内容。 + * 幂等:列已存在则跳过。 + */ + +const TABLE_NAME = 'wms_stock_warehouse'; +const COLUMN_NAME = 'sn_code_rules'; + +/** + * 判断列是否已存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} columnName 列名。 + * @return {Promise} 是否存在。 + */ +async function columnExists(queryInterface, tableName, columnName) { + const described = await queryInterface.describeTable(tableName); + return Boolean(described && described[columnName]); +} + +module.exports = { + /** + * 新增 sn_code_rules 列。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 构造函数。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + if (await columnExists(queryInterface, TABLE_NAME, COLUMN_NAME)) { + console.log(`[20261113203000-add-sn-code-rules-to-stock-warehouse] skip: ${TABLE_NAME}.${COLUMN_NAME} exists`); + return; + } + + await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, { + type: Sequelize.JSON, + allowNull: true, + defaultValue: null, + comment: 'SN码规则(JSON数组):match_type/match_value/keep_mode,多条按顺序匹配', + }); + + console.log(`[20261113203000-add-sn-code-rules-to-stock-warehouse] added ${TABLE_NAME}.${COLUMN_NAME}`); + }, + + /** + * 回滚:删除 sn_code_rules 列。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + if (!await columnExists(queryInterface, TABLE_NAME, COLUMN_NAME)) { + console.log(`[20261113203000-add-sn-code-rules-to-stock-warehouse] skip: ${TABLE_NAME}.${COLUMN_NAME} missing`); + return; + } + + await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME); + console.log(`[20261113203000-add-sn-code-rules-to-stock-warehouse] removed ${TABLE_NAME}.${COLUMN_NAME}`); + }, +}; diff --git a/database/migrations/20261113233000-add-store-id-and-indexes-to-order-item-sn.js b/database/migrations/20261113233000-add-store-id-and-indexes-to-order-item-sn.js new file mode 100644 index 0000000..5d272f1 --- /dev/null +++ b/database/migrations/20261113233000-add-store-id-and-indexes-to-order-item-sn.js @@ -0,0 +1,160 @@ +'use strict'; + +/** + * wms_order_item_sn 增补货主字段与 SN 码索引。 + * + * 1. 新增 store_id(货主ID,可空):复核落库时从订单冗余,便于按货主隔离查询/统计; + * 历史数据按 order_id + warehouse_id 关联各仓库订单分表回填。 + * 2. 新增 idx_wms_order_item_sn_sn_code:支撑「按 SN 码反查订单」的查询条件 + * (订单列表 where.sn_code → 先查 SN 表拿 order_id 再过滤订单,不改订单表结构); + * 原唯一键 uk_wms_order_item_sn_warehouse_sn_code 以 warehouse_id 打头, + * 单按 sn_code 查询无法使用,故补一条 sn_code 单列索引。 + * 3. 新增 idx_wms_order_item_sn_store_id:按货主过滤/统计。 + * + * 幂等:列与索引已存在则跳过。 + */ + +const TABLE_NAME = 'wms_order_item_sn'; +const COLUMN_NAME = 'store_id'; +const INDEX_SN_CODE = 'idx_wms_order_item_sn_sn_code'; +const INDEX_STORE_ID = 'idx_wms_order_item_sn_store_id'; +/** 订单分表命名:wms_order_delivery_{warehouseId}[_history|_dispatch|_outsourced] */ +const ORDER_SHARD_PATTERN = /^wms_order_delivery_(\d+)(?:_(history|dispatch|outsourced))?$/; + +/** + * 判断列是否存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} columnName 列名。 + * @return {Promise} 是否存在。 + */ +async function columnExists(queryInterface, tableName, columnName) { + const described = await queryInterface.describeTable(tableName); + return Boolean(described && described[columnName]); +} + +/** + * 判断索引是否存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} indexName 索引名。 + * @return {Promise} 是否存在。 + */ +async function indexExists(queryInterface, tableName, indexName) { + const indexes = await queryInterface.showIndex(tableName); + return (Array.isArray(indexes) ? indexes : []).some(index => index.name === indexName); +} + +/** + * 列出库内全部订单分表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 分表名列表。 + */ +async function listOrderShardTables(queryInterface) { + const [ rows ] = await queryInterface.sequelize.query( + 'SELECT TABLE_NAME AS tableName FROM INFORMATION_SCHEMA.TABLES ' + + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE \'wms_order_delivery\\_%\' ' + + 'ORDER BY TABLE_NAME' + ); + return (rows || []) + .map(row => String(row.tableName || row.TABLE_NAME || '')) + .filter(name => ORDER_SHARD_PATTERN.test(name)); +} + +/** + * 从订单分表回填 store_id(仅回填尚未赋值的行)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string[]} shardTables 订单分表名。 + * @return {Promise} 每张分表的回填条数。 + */ +async function backfillStoreId(queryInterface, shardTables) { + const results = []; + + for (const tableName of shardTables) { + const [ result ] = await queryInterface.sequelize.query( + `UPDATE ${TABLE_NAME} sn + INNER JOIN ${tableName} o + ON o.id = sn.order_id + AND o.warehouse_id = sn.warehouse_id + SET sn.store_id = o.store_id + WHERE sn.store_id IS NULL + AND o.store_id IS NOT NULL + AND o.store_id > 0` + ); + results.push({ tableName, affectedRows: Number((result && result.affectedRows) || 0) }); + } + + return results; +} + +module.exports = { + /** + * 执行迁移。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 构造函数。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const log = []; + + if (await columnExists(queryInterface, TABLE_NAME, COLUMN_NAME)) { + log.push(`skip column ${COLUMN_NAME} (exists)`); + } else { + await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + after: 'warehouse_id', + comment: '货主ID(复核落库时从订单冗余)', + }); + log.push(`added column ${COLUMN_NAME}`); + } + + const shardTables = await listOrderShardTables(queryInterface); + const backfillResults = await backfillStoreId(queryInterface, shardTables); + log.push(`backfill: ${JSON.stringify(backfillResults)}`); + + if (await indexExists(queryInterface, TABLE_NAME, INDEX_SN_CODE)) { + log.push(`skip index ${INDEX_SN_CODE} (exists)`); + } else { + await queryInterface.addIndex(TABLE_NAME, [ 'sn_code' ], { name: INDEX_SN_CODE }); + log.push(`added index ${INDEX_SN_CODE}`); + } + + if (await indexExists(queryInterface, TABLE_NAME, INDEX_STORE_ID)) { + log.push(`skip index ${INDEX_STORE_ID} (exists)`); + } else { + await queryInterface.addIndex(TABLE_NAME, [ 'store_id' ], { name: INDEX_STORE_ID }); + log.push(`added index ${INDEX_STORE_ID}`); + } + + console.log('[20261113233000-add-store-id-and-indexes-to-order-item-sn] up:', log.join(' | ')); + }, + + /** + * 回滚:删除索引与 store_id 列。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + const log = []; + + for (const indexName of [ INDEX_SN_CODE, INDEX_STORE_ID ]) { + if (await indexExists(queryInterface, TABLE_NAME, indexName)) { + await queryInterface.removeIndex(TABLE_NAME, indexName); + log.push(`removed index ${indexName}`); + } else { + log.push(`skip index ${indexName} (missing)`); + } + } + + if (await columnExists(queryInterface, TABLE_NAME, COLUMN_NAME)) { + await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME); + log.push(`removed column ${COLUMN_NAME}`); + } else { + log.push(`skip column ${COLUMN_NAME} (missing)`); + } + + console.log('[20261113233000-add-store-id-and-indexes-to-order-item-sn] down:', log.join(' | ')); + }, +}; diff --git a/docs/openapi-callback-events.md b/docs/openapi-callback-events.md index c9078df..0f070be 100644 --- a/docs/openapi-callback-events.md +++ b/docs/openapi-callback-events.md @@ -39,6 +39,8 @@ POST {callbackUrl}?method={模块.动作}&v=1.0×tamp={timestamp}&app_key={s `callbackUrl` 来自 `api_app` 表(`callback_url` 字段,要求 `is_enabled=1` 且 `callback_url` 非空)。 +> 签约关系级接口配置(`storeWarehouse.store.saveApiConfig`)不再接收 `callback_url` 入参:保存时统一写入 `config.openapi.defaultCallbackUrl`(未配置时写 `null`),因此上表取值实际由该配置项决定,修改回调地址需调整环境配置后重新保存接口配置。 + | query 参数 | 类型 | 必填 | 说明 | |---|---|---|---| | `method` | string | 是 | 回调 method,`模块.动作` 格式(与奇门对应接口对应;报文体不再携带 `event` 字段);URL 中做 `encodeURIComponent` | @@ -356,6 +358,7 @@ app_key=APP2024011514301234&method=entryorder.confirm×tamp=1758047400&v=1.0 - 运单号来源:显式 `waybillCodes`,或 `where`(与 `waybill.warehouse.list` 同一套筛选口径,不含分页/排序;匹配数上限 5000,超限要求缩小范围) - 目标应用解析:未显式传 `appKey` 时,取该仓库 `callback_functions` 勾选了 `waybill.getreceive` 的首个应用(按 `id` 升序) - 批量上限:单次回调**最多 10 个运单号**(外部接口上限),超出自动切批并逐批更新任务进度 +- 运单号后缀:运单在该仓库的 `wms_order_express` 命中、且其 `logistics_interface_id` 关联的 `wms_express_interface.sender_tel` 至少 4 位数字时,出站统一发送 `运单号|寄件电话后四位`(如 `776447927635244|8000`,非数字字符先剔除),供外部接口校验收寄件人手机号;未命中运单、未关联接口或电话不足四位时按纯运单号发送。回写仍按纯运单号匹配,外部响应里带 `|后缀` 也能正确回写 - **签名口径(与 3.1~3.5 不同)**:`sign = MD5(appSecret + timestamp + bodyJson)`,即 `methods/warehouse_notify.json` 描述的仓库通知协议,而非 2.4 节的 `MD5(canonicalQuery + appSecret + MD5(body))`;实现为 `openapi/callback.js#signCallback({ signMode: 'simple' })`。query 仍携带 `method/v/timestamp/app_key/sign` - 失败识别:HTTP 200 但响应体 `code` 非 `0/1/200`(如验签失败返回 `{"code":401,"msg":"签名验证失败"}`)时整批判失败,不写入揽收状态 - `request` 结构(经 `sendByAppKey` 统一包装,线路报文为 `{ request: {...} }`): @@ -363,11 +366,14 @@ app_key=APP2024011514301234&method=entryorder.confirm×tamp=1758047400&v=1.0 ```json { "request": { - "waybill_codes": [ "YT1234567890" ] + "waybill_codes": [ "YT1234567890|8000" ] } } ``` +> 无寄件电话后四位可补时,`waybill_codes` 元素为纯运单号(`"YT1234567890"`)。 +``` + - 外部**响应**:裸数组 `[{ "waybill_code": "YT1234567890", "is_galaxy_receive": 1 }]`;同时兼容 `{ "code": 200, "data": [...] }` 包装 - `is_galaxy_receive` 兼容取值:`1`/`0`、`'Y'`/`'N'`(大小写不敏感)、布尔值;非法取值计入 `failed`,不写库 - 回写口径:按 `waybill_code` + `warehouse_id` 更新 `wms_order_express.is_galaxy_receive`(`1→Y`、`0→N`),跨仓不串写 @@ -375,10 +381,10 @@ app_key=APP2024011514301234&method=entryorder.confirm×tamp=1758047400&v=1.0 ### 3.7 waybill.getTrace(查询型回调:物流轨迹) - label:运单物流轨迹查询 -- description:按运单号批量查询物流轨迹;消费外部响应并落库 `wms_order_express_trace` +- description:按运单号查询物流轨迹;消费外部响应并直接返回给调用方(**不落库**) - 注册位置:`app/lib/callback_functions.js#CALLBACK_FUNCTIONS` -- 实现:`app/service/systems/waybill.js#queryTraces` + `#saveTraces`;业务入口 `waybill.warehouse.updateTrace`(进度走 `waybill.warehouse.updateTraceTaskProgress`) -- 入参:与 `waybill.getreceive` 一致(`{ request: { waybill_codes: [...] } }`,单批最多 10 单);签名同样为 `MD5(appSecret + timestamp + bodyJson)` +- 实现:`app/service/systems/waybill.js#fetchTracesByWaybill`;业务入口 `waybill.warehouse.getTrace`(单运单、实时回源) +- 入参:`{ request: { waybill_codes: ["770358128188071"] } }`(单运单),运单号同样按 3.6 的规则补寄件电话后四位(`运单号|后四位`);签名同样为 `MD5(appSecret + timestamp + bodyJson)` - 响应: ```json @@ -395,11 +401,12 @@ app_key=APP2024011514301234&method=entryorder.confirm×tamp=1758047400&v=1.0 }] ``` -- 兼容:`trace` 可为数组(一个运单多条轨迹)、`traces` / `traceList` 数组、`{ code, data: [...] }` 包装 -- **`trace: []`(暂无轨迹)**:属正常业务状态(如刚下单未揽收),只计入结果 `empty`,不落库、不计失败 -- **`weight`**:可能返回字符串小数(如 `"0.99"`),WMS 统一转数字并按 `DECIMAL(10,3)` 落库 -- 落库:`wms_order_express_trace`,唯一键 `(express_id, op_time, scan_type)` 幂等,命中时更新 `memo` / `op_org_city_name` / `weight` / `raw_data` -- 失败识别:与 3.6 相同(HTTP 200 但 `code` 非 `0/1/200` 整批判失败) +- 兼容:`trace` 可为数组(一个运单多条轨迹)或对象、`traces` / `traceList` 数组、`{ code, data: [...] }` 包装、单个对象返回;响应行 `waybillNo` 带 `|后四位` 后缀时按纯运单号匹配 +- **`trace: []`(暂无轨迹)**:属正常业务状态(如刚下单未揽收),接口返回 `success` + `total=0` +- **`weight`**:可能返回字符串小数(如 `"0.99"`),WMS 统一转数字保留 3 位小数 +- **不落库**:轨迹表 `wms_order_express_trace` 已删除(迁移 `20261111205500`),每次查询都实时回源 +- **揽收联动**:命中轨迹(非空)时把该运单 `wms_order_express.is_galaxy_receive` 置为 `Y`(只升不降),计数见返回的 `received_updated` +- 失败识别:与 3.6 相同(HTTP 200 但 `code` 非 `0/1/200` 视为失败);失败时入站接口直接返回错误,无本地兜底 ## 4. timestamp 规范(2026-09-12 已统一为秒) diff --git a/docs/report-config-guide.md b/docs/report-config-guide.md index 94c551b..7120f51 100644 --- a/docs/report-config-guide.md +++ b/docs/report-config-guide.md @@ -195,7 +195,9 @@ report.generate(method 层,异步任务,入参 report_id) 与订单导出 item 模式的差异:不含 `item_image`(商品图片)列,另附加 3 列—— `source_order_codes`(平台交易单号,位置紧跟「外部单号」)、`intercept_notice_time`(通知拦截时间)、 -`intercept_confirm_time`(库内确定拦截时间),订单导出无这 3 列。配置示例: +`intercept_confirm_time`(库内确定拦截时间),订单导出无这 3 列; +另外订单导出 item 模式新增了 `sn_quantity`(SN码数量,明细中启用序列号管理商品的 plan_qty)与 +`sn_codes`(SN码,该商品行复核时登记的 SN 列表),waybill 模式新增 `sn_codes_summary`(SN码汇总,订单级),本报表未启用这些列。配置示例: ```json // report.definition.save(新增拦截明细报表) diff --git a/methods/changes/system.json b/methods/changes/system.json index a693aa5..3e82cd5 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,381 @@ [ + { + "version": "0.3.349", + "date": "2026-11-13", + "type": "fixed", + "summary": "修正 SN 订单限制:允许按订单 ID 抓取散单,仅保持「不出现在散单/团购策略候选」", + "methods": [ + "order.wave.singleFetchByIds" + ], + "notes": [ + "问题:singleFetchByIds 把 has_sn_item='Y' 的订单一并排除(excluded_sn_order_ids),导致 SN 订单无法按订单抓取散单。", + "现改为:SN 订单允许按订单 ID 显式抓取,不再受 SN 标记限制;excluded_sn_order_ids 字段保留在响应中但恒为空数组(向后兼容)。", + "抓取后的波次 item_part_type='manual_ids',拣货侧固定走先拣后分 pick_mode=3,与 SN 策略要求的先拣后分一致,SN 采集仍在复核环节按 sn_map 提交。", + "保持不变:散单策略与团购策略候选仍排除 SN 订单(order.wave.singleOrderFetchList、fetchableOrderCount、runFetchTask 结构抓取、自动加团),SN 订单只由 SN 策略(strategy_type=3)自动抓取。B2B / 已拦截 / 已锁定订单仍不允许抓取。" + ] + }, + { + "version": "0.3.348", + "date": "2026-11-13", + "type": "added", + "summary": "订单列表支持按 SN 码反查订单(where.sn_code),SN 码表补 store_id 与查询索引", + "methods": [ + "order.list", + "order.reviewOrder.list", + "order.pendingOrder.list", + "order.outboundOrder.list", + "order.expectionOrder.list", + "order.entrustOrder.list", + "order.deliveryOrder.list", + "order.deliveryExpectionOrder.list", + "order.archiveOrder.list" + ], + "notes": [ + "以上列表接口的 where 均支持 sn_code / snCode / sn_codes / snCodes:先按仓库 + SN 码查询 wms_order_item_sn 取 order_id,再以 id IN (...) 回填订单列表条件,订单表结构不变;未命中返回空列表。", + "取值支持单个字符串、逗号/空格/分号分隔的多个码、字符串数组、{ value } 结构;按完整 SN 码精确匹配(扫码所得即完整码),去重后最多一次 IN 查询;未传该条件不查 SN 表。", + "数据库迁移 20261113233000-add-store-id-and-indexes-to-order-item-sn.js 已在本地与生产执行:wms_order_item_sn 新增 store_id(BIGINT UNSIGNED,可空),新增 idx_wms_order_item_sn_sn_code 与 idx_wms_order_item_sn_store_id,并按 order_id + warehouse_id 关联各仓库订单分表回填历史 store_id(生产回填 160 行,无遗漏)。", + "复核提交落库 wms_order_item_sn 时写入 store_id(取自订单 store_id,BOUND→VERIFIED 升级同样补写),便于后续按货主隔离查询/统计。" + ] + }, + { + "version": "0.3.347", + "date": "2026-11-13", + "type": "added", + "summary": "商品新增 SN 码规则(wms_stock_warehouse.sn_code_rules),复核扫描视图 scanOrder 下发 sn_code_rules 供前端扫码校验", + "methods": [ + "stock.warehouse.saveWarehouseStock", + "stock.warehouse.createWarehouseStock", + "stock.warehouse.getInfo", + "order.recheckOrder.scanOrder" + ], + "notes": [ + "新增字段 wms_stock_warehouse.sn_code_rules(JSON 数组,可空),迁移 20261113203000-add-sn-code-rules-to-stock-warehouse.js 已在本地与生产执行。", + "一条规则三步:match_type=prefix(匹配前缀)/suffix(匹配后缀);match_value=要匹配的前缀或后缀字符串;keep_mode=full(整个扫码内容作为 SN 码)/strip(去掉匹配到的前缀或后缀后再作为 SN 码)。多条规则按数组顺序匹配,命中第一条生效,未命中则扫码内容原样作为 SN 码。", + "保存入参 sn_code_rules / snCodeRules 支持数组或 JSON 字符串,元素字段兼容 match_type/matchType、match_value/matchValue、keep_mode/keepMode;整体覆盖保存,传 [] 清空,不传则不更新(创建时不传存空数组)。", + "格式校验(保存即报错,错误信息带第几条):必须是数组或合法 JSON 数组;元素必须是对象;match_type 仅 prefix/suffix;match_value 去空白后 1~64 字符;keep_mode 仅 full/strip;同位置同串同处理方式视为重复;最多 20 条。", + "order.recheckOrder.scanOrder(含团购波次视图 stocks[])商品行新增 sn_code_rules 数组,与 need_sn 并列输出;无规则返回 [],存量脏数据(非法 JSON)按 [] 兜底不影响扫描视图。stock.warehouse.getInfo 回显同步输出该字段。" + ] + }, + { + "version": "0.3.346", + "date": "2026-11-13", + "type": "updated", + "summary": "订单导出表头枚举补全(拦截状态、复核时间),并明确 export_columns 白名单会过滤新增列", + "methods": [ + "order.export" + ], + "notes": [ + "export_columns 枚举由 55 个修正为 57 个,补入此前遗漏的「拦截状态」(字段 intercept_status)与「复核时间」(字段 recheck_time)。", + "新增说明:一旦传入 export_columns,服务端只按白名单过滤输出列,新增列(拦截状态、SN码数量、SN码汇总、SN码)必须由前端导出列选项同步加上,否则导出表头里看不到;不传该参数才输出当前模式全部列(waybill 48 列 / item 51 列)。", + "本次仅文档更正,服务端列定义与导出逻辑未改动。" + ] + }, + { + "version": "0.3.345", + "date": "2026-11-13", + "type": "updated", + "summary": "奇门 deliveryorder.confirm 报文结构修正:orderLines 的 snList 输出 子节点,多包裹 packages 正确闭合", + "methods": [ + "order.pendingOrder.syncOrderIds" + ], + "notes": [ + "orderLines[].snList 现按奇门规范输出 SN码…;此前 XML 生成器对标量数组统一用 包裹,再被 orderLines 内的 item→orderLine 替换,实际发出的是 …。", + "packages 修正:一单多运单号(多个包裹)时,第二个及之后包裹此前会被序列化成 并导致 / 错位;现输出标准 ……。", + "snList 仍只挂在 orderLines[].orderLine 上(数据源 wms_order_item_sn,状态 VERIFIED/REISSUED),packages.package[].items 不含 snList,MRO/手工通知与出库单回传(stockout.confirm)不受影响。", + "SN 长度分流:奇门 orderLine.sn 限长 50,超长 SN(二维码/链接型)改由 orderLine.qrCode 承载,多个用分号拼接,并与明细自带 qr_code 合并去重;API/JSON 渠道不做此限制,仍全部放在 snList。" + ] + }, + { + "version": "0.3.344", + "date": "2026-11-13", + "type": "updated", + "summary": "复核扫描视图 scanOrder 商品行新增 need_sn 标识(是否需要采集 SN 码)", + "methods": [ + "order.recheckOrder.scanOrder" + ], + "notes": [ + "scanOrder 返回的 stock[] 每项新增 need_sn:Y=该商品启用序列号管理(wms_stock_warehouse.is_sn_mgmt='Y'),复核提交时必须通过 sn_map 上传该商品全部 SN 码;N=无需采集。", + "团购模式(list_type=group)波次视图中的 stocks[] 同步输出 need_sn,PDA 可直接按商品行切换 SN 扫描。", + "need_sn 与 need_recheck(是否需要复核)互相独立,可同时为 Y。", + "SN 标记按当前仓库过滤一次批量查询(id IN stockIds AND warehouse_id=? AND is_sn_mgmt='Y'),不改变原有 stock 字段与其他返回结构。" + ] + }, + { + "version": "0.3.343", + "date": "2026-11-13", + "type": "updated", + "summary": "order.wave.waveStrategyList 的 strategy_type 过滤支持数组多选(如 [1, 3])", + "methods": [ + "order.wave.waveStrategyList" + ], + "notes": [ + "顶层 strategy_type 与 where.strategy_type 均支持数组写法,如 { strategy_type: [1, 3] };顶层优先于 where。", + "单值写法(1 / \"2\")保持原有行为,仍以等值条件过滤;数组长度 > 1 时按 IN 过滤,数组内字符串会被转换为数字并去重。", + "数组内出现 1/2/3 之外的值(如 [1, 4])直接报错:strategy_type 仅支持 1(散单)、2(团购) 或 3(SN),数组写法如 [1, 3]。", + "空数组表示不过滤,等价于不传 strategy_type。", + "info.order_count 的全部策略命中订单总数统计同口径支持数组:策略侧按 IN (1, 3) 过滤,SN 分支与非 SN 分支各自叠加该条件。" + ] + }, + { + "version": "0.3.342", + "date": "2026-11-13", + "type": "updated", + "summary": "SN 码长度上限扩至 512 字符(支持链接/二维码),订单导出新增 SN 码汇总与商品行 SN 码列表", + "methods": [ + "order.export", + "order.recheckOrder.confirmRecheck" + ], + "notes": [ + "wms_order_item_sn / wms_order_item_sn_log 的 sn_code 由 VARCHAR(128) 扩至 VARCHAR(512)(迁移 20261113160000-enlarge-order-item-sn-code.js);唯一索引 (warehouse_id, sn_code) 仍在上限内。", + "confirmRecheck:单个 SN 码超过 512 字符直接失败,提示「SN码长度不能超过512个字符」,支持链接/二维码内容作为 SN 码。", + "order.export 新增列:waybill 模式「SN码汇总」(sn_codes_summary,订单级全部已登记 SN,仅主单号行输出)、item 模式「SN码」(sn_codes,该商品行登记的 SN 列表);表头枚举 53 → 55。", + "导出只输出 sn_status ∈ BOUND/VERIFIED/REISSUED 的 SN(排除 RETURNED/INVALID),按 wms_order_item_sn.id 升序拼接,逗号分隔。" + ] + }, + { + "version": "0.3.341", + "date": "2026-11-13", + "type": "updated", + "summary": "订单导出新增「SN码数量」列:明细中启用序列号管理商品的 plan_qty 合计", + "methods": [ + "order.export" + ], + "notes": [ + "导出列新增「SN码数量」(字段 sn_quantity),位置紧随「订单商品总数」,waybill / item 两种模式均可选,导出表头枚举由 52 个变为 53 个。", + "口径:订单明细中 stock_warehouse.is_sn_mgmt='Y' 的商品 plan_qty 合计(非 SN 商品不计入),用于账单核对 SN 码数量。", + "waybill 模式:仅主单号行输出订单级合计,子单号行置 0(与「订单商品总类数 / 订单商品总数」一致,避免重复统计)。", + "item 模式:按商品明细行输出该行的 SN 数量,非 SN 商品行为 0,行求和即为订单合计。", + "SN 商品识别按当前导出仓库(warehouse_id)过滤,并对软删商品(paranoid:false)保持兼容。" + ] + }, + { + "version": "0.3.340", + "date": "2026-11-13", + "type": "updated", + "summary": "复核 SN 提交改为唯一格式:sn_map(stock_id -> SN 码列表),移除 sn_list / sn_codes", + "methods": [ + "order.recheckOrder.confirmRecheck" + ], + "notes": [ + "入参只保留 sn_map:{ \"stock_id\": [\"sn_code\", ...] },key 为仓库商品ID(stock_id),value 为该商品的 SN 码列表(兼容逗号/换行分隔字符串)。", + "不再支持 sn_list(按 order_item_id 提交)与 sn_codes(扁平列表);旧格式会被忽略,SN 订单会返回「必须上传全部SN码」。", + "数量校验口径:同一 stock_id 的 SN 数量必须等于该商品在订单内所有明细 plan_qty 合计;同商品多明细时按明细ID升序、按各明细 plan_qty 顺序拆分写入 wms_order_item_sn.order_item_id。", + "非 SN 商品或不属于当前订单的 stock_id 提交 SN 时返回「提交的SN码对应商品不在订单中或未启用序列号管理:stock_id=x」。" + ] + }, + { + "version": "0.3.339", + "date": "2026-11-13", + "type": "updated", + "summary": "SN 策略忽略同结构最大/最小数量限制:抓取候选与列表匹配订单数统一按 SN 口径统计", + "methods": [ + "order.wave.waveStrategyFetchPda", + "order.wave.waveStrategyFetchAdmin", + "order.wave.waveStrategyCreate", + "order.wave.waveStrategyUpdate", + "order.wave.waveStrategyList" + ], + "notes": [ + "SN 策略(strategy_type=3)抓取候选 SQL 不再 JOIN 同结构统计子查询,也不再按 min_same_structure/max_same_structure 过滤;SN 订单只能由 SN 策略抓取,按结构区间过滤会导致单件/少量 SN 订单永远抓不到。", + "列表 matched_order_count_filtered 与 info.order_count 增加 SN 分支:SN 策略只统计命中该策略且满足订单池条件的 SN 订单,不做同结构区间过滤。", + "散单/团购策略的统计口径不变,仍按同结构区间过滤,并统一排除 SN 订单(与抓取口径一致)。", + "本地库实测(仓库 100000、SN 策略 id=9、1~12 同结构区间):忽略区间后候选 2757 单,按区间仅 546 单。" + ] + }, + { + "version": "0.3.338", + "date": "2026-11-13", + "type": "updated", + "summary": "SN 订单回传改为按「SN 齐套 + 已复核」判定,复核通过后自动异步回传一次", + "methods": [ + "order.pendingOrder.syncOrderIds", + "order.recheckOrder.confirmRecheck" + ], + "notes": [ + "order.pendingOrder.syncOrderIds:不再对 SN 订单无差别拦截,改为按明细判定——每个序列号明细的已发出 SN(VERIFIED/REISSUED)数量必须等于 plan_qty,且订单 recheck_status='fin',才允许回传。", + "不满足时仍返回 failed_reason=sn_batch_forbidden,文案改为「SN订单SN明细未齐套或未复核完成,不允许回传」,订单保持 sync_status=error + step=3 待处理异常。", + "order.recheckOrder.confirmRecheck:复核成功后对 SN 订单按签约策略 auto_sync_back 异步触发一次 syncOrderIds(失败仅记录日志,不影响复核结果;已同步订单跳过)。", + "回传报文 orderLines[].snList 改为按 wms_order_item_sn 中 VERIFIED/REISSUED 的 SN 填充,避免 SN 订单回传平台时缺少 SN。" + ] + }, + { + "version": "0.3.337", + "date": "2026-11-13", + "type": "updated", + "summary": "复核接口强制 SN 订单提交 SN 码:按明细数量校验、校验是否已发过、同事务落库", + "methods": [ + "order.recheckOrder.confirmRecheck", + "order.recheckOrder.batchQuickRecheck", + "order.recheckOrder.batchQuickRecheckByWave", + "order.recheckOrder.queryRecheckOrderSingleList" + ], + "notes": [ + "confirmRecheck:has_sn_item='Y' 的订单必须提交 sn_list / sn_map / sn_codes;非 SN 订单提交 SN 码直接失败。", + "数量校验:每个序列号管理明细的 SN 数量必须等于该明细 plan_qty;非序列号管理明细不允许提交 SN 码;同批次 SN 不可重复。", + "是否已发过:SN 已被其它订单/明细占用,或流水已存在 VERIFIED/REISSUED 记录(随其它订单发出)时判定失败。", + "落库:校验通过写入 wms_order_item_sn(sn_status=VERIFIED、verify_status=PASS)与 wms_order_item_sn_log(action_type=VERIFY),并与订单复核状态更新同一事务,任一失败整体回滚。", + "幂等:同订单同明细重复提交已 VERIFIED 的 SN 不重复写入;状态为 BOUND 的 SN 升级为 VERIFIED 并补一条流水。", + "batchQuickRecheck / batchQuickRecheckByWave:SN 订单直接返回失败(reason=复核失败: SN订单需在单订单复核中提交SN码,不支持快捷复核),避免绕过 SN 校验。", + "confirmRecheck 传 wave_id 触发团购波次批量复核时,若波次内存在 SN 订单直接失败:SN订单不支持团购波次复核。", + "响应新增 has_sn_item、sn_count、sn_item_count。", + "queryRecheckOrderSingleList:散单复核列表新增 has_sn_item(Y/N),供前端判断是否需要采集 SN 码。" + ] + }, + { + "version": "0.3.336", + "date": "2026-11-13", + "type": "updated", + "summary": "波次策略新增 SN 类型(strategy_type=3):创建固定先拣后分,快扫只匹配 SN 订单", + "methods": [ + "order.wave.waveStrategyList", + "order.wave.waveStrategyCreate", + "order.wave.waveStrategyUpdate" + ], + "notes": [ + "strategy_type 取值扩展为 1-散单 / 2-团购 / 3-SN(序列号管理)。", + "创建/更新为 3 时 batch_mode 固定为 2(先拣后分),拣货模式固定 pick_mode=3;显式传入的 pick_mode / batch_mode 不生效。", + "快速扫描互斥:SN 策略只命中 has_sn_item='Y' 的订单;散单/团购策略不命中 SN 订单。", + "策略抓取候选:strategy_type=3 只取 SN 订单,1/2 排除 SN 订单;同结构计数口径同步按类型区分。", + "SN 策略建波沿用散单建波形态(wave_type=2)+ pick_mode=3,按 SKU 上限与批次最大订单数切片。" + ] + }, + { + "version": "0.3.335", + "date": "2026-11-13", + "type": "updated", + "summary": "散单波次抓取同样排除 SN(序列号管理)订单:singleOrderFetchList / singleFetch / singleFetchByIds", + "methods": [ + "order.wave.singleOrderFetchList", + "order.wave.singleFetch", + "order.wave.singleFetchByIds" + ], + "notes": [ + "承接 0.3.334:此前仅团购抓取排除 SN,本次起散单抓取同样排除,SN 订单不再进入任何波次(wave_type=1 团购 / 2 散单)。", + "singleOrderFetchList / singleFetch:候选条件与结构抓取统一排除 has_sn_item='Y'。", + "singleFetchByIds:按订单ID抓取时直接跳过 SN 订单,响应新增 excluded_sn_order_ids。", + "散单策略(strategy_type=1)候选与团购策略一致,建波前过滤 SN 订单。" + ] + }, + { + "version": "0.3.334", + "date": "2026-11-13", + "type": "updated", + "summary": "团购波次抓取排除 SN(序列号管理)订单:groupOrderFetchList / groupFetch / fetchableOrderCount", + "methods": [ + "order.wave.groupOrderFetchList", + "order.wave.groupFetch", + "order.wave.fetchableOrderCount" + ], + "notes": [ + "数据口径:订单表 has_sn_item='Y' 视为 SN 订单;NULL 视为非 SN(兼容未回填存量行)。", + "groupOrderFetchList / fetchableOrderCount:候选条件新增 SN 排除,列表与可抓取数不再包含 SN 订单。", + "groupFetch(含 fetch/自动加团):团购结构抓取增加 SN 排除;散单抓取(singleFetch / singleFetchByIds)不受影响,SN 订单仍可走散单。", + "团购策略(strategy_type=2)候选与同结构合并同样排除 SN 订单。" + ] + }, + { + "version": "0.3.333", + "date": "2026-11-13", + "type": "updated", + "summary": "补记 order.list(订单工作台入口)支持 is_sn_order 是否序列号订单筛选", + "methods": [ + "order.list" + ], + "notes": [ + "0.3.332 已为 order.reviewOrder.list / order.pendingOrder.list / order.outboundOrder.list / order.expectionOrder.list / order.entrustOrder.list / order.deliveryOrder.list / order.deliveryExpectionOrder.list / order.archiveOrder.list 补充 is_sn_order 文档;本次补齐 order.list(同为 listByModule 共用筛选链路)。", + "筛选与返回字段口径同 0.3.332:has_sn_item(订单表 Y/N 冗余列)+ is_sn_order(响应归一化 Y/N)。" + ] + }, + { + "version": "0.3.332", + "date": "2026-11-13", + "type": "updated", + "summary": "订单工作台各列表新增 is_sn_order(是否序列号订单)筛选,并返回 has_sn_item / is_sn_order 标记", + "methods": [ + "order.reviewOrder.list", + "order.pendingOrder.list", + "order.outboundOrder.list", + "order.expectionOrder.list", + "order.entrustOrder.list", + "order.deliveryOrder.list", + "order.deliveryExpectionOrder.list", + "order.archiveOrder.list" + ], + "notes": [ + "筛选口径:订单表新增 has_sn_item(Y/N),建单时按明细 stock_warehouse.is_sn_mgmt 聚合写入,任一明细 is_sn_mgmt=Y 即为 Y。", + "取值兼容:Y/N、true/false、1/0、是/否,支持简写与 { value } 标准结构;非法值返回 400(is_sn_order 参数不合法)。", + "存量订单通过迁移 20261113151000-backfill-order-has-sn-item 按明细回填;回填前 has_sn_item 为 NULL 的行在 is_sn_order=N 条件下按非序列号订单返回。", + "列表响应新增 has_sn_item(原始 Y/N)与 is_sn_order(归一化 Y/N)字段,便于前端展示序列号订单标记。" + ] + }, + { + "version": "0.3.331", + "date": "2026-11-12", + "type": "updated", + "summary": "轨迹与揽收查询出站运单号补寄件电话后四位:waybill.warehouse.getTrace / waybill.warehouse.updateReceive 调用外部接口时发送「运单号|后四位」", + "methods": [ + "waybill.warehouse.getTrace", + "waybill.warehouse.updateReceive" + ], + "notes": [ + "背景:中通轨迹 / 揽收查询接口要求携带收寄件人手机号后四位(如 776447927635244|8000)才返回数据。", + "取值口径:按 warehouse_id 命中 wms_order_express 后,用 logistics_interface_id 关联 wms_express_interface.sender_tel,剔除非数字后取后四位。", + "降级:未命中运单、logistics_interface_id 为空、接口未配置电话或电话不足四位时,按纯运单号发送,行为与改动前一致。", + "回写隔离:仅出站报文带后缀,库内匹配与回写(含 wms_order_express.is_galaxy_receive)仍使用纯运单号;外部响应带 |后缀 也能正确匹配。" + ] + }, + { + "version": "0.3.330", + "date": "2026-11-11", + "type": "updated", + "summary": "轨迹查询改为全部回源:waybill.warehouse.getTrace 实时调用外部接口返回,不再落库;下线 waybill.warehouse.updateTrace 与 updateTraceTaskProgress,删除 wms_order_express_trace 表", + "methods": [ + "waybill.warehouse.getTrace", + "waybill.warehouse.updateTrace", + "waybill.warehouse.updateTraceTaskProgress" + ], + "notes": [ + "业务调整:轨迹数据不再本地存储,查询一律实时回源,避免同步延迟与数据双写。", + "getTrace:去掉 refresh 入参(已无本地缓存),去掉 refreshed / refresh_error 返回;返回改为 { waybill_code, total, list, received_updated },list 字段不再含数据库 id / express_id / order_id。", + "揽收联动保留:轨迹非空则把该运单 is_galaxy_receive 置为 Y(只升不降),计数见 received_updated。", + "下线接口:waybill.warehouse.updateTrace、waybill.warehouse.updateTraceTaskProgress 已从代码与文档移除(原异步任务 no longer 适用)。", + "数据库:迁移 20261111205500-drop-wms-order-express-trace.js 删除 wms_order_express_trace,已在开发库与生产库执行;模型 app/model/order_express_trace.js 一并删除。", + "失败口径变化:未配置承接应用或外部接口异常时 getTrace 直接返回失败(此前降级返回本地空数据),避免「空结果」误导。" + ] + }, + { + "version": "0.3.329", + "date": "2026-11-11", + "type": "updated", + "summary": "轨迹同步联动揽收状态:拿到轨迹的运单自动把 is_galaxy_receive 置为 Y(只升不降),任务结果新增 received_updated 计数;getTrace 回源命中时同样生效", + "methods": [ + "waybill.warehouse.updateTrace", + "waybill.warehouse.updateTraceTaskProgress", + "waybill.warehouse.getTrace" + ], + "notes": [ + "背景:有物流轨迹即说明快递已揽收,原先轨迹与揽收状态两条链路互不相通,需要额外调用 updateReceive 才能更新揽收状态。", + "现口径:saveTraces 落库后,对本次拿到轨迹且能匹配到运单的 waybill_code 执行 UPDATE wms_order_express SET is_galaxy_receive='Y'(条件:同仓库、is_galaxy_receive <> 'Y' 或 IS NULL),只升不降。", + "计数:任务 result.received_updated 为实际影响的运单数;提示语追加「揽收状态更新 N 单」。", + "失败隔离:揽收状态更新异常只写 warn 日志,不影响轨迹落库与任务状态。", + "getTrace 自动回源命中轨迹时,同样会触发该联动。" + ] + }, + { + "version": "0.3.328", + "date": "2026-11-11", + "type": "updated", + "summary": "waybill.warehouse.getTrace 支持本地无轨迹时自动回源(并可 refresh=true 强制刷新),新增 refresh 入参与 refreshed / refresh_error 返回字段,解决「外部有轨迹但本地未同步」时查不到的问题", + "methods": [ + "waybill.warehouse.getTrace" + ], + "notes": [ + "背景:getTrace 仅读本地 wms_order_express_trace;若该运单尚未执行过 updateTrace,本地无数据会返回 total=0,而外部实际已有轨迹。", + "现口径:本地无轨迹时自动调用 waybill.getTrace 回源一次并落库,然后再查本地返回;传 refresh=true 时无论本地有无都强制回源。", + "降级:未配置承接应用(callback_functions 未勾选 waybill.getTrace)或外部接口异常时,不阻断查询,返回本地数据并带回 refresh_error。", + "返回新增 refreshed(是否回源)与 refresh_error(回源失败原因)。" + ] + }, { "version": "0.3.327", "date": "2026-11-11", @@ -12942,5 +13319,24 @@ "代码变更:app/service/systemMethods/index.js 新增 buildExpressProductTypeMap 与 attachExpressProductTypes,getShopExpressList 在返回前按平台补充字段(PDD 跳过、不读取产品类型缓存);methods/system.json 同步 data.list 说明与 product_types 子字段文档。" ], "module": "index" + }, + { + "version": "2026.11.14-storeWarehouse.store.saveApiConfig-contract-open-api", + "date": "2026-11-14", + "type": "updated", + "summary": "storeWarehouse.store.saveApiConfig 签约关系级接口配置统一按货主开放接口落库:interface_type_id=3(OPEN_API_WAREHOUSE)自动映射为 2(OPEN_API),货主主体也可维护,callback_url 改由 config.openapi.defaultCallbackUrl 注入", + "methods": [ + "storeWarehouse.store.saveApiConfig", + "storeWarehouse.store.listApiConfig" + ], + "notes": [ + "货主不能创建仓库接口:saveApiConfig 通过 resolveContractApiInterfaceType 解析接口类型,传入 OPEN_API_WAREHOUSE(id=3)时改为按 OPEN_API(id=2,货主开放接口)落库,wms_api_app.interface_type_id 实际写入 2,并记录 warn 日志;未配置启用的 OPEN_API 类型时返回 404「未配置可用的货主开放接口类型」。", + "货主主体可维护:移除 saveApiConfig 中的 ensureWarehouseSubject 校验,project=store 的当前主体也能保存签约关系下的接口配置(deleteQimenConfig、savePolicyConfig、adjustPrintQuantity 仍仅仓库主体可操作)。", + "callback_url 不再取入参:入参 callback_url/callbackUrl 一律忽略,统一写入 config.openapi.defaultCallbackUrl(新增配置项,默认空字符串;为空或长度超过 500 时写 null),值来源为 app/service/systems/store_warehouse.js#getDefaultApiCallbackUrl。", + "listApiConfig 的 interface_type_id 过滤同步映射:传 3 时按 2 过滤,避免保存后按 3 查询查不到配置。", + "回调链路口径不变:service/openapi/callback.js、order_async.js、inbound_direct_log.js 等仍读取 wms_api_app.callback_url,只是该值改由配置统一注入。", + "代码变更:app/service/systems/store_warehouse.js(新增 resolveContractApiInterfaceType / getDefaultApiCallbackUrl,saveApiConfig 与 listApiConfig 调整)、config/config.default.js(新增 config.openapi.defaultCallbackUrl)、methods/system.json 同步 method 文档、测试 test/app/service/systems/store_warehouse.saveApiConfig.test.js 与 store_warehouse.listApiConfig.test.js。" + ], + "module": "storeWarehouse" } ] diff --git a/methods/system.json b/methods/system.json index 3d548cd..df4106b 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.327", - "updatedAt": "2026-11-11", + "version": "0.3.350", + "updatedAt": "2026-11-14", "headers": [ { "name": "platform", @@ -2687,7 +2687,7 @@ "type": "object", "required": false, "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会自动标准化;禁止传入 warehouse_id / warehouseId。支持虚拟字段:buyer_message_has(覆盖 buyer_message/seller_message/remark 三个字段,任一有值即为有留言,value=true/false),express_numbers / waybill_codes(运单号筛选),wave_index(波次内序号筛选,联查 wms_order_wave_index,支持 eq/in/gt/lt/ge/le/between/notbetween,between 要求 value 为长度 2 的数组,如 {\"wave_index\":{\"operator\":\"between\",\"value\":[1,50]}}),wave_scope(波次范围筛选,直接按订单表 wave_scope 字段过滤,支持单个值、数组多选或 { operator, value } 结构;取值:0=未分配波次,1=大团购,2=散单,3=小团购,4=单品单件;示例 {\"wave_scope\":{\"operator\":\"in\",\"value\":[1,3]}} 筛选大团购+小团购,{\"wave_scope\":0} 筛选未分配波次订单)。create_channel(订单来源渠道筛选,按订单表 create_channel 列过滤;枚举:MANUAL=手工单、API=接口、QM=奇门、STOCKOUT=出库转单)。支持简写与标准结构:{\"create_channel\":\"MANUAL\"} 单值精确、{\"create_channel\":[\"QM\",\"API\"]} 裸数组按 in 多选、{\"create_channel\":{\"operator\":\"in\",\"value\":[\"QM\",\"API\"]}} 标准结构多选、{\"create_channel\":{\"operator\":\"ne\",\"value\":\"MANUAL\"}} 排除指定渠道。注意:列表响应中的 create_channel 已格式化为中文标签(手工单/接口/奇门/出库转单),查询条件请传英文枚举值。" + "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会自动标准化;禁止传入 warehouse_id / warehouseId。支持虚拟字段:buyer_message_has(覆盖 buyer_message/seller_message/remark 三个字段,任一有值即为有留言,value=true/false),express_numbers / waybill_codes(运单号筛选),wave_index(波次内序号筛选,联查 wms_order_wave_index,支持 eq/in/gt/lt/ge/le/between/notbetween,between 要求 value 为长度 2 的数组,如 {\"wave_index\":{\"operator\":\"between\",\"value\":[1,50]}}),wave_scope(波次范围筛选,直接按订单表 wave_scope 字段过滤,支持单个值、数组多选或 { operator, value } 结构;取值:0=未分配波次,1=大团购,2=散单,3=小团购,4=单品单件;示例 {\"wave_scope\":{\"operator\":\"in\",\"value\":[1,3]}} 筛选大团购+小团购,{\"wave_scope\":0} 筛选未分配波次订单)。create_channel(订单来源渠道筛选,按订单表 create_channel 列过滤;枚举:MANUAL=手工单、API=接口、QM=奇门、STOCKOUT=出库转单)。支持简写与标准结构:{\"create_channel\":\"MANUAL\"} 单值精确、{\"create_channel\":[\"QM\",\"API\"]} 裸数组按 in 多选、{\"create_channel\":{\"operator\":\"in\",\"value\":[\"QM\",\"API\"]}} 标准结构多选、{\"create_channel\":{\"operator\":\"ne\",\"value\":\"MANUAL\"}} 排除指定渠道。注意:列表响应中的 create_channel 已格式化为中文标签(手工单/接口/奇门/出库转单),查询条件请传英文枚举值。 is_sn_order(是否序列号订单筛选,按订单表 has_sn_item 列过滤):Y=仅序列号订单、N=仅非序列号订单;兼容 true/false、1/0、是/否,支持 {\"is_sn_order\":\"Y\"} 简写与 {\"is_sn_order\":{\"value\":\"Y\"}} 标准结构;存量订单已按明细 stock_warehouse.is_sn_mgmt 回填;sn_code / snCode / sn_codes / snCodes(按 SN 码反查订单:先查 wms_order_item_sn 拿 order_id 再回填到订单列表条件,订单表结构不变;值支持单个字符串、逗号/空格/分号分隔的多个码、字符串数组或 { value } 结构,按完整 SN 码精确匹配)。" }, { "name": "sort", @@ -2702,7 +2702,7 @@ "name": "list", "type": "array", "required": true, - "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段;wave_index(波次内序号,联查 wms_order_wave_index,无记录时为 0)。" + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段;wave_index(波次内序号,联查 wms_order_wave_index,无记录时为 0)。;列表行新增 has_sn_item(原始 Y/N)与 is_sn_order(归一化 Y/N)字段。" }, { "name": "pagination", @@ -3393,7 +3393,7 @@ "type": "array", "required": false, "source": "body", - "description": "导出表头字段白名单(中文表头字符串数组,如 [\"系统订单号\",\"外部订单号\"]);不传或空数组时输出全部列。枚举(共 52 个,校验不区分导出模式):系统订单号、外部订单号、平台单号、订单ID、订单号、外部单号、订单状态、抓取波次号、波次号、波次序号、货主、平台、来源、店铺昵称、收件人、收件人电话、省、市、区、镇、详细地址、商品明细、仓库商品名称、商品条码、商品图片、数量、物流公司、运单号、业务类型、运单接口、包材ID、包材编码、包材名称、分配时间、订单商品总类数、订单商品总数、商品重量、称重重量(g)、订单金额、实收金额、创建时间、支付时间、发货时间、出库状态、复核状态、复核完成状态、配货状态、打包状态、备注、买家留言、卖家留言、归档时间。其中仅 waybill 模式输出:系统订单号、外部订单号、平台单号、抓取波次号、商品明细;仅 item 模式输出:订单ID、订单号、外部单号、波次号、仓库商品名称、商品条码、商品图片、数量;其余为两种模式通用(选了当前模式不存在的表头时该列自动忽略)。来源列(字段 create_channel,中文取值:手工单/接口/奇门/出库转单)位于平台列之后,waybill/item 两种模式均输出。传入非法表头会报错(错误信息列出非法值);支持 export_columns 与 exportColumns 两种写法" + "description": "导出表头字段白名单(中文表头字符串数组,如 [\"系统订单号\",\"外部订单号\"]);不传或空数组时输出全部列。枚举(共 57 个,校验不区分导出模式):系统订单号、外部订单号、平台单号、订单ID、订单号、外部单号、订单状态、拦截状态、抓取波次号、波次号、波次序号、货主、平台、来源、店铺昵称、收件人、收件人电话、省、市、区、镇、详细地址、商品明细、仓库商品名称、商品条码、商品图片、数量、物流公司、运单号、业务类型、运单接口、包材ID、包材编码、包材名称、分配时间、订单商品总类数、订单商品总数、SN码数量、SN码、SN码汇总、商品重量、称重重量(g)、订单金额、实收金额、创建时间、支付时间、发货时间、出库状态、复核状态、复核完成状态、复核时间、配货状态、打包状态、备注、买家留言、卖家留言、归档时间。其中仅 waybill 模式输出:系统订单号、外部订单号、平台单号、抓取波次号、商品明细、SN码汇总;仅 item 模式输出:订单ID、订单号、外部单号、波次号、仓库商品名称、商品条码、商品图片、数量、SN码;其余为两种模式通用(选了当前模式不存在的表头时该列自动忽略)。注意:一旦传入白名单,服务端只按白名单过滤输出列,新增列(如拦截状态、SN码数量、SN码汇总、SN码)必须由调用方在前端导出列选项里同步加上,否则不会出现在导出表头中;不传该参数才会输出当前模式全部列。来源列(字段 create_channel,中文取值:手工单/接口/奇门/出库转单)位于平台列之后,waybill/item 两种模式均输出。传入非法表头会报错(错误信息列出非法值);支持 export_columns 与 exportColumns 两种写法;SN码数量(字段 sn_quantity)为订单明细中启用序列号管理(stock_warehouse.is_sn_mgmt='Y')商品的 plan_qty 合计,用于账单核对:waybill 模式仅在主单号行输出合计值(子单号行为 0),item 模式按商品明细行输出该行 SN 数量(非 SN 商品行为 0)。 SN码(item 模式,字段 sn_codes)为该商品行在复核时登记的 SN 码列表(排序列出,状态限定 BOUND/VERIFIED/REISSUED,排除退回/作废);SN码汇总(waybill 模式,字段 sn_codes_summary)为该订单全部已登记 SN 码的汇总列表,仅主单号行输出(子单号行为空)。" } ], "response": [ @@ -3584,7 +3584,7 @@ "type": "object", "required": false, "source": "body", - "description": "统一 where 条件对象;禁止传入 warehouse_id / warehouseId。create_channel(订单来源渠道筛选,按订单表 create_channel 列过滤;枚举:MANUAL=手工单、API=接口、QM=奇门、STOCKOUT=出库转单)。支持简写与标准结构:{\"create_channel\":\"MANUAL\"} 单值精确、{\"create_channel\":[\"QM\",\"API\"]} 裸数组按 in 多选、{\"create_channel\":{\"operator\":\"in\",\"value\":[\"QM\",\"API\"]}} 标准结构多选、{\"create_channel\":{\"operator\":\"ne\",\"value\":\"MANUAL\"}} 排除指定渠道。注意:列表响应中的 create_channel 已格式化为中文标签(手工单/接口/奇门/出库转单),查询条件请传英文枚举值。" + "description": "统一 where 条件对象;禁止传入 warehouse_id / warehouseId。create_channel(订单来源渠道筛选,按订单表 create_channel 列过滤;枚举:MANUAL=手工单、API=接口、QM=奇门、STOCKOUT=出库转单)。支持简写与标准结构:{\"create_channel\":\"MANUAL\"} 单值精确、{\"create_channel\":[\"QM\",\"API\"]} 裸数组按 in 多选、{\"create_channel\":{\"operator\":\"in\",\"value\":[\"QM\",\"API\"]}} 标准结构多选、{\"create_channel\":{\"operator\":\"ne\",\"value\":\"MANUAL\"}} 排除指定渠道。注意:列表响应中的 create_channel 已格式化为中文标签(手工单/接口/奇门/出库转单),查询条件请传英文枚举值。 is_sn_order(是否序列号订单筛选,按订单表 has_sn_item 列过滤):Y=仅序列号订单、N=仅非序列号订单;兼容 true/false、1/0、是/否,支持 {\"is_sn_order\":\"Y\"} 简写与 {\"is_sn_order\":{\"value\":\"Y\"}} 标准结构;存量订单已按明细 stock_warehouse.is_sn_mgmt 回填;sn_code / snCode / sn_codes / snCodes(按 SN 码反查订单:先查 wms_order_item_sn 拿 order_id 再回填到订单列表条件,订单表结构不变;值支持单个字符串、逗号/空格/分号分隔的多个码、字符串数组或 { value } 结构,按完整 SN 码精确匹配)。" }, { "name": "sort", @@ -3599,7 +3599,7 @@ "name": "list", "type": "array", "required": true, - "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段;wave_index(波次内序号,联查 wms_order_wave_index,无记录时为 0)。" + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段;wave_index(波次内序号,联查 wms_order_wave_index,无记录时为 0)。;列表行新增 has_sn_item(原始 Y/N)与 is_sn_order(归一化 Y/N)字段。" }, { "name": "pagination", @@ -3875,7 +3875,7 @@ "type": "object", "required": false, "source": "body", - "description": "统一 where 条件对象;禁止传入 warehouse_id / warehouseId。where 无字段白名单,可直接传订单表列名。lock_status 锁定状态筛选(筛选值用数据库原始枚举 none/warehouse/store,不是响应中的 Y/N;ne 表示不等于;条件值为空自动忽略):未锁定 {\"lock_status\":\"none\"};已锁定(所有非 none){\"lock_status\":{\"operator\":\"ne\",\"value\":\"none\"}}。create_channel(订单来源渠道筛选,按订单表 create_channel 列过滤;枚举:MANUAL=手工单、API=接口、QM=奇门、STOCKOUT=出库转单)。支持简写与标准结构:{\"create_channel\":\"MANUAL\"} 单值精确、{\"create_channel\":[\"QM\",\"API\"]} 裸数组按 in 多选、{\"create_channel\":{\"operator\":\"in\",\"value\":[\"QM\",\"API\"]}} 标准结构多选、{\"create_channel\":{\"operator\":\"ne\",\"value\":\"MANUAL\"}} 排除指定渠道。注意:列表响应中的 create_channel 已格式化为中文标签(手工单/接口/奇门/出库转单),查询条件请传英文枚举值。confirm_print_status(确认打印状态筛选,按订单表列过滤;枚举:none=未确认打印、fin=已确认打印)。支持简写与标准结构(同 create_channel 示例),如 {\"confirm_print_status\":\"fin\"} 只查已确认打印订单。claim_status(领料状态筛选,按订单表列过滤;枚举:none=未领料、padding=领料中、fin=已领料、error=异常)。支持简写与标准结构(同 create_channel 示例),如 {\"claim_status\":{\"operator\":\"ne\",\"value\":\"fin\"}} 查未完成领料的订单。" + "description": "统一 where 条件对象;禁止传入 warehouse_id / warehouseId。where 无字段白名单,可直接传订单表列名。lock_status 锁定状态筛选(筛选值用数据库原始枚举 none/warehouse/store,不是响应中的 Y/N;ne 表示不等于;条件值为空自动忽略):未锁定 {\"lock_status\":\"none\"};已锁定(所有非 none){\"lock_status\":{\"operator\":\"ne\",\"value\":\"none\"}}。create_channel(订单来源渠道筛选,按订单表 create_channel 列过滤;枚举:MANUAL=手工单、API=接口、QM=奇门、STOCKOUT=出库转单)。支持简写与标准结构:{\"create_channel\":\"MANUAL\"} 单值精确、{\"create_channel\":[\"QM\",\"API\"]} 裸数组按 in 多选、{\"create_channel\":{\"operator\":\"in\",\"value\":[\"QM\",\"API\"]}} 标准结构多选、{\"create_channel\":{\"operator\":\"ne\",\"value\":\"MANUAL\"}} 排除指定渠道。注意:列表响应中的 create_channel 已格式化为中文标签(手工单/接口/奇门/出库转单),查询条件请传英文枚举值。confirm_print_status(确认打印状态筛选,按订单表列过滤;枚举:none=未确认打印、fin=已确认打印)。支持简写与标准结构(同 create_channel 示例),如 {\"confirm_print_status\":\"fin\"} 只查已确认打印订单。claim_status(领料状态筛选,按订单表列过滤;枚举:none=未领料、padding=领料中、fin=已领料、error=异常)。支持简写与标准结构(同 create_channel 示例),如 {\"claim_status\":{\"operator\":\"ne\",\"value\":\"fin\"}} 查未完成领料的订单。 is_sn_order(是否序列号订单筛选,按订单表 has_sn_item 列过滤):Y=仅序列号订单、N=仅非序列号订单;兼容 true/false、1/0、是/否,支持 {\"is_sn_order\":\"Y\"} 简写与 {\"is_sn_order\":{\"value\":\"Y\"}} 标准结构;存量订单已按明细 stock_warehouse.is_sn_mgmt 回填;sn_code / snCode / sn_codes / snCodes(按 SN 码反查订单:先查 wms_order_item_sn 拿 order_id 再回填到订单列表条件,订单表结构不变;值支持单个字符串、逗号/空格/分号分隔的多个码、字符串数组或 { value } 结构,按完整 SN 码精确匹配)。" }, { "name": "sort", @@ -3890,7 +3890,7 @@ "name": "list", "type": "array", "required": true, - "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段;raw 行数据包含 confirm_print_status(确认打印状态,none/fin)与 claim_status(领料状态,none/padding/fin/error)字段;wave_index(波次内序号,联查 wms_order_wave_index,无记录时为 0)。lock_status 字段统一输出为 Y/N:none(含空值)→ 'N',其余值(如 warehouse/store)→ 'Y'。" + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段;raw 行数据包含 confirm_print_status(确认打印状态,none/fin)与 claim_status(领料状态,none/padding/fin/error)字段;wave_index(波次内序号,联查 wms_order_wave_index,无记录时为 0)。lock_status 字段统一输出为 Y/N:none(含空值)→ 'N',其余值(如 warehouse/store)→ 'Y'。;列表行新增 has_sn_item(原始 Y/N)与 is_sn_order(归一化 Y/N)字段。" }, { "name": "pagination", @@ -4417,7 +4417,7 @@ }, { "method": "order.pendingOrder.syncOrderIds", - "description": "同步待处理订单(异步模式)。提交后立即返回 request_id,后台异步执行同步流程。调用方需通过 syncOrderIdsProgress 接口轮询任务进度与最终结果。后台会按 create_channel 分组并行派发同步任务(QM/MANUAL/API);单订单失败写入错误状态(sync_status='error')并标记待处理异常,不影响整批结果;已同步完成(sync_status='fin')的订单会被自动跳过防重复。SN管理订单和快递未分配订单在同步前即被标记为 error 并跳过派发。API 渠道订单逐单先回传 deliveryorder.confirm,回调成功后才扣减库存并更新 sync_status='fin'(回调失败/异常置 error、不扣减库存,可重新派发);QM/MANUAL 渠道派发成功后更新 sync_status='fin',防止重复同步。", + "description": "同步待处理订单(异步模式)。提交后立即返回 request_id,后台异步执行同步流程。调用方需通过 syncOrderIdsProgress 接口轮询任务进度与最终结果。后台会按 create_channel 分组并行派发同步任务(QM/MANUAL/API);单订单失败写入错误状态(sync_status='error')并标记待处理异常,不影响整批结果;已同步完成(sync_status='fin')的订单会被自动跳过防重复。SN(序列号管理)订单不再无差别拦截:仅当「订单未复核完成」或「SN 明细未齐套(存在序列号明细的已发出 SN 数量少于 plan_qty)」时标记为 error 并跳过派发(failed_reason=sn_batch_forbidden);已复核且 SN 齐套的 SN 订单与普通订单一样参与回传,回传报文 orderLines[].snList 会带上已发出(VERIFIED/REISSUED)的 SN 码。快递未分配订单在同步前即被标记为 error 并跳过派发。API 渠道订单逐单先回传 deliveryorder.confirm,回调成功后才扣减库存并更新 sync_status='fin'(回调失败/异常置 error、不扣减库存,可重新派发);QM/MANUAL 渠道派发成功后更新 sync_status='fin',防止重复同步。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -4473,6 +4473,10 @@ { "code": 400, "message": "order_ids 不能为空或格式错误" + }, + { + "code": 200, + "message": "failed_reason=sn_batch_forbidden:SN订单SN明细未齐套或未复核完成,不允许回传" } ] }, @@ -6503,7 +6507,7 @@ "list": [ { "method": "order.recheckOrder.scanOrder", - "description": "扫描关键词并返回以波次为单位的复核视图。支持运单号、波次号、车号三种匹配模式。运单号/波次号命中(散单)返回扁平化订单列表 list_type='single',车号命中(团单)返回嵌套波次结构 list_type='group'。运单号命中但订单无波次信息时,退回单订单详情模式(list 每项含 detail/items/expresses/logs)。所有模式的 list[] 每项均附带 items_weight(订单商品总重量)与 suggested_package_material(推荐包材信息,无推荐时为 null)。", + "description": "扫描关键词并返回以波次为单位的复核视图。支持运单号、波次号、车号三种匹配模式。运单号/波次号命中(散单)返回扁平化订单列表 list_type='single',车号命中(团单)返回嵌套波次结构 list_type='group'。运单号命中但订单无波次信息时,退回单订单详情模式(list 每项含 detail/items/expresses/logs)。所有模式的 list[] 每项均附带 items_weight(订单商品总重量)与 suggested_package_material(推荐包材信息,无推荐时为 null)。 商品行新增 need_sn(Y/N)标识是否需要采集 SN 码,便于 PDA 复核页直接按商品行切换 SN 扫描;团购模式的波次视图 stocks[] 同样输出该字段。商品行同时下发 sn_code_rules(该商品的 SN 码规则数组,来自 wms_stock_warehouse.sn_code_rules),前端可据此把扫到的码加工成 SN 码(match_type=prefix/suffix 匹配前缀或后缀、match_value=前缀/后缀字符串、keep_mode=full 保留全码|strip 去掉前后缀),团购模式 stocks[] 同样输出。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -6754,6 +6758,16 @@ "name": "has_shared_barcode", "type": "boolean", "description": "是否存在共享条码(同一条码出现在多个不同 stock_id 中)" + }, + { + "name": "need_sn", + "type": "string", + "description": "该商品行是否需要采集 SN 码:Y是 N否(来自 wms_stock_warehouse.is_sn_mgmt);为 Y 时提交复核需通过 sn_map 上传该商品全部 SN 码" + }, + { + "name": "sn_code_rules", + "type": "array", + "description": "该商品的 SN 码规则(来自 wms_stock_warehouse.sn_code_rules),用于前端扫码校验/加工;无规则时为空数组。元素:{ match_type: prefix前缀|suffix后缀, match_value: 前缀或后缀字符串, keep_mode: full整个扫码内容作为SN码|strip去掉前缀或后缀后作为SN码 };多条按数组顺序匹配,命中第一条生效,未命中则扫码内容原样作为 SN 码" } ] }, @@ -7105,7 +7119,7 @@ }, { "method": "order.recheckOrder.confirmRecheck", - "description": "按订单 ID 确认复核并记录复核任务到 wms_recheck_task(入参兼容 id/orderId)。确认复核后,若该订单所属波次拣货任务下所有订单均已复核完成,则自动解绑车任务:清空 wms_wave_pick_task 的车绑定信息(current_cart_id、current_cart_code_snapshot)、停用 wms_pick_task_cart_binding 绑定记录(is_active=0 并记录解绑人和时间)并释放 wms_pick_cart(清空 current_task_id、bind_user_id)。解绑失败仅记录 warn 日志,不影响复核主流程。复核状态更新后,会先自动清理波次内「已拦截且未打印」的订单(wave_id 清零回池、删除波次索引与任务订单关联、回写波次统计、写 ORDER_WAVE_REMOVE 日志并触发波次策略快扫),避免拦截订单卡住波次完成判定;已打印的拦截订单保持不动。", + "description": "按订单 ID 确认复核并记录复核任务到 wms_recheck_task(入参兼容 id/orderId)。确认复核后,若该订单所属波次拣货任务下所有订单均已复核完成,则自动解绑车任务:清空 wms_wave_pick_task 的车绑定信息(current_cart_id、current_cart_code_snapshot)、停用 wms_pick_task_cart_binding 绑定记录(is_active=0 并记录解绑人和时间)并释放 wms_pick_cart(清空 current_task_id、bind_user_id)。解绑失败仅记录 warn 日志,不影响复核主流程。复核状态更新后,会先自动清理波次内「已拦截且未打印」的订单(wave_id 清零回池、删除波次索引与任务订单关联、回写波次统计、写 ORDER_WAVE_REMOVE 日志并触发波次策略快扫),避免拦截订单卡住波次完成判定;已打印的拦截订单保持不动。SN(序列号管理)订单复核:订单 has_sn_item='Y' 时必须通过 sn_map 提交全部 SN 码(key=仓库商品ID stock_id,value=该商品的 SN 码列表,数量必须等于该商品在订单内的 plan_qty 合计);服务端会校验 SN 是否重复、是否已被其它订单占用、是否已随其它订单发货;校验通过后 SN 与复核状态在同一事务内落库(wms_order_item_sn + wms_order_item_sn_log),任一失败整体回滚并返回失败。非 SN 商品不允许提交 SN 码。 单个 SN 码最长 512 字符(wms_order_item_sn.sn_code 为 VARCHAR(512)),支持以链接/二维码内容作为 SN 码,超长直接返回失败。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -7123,6 +7137,13 @@ "required": true, "source": "body|query", "description": "订单 ID;优先使用 order_id,兼容别名 id 与 orderId" + }, + { + "name": "sn_map", + "type": "object", + "required": false, + "source": "body|query", + "description": "SN 码提交(唯一格式):{ \"stock_id\": [ \"sn_code\", ... ] },key 为仓库商品ID(订单明细里的 stock_id),value 为该商品的 SN 码列表(也兼容逗号/换行分隔的字符串);SN 订单必填。" } ], "response": [ @@ -7155,6 +7176,24 @@ "type": "string", "required": true, "description": "复核任务编号" + }, + { + "name": "has_sn_item", + "type": "string", + "required": true, + "description": "是否含序列号管理商品:Y是 N否" + }, + { + "name": "sn_count", + "type": "number", + "required": true, + "description": "本次提交并校验通过的 SN 数量(非 SN 订单为 0)" + }, + { + "name": "sn_item_count", + "type": "number", + "required": true, + "description": "本次提交涉及的序列号管理明细数(非 SN 订单为 0)" } ], "errors": [ @@ -7169,6 +7208,42 @@ { "code": 400, "message": "订单未拣货,不允许复核。" + }, + { + "code": 400, + "message": "订单包含序列号管理商品,提交复核时必须上传全部SN码" + }, + { + "code": 400, + "message": "商品[商品编码 商品名称]需提交N个SN码,实际提交M个(N=该商品 plan_qty 合计)" + }, + { + "code": 400, + "message": "SN码重复提交:SN-A、SN-B" + }, + { + "code": 400, + "message": "SN码[SN-A]已被其他订单占用,不可重复使用" + }, + { + "code": 400, + "message": "SN码[SN-A]已随订单[12345]发货,不可重复使用" + }, + { + "code": 400, + "message": "订单序列号商品信息缺失,无法校验SN码,请检查商品是否启用序列号管理" + }, + { + "code": 400, + "message": "SN订单不支持团购波次复核,请使用单订单复核并提交SN码" + }, + { + "code": 400, + "message": "提交的SN码对应商品不在订单中或未启用序列号管理:stock_id=501" + }, + { + "code": 400, + "message": "SN码长度不能超过512个字符(支持链接/二维码内容作为SN码)" } ] }, @@ -7669,7 +7744,7 @@ }, { "method": "order.recheckOrder.batchQuickRecheck", - "description": "批量快捷复核:传入订单 IDs 列表,对每个有效订单执行前置检查(已分配储位、已分配快递、已同步且未被拦截),必要时自动完成拣货(含库存锁定校验与扣减、库存流水写入、拣货任务状态同步)后标记复核(含复核任务记录、任务复核状态更新、车任务解绑、操作日志)。每个订单在独立事务中执行,支持部分失败,不满足条件的订单跳过并返回原因。复核状态更新后,会先自动清理波次内「已拦截且未打印」的订单(wave_id 清零回池、删除波次索引与任务订单关联、回写波次统计、写 ORDER_WAVE_REMOVE 日志并触发波次策略快扫),避免拦截订单卡住波次完成判定;已打印的拦截订单保持不动。", + "description": "批量快捷复核:传入订单 IDs 列表,对每个有效订单执行前置检查(已分配储位、已分配快递、已同步且未被拦截),必要时自动完成拣货(含库存锁定校验与扣减、库存流水写入、拣货任务状态同步)后标记复核(含复核任务记录、任务复核状态更新、车任务解绑、操作日志)。每个订单在独立事务中执行,支持部分失败,不满足条件的订单跳过并返回原因。复核状态更新后,会先自动清理波次内「已拦截且未打印」的订单(wave_id 清零回池、删除波次索引与任务订单关联、回写波次统计、写 ORDER_WAVE_REMOVE 日志并触发波次策略快扫),避免拦截订单卡住波次完成判定;已打印的拦截订单保持不动。SN(序列号管理)订单不支持快捷复核:has_sn_item='Y' 的订单会直接返回失败,需改用单订单复核并提交 SN 码,避免绕过 SN 校验。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -7727,7 +7802,7 @@ { "name": "reason", "type": "string", - "description": "失败原因(未分配储位 / 没有分配快递 / 没有同步 / 已拦截 / 未找到对应订单 / 复核失败: xxx)" + "description": "失败原因(未分配储位 / 没有分配快递 / 没有同步 / 已拦截 / 未找到对应订单 / 复核失败: xxx;SN 订单为 复核失败: SN订单需在单订单复核中提交SN码,不支持快捷复核)" } ] }, @@ -7753,7 +7828,7 @@ }, { "method": "order.recheckOrder.batchQuickRecheckByWave", - "description": "按波次批量快捷复核:传入波次 IDs 列表,对每个波次下所有有效订单执行前置检查(已分配储位、已分配快递、已同步且未被拦截),必要时自动完成拣货(含库存锁定校验与扣减、库存流水写入、拣货任务状态同步)后标记复核(含复核任务记录、任务复核状态更新、车任务解绑、操作日志)。每个订单在独立事务中执行,支持部分失败,不满足条件的订单跳过并返回原因。复核状态更新后,会先自动清理波次内「已拦截且未打印」的订单(wave_id 清零回池、删除波次索引与任务订单关联、回写波次统计、写 ORDER_WAVE_REMOVE 日志并触发波次策略快扫),避免拦截订单卡住波次完成判定;已打印的拦截订单保持不动。", + "description": "按波次批量快捷复核:传入波次 IDs 列表,对每个波次下所有有效订单执行前置检查(已分配储位、已分配快递、已同步且未被拦截),必要时自动完成拣货(含库存锁定校验与扣减、库存流水写入、拣货任务状态同步)后标记复核(含复核任务记录、任务复核状态更新、车任务解绑、操作日志)。每个订单在独立事务中执行,支持部分失败,不满足条件的订单跳过并返回原因。复核状态更新后,会先自动清理波次内「已拦截且未打印」的订单(wave_id 清零回池、删除波次索引与任务订单关联、回写波次统计、写 ORDER_WAVE_REMOVE 日志并触发波次策略快扫),避免拦截订单卡住波次完成判定;已打印的拦截订单保持不动。SN(序列号管理)订单不支持快捷复核:has_sn_item='Y' 的订单会直接返回失败,需改用单订单复核并提交 SN 码,避免绕过 SN 校验。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -7821,7 +7896,7 @@ { "name": "reason", "type": "string", - "description": "失败原因(未分配储位 / 没有分配快递 / 没有同步 / 已拦截 / 波次下无订单 / 复核失败: xxx)" + "description": "失败原因(未分配储位 / 没有分配快递 / 没有同步 / 已拦截 / 波次下无订单 / 复核失败: xxx;SN 订单为 复核失败: SN订单需在单订单复核中提交SN码,不支持快捷复核)" } ] }, @@ -7879,7 +7954,7 @@ "name": "list", "type": "array", "required": true, - "description": "散单复核订单列表,每项含 order_id、delivery_order_code、order_type、wave_id、wave_no、pick_status、recheck_status、shop_nick、logistics_name、items_count、items_total、items_weight、weight_type、waybill_code、wave_index、status、create_at、recheck_time" + "description": "散单复核订单列表,每项含 order_id、delivery_order_code、order_type、wave_id、wave_no、pick_status、recheck_status、shop_nick、logistics_name、items_count、items_total、items_weight、weight_type、waybill_code、wave_index、status、create_at、recheck_time、has_sn_item(新增:是否含序列号管理商品 Y/N,SN 订单复核必须提交 SN 码)" }, { "name": "pagination", @@ -8389,7 +8464,7 @@ "list": [ { "method": "order.wave.waveStrategyList", - "description": "查询当前仓库波次策略列表。仅查询当前登录仓库在 wms_wave_strategy 中的数据,返回标准 list/pagination 结构。", + "description": "查询当前仓库波次策略列表。仅查询当前登录仓库在 wms_wave_strategy 中的数据,返回标准 list/pagination 结构。 matched_order_count_filtered 口径:散单/团购策略按同结构数量区间(require_same_express=1 时按「结构+快递」分组)统计;SN 策略(strategy_type=3)忽略同结构区间,只统计命中该策略且满足订单池条件的 SN 订单。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -8410,17 +8485,17 @@ }, { "name": "strategy_type", - "type": "number", + "type": "number | array", "required": false, "source": "body", - "description": "仅支持 1=散单、2=团购;与 where.strategy_type 同时存在时以顶层 strategy_type 为准。" + "description": "仅支持 1=散单、2=团购、3=SN(序列号管理);支持数组多选,如 [1, 3]。与 where.strategy_type 同时存在时以顶层 strategy_type 为准。" }, { "name": "where", "type": "object", "required": false, "source": "body", - "description": "当前仅支持 where.strategy_type(1/2);其余 where 字段暂不支持。" + "description": "当前仅支持 where.strategy_type(1/2/3,支持数组如 [1, 3]);其余 where 字段暂不支持。" }, { "name": "calculate_next_fetch_order_count / calculateNextFetchOrderCount", @@ -8682,7 +8757,7 @@ }, { "code": "400", - "message": "strategy_type 非法(仅支持 1/2)" + "message": "strategy_type 非法(仅支持 1/2/3;支持数组写法如 [1, 3],任一元组非法即报错)" }, { "code": "500", @@ -8692,7 +8767,7 @@ }, { "method": "order.wave.waveStrategyCreate", - "description": "新增波次策略。warehouse_id 与 creator_name 强制使用当前上下文,不接受外部覆盖。创建成功后会推进仓库的 wave_strategy_version 并失效相关缓存。", + "description": "新增波次策略。warehouse_id 与 creator_name 强制使用当前上下文,不接受外部覆盖。创建成功后会推进仓库的 wave_strategy_version 并失效相关缓存。 strategy_type=3(SN)时 min_same_structure/max_same_structure 可传入但不生效:SN 策略的抓取与匹配订单数统计都会忽略同结构区间。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -8716,14 +8791,14 @@ "type": "number", "required": true, "source": "body", - "description": "策略类型(必填,正整数):1-散单 2-团购" + "description": "策略类型(必填,正整数):1-散单 2-团购 3-SN(序列号管理)。strategy_type=3 时固定批次模式为「先拣后分」(batch_mode=2),拣货模式固定 pick_mode=3。" }, { "name": "batch_mode", "type": "number", "required": true, "source": "body", - "description": "拣货模式(必填,正整数)" + "description": "拣货模式(正整数):1-单品单件 2-先拣后分 3-边拣边分 4-边拣边分H型 5-播种墙 6-流利架。strategy_type=3 时无需传,服务端固定写入 2(先拣后分)。" }, { "name": "status", @@ -8879,7 +8954,7 @@ }, { "method": "order.wave.waveStrategyUpdate", - "description": "修改波次策略。warehouse_id 与 creator_name 强制使用当前上下文,不接受外部覆盖。id(或 strategy_id/strategyId)为必填主键,其他字段为可选更新;更新成功后会推进仓库的 wave_strategy_version 并失效相关缓存。", + "description": "修改波次策略。warehouse_id 与 creator_name 强制使用当前上下文,不接受外部覆盖。id(或 strategy_id/strategyId)为必填主键,其他字段为可选更新;更新成功后会推进仓库的 wave_strategy_version 并失效相关缓存。 strategy_type=3(SN)时 min_same_structure/max_same_structure 可传入但不生效:SN 策略的抓取与匹配订单数统计都会忽略同结构区间。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -8910,7 +8985,7 @@ "type": "number", "required": false, "source": "body", - "description": "策略类型(可选,正整数)" + "description": "策略类型(可选,正整数):1-散单 2-团购 3-SN(序列号管理)。改为 3 时服务端同步将 batch_mode 固定为 2(先拣后分)。" }, { "name": "batch_mode", @@ -9140,7 +9215,7 @@ }, { "method": "order.wave.waveStrategyFetchPda", - "description": "按策略提交并创建抓取主流程任务(PDA)。当前为最小主流程:进行入参校验并创建任务记录,返回创建结果与计划预览;后续扫描/执行阶段将扩展为完整执行流。 注意:当存在未完成任务时,接口返回 fetch_state=3 且同时返回 existing task_id/task_no,前端可直接进入拣货流程。 小团购跨池同结构合并规则:候选订单按创建时间分割为第一池(今日 0 点前)与第二池(今日订单),只有第一池抓取完毕才抓取第二池;小团购(pickMode=1)第一池抓取时,按第一池候选分组出现过的结构 key(require_same_express=1 时为「结构+快递」组合)将同结构全池订单(不限策略匹配、不含池边界)并入候选,随后复用既有分组建波流程,修复同结构订单被两池分割后单独成波(1 单 1 波次)的问题。合并触发条件:小团购 pickMode=1、第一池非空(candidate_pool_stage=first)、策略 max_same_structure 为正整数且≠999;max_same_structure 为 null/999 的团购策略跳过合并维持现状,大团购 pickMode=5 与后台抓取入口(order.wave.waveStrategyFetchAdmin)不覆盖;同结构全池查询无新增订单时亦不合并。", + "description": "按策略提交并创建抓取主流程任务(PDA)。当前为最小主流程:进行入参校验并创建任务记录,返回创建结果与计划预览;后续扫描/执行阶段将扩展为完整执行流。 注意:当存在未完成任务时,接口返回 fetch_state=3 且同时返回 existing task_id/task_no,前端可直接进入拣货流程。 小团购跨池同结构合并规则:候选订单按创建时间分割为第一池(今日 0 点前)与第二池(今日订单),只有第一池抓取完毕才抓取第二池;小团购(pickMode=1)第一池抓取时,按第一池候选分组出现过的结构 key(require_same_express=1 时为「结构+快递」组合)将同结构全池订单(不限策略匹配、不含池边界)并入候选,随后复用既有分组建波流程,修复同结构订单被两池分割后单独成波(1 单 1 波次)的问题。合并触发条件:小团购 pickMode=1、第一池非空(candidate_pool_stage=first)、策略 max_same_structure 为正整数且≠999;max_same_structure 为 null/999 的团购策略跳过合并维持现状,大团购 pickMode=5 与后台抓取入口(order.wave.waveStrategyFetchAdmin)不覆盖;同结构全池查询无新增订单时亦不合并。 SN 策略(strategy_type=3)忽略同结构最小/最大数量限制(min_same_structure/max_same_structure):SN 订单只能由 SN 策略抓取,若按散单同结构区间过滤会永远抓不到单件/少量 SN 订单;其余仍按订单池(wave_id=0、step!=0、快递/储位已分配、未打印、未拦截、未锁定)与 batch_max_skus/batch_max_orders 切片。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -9300,7 +9375,7 @@ }, { "method": "order.wave.waveStrategyFetchAdmin", - "description": "按策略提交并创建抓取主流程任务(后台管理)。当前为最小主流程:执行入参校验并创建任务记录,返回创建结果与计划预览;后续将扩展完整扫描/执行链路。 注意:当存在未完成任务时,接口返回 fetch_state=3 且同时返回 existing task_id/task_no,前端可直接进入拣货流程。", + "description": "按策略提交并创建抓取主流程任务(后台管理)。当前为最小主流程:执行入参校验并创建任务记录,返回创建结果与计划预览;后续将扩展完整扫描/执行链路。 注意:当存在未完成任务时,接口返回 fetch_state=3 且同时返回 existing task_id/task_no,前端可直接进入拣货流程。 SN 策略(strategy_type=3)忽略同结构最小/最大数量限制(min_same_structure/max_same_structure):SN 订单只能由 SN 策略抓取,若按散单同结构区间过滤会永远抓不到单件/少量 SN 订单;其余仍按订单池(wave_id=0、step!=0、快递/储位已分配、未打印、未拦截、未锁定)与 batch_max_skus/batch_max_orders 切片。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -9440,15 +9515,18 @@ "errors": [ { "code": "400", - "description": "参数校验失败(详见 validation_errors)" + "description": "参数校验失败(详见 validation_errors)", + "message": "请求失败" }, { "code": "400", - "description": "未识别到当前仓库上下文" + "description": "未识别到当前仓库上下文", + "message": "请求失败" }, { "code": "500", - "description": "创建任务失败或内部错误,message 字段含简短说明" + "description": "创建任务失败或内部错误,message 字段含简短说明", + "message": "请求失败" } ] }, @@ -9573,7 +9651,7 @@ }, { "method": "order.wave.groupOrderFetchList", - "description": "按机器结构分组的可抓取列表。仅处理待处理订单(排除待审核),且排除已在波次中的订单。", + "description": "按机器结构分组的可抓取列表。仅处理待处理订单(排除待审核),且排除已在波次中的订单。;已排除 SN(序列号管理)订单(has_sn_item='Y'),SN 订单不参与团购抓取。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -9662,7 +9740,7 @@ }, { "method": "order.wave.singleFetchByIds", - "description": "按订单 ID 列表抓取到一个散单波次。仅处理当前仓库的待处理订单(step in [1,2,3]),排除已在波次中的订单(wave_id>0),不区分快递;成功抓取后批量写入订单操作日志;当无可抓取订单时返回 wave_id=0。已锁定订单(lock_status 非 none)不允许抓取波次,返回 excluded_locked_order_ids。", + "description": "按订单 ID 列表抓取到一个散单波次。仅处理当前仓库的待处理订单(step in [1,2,3]),排除已在波次中的订单(wave_id>0),不区分快递;成功抓取后批量写入订单操作日志;当无可抓取订单时返回 wave_id=0。已锁定订单(lock_status 非 none)不允许抓取波次,返回 excluded_locked_order_ids。B2B 订单不参与抓取,返回 excluded_b2b_order_ids。SN(序列号管理)订单允许按订单 ID 显式抓取散单:SN 策略类型的含义只是「不会被散单/团购策略自动抓取」,手工按订单抓取不受限,因此 excluded_sn_order_ids 恒为空数组(字段保留兼容);抓取后的 manual_ids 波次在拣货侧固定走先拣后分(pick_mode=3),与 SN 策略一致。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -9736,6 +9814,12 @@ "type": "array", "required": false, "description": "入参中未在数据库中找到的订单 ID" + }, + { + "name": "excluded_sn_order_ids", + "type": "array", + "required": false, + "description": "因 SN(序列号管理)被排除、未加入波次的订单ID列表;SN 订单现已允许按订单抓取,该字段恒为空数组(保留兼容)" } ], "errors": [ @@ -9877,7 +9961,7 @@ }, { "method": "order.wave.singleOrderFetchList", - "description": "按机器结构分组的散单候选列表。仅处理待处理订单(排除待审核),且排除已在波次中的订单。与 order.wave.groupOrderFetchList 不同:groupOrderFetchList 返回满足同组订单数量 >= same_order_quantity(或仓库配置 min_group_order_fetch_quantity)的团购命中分组;singleOrderFetchList 则排除这些团购命中分组,仅返回同组订单数量小于该阈值的散单候选分组(即 < same_order_quantity)。", + "description": "按机器结构分组的散单候选列表。仅处理待处理订单(排除待审核),且排除已在波次中的订单。与 order.wave.groupOrderFetchList 不同:groupOrderFetchList 返回满足同组订单数量 >= same_order_quantity(或仓库配置 min_group_order_fetch_quantity)的团购命中分组;singleOrderFetchList 则排除这些团购命中分组,仅返回同组订单数量小于该阈值的散单候选分组(即 < same_order_quantity)。;已排除 SN(序列号管理)订单(has_sn_item='Y'),SN 订单不参与散单抓取。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -11220,7 +11304,7 @@ }, { "method": "order.wave.groupFetch", - "description": "抓取团购接口(异步任务提交)", + "description": "抓取团购接口(异步任务提交);团购抓取会排除 SN(序列号管理)订单。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -11291,7 +11375,7 @@ }, { "method": "order.wave.singleFetch", - "description": "抓取散单接口(异步任务提交)", + "description": "抓取散单接口(异步任务提交);散单抓取同样排除 SN(序列号管理)订单。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -11775,7 +11859,7 @@ }, { "method": "order.wave.fetchableOrderCount", - "description": "统计当前仓库团购可抓取订单数。口径与 order.wave.groupOrderFetchList 完全一致(同一候选条件 + items_hash 粗分组 + 团购阈值过滤),但不分页、不查订单明细,仅返回达到团购阈值分组的数量与组内订单数合计。注意与 groupOrderFetchList 的口径差异:其 pagination.total 是分组数,本方法 order_count 是命中分组的订单数合计。", + "description": "统计当前仓库团购可抓取订单数。口径与 order.wave.groupOrderFetchList 完全一致(同一候选条件 + items_hash 粗分组 + 团购阈值过滤),但不分页、不查订单明细,仅返回达到团购阈值分组的数量与组内订单数合计。注意与 groupOrderFetchList 的口径差异:其 pagination.total 是分组数,本方法 order_count 是命中分组的订单数合计。;统计口径同样排除 SN(序列号管理)订单。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -11908,7 +11992,7 @@ "type": "object", "required": false, "source": "body", - "description": "统一 where 条件对象;禁止传入 warehouse_id / warehouseId。create_channel(订单来源渠道筛选,按订单表 create_channel 列过滤;枚举:MANUAL=手工单、API=接口、QM=奇门、STOCKOUT=出库转单)。支持简写与标准结构:{\"create_channel\":\"MANUAL\"} 单值精确、{\"create_channel\":[\"QM\",\"API\"]} 裸数组按 in 多选、{\"create_channel\":{\"operator\":\"in\",\"value\":[\"QM\",\"API\"]}} 标准结构多选、{\"create_channel\":{\"operator\":\"ne\",\"value\":\"MANUAL\"}} 排除指定渠道。注意:列表响应中的 create_channel 已格式化为中文标签(手工单/接口/奇门/出库转单),查询条件请传英文枚举值。" + "description": "统一 where 条件对象;禁止传入 warehouse_id / warehouseId。create_channel(订单来源渠道筛选,按订单表 create_channel 列过滤;枚举:MANUAL=手工单、API=接口、QM=奇门、STOCKOUT=出库转单)。支持简写与标准结构:{\"create_channel\":\"MANUAL\"} 单值精确、{\"create_channel\":[\"QM\",\"API\"]} 裸数组按 in 多选、{\"create_channel\":{\"operator\":\"in\",\"value\":[\"QM\",\"API\"]}} 标准结构多选、{\"create_channel\":{\"operator\":\"ne\",\"value\":\"MANUAL\"}} 排除指定渠道。注意:列表响应中的 create_channel 已格式化为中文标签(手工单/接口/奇门/出库转单),查询条件请传英文枚举值。 is_sn_order(是否序列号订单筛选,按订单表 has_sn_item 列过滤):Y=仅序列号订单、N=仅非序列号订单;兼容 true/false、1/0、是/否,支持 {\"is_sn_order\":\"Y\"} 简写与 {\"is_sn_order\":{\"value\":\"Y\"}} 标准结构;存量订单已按明细 stock_warehouse.is_sn_mgmt 回填;sn_code / snCode / sn_codes / snCodes(按 SN 码反查订单:先查 wms_order_item_sn 拿 order_id 再回填到订单列表条件,订单表结构不变;值支持单个字符串、逗号/空格/分号分隔的多个码、字符串数组或 { value } 结构,按完整 SN 码精确匹配)。" }, { "name": "sort", @@ -11923,7 +12007,7 @@ "name": "list", "type": "array", "required": true, - "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节);本次新增 wave_index(波次内序号,联查 wms_order_wave_index,无记录时为 0)。" + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节);本次新增 wave_index(波次内序号,联查 wms_order_wave_index,无记录时为 0)。;列表行新增 has_sn_item(原始 Y/N)与 is_sn_order(归一化 Y/N)字段。" }, { "name": "pagination", @@ -12156,7 +12240,7 @@ "type": "object", "required": false, "source": "body", - "description": "统一 where 条件对象;禁止传入 warehouse_id / warehouseId。create_channel(订单来源渠道筛选,按订单表 create_channel 列过滤;枚举:MANUAL=手工单、API=接口、QM=奇门、STOCKOUT=出库转单)。支持简写与标准结构:{\"create_channel\":\"MANUAL\"} 单值精确、{\"create_channel\":[\"QM\",\"API\"]} 裸数组按 in 多选、{\"create_channel\":{\"operator\":\"in\",\"value\":[\"QM\",\"API\"]}} 标准结构多选、{\"create_channel\":{\"operator\":\"ne\",\"value\":\"MANUAL\"}} 排除指定渠道。注意:列表响应中的 create_channel 已格式化为中文标签(手工单/接口/奇门/出库转单),查询条件请传英文枚举值。" + "description": "统一 where 条件对象;禁止传入 warehouse_id / warehouseId。create_channel(订单来源渠道筛选,按订单表 create_channel 列过滤;枚举:MANUAL=手工单、API=接口、QM=奇门、STOCKOUT=出库转单)。支持简写与标准结构:{\"create_channel\":\"MANUAL\"} 单值精确、{\"create_channel\":[\"QM\",\"API\"]} 裸数组按 in 多选、{\"create_channel\":{\"operator\":\"in\",\"value\":[\"QM\",\"API\"]}} 标准结构多选、{\"create_channel\":{\"operator\":\"ne\",\"value\":\"MANUAL\"}} 排除指定渠道。注意:列表响应中的 create_channel 已格式化为中文标签(手工单/接口/奇门/出库转单),查询条件请传英文枚举值。 is_sn_order(是否序列号订单筛选,按订单表 has_sn_item 列过滤):Y=仅序列号订单、N=仅非序列号订单;兼容 true/false、1/0、是/否,支持 {\"is_sn_order\":\"Y\"} 简写与 {\"is_sn_order\":{\"value\":\"Y\"}} 标准结构;存量订单已按明细 stock_warehouse.is_sn_mgmt 回填;sn_code / snCode / sn_codes / snCodes(按 SN 码反查订单:先查 wms_order_item_sn 拿 order_id 再回填到订单列表条件,订单表结构不变;值支持单个字符串、逗号/空格/分号分隔的多个码、字符串数组或 { value } 结构,按完整 SN 码精确匹配)。" }, { "name": "sort", @@ -12171,7 +12255,7 @@ "name": "list", "type": "array", "required": true, - "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段;wave_index(波次内序号,联查 wms_order_wave_index,无记录时为 0)。" + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段;wave_index(波次内序号,联查 wms_order_wave_index,无记录时为 0)。;列表行新增 has_sn_item(原始 Y/N)与 is_sn_order(归一化 Y/N)字段。" }, { "name": "pagination", @@ -12341,7 +12425,7 @@ "type": "object", "required": false, "source": "body", - "description": "统一 where 条件对象;禁止传入 warehouse_id / warehouseId。create_channel(订单来源渠道筛选,按订单表 create_channel 列过滤;枚举:MANUAL=手工单、API=接口、QM=奇门、STOCKOUT=出库转单)。支持简写与标准结构:{\"create_channel\":\"MANUAL\"} 单值精确、{\"create_channel\":[\"QM\",\"API\"]} 裸数组按 in 多选、{\"create_channel\":{\"operator\":\"in\",\"value\":[\"QM\",\"API\"]}} 标准结构多选、{\"create_channel\":{\"operator\":\"ne\",\"value\":\"MANUAL\"}} 排除指定渠道。注意:列表响应中的 create_channel 已格式化为中文标签(手工单/接口/奇门/出库转单),查询条件请传英文枚举值。" + "description": "统一 where 条件对象;禁止传入 warehouse_id / warehouseId。create_channel(订单来源渠道筛选,按订单表 create_channel 列过滤;枚举:MANUAL=手工单、API=接口、QM=奇门、STOCKOUT=出库转单)。支持简写与标准结构:{\"create_channel\":\"MANUAL\"} 单值精确、{\"create_channel\":[\"QM\",\"API\"]} 裸数组按 in 多选、{\"create_channel\":{\"operator\":\"in\",\"value\":[\"QM\",\"API\"]}} 标准结构多选、{\"create_channel\":{\"operator\":\"ne\",\"value\":\"MANUAL\"}} 排除指定渠道。注意:列表响应中的 create_channel 已格式化为中文标签(手工单/接口/奇门/出库转单),查询条件请传英文枚举值。 is_sn_order(是否序列号订单筛选,按订单表 has_sn_item 列过滤):Y=仅序列号订单、N=仅非序列号订单;兼容 true/false、1/0、是/否,支持 {\"is_sn_order\":\"Y\"} 简写与 {\"is_sn_order\":{\"value\":\"Y\"}} 标准结构;存量订单已按明细 stock_warehouse.is_sn_mgmt 回填;sn_code / snCode / sn_codes / snCodes(按 SN 码反查订单:先查 wms_order_item_sn 拿 order_id 再回填到订单列表条件,订单表结构不变;值支持单个字符串、逗号/空格/分号分隔的多个码、字符串数组或 { value } 结构,按完整 SN 码精确匹配)。" }, { "name": "sort", @@ -12356,7 +12440,7 @@ "name": "list", "type": "array", "required": true, - "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段;wave_index(波次内序号,联查 wms_order_wave_index,无记录时为 0)。" + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段;wave_index(波次内序号,联查 wms_order_wave_index,无记录时为 0)。;列表行新增 has_sn_item(原始 Y/N)与 is_sn_order(归一化 Y/N)字段。" }, { "name": "pagination", @@ -12479,7 +12563,7 @@ "type": "object", "required": false, "source": "body", - "description": "统一 where 条件对象;禁止传入 warehouse_id / warehouseId。create_channel(订单来源渠道筛选,按订单表 create_channel 列过滤;枚举:MANUAL=手工单、API=接口、QM=奇门、STOCKOUT=出库转单)。支持简写与标准结构:{\"create_channel\":\"MANUAL\"} 单值精确、{\"create_channel\":[\"QM\",\"API\"]} 裸数组按 in 多选、{\"create_channel\":{\"operator\":\"in\",\"value\":[\"QM\",\"API\"]}} 标准结构多选、{\"create_channel\":{\"operator\":\"ne\",\"value\":\"MANUAL\"}} 排除指定渠道。注意:列表响应中的 create_channel 已格式化为中文标签(手工单/接口/奇门/出库转单),查询条件请传英文枚举值。" + "description": "统一 where 条件对象;禁止传入 warehouse_id / warehouseId。create_channel(订单来源渠道筛选,按订单表 create_channel 列过滤;枚举:MANUAL=手工单、API=接口、QM=奇门、STOCKOUT=出库转单)。支持简写与标准结构:{\"create_channel\":\"MANUAL\"} 单值精确、{\"create_channel\":[\"QM\",\"API\"]} 裸数组按 in 多选、{\"create_channel\":{\"operator\":\"in\",\"value\":[\"QM\",\"API\"]}} 标准结构多选、{\"create_channel\":{\"operator\":\"ne\",\"value\":\"MANUAL\"}} 排除指定渠道。注意:列表响应中的 create_channel 已格式化为中文标签(手工单/接口/奇门/出库转单),查询条件请传英文枚举值。 is_sn_order(是否序列号订单筛选,按订单表 has_sn_item 列过滤):Y=仅序列号订单、N=仅非序列号订单;兼容 true/false、1/0、是/否,支持 {\"is_sn_order\":\"Y\"} 简写与 {\"is_sn_order\":{\"value\":\"Y\"}} 标准结构;存量订单已按明细 stock_warehouse.is_sn_mgmt 回填;sn_code / snCode / sn_codes / snCodes(按 SN 码反查订单:先查 wms_order_item_sn 拿 order_id 再回填到订单列表条件,订单表结构不变;值支持单个字符串、逗号/空格/分号分隔的多个码、字符串数组或 { value } 结构,按完整 SN 码精确匹配)。" }, { "name": "sort", @@ -12494,7 +12578,7 @@ "name": "list", "type": "array", "required": true, - "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段;wave_index(波次内序号,联查 wms_order_wave_index,无记录时为 0)。" + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段;wave_index(波次内序号,联查 wms_order_wave_index,无记录时为 0)。;列表行新增 has_sn_item(原始 Y/N)与 is_sn_order(归一化 Y/N)字段。" }, { "name": "pagination", @@ -13062,7 +13146,7 @@ "type": "object", "required": false, "source": "body", - "description": "统一 where 条件对象;禁止传入 warehouse_id / warehouseId。create_channel(订单来源渠道筛选,按订单表 create_channel 列过滤;枚举:MANUAL=手工单、API=接口、QM=奇门、STOCKOUT=出库转单)。支持简写与标准结构:{\"create_channel\":\"MANUAL\"} 单值精确、{\"create_channel\":[\"QM\",\"API\"]} 裸数组按 in 多选、{\"create_channel\":{\"operator\":\"in\",\"value\":[\"QM\",\"API\"]}} 标准结构多选、{\"create_channel\":{\"operator\":\"ne\",\"value\":\"MANUAL\"}} 排除指定渠道。注意:列表响应中的 create_channel 已格式化为中文标签(手工单/接口/奇门/出库转单),查询条件请传英文枚举值。" + "description": "统一 where 条件对象;禁止传入 warehouse_id / warehouseId。create_channel(订单来源渠道筛选,按订单表 create_channel 列过滤;枚举:MANUAL=手工单、API=接口、QM=奇门、STOCKOUT=出库转单)。支持简写与标准结构:{\"create_channel\":\"MANUAL\"} 单值精确、{\"create_channel\":[\"QM\",\"API\"]} 裸数组按 in 多选、{\"create_channel\":{\"operator\":\"in\",\"value\":[\"QM\",\"API\"]}} 标准结构多选、{\"create_channel\":{\"operator\":\"ne\",\"value\":\"MANUAL\"}} 排除指定渠道。注意:列表响应中的 create_channel 已格式化为中文标签(手工单/接口/奇门/出库转单),查询条件请传英文枚举值。 is_sn_order(是否序列号订单筛选,按订单表 has_sn_item 列过滤):Y=仅序列号订单、N=仅非序列号订单;兼容 true/false、1/0、是/否,支持 {\"is_sn_order\":\"Y\"} 简写与 {\"is_sn_order\":{\"value\":\"Y\"}} 标准结构;存量订单已按明细 stock_warehouse.is_sn_mgmt 回填;sn_code / snCode / sn_codes / snCodes(按 SN 码反查订单:先查 wms_order_item_sn 拿 order_id 再回填到订单列表条件,订单表结构不变;值支持单个字符串、逗号/空格/分号分隔的多个码、字符串数组或 { value } 结构,按完整 SN 码精确匹配)。" }, { "name": "sort", @@ -13077,7 +13161,7 @@ "name": "list", "type": "array", "required": true, - "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段;wave_index(波次内序号,联查 wms_order_wave_index,无记录时为 0)。" + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段;wave_index(波次内序号,联查 wms_order_wave_index,无记录时为 0)。;列表行新增 has_sn_item(原始 Y/N)与 is_sn_order(归一化 Y/N)字段。" }, { "name": "pagination", @@ -13206,7 +13290,7 @@ "type": "object", "required": false, "source": "body", - "description": "统一 where 条件对象;禁止传入 warehouse_id / warehouseId。create_channel(订单来源渠道筛选,按订单表 create_channel 列过滤;枚举:MANUAL=手工单、API=接口、QM=奇门、STOCKOUT=出库转单)。支持简写与标准结构:{\"create_channel\":\"MANUAL\"} 单值精确、{\"create_channel\":[\"QM\",\"API\"]} 裸数组按 in 多选、{\"create_channel\":{\"operator\":\"in\",\"value\":[\"QM\",\"API\"]}} 标准结构多选、{\"create_channel\":{\"operator\":\"ne\",\"value\":\"MANUAL\"}} 排除指定渠道。注意:列表响应中的 create_channel 已格式化为中文标签(手工单/接口/奇门/出库转单),查询条件请传英文枚举值。" + "description": "统一 where 条件对象;禁止传入 warehouse_id / warehouseId。create_channel(订单来源渠道筛选,按订单表 create_channel 列过滤;枚举:MANUAL=手工单、API=接口、QM=奇门、STOCKOUT=出库转单)。支持简写与标准结构:{\"create_channel\":\"MANUAL\"} 单值精确、{\"create_channel\":[\"QM\",\"API\"]} 裸数组按 in 多选、{\"create_channel\":{\"operator\":\"in\",\"value\":[\"QM\",\"API\"]}} 标准结构多选、{\"create_channel\":{\"operator\":\"ne\",\"value\":\"MANUAL\"}} 排除指定渠道。注意:列表响应中的 create_channel 已格式化为中文标签(手工单/接口/奇门/出库转单),查询条件请传英文枚举值。 is_sn_order(是否序列号订单筛选,按订单表 has_sn_item 列过滤):Y=仅序列号订单、N=仅非序列号订单;兼容 true/false、1/0、是/否,支持 {\"is_sn_order\":\"Y\"} 简写与 {\"is_sn_order\":{\"value\":\"Y\"}} 标准结构;存量订单已按明细 stock_warehouse.is_sn_mgmt 回填;sn_code / snCode / sn_codes / snCodes(按 SN 码反查订单:先查 wms_order_item_sn 拿 order_id 再回填到订单列表条件,订单表结构不变;值支持单个字符串、逗号/空格/分号分隔的多个码、字符串数组或 { value } 结构,按完整 SN 码精确匹配)。" }, { "name": "sort", @@ -13221,7 +13305,7 @@ "name": "list", "type": "array", "required": true, - "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段;wave_index(波次内序号,联查 wms_order_wave_index,无记录时为 0)。" + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段;wave_index(波次内序号,联查 wms_order_wave_index,无记录时为 0)。;列表行新增 has_sn_item(原始 Y/N)与 is_sn_order(归一化 Y/N)字段。" }, { "name": "pagination", @@ -19617,6 +19701,13 @@ "required": false, "source": "body", "description": "是否需要复核:Y=需要复核,N=不需要复核(非 Y/N 值会报错)" + }, + { + "name": "sn_code_rules / snCodeRules", + "type": "array", + "required": false, + "source": "body", + "description": "SN 码规则数组(整体覆盖保存,最多 20 条;传 [] 表示清空,不传该字段则保持原值)。元素三步:match_type/matchType=prefix(匹配前缀)或 suffix(匹配后缀);match_value/matchValue=要匹配的前缀或后缀字符串(去首尾空白后 1~64 字符);keep_mode/keepMode=full(整个扫码内容作为 SN 码)或 strip(去掉匹配到的前缀/后缀后再作为 SN 码)。多条按数组顺序匹配,命中第一条生效。格式非法(非数组、取值非法、match_value 为空或超长、规则重复、超 20 条)直接报错并指出第几条。存储于 wms_stock_warehouse.sn_code_rules(JSON),复核扫描视图 scanOrder 以 stock[].sn_code_rules 下发前端" } ], "response": [], @@ -19642,6 +19733,13 @@ "required": false, "source": "body", "description": "是否需要复核:Y=需要复核,N=不需要复核;缺省默认 Y(需要复核)" + }, + { + "name": "sn_code_rules / snCodeRules", + "type": "array", + "required": false, + "source": "body", + "description": "SN 码规则数组,创建时未传则存空数组。元素三步:match_type=prefix(前缀)或 suffix(后缀);match_value=要匹配的前缀或后缀字符串(1~64 字符);keep_mode=full(整个扫码内容作为 SN 码)或 strip(去掉前缀/后缀后作为 SN 码)。多条按数组顺序匹配,命中第一条生效;格式非法直接报错" } ], "response": [], @@ -30107,7 +30205,7 @@ }, { "method": "storeWarehouse.store.saveApiConfig", - "description": "新增或更新签约关系下的接口配置。QM_WMS 类型须填写奇门字段;OPEN_API 类型由系统自动生成 self_app_key 和 self_app_secret", + "description": "新增或更新签约关系下的接口配置。QM_WMS 类型须填写奇门字段;OPEN_API 类型由系统自动生成 self_app_key 和 self_app_secret。签约关系级配置统一按货主开放接口落库:传入仓库开放接口(interface_type_id=3)时自动映射为货主开放接口(interface_type_id=2),货主主体也可维护", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -30131,7 +30229,7 @@ "type": "number", "required": true, "source": "body", - "description": "接口类型ID,必须是 wms_interface_type 已存在的类型" + "description": "接口类型ID,必须是 wms_interface_type 已存在的类型;传 3(OPEN_API_WAREHOUSE 仓库开放接口)时按 2(OPEN_API 货主开放接口)落库" }, { "name": "qimen_app_key", @@ -30166,13 +30264,15 @@ "type": "string", "required": false, "source": "body", - "description": "API 回调通知 URL(可选),最大 500 字符;配置后订单状态变更时将回调通知推送到此地址;兼容别名 callbackUrl" + "description": "【已忽略】回调地址不再由入参维护:保存时统一取 config.openapi.defaultCallbackUrl,传入值(含别名 callbackUrl)不再写入" } ], "response": [], "errors": [], "notes": [ - "callback_url:OpenAPI 类型的接口可配置回调地址,订单同步完成/取消等事件将推送到此 URL" + "签约关系级接口配置统一按货主开放接口(OPEN_API)维护:interface_type_id=3(OPEN_API_WAREHOUSE 仓库开放接口)会被映射为 2(OPEN_API 货主开放接口)后落库,仓库不再通过该接口产生仓库开放接口配置", + "货主主体(project=store)也可以维护签约关系下的接口配置,不再要求当前主体为仓库", + "callback_url:签约关系配置保存时统一写入 config.openapi.defaultCallbackUrl(未配置时写 null),入参 callback_url/callbackUrl 一律忽略" ] }, { @@ -42949,7 +43049,7 @@ }, { "method": "waybill.warehouse.updateReceive", - "description": "批量更新运单是否揽收-仓库侧:按运单号(或按 where 筛选条件圈选的运单号)调用外部访问接口 waybill.getreceive 查询揽收状态(单批最多 10 单,超出自动切批),并把结果回写 wms_order_express.is_galaxy_receive(按 warehouse_id 隔离)。异步任务模式,提交后通过 updateReceiveTaskProgress 查询进度。仓库未配置承接该回调方法的 API 应用时直接失败,不创建任务。", + "description": "批量更新运单是否揽收-仓库侧:按运单号(或按 where 筛选条件圈选的运单号)调用外部访问接口 waybill.getreceive 查询揽收状态(单批最多 10 单,超出自动切批),并把结果回写 wms_order_express.is_galaxy_receive(按 warehouse_id 隔离)。出站运单号会按 wms_order_express.logistics_interface_id 关联的 wms_express_interface.sender_tel 补寄件电话后四位(运单号|后四位)。异步任务模式,提交后通过 updateReceiveTaskProgress 查询进度。仓库未配置承接该回调方法的 API 应用时直接失败,不创建任务。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -43238,313 +43338,9 @@ } ] }, - { - "method": "waybill.warehouse.updateTrace", - "description": "批量更新运单物流轨迹-仓库侧:按运单号(或按 where 筛选条件圈选的运单号)调用外部访问接口 waybill.getTrace 查询轨迹(单批最多 10 单,超出自动切批),结果按 (express_id, op_time, scan_type) 幂等落库到 wms_order_express_trace(仓库隔离)。异步任务模式,提交后通过 updateTraceTaskProgress 查询进度。仓库未配置承接该回调方法的 API 应用时直接失败,不创建任务。", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "****** warehouseId(仓库上下文,ctx.user.store_id)" - } - ], - "params": [ - { - "name": "waybillCodes", - "type": "array", - "required": false, - "source": "body", - "description": "运单号列表(字符串数组),提交后按 10 单一批调用外部接口;与 where 二选一,两者都传时以 waybillCodes 为准" - }, - { - "name": "waybill_codes", - "type": "array", - "required": false, - "source": "body", - "description": "waybillCodes 的下划线别名,二者取其一" - }, - { - "name": "where", - "type": "object", - "required": false, - "source": "body", - "description": "筛选条件,与 waybill.warehouse.list 完全一致(不含 pagination/sort),支持 waybillCode / mainWaybillCode / orderId / logisticsCode / status / isBack / isIntercept / isGalaxyReceive / keyword / createdAt 等;服务端先按条件解析运单号再走同一任务链路,匹配数超过 5000 条时失败并要求缩小范围" - } - ], - "response": [ - { - "name": "code", - "type": "number", - "required": true, - "description": "业务状态码,200 表示成功" - }, - { - "name": "message", - "type": "string", - "required": true, - "description": "业务提示信息" - }, - { - "name": "data", - "type": "object", - "required": true, - "description": "成功时返回的任务受理信息(异步任务模式)", - "children": [ - { - "name": "task_id", - "type": "string", - "required": true, - "description": "异步任务ID,前缀 waybill_trace_,用于通过 updateTraceTaskProgress 查询进度" - }, - { - "name": "status", - "type": "string", - "required": true, - "description": "任务状态:submitted(已提交)/ running(执行中)/ success(成功)/ failed(失败)" - }, - { - "name": "progress", - "type": "number", - "required": false, - "description": "任务进度百分比(0-100)" - }, - { - "name": "current_count", - "type": "number", - "required": false, - "description": "已查询的运单数" - }, - { - "name": "total_count", - "type": "number", - "required": false, - "description": "本次提交的运单总数" - }, - { - "name": "message", - "type": "string", - "required": false, - "description": "任务状态说明" - }, - { - "name": "update_time", - "type": "string", - "required": false, - "description": "任务最近更新时间" - } - ] - } - ], - "errors": [ - { - "code": "401", - "message": "未登录,请先登录" - }, - { - "code": "403", - "message": "如需更新运单物流轨迹信息,到【设置】->【基础设置】->【API开放接口】配置相应的外部访问接口" - }, - { - "code": "405", - "message": "参数校验失败:运单号不能为空,或传入 where 筛选条件" - }, - { - "code": "405", - "message": "参数校验失败:符合条件的运单超过 5000 条,请缩小筛选范围或直接传 waybillCodes" - }, - { - "code": "405", - "message": "参数校验失败:未匹配到符合条件的运单" - }, - { - "code": "500", - "message": "服务器内部错误:更新物流轨迹任务创建失败" - } - ], - "notes": [ - "链路:systemMethods/waybill/warehouse.js#updateTrace → systems/waybill.js#queryTraces → openapi/callback.js#sendByAppKey(event=waybill.getTrace)", - "请求与 waybill.getreceive 一致:{ request: { waybill_codes: [...] } },单批最多 10 个运单号,超出自动切批并在每批完成后更新任务进度", - "外部返回格式:[{ waybillNo, trace: {...} }],trace 可为对象或数组(空数组表示暂无轨迹);兼容 { code, data: [...] } 包装。weight 可能为字符串小数(如 \"0.99\"),统一转数字保留 3 位小数落库", - "落库:写 wms_order_express_trace,express_id 由 waybill_code + warehouse_id 匹配 wms_order_express 得到;按 (express_id, op_time, scan_type) 幂等,已存在则更新 memo/op_org_city_name/weight/raw_data;weight 列为 DECIMAL(10,3)", - "匹配不到运单的轨迹不计入落库,运单号写入任务 result.not_found", - "签名口径:与 waybill.getreceive 一致(signMode=simple,MD5(appSecret + timestamp + bodyJson))", - "签名字段映射:opTime→op_time、outBizCode→out_biz_code、memo→memo、opOrgCityName→op_org_city_name、weight→weight、scanType→scan_type,原始报文存 raw_data", - "where 圈选上限 5000 条(与 updateReceive 一致);运单号来源优先级 waybillCodes > where", - "任务进度:task_id 前缀 waybill_trace_,Redis 缓存键前缀 waybill_trace_task_,与导出(waybill_export_)、揽收(waybill_receive_)互相隔离", - "目标应用:仓库下 callback_functions 勾选了 waybill.getTrace 的首个启用应用(按 id 升序)", - "暂无轨迹(trace 为空数组):只计入结果 empty,不判失败、不落库;任务仍为 success" - ] - }, - { - "method": "waybill.warehouse.updateTraceTaskProgress", - "description": "运单物流轨迹更新进度查询-仓库侧:按 task_id 或 taskId 查询异步任务执行进度。任务进度通过 Redis 缓存存储,任务 ID 前缀 waybill_trace_。", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "****** warehouseId(仓库上下文,ctx.user.store_id)" - } - ], - "params": [ - { - "name": "task_id", - "type": "string", - "required": false, - "source": "body", - "description": "异步任务ID(前缀 waybill_trace_)。与 taskId 二选一" - }, - { - "name": "taskId", - "type": "string", - "required": false, - "source": "body", - "description": "异步任务ID(别名,优先使用)" - } - ], - "response": [ - { - "name": "code", - "type": "number", - "required": true, - "description": "业务状态码,200 表示成功" - }, - { - "name": "message", - "type": "string", - "required": true, - "description": "业务提示信息" - }, - { - "name": "data", - "type": "object", - "required": true, - "description": "成功时返回的任务进度信息", - "children": [ - { - "name": "task_id", - "type": "string", - "required": true, - "description": "任务ID" - }, - { - "name": "status", - "type": "string", - "required": true, - "description": "任务状态:submitted / running / success / failed / not_found" - }, - { - "name": "progress", - "type": "number", - "required": false, - "description": "任务进度百分比(0-100)" - }, - { - "name": "current_count", - "type": "number", - "required": false, - "description": "当前已处理的运单数" - }, - { - "name": "total_count", - "type": "number", - "required": false, - "description": "本次提交的运单总数" - }, - { - "name": "message", - "type": "string", - "required": false, - "description": "任务状态说明" - }, - { - "name": "result", - "type": "object", - "required": false, - "description": "任务执行结果(status=success 时返回)", - "children": [ - { - "name": "total", - "type": "number", - "required": false, - "description": "本次提交的运单总数" - }, - { - "name": "matched", - "type": "number", - "required": false, - "description": "匹配到运单记录的运单数" - }, - { - "name": "inserted", - "type": "number", - "required": false, - "description": "新增的轨迹条数" - }, - { - "name": "updated", - "type": "number", - "required": false, - "description": "已存在并更新的轨迹条数" - }, - { - "name": "empty", - "type": "array", - "required": false, - "description": "暂无轨迹的运单号列表(外部返回 trace: [],属正常业务状态,不计失败)" - }, - { - "name": "not_found", - "type": "array", - "required": false, - "description": "当前仓库下未匹配到运单或轨迹为空的运单号列表" - }, - { - "name": "failed", - "type": "array", - "required": false, - "description": "失败明细 [{ waybill_code, reason }]:回调失败、业务码失败或返回值非法" - } - ] - }, - { - "name": "error", - "type": "string", - "required": false, - "description": "错误信息(status=failed 时返回)" - }, - { - "name": "update_time", - "type": "string", - "required": false, - "description": "任务最近更新时间" - } - ] - } - ], - "errors": [ - { - "code": "401", - "message": "未登录,请先登录" - }, - { - "code": "404", - "message": "任务不存在或已过期" - }, - { - "code": "500", - "message": "服务器内部错误:物流轨迹更新进度查询失败" - } - ] - }, { "method": "waybill.warehouse.getTrace", - "description": "查询单个运单的物流轨迹-仓库侧:按运单号一次返回该运单下的全部轨迹(不分页),按操作时间倒序排列(最新在前)。仅返回当前仓库数据(warehouse_id 隔离),运单号不存在时返回空列表。", + "description": "查询单个运单的全部物流轨迹-仓库侧:按运单号实时调用外部访问接口 waybill.getTrace 查询(全部回源,不做本地存储),一次返回全部轨迹(不分页),按操作时间倒序排列(最新在前);命中轨迹时顺带把该运单 is_galaxy_receive 置为 Y(只升不降)。出站运单号会按 wms_order_express.logistics_interface_id 关联的 wms_express_interface.sender_tel 补寄件电话后四位(运单号|后四位)。仓库未配置承接该回调方法的 API 应用时直接失败。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -43588,7 +43384,7 @@ "name": "data", "type": "object", "required": true, - "description": "运单轨迹信息", + "description": "??????", "children": [ { "name": "waybill_code", @@ -43608,24 +43404,6 @@ "required": true, "description": "轨迹列表(按 op_time 倒序,不分页)", "children": [ - { - "name": "id", - "type": "number", - "required": false, - "description": "轨迹记录ID" - }, - { - "name": "express_id", - "type": "number", - "required": false, - "description": "运单ID(wms_order_express.id)" - }, - { - "name": "order_id", - "type": "number", - "required": false, - "description": "订单ID" - }, { "name": "op_time", "type": "string", @@ -43666,9 +43444,15 @@ "name": "raw_data", "type": "object", "required": false, - "description": "原始轨迹报文(未建模字段兜底)" + "description": "外部原始轨迹对象" } ] + }, + { + "name": "received_updated", + "type": "number", + "required": false, + "description": "因本次命中轨迹而把 is_galaxy_receive 置为 Y 的运单数(0 或 1;只升不降)" } ] } @@ -43684,16 +43468,22 @@ }, { "code": "500", - "message": "服务器内部错误:运单轨迹查询失败" + "message": "运单轨迹查询失败:如需查询运单物流轨迹,到【设置】->【基础设置】->【API开放接口】配置相应的外部访问接口" + }, + { + "code": "500", + "message": "运单轨迹查询失败:{外部接口错误信息}" } ], "notes": [ - "链路:systemMethods/waybill/warehouse.js#getTrace → systems/waybill.js#listTracesByWaybill → wms_order_express_trace", - "只读接口:不调用外部接口、不落库,仅查询已由 waybill.warehouse.updateTrace 落库的轨迹", - "不分页:一次返回该运单号下全部轨迹(按 op_time DESC, id DESC 排序)", - "仓库隔离:查询条件固定带 warehouse_id = 当前登录仓库,跨仓不可见", - "运单号不存在或该仓库无轨迹时返回 success + total=0 + list=[],不报错", - "同一运单号若存在主单/子单多条运单记录,轨迹按 waybill_code 聚合返回(轨迹表已冗余 waybill_code)" + "链路:systemMethods/waybill/warehouse.js#getTrace → systems/waybill.js#fetchTracesByWaybill → openapi/callback.js#sendByAppKey(event=waybill.getTrace)", + "全部回源(2026-11-11 调整):不做本地存储,wms_order_express_trace 已下线删除;每次查询都实时调用外部接口", + "请求体:{ request: { waybill_codes: [运单号] } };签名口径与 waybill.getreceive 一致(MD5(appSecret + timestamp + bodyJson))", + "响应解析:[{ waybillNo, trace: [...] }],trace 可为对象或数组,另兼容 { code, data: [...] } 与单个对象返回", + "排序:按 op_time 倒序;weight 支持字符串小数(如 \"0.99\"),统一转数字保留 3 位小数", + "揽收联动:轨迹非空时把该运单 is_galaxy_receive 置为 Y(只升不降,失败只记日志不阻断查询);trace 为空不更新", + "失败口径:未配置承接应用或外部接口异常时直接返回失败(无本地兜底);trace 为空属于正常结果(success + total=0)", + "目标应用:仓库下 callback_functions 勾选了 waybill.getTrace 的首个启用应用(按 id 升序)" ] } ] diff --git a/test/app/lib/qimen_client.test.js b/test/app/lib/qimen_client.test.js index 0fbe9a9..5fc87c4 100644 --- a/test/app/lib/qimen_client.test.js +++ b/test/app/lib/qimen_client.test.js @@ -9,7 +9,12 @@ function buildRequestXml(payload = {}) { const packages = Array.isArray(request.packages?.package) ? request.packages.package : []; const serializedLines = orderLines - .map(line => ` ${line.orderLineNo || ''}${line.itemCode || ''}`) + .map(line => { + const snListXml = Array.isArray(line.snList) && line.snList.length > 0 + ? `${line.snList.map(sn => `${sn}`).join('')}` + : ''; + return ` ${line.orderLineNo || ''}${line.itemCode || ''}${snListXml}`; + }) .join('\n'); const serializedPackages = packages @@ -116,6 +121,76 @@ describe('test/app/lib/qimen_client.test.js', () => { assert.doesNotMatch(sentXml, /\s*/); }); + it('should serialize delivery confirm snList with sn child nodes', async () => { + const app = { + config: { + qimen: { + appKey: 'WMS_APP_KEY', + security: 'WMS_SECRET', + }, + }, + formatDate() { + return '2026-04-24 10:00:00'; + }, + }; + + const client = new QimenClient(app); + let sentXml = ''; + + client.sendRequest = async (url, requestData) => { + sentXml = String(requestData || ''); + return { + queryId: 'Q-TEST-3', + res: 'success200ok', + }; + }; + + const runtime = { + ctx: { + app, + service: { + qimen: { + async parseXmlToArray() { + return { response: { flag: 'success', code: '200', message: 'ok' } }; + }, + async saveQimenLog() { + return 3; + }, + }, + systems: { + sign: { + async toXml(payload) { + return buildRequestXml(payload); + }, + async signTopRequest() { + return 'MOCK-SIGN'; + }, + }, + }, + }, + }, + }; + + await client.send('taobao.qimen.deliveryorder.confirm', 'OWNER-001', { + deliveryOrder: { + deliveryOrderCode: 'DO-1003', + }, + packages: { + package: [], + }, + orderLines: [ + { + orderLineNo: '1', + itemCode: 'SKU-SN', + snList: [ 'SN-A', 'SN-B' ], + }, + ], + }, runtime); + + assert.match(sentXml, /\s*SN-A<\/sn>\s*SN-B<\/sn>\s*<\/snList>/); + assert.doesNotMatch(sentXml, /\s*/); + }); + it('should omit customerId and costomer_id when customerId is null', async () => { const app = { config: { diff --git a/test/app/service/systemMethods/order/wave.singleFetchByIds.test.js b/test/app/service/systemMethods/order/wave.singleFetchByIds.test.js index 40852f4..a2c5fd0 100644 --- a/test/app/service/systemMethods/order/wave.singleFetchByIds.test.js +++ b/test/app/service/systemMethods/order/wave.singleFetchByIds.test.js @@ -142,6 +142,10 @@ function createHarness({ orders = [], storeId = 100000 } = {}) { items_hash: row.items_hash, items: row.items, logistics_name: row.logistics_name, + intercept_status: row.intercept_status, + lock_status: row.lock_status, + is_b2b: row.is_b2b, + has_sn_item: row.has_sn_item, })); }, @@ -287,4 +291,38 @@ describe('test/app/service/systemMethods/order/wave.singleFetchByIds.test.js', ( assert.equal(state.committed, true); assert.equal(state.rolledBack, false); }); + + it('should allow SN orders to be fetched by order ids', async () => { + const { service } = createHarness({ + orders: [ + { id: 401, wave_id: 0, wave_no: '', step: 1, status: 'new', outbound_status: 'none', has_sn_item: 'Y' }, + { id: 402, wave_id: 0, wave_no: '', step: 1, status: 'new', outbound_status: 'none', has_sn_item: 'N' }, + ], + }); + + const result = await service.singleFetchByIds({ ids: [ 401, 402 ] }); + + assert.equal(result.flag, 'success'); + assert.deepEqual(result.fetched_order_ids, [ 401, 402 ]); + assert.equal(result.fetched_order_count, 2); + assert.deepEqual(result.excluded_sn_order_ids, []); + assert.deepEqual(result.skipped_order_ids, []); + }); + + it('should still exclude B2B and intercepted orders while allowing SN orders', async () => { + const { service } = createHarness({ + orders: [ + { id: 501, wave_id: 0, wave_no: '', step: 1, status: 'new', outbound_status: 'none', has_sn_item: 'Y' }, + { id: 502, wave_id: 0, wave_no: '', step: 1, status: 'new', outbound_status: 'none', is_b2b: 'Y' }, + { id: 503, wave_id: 0, wave_no: '', step: 1, status: 'new', outbound_status: 'none', intercept_status: 'padding' }, + ], + }); + + const result = await service.singleFetchByIds({ ids: [ 501, 502, 503 ] }); + + assert.deepEqual(result.fetched_order_ids, [ 501 ]); + assert.deepEqual(result.excluded_b2b_order_ids, [ 502 ]); + assert.deepEqual(result.excluded_intercepted_order_ids, [ 503 ]); + assert.deepEqual(result.excluded_sn_order_ids, []); + }); }); diff --git a/test/app/service/systemMethods/order/wave.waveStrategyList.test.js b/test/app/service/systemMethods/order/wave.waveStrategyList.test.js index 9af8ad7..816debf 100644 --- a/test/app/service/systemMethods/order/wave.waveStrategyList.test.js +++ b/test/app/service/systemMethods/order/wave.waveStrategyList.test.js @@ -1,6 +1,7 @@ 'use strict'; const assert = require('node:assert/strict'); +const { Op } = require('sequelize'); const WaveService = require('../../../../../app/service/systemMethods/order/wave'); @@ -49,6 +50,11 @@ function createHarness(options = {}) { user: { store_id: warehouseId, }, + logger: { + info() {}, + warn() {}, + error() {}, + }, model: { QueryTypes: { SELECT: 'SELECT', @@ -63,6 +69,9 @@ function createHarness(options = {}) { }, }, async query(sql, queryOptions) { + if (options.countError) { + throw options.countError; + } captures.querySql = String(sql || ''); captures.queryOptions = queryOptions; return matchedRows; @@ -198,4 +207,123 @@ describe('test/app/service/systemMethods/order/wave.waveStrategyList.test.js', ( assert.equal(result.list[0].matched_order_count_filtered, 3); assert.equal(result.list[0].next_fetch_order_count, 2); }); + + it('should degrade matched_order_count_filtered to 0 when count query fails', async () => { + const { service } = createHarness({ + warehouseId: 200004, + countError: new Error("Unknown column 'o.has_sn_item' in 'where clause'"), + }); + + const result = await service.waveStrategyList({ + pagination: { + page: 1, + pageSize: 20, + }, + }); + + assert.equal(result.flag, 'success'); + assert.ok(Array.isArray(result.list)); + assert.equal(result.list.length, 2); + assert.equal(result.list[0].matched_order_count_filtered, 0); + assert.equal(result.list[1].matched_order_count_filtered, 0); + }); + + it('should degrade next_fetch_order_count to 0 when preview fails', async () => { + const { service } = createHarness({ + warehouseId: 200005, + countError: new Error("Unknown column 'o.has_sn_item' in 'where clause'"), + }); + + const result = await service.waveStrategyList({ + calculate_next_fetch_order_count: 1, + pagination: { + page: 1, + pageSize: 20, + }, + }); + + assert.equal(result.flag, 'success'); + assert.ok(Array.isArray(result.list)); + assert.equal(result.list[0].matched_order_count_filtered, 0); + assert.equal(result.list[0].next_fetch_order_count, 0); + }); + + it('should support where.strategy_type array by querying with IN filter', async () => { + const { service, captures } = createHarness({ warehouseId: 200006 }); + + const result = await service.waveStrategyList({ + calculate_next_fetch_order_count: 1, + pagination: { + page: 1, + pageSize: 1000, + }, + where: { + strategy_type: [ 1, 3 ], + }, + }); + + assert.deepEqual(captures.findOptions.where, { + warehouse_id: 200006, + strategy_type: { [Op.in]: [ 1, 3 ] }, + }); + assert.ok(captures.querySql.includes('s.strategy_type IN (1, 3)')); + assert.ok(!captures.querySql.includes(':strategyType')); + assert.equal(result.flag, 'success'); + assert.ok(Array.isArray(result.list)); + }); + + it('should dedupe and normalize strategy_type array from string values', async () => { + const { service, captures } = createHarness({ warehouseId: 200007 }); + + await service.waveStrategyList({ + strategy_type: [ '1', 1, '3' ], + pagination: { page: 1, pageSize: 20 }, + }); + + assert.deepEqual(captures.findOptions.where, { + warehouse_id: 200007, + strategy_type: { [Op.in]: [ 1, 3 ] }, + }); + }); + + it('should fall back to unfiltered query when strategy_type array is empty', async () => { + const { service, captures } = createHarness({ warehouseId: 200008 }); + + await service.waveStrategyList({ + strategy_type: [], + pagination: { page: 1, pageSize: 20 }, + }); + + assert.deepEqual(captures.findOptions.where, { + warehouse_id: 200008, + }); + assert.ok(!captures.querySql.includes('s.strategy_type IN (')); + }); + + it('should keep single strategy_type as scalar filter', async () => { + const { service, captures } = createHarness({ warehouseId: 200009 }); + + await service.waveStrategyList({ + strategy_type: '2', + pagination: { page: 1, pageSize: 20 }, + }); + + assert.deepEqual(captures.findOptions.where, { + warehouse_id: 200009, + strategy_type: 2, + }); + assert.ok(captures.querySql.includes('s.strategy_type IN (2)')); + }); + + it('should throw when strategy_type array contains unsupported value', async () => { + const { service } = createHarness({ warehouseId: 200010 }); + + await assert.rejects( + service.waveStrategyList({ + where: { strategy_type: [ 1, 4 ] }, + pagination: { page: 1, pageSize: 20 }, + }), + /strategy_type 仅支持 1\(散单\)、2\(团购\) 或 3\(SN\)/ + ); + }); }); diff --git a/test/app/service/systems/express_platform.cainiao.test.js b/test/app/service/systems/express_platform.cainiao.test.js index 8480229..163c71d 100644 --- a/test/app/service/systems/express_platform.cainiao.test.js +++ b/test/app/service/systems/express_platform.cainiao.test.js @@ -28,6 +28,7 @@ function createCainiaoHarness(options = {}) { operationLogCreateOperationLogs: 0, operationLogPayloads: [], getContractConfigCalls: [], + filterAutoSyncSnOrderIdsCalls: [], syncOrderIdsCalls: [], }; @@ -143,6 +144,15 @@ function createCainiaoHarness(options = {}) { systemMethods: { order: { pendingOrder: { + async filterAutoSyncSnOrderIds(request) { + calls.filterAutoSyncSnOrderIdsCalls.push(request); + const skipped = Array.isArray(options.snOrderIds) ? options.snOrderIds : []; + const requestOrderIds = Array.isArray(request.orderIds) ? request.orderIds : []; + return { + orderIds: requestOrderIds.filter(orderId => !skipped.includes(orderId)), + skippedSnOrderIds: requestOrderIds.filter(orderId => skipped.includes(orderId)), + }; + }, async syncOrderIds(request) { calls.syncOrderIdsCalls.push(request); return { flag: 'success' }; @@ -370,6 +380,12 @@ describe('test/app/service/systems/express_platform.cainiao.test.js', () => { assert.equal(calls.getContractConfigCalls.length, 1); assert.deepEqual(calls.getContractConfigCalls[0], { warehouseId: 100000, storeId: 5001 }); + assert.equal(calls.filterAutoSyncSnOrderIdsCalls.length, 1); + assert.deepEqual(calls.filterAutoSyncSnOrderIdsCalls[0], { + orderIds: [ 2001 ], + warehouseId: 100000, + source: 'cainiao', + }); assert.equal(calls.syncOrderIdsCalls.length, 1); assert.deepEqual(calls.syncOrderIdsCalls[0], { orderIds: [ 2001 ], @@ -377,6 +393,15 @@ describe('test/app/service/systems/express_platform.cainiao.test.js', () => { }); }); + it('auto_sync_back 开启时 SN 订单静默跳过,不触发同步回传', async () => { + const { service, calls } = createCainiaoHarness({ snOrderIds: [ 2001 ] }); + + await service.cainiao(buildPayload()); + + assert.equal(calls.filterAutoSyncSnOrderIdsCalls.length, 1); + assert.equal(calls.syncOrderIdsCalls.length, 0); + }); + it('auto_sync_back 关闭时不应触发订单同步回传', async () => { const { service, calls } = createCainiaoHarness({ contractConfig: { policy_config: { auto_sync_back: 0 } }, diff --git a/test/app/service/systems/express_platform.pdd.ext_data.test.js b/test/app/service/systems/express_platform.pdd.ext_data.test.js index da2fc21..c75d2b7 100644 --- a/test/app/service/systems/express_platform.pdd.ext_data.test.js +++ b/test/app/service/systems/express_platform.pdd.ext_data.test.js @@ -22,6 +22,7 @@ function createPddHarness(options = {}) { printQuantityLogCreate: 0, operationLogCreateOperationLogs: 0, getContractConfigCalls: [], + filterAutoSyncSnOrderIdsCalls: [], syncOrderIdsCalls: [], }; @@ -38,6 +39,9 @@ function createPddHarness(options = {}) { or: 'or', }, }, + async setCacheAsync() { + // no-op in tests + }, }, model: { async transaction(callback) { @@ -106,6 +110,15 @@ function createPddHarness(options = {}) { systemMethods: { order: { pendingOrder: { + async filterAutoSyncSnOrderIds(request) { + calls.filterAutoSyncSnOrderIdsCalls.push(request); + const skipped = Array.isArray(options.snOrderIds) ? options.snOrderIds : []; + const requestOrderIds = Array.isArray(request.orderIds) ? request.orderIds : []; + return { + orderIds: requestOrderIds.filter(orderId => !skipped.includes(orderId)), + skippedSnOrderIds: requestOrderIds.filter(orderId => skipped.includes(orderId)), + }; + }, async syncOrderIds(request) { calls.syncOrderIdsCalls.push(request); return { flag: 'success' }; @@ -239,6 +252,9 @@ describe('test/app/service/systems/express_platform.pdd.ext_data.test.js', () => assert.equal(calls.getContractConfigCalls.length, 1); assert.deepEqual(calls.getContractConfigCalls[0], { warehouseId: 100000, storeId: 5001 }); + assert.equal(calls.filterAutoSyncSnOrderIdsCalls.length, 1); + assert.equal(calls.filterAutoSyncSnOrderIdsCalls[0].source, 'pdd'); + assert.equal(calls.filterAutoSyncSnOrderIdsCalls[0].warehouseId, 100000); assert.equal(calls.syncOrderIdsCalls.length, 1); assert.deepEqual(calls.syncOrderIdsCalls[0], { orderIds: [ 2001 ], @@ -246,6 +262,15 @@ describe('test/app/service/systems/express_platform.pdd.ext_data.test.js', () => }); }); + it('auto_sync_back 开启时 SN 订单静默跳过,不触发同步回传', async () => { + const { service, calls } = createPddHarness({ snOrderIds: [ 2001 ] }); + + await service.pdd(buildPayload()); + + assert.equal(calls.filterAutoSyncSnOrderIdsCalls.length, 1); + assert.equal(calls.syncOrderIdsCalls.length, 0); + }); + it('auto_sync_back 关闭时不应触发订单同步回传', async () => { const { service, calls } = createPddHarness({ contractConfig: { policy_config: { auto_sync_back: 0 } }, diff --git a/test/app/service/systems/express_platform.polyapi.test.js b/test/app/service/systems/express_platform.polyapi.test.js index a8e04d4..e1d3d5c 100644 --- a/test/app/service/systems/express_platform.polyapi.test.js +++ b/test/app/service/systems/express_platform.polyapi.test.js @@ -49,6 +49,7 @@ function createPolyapiHarness(options = {}) { getWaybillAsyncOrderDeliveryModel: 0, getWaybillAsyncOrderDeliveryModelArgs: [], getContractConfigCalls: [], + filterAutoSyncSnOrderIdsCalls: [], syncOrderIdsCalls: [], callSequence: [], }; @@ -276,6 +277,15 @@ function createPolyapiHarness(options = {}) { systemMethods: { order: { pendingOrder: { + async filterAutoSyncSnOrderIds(request) { + calls.filterAutoSyncSnOrderIdsCalls.push(request); + const skipped = Array.isArray(options.snOrderIds) ? options.snOrderIds : []; + const requestOrderIds = Array.isArray(request.orderIds) ? request.orderIds : []; + return { + orderIds: requestOrderIds.filter(orderId => !skipped.includes(orderId)), + skippedSnOrderIds: requestOrderIds.filter(orderId => skipped.includes(orderId)), + }; + }, async syncOrderIds(request) { calls.syncOrderIdsCalls.push(request); return { flag: 'success' }; @@ -528,6 +538,12 @@ describe('test/app/service/systems/express_platform.polyapi.test.js', () => { assert.equal(calls.getContractConfigCalls.length, 1); assert.deepEqual(calls.getContractConfigCalls[0], { warehouseId: 100000, storeId: 2001 }); + assert.equal(calls.filterAutoSyncSnOrderIdsCalls.length, 1); + assert.deepEqual(calls.filterAutoSyncSnOrderIdsCalls[0], { + orderIds: [ 101, 102 ], + warehouseId: 100000, + source: 'polyapi', + }); assert.equal(calls.syncOrderIdsCalls.length, 1); assert.deepEqual(calls.syncOrderIdsCalls[0], { orderIds: [ 101, 102 ], @@ -535,6 +551,15 @@ describe('test/app/service/systems/express_platform.polyapi.test.js', () => { }); }); + it('auto_sync_back 开启时 SN 订单静默跳过,不触发同步回传', async () => { + const { calls, service } = createPolyapiHarness({ snOrderIds: [ 101, 102 ] }); + + await service.polyapi(buildPolyapiPayload()); + + assert.equal(calls.filterAutoSyncSnOrderIdsCalls.length, 1); + assert.equal(calls.syncOrderIdsCalls.length, 0); + }); + it('auto_sync_back 关闭时不应触发订单同步回传', async () => { const { calls, service } = createPolyapiHarness({ contractConfig: { policy_config: { auto_sync_back: 0 } }, diff --git a/test/app/service/systems/order_async.syncOrderIds.test.js b/test/app/service/systems/order_async.syncOrderIds.test.js index bb43bfd..ac03899 100644 --- a/test/app/service/systems/order_async.syncOrderIds.test.js +++ b/test/app/service/systems/order_async.syncOrderIds.test.js @@ -9,8 +9,9 @@ function createHarness(options = {}) { const outboundCalls = []; const noticeCalls = []; const transactionCalls = []; + const callbackCalls = []; const orderRows = Array.isArray(options.orderRows) - ? options.orderRows.map(item => ({ ...item })) + ? options.orderRows.map(item => ({ from_key: 'APP-KEY-1', ...item })) : [ { id: 1, @@ -24,6 +25,7 @@ function createHarness(options = {}) { storage_fee: 12.5, package_code: 'PK-1', invoice_no: 'INV-1', + from_key: 'APP-KEY-1', }, ]; const orderItems = Array.isArray(options.orderItems) @@ -84,6 +86,10 @@ function createHarness(options = {}) { async transaction(callback) { const transaction = { id: `tx-${transactionCalls.length + 1}`, + LOCK: { + UPDATE: 'UPDATE', + SHARE: 'SHARE', + }, }; transactionCalls.push({ transaction }); @@ -162,6 +168,26 @@ function createHarness(options = {}) { return rows.filter(item => normalizedIds.includes(Number(item.order_id))); }, }, + OrderItemSn: { + async findAll(query = {}) { + const rows = (Array.isArray(options.snRows) ? options.snRows : []).map(row => ({ ...row })); + const where = (query && query.where) || {}; + + const matchesIn = (field, value) => { + const condition = where[field]; + if (condition === undefined) return true; + const symbolKeys = condition && typeof condition === 'object' ? Object.getOwnPropertySymbols(condition) : []; + if (symbolKeys.length === 0) return String(condition) === String(value); + const allowed = condition[symbolKeys[0]]; + return Array.isArray(allowed) && allowed.map(String).includes(String(value)); + }; + + return rows.filter(row => (row.warehouse_id === undefined || matchesIn('warehouse_id', row.warehouse_id)) + && matchesIn('order_id', row.order_id) + && matchesIn('order_item_id', row.order_item_id) + && matchesIn('sn_status', String(row.sn_status || '').trim().toUpperCase())); + }, + }, }, user: { store_id: 100000, @@ -202,6 +228,25 @@ function createHarness(options = {}) { }, }, }, + openapi: { + callback: { + async sendByAppKey(payload = {}) { + callbackCalls.push(payload); + if (typeof options.onCallbackSend === 'function') { + return await options.onCallbackSend(payload); + } + + return { + success: true, + retryCount: 0, + response: { + flag: 'success', + code: '200', + }, + }; + }, + }, + }, }, logger: { info() {}, @@ -219,6 +264,7 @@ function createHarness(options = {}) { outboundCalls, noticeCalls, transactionCalls, + callbackCalls, }; } @@ -274,6 +320,114 @@ describe('test/app/service/systems/order_async.syncOrderIds.test.js', () => { assert.equal(result.orders.length, 1); }); + it('should fill orderLines[].snList from wms_order_item_sn for QM confirm', async () => { + const { service, sendCalls } = createHarness({ + orderItems: [ + { + id: 101, + order_id: 1, + order_line_no: '1', + item_code: 'SKU-SN', + item_id: '1001', + item_name: 'SN 商品', + plan_qty: 2, + actual_qty: 2, + inventory_type: 'ZP', + }, + ], + snRows: [ + { warehouse_id: 100000, order_id: 1, order_item_id: 101, sn_code: 'SN-A', sn_status: 'VERIFIED' }, + { warehouse_id: 100000, order_id: 1, order_item_id: 101, sn_code: 'SN-B', sn_status: 'VERIFIED' }, + { warehouse_id: 100000, order_id: 1, order_item_id: 102, sn_code: 'SN-OTHER', sn_status: 'VERIFIED' }, + { warehouse_id: 100000, order_id: 1, order_item_id: 101, sn_code: 'SN-RETURNED', sn_status: 'RETURNED' }, + ], + }); + + const result = await service.syncQmOrders({ + create_channel: 'QM', + order_ids: [ 1 ], + order_count: 1, + orders: [{ id: 1 }], + }, { + warehouseId: 100000, + customerId: 'OWNER-001', + }); + + assert.equal(result.status, 'success'); + assert.equal(sendCalls.length, 1); + assert.deepEqual(sendCalls[0].data.orderLines[0].snList, [ 'SN-A', 'SN-B' ]); + // 包裹明细不带 snList(与奇门 deliveryorder.confirm 一致:snList 只在 orderLines 上) + assert.equal(sendCalls[0].data.packages.package[0].items[0].snList, undefined); + }); + + it('should route over-length SN codes to orderLine.qrCode', async () => { + const longSnCode = `https://trace.example.com/sn?code=${'A'.repeat(60)}`; + const { service, sendCalls } = createHarness({ + orderItems: [ + { + id: 101, + order_id: 1, + order_line_no: '1', + item_code: 'SKU-SN', + item_id: '1001', + item_name: 'SN 商品', + plan_qty: 3, + actual_qty: 3, + inventory_type: 'ZP', + qr_code: 'QR-EXIST', + }, + ], + snRows: [ + { warehouse_id: 100000, order_id: 1, order_item_id: 101, sn_code: 'SN-A', sn_status: 'VERIFIED' }, + { warehouse_id: 100000, order_id: 1, order_item_id: 101, sn_code: longSnCode, sn_status: 'VERIFIED' }, + ], + }); + + await service.syncQmOrders({ + create_channel: 'QM', + order_ids: [ 1 ], + order_count: 1, + orders: [{ id: 1 }], + }, { + warehouseId: 100000, + customerId: 'OWNER-001', + }); + + assert.deepEqual(sendCalls[0].data.orderLines[0].snList, [ 'SN-A' ]); + assert.equal(sendCalls[0].data.orderLines[0].qrCode, `QR-EXIST;${longSnCode}`); + }); + + it('should keep snList empty for non-SN order', async () => { + const { service, sendCalls } = createHarness({ + orderItems: [ + { + id: 101, + order_id: 1, + order_line_no: '1', + item_code: 'SKU-NORMAL', + item_id: '1001', + item_name: '普通商品', + plan_qty: 2, + actual_qty: 2, + inventory_type: 'ZP', + }, + ], + snRows: [], + }); + + await service.syncQmOrders({ + create_channel: 'QM', + order_ids: [ 1 ], + order_count: 1, + orders: [{ id: 1 }], + }, { + warehouseId: 100000, + customerId: 'OWNER-001', + }); + + assert.deepEqual(sendCalls[0].data.orderLines[0].snList, []); + }); + it('should rollback local success handling and mark exception when stock deduction fails', async () => { const { service, updates, outboundCalls } = createHarness({ async onOutbound() { @@ -611,7 +765,7 @@ describe('test/app/service/systems/order_async.syncOrderIds.test.js', () => { }); it('should process API orders with stock deduction and success status', async () => { - const { service, outboundCalls } = createHarness(); + const { service, outboundCalls, callbackCalls } = createHarness(); const result = await service.syncApiOrders({ create_channel: 'API', @@ -633,11 +787,46 @@ describe('test/app/service/systems/order_async.syncOrderIds.test.js', () => { assert.equal(result.sync_results.length, 1); assert.equal(result.sync_results[0].status, 'success'); assert.equal(outboundCalls.length, 1); - assert.deepEqual(outboundCalls[0].meta, { - orderId: 1, - orderNo: 'DO-1001', - orderItemId: 101, + + // OpenAPI 回调报文与奇门同层级 { request: {...} },orderLines[].snList 必须带上 SN + assert.equal(callbackCalls.length, 1); + assert.equal(callbackCalls[0].event, 'deliveryorder.confirm'); + assert.equal(callbackCalls[0].appKey, 'APP-KEY-1'); + assert.deepEqual(callbackCalls[0].request.orderLines[0].snList, [ 'SN-1', 'SN-2' ]); + }); + + it('should keep over-length SN codes in snList for API callback (no qrCode split)', async () => { + const longSnCode = `HTTPS://SUYUAN.HULIANZAOWU.COM/PRODUCT?Q=${'A'.repeat(40)}`; + const { service, callbackCalls } = createHarness({ + orderItems: [ + { + id: 101, + order_id: 1, + order_line_no: '1', + item_code: 'SKU-SN', + item_id: '1001', + item_name: 'SN 商品', + plan_qty: 1, + actual_qty: 1, + inventory_type: 'ZP', + }, + ], + snRows: [ + { warehouse_id: 100000, order_id: 1, order_item_id: 101, sn_code: longSnCode, sn_status: 'VERIFIED' }, + ], }); + + await service.syncApiOrders({ + create_channel: 'API', + order_ids: [ 1 ], + order_count: 1, + orders: [{ id: 1 }], + }, { + warehouseId: 100000, + }); + + assert.deepEqual(callbackCalls[0].request.orderLines[0].snList, [ longSnCode ]); + assert.equal(callbackCalls[0].request.orderLines[0].qrCode, ''); }); it('should process QM orders concurrently per order', async () => { diff --git a/test/app/service/systems/storage_report_export.test.js b/test/app/service/systems/storage_report_export.test.js index 0552663..1d16dc7 100644 --- a/test/app/service/systems/storage_report_export.test.js +++ b/test/app/service/systems/storage_report_export.test.js @@ -82,7 +82,7 @@ function createSummaryList() { ]; } -function createHarness({ detailRows = [], summaryList = [] } = {}) { +function createHarness({ detailRows = [], summaryList = [], orderLocations = null, orderDeliveryRows = [] } = {}) { const captured = { queries: [], upload: null, @@ -147,11 +147,34 @@ function createHarness({ detailRows = [], summaryList = [] } = {}) { .slice(0, 5000) .map(row => ({ ...row })); } + if (/wms_order_delivery_\d+(_dispatch|_history|_outsourced)?\b/.test(sql)) { + const ids = (options.replacements && options.replacements.ids) || []; + return orderDeliveryRows.filter(row => ids.includes(Number(row.id))); + } if (sql.includes('wms_entry_order') || sql.includes('wms_order_delivery') || sql.includes('wms_order_express')) { return []; } return []; }, + OrderDeliveryFactory: orderLocations + ? { + generateTableName(warehouseId, type) { + return type === 'current' + ? `wms_order_delivery_${warehouseId}` + : `wms_order_delivery_${warehouseId}_${type}`; + }, + async getOrderLocations(orderIds) { + const locationMap = new Map(); + for (const orderId of orderIds) { + const location = orderLocations[String(orderId)]; + if (location) { + locationMap.set(Number(orderId), location); + } + } + return locationMap; + }, + } + : undefined, Store: { async findAll() { return [{ id: 1000305, company_name: '测试货主' }]; @@ -273,4 +296,59 @@ describe('test/app/service/systems/storage_report_export.test.js', () => { assert.equal(detailSheet.rowCount, 1, '空明细 sheet 应只有表头行'); assert.equal(detailSheet.getCell('A1').value, '时间'); }); + + it('订单出库单据号取发货单号(按订单ID定位配送分表),平台交易单号取 source_order_codes', async () => { + const baseRow = createDetailRows(1)[0]; + const detailRows = [ + { + ...baseRow, + id: 1, + transaction_type: 'OUTBOUND', + order_type: 'ORDER', + order_no: '6919442205411192615', + order_id: 1677331, + warehouse_id: 1000028, + }, + { + ...baseRow, + id: 2, + transaction_type: 'INBOUND', + order_type: 'RECEIVING', + order_no: 'RK-20261112-001', + order_id: 0, + }, + ]; + const { service, captured } = createHarness({ + detailRows, + summaryList: createSummaryList(), + orderLocations: { 1677331: 'dispatch' }, + orderDeliveryRows: [ + { + id: 1677331, + delivery_order_code: '231608698482-SDO1037663570473-59329', + source_order_codes: '6919442205411192615', + }, + ], + }); + + const result = await service.export(null, null, false, [], null, '', 'store', null, '', async () => {}); + assert.ok(result && result.filename, '应返回文件名'); + + // 位置索引命中 dispatch 后直达分表,不再扫描 current/history + const shardQueries = captured.queries + .map(query => query.sql) + .filter(sql => /wms_order_delivery_\d+/.test(sql)); + assert.equal(shardQueries.length, 1, `应只查询一次配送分表,实际 ${shardQueries.length} 次`); + assert.ok(shardQueries[0].includes('wms_order_delivery_1000028_dispatch'), '应按订单所属仓库查询 dispatch 分表'); + + const workbook = new ExcelJS.Workbook(); + await workbook.xlsx.load(captured.uploadedBuffer); + const detailSheet = workbook.getWorksheet('变更记录'); + // Q=单据号、R=单据ID、T=平台交易单号 + assert.equal(detailSheet.getCell('Q1').value, '单据号'); + assert.equal(detailSheet.getCell('Q2').value, '231608698482-SDO1037663570473-59329', '订单出库单据号应取发货单号'); + assert.equal(detailSheet.getCell('R2').value, 1677331, '单据ID 保持订单主键'); + assert.equal(detailSheet.getCell('T2').value, '6919442205411192615', '平台交易单号取 source_order_codes'); + assert.equal(detailSheet.getCell('Q3').value, 'RK-20261112-001', '无发货单记录时回退流水单据号'); + }); }); diff --git a/test/app/service/systems/store_warehouse.listApiConfig.test.js b/test/app/service/systems/store_warehouse.listApiConfig.test.js index c5005ce..4bbfe35 100644 --- a/test/app/service/systems/store_warehouse.listApiConfig.test.js +++ b/test/app/service/systems/store_warehouse.listApiConfig.test.js @@ -17,6 +17,7 @@ function createListApiConfigHarness(options = {}) { const capture = { apiAppFindAllArgs: [], qimenAppFindAllArgs: [], + interfaceTypeFindOneArgs: [], }; const rows = options.rows || []; @@ -50,7 +51,14 @@ function createListApiConfigHarness(options = {}) { return qimenApps.filter(item => appKeys.includes(item.app_key)); }, }, - InterfaceType: {}, + InterfaceType: { + async findOne(args = {}) { + capture.interfaceTypeFindOneArgs.push(args); + const { where = {} } = args; + return (options.interfaceTypes || []).find(item => Object.entries(where) + .every(([ key, value ]) => item[key] === value)) || null; + }, + }, }, logger: { info() {}, @@ -129,4 +137,21 @@ describe('test/app/service/systems/store_warehouse.listApiConfig.test.js', () => app_key: [ 'qm-app-key-1' ], }); }); + + it('should map warehouse open api filter to store open api configs', async () => { + const { service, capture } = createListApiConfigHarness({ + interfaceTypes: [ + { id: 2, interface_code: 'OPEN_API', interface_name: '货主开放接口', interface_category: 'OPEN_API', is_enabled: 1 }, + { id: 3, interface_code: 'OPEN_API_WAREHOUSE', interface_name: '仓库开放接口', interface_category: 'OPEN_API', is_enabled: 1 }, + ], + }); + + await service.listApiConfig({ + id: 88, + interface_type_id: 3, + }); + + assert.equal(capture.apiAppFindAllArgs.length, 1); + assert.equal(Number(capture.apiAppFindAllArgs[0].where.interface_type_id), 2); + }); }); diff --git a/test/app/service/systems/store_warehouse.saveApiConfig.test.js b/test/app/service/systems/store_warehouse.saveApiConfig.test.js index 19dff93..98fb561 100644 --- a/test/app/service/systems/store_warehouse.saveApiConfig.test.js +++ b/test/app/service/systems/store_warehouse.saveApiConfig.test.js @@ -13,8 +13,12 @@ const StoreWarehouseService = require('../../../../app/service/systems/store_war function createSaveApiConfigHarness(options = {}) { const interfaceType = { id: Number(options.interfaceTypeId || 7), + interface_code: options.interfaceCode || 'QM_WMS', interface_category: options.interfaceCategory || 'QM_WMS', }; + const effectiveInterfaceType = options.interfaceCode === 'OPEN_API_WAREHOUSE' && options.storeInterfaceType + ? options.storeInterfaceType + : interfaceType; const relation = { id: Number(options.relationId || 88), warehouse_id: Number(options.warehouseId || 100000), @@ -22,6 +26,7 @@ function createSaveApiConfigHarness(options = {}) { const capture = { qimenAppFindOneArgs: [], apiAppFindOneArgs: [], + interfaceTypeFindOneArgs: [], apiAppCreatePayload: null, apiAppUpdatePayload: null, operationLogPayload: null, @@ -44,8 +49,8 @@ function createSaveApiConfigHarness(options = {}) { persistedConfig = { ...options.existingConfig, interface_type: { - id: interfaceType.id, - interface_category: interfaceType.interface_category, + id: effectiveInterfaceType.id, + interface_category: effectiveInterfaceType.interface_category, }, }; existingConfig = { @@ -56,8 +61,8 @@ function createSaveApiConfigHarness(options = {}) { ...persistedConfig, ...payload, interface_type: { - id: interfaceType.id, - interface_category: interfaceType.interface_category, + id: effectiveInterfaceType.id, + interface_category: effectiveInterfaceType.interface_category, }, }; return this; @@ -67,7 +72,7 @@ function createSaveApiConfigHarness(options = {}) { const ctx = { app: { - config: {}, + config: options.config || {}, Sequelize, }, user: { @@ -97,8 +102,8 @@ function createSaveApiConfigHarness(options = {}) { id: Number(options.createdConfigId || 321), ...payload, interface_type: { - id: interfaceType.id, - interface_category: interfaceType.interface_category, + id: effectiveInterfaceType.id, + interface_category: effectiveInterfaceType.interface_category, }, }; return { @@ -112,7 +117,12 @@ function createSaveApiConfigHarness(options = {}) { }; }, }, - InterfaceType: {}, + InterfaceType: { + async findOne(args = {}) { + capture.interfaceTypeFindOneArgs.push(args); + return options.storeInterfaceType || null; + }, + }, StoreWarehouse: { async findByPk(id) { return { @@ -141,9 +151,12 @@ function createSaveApiConfigHarness(options = {}) { ctx.app.model = ctx.model; const service = new StoreWarehouseService(ctx); - service.getCurrentSubject = async () => ({ role: 'warehouse' }); + service.getCurrentSubject = async () => options.currentSubject || { + id: relation.warehouse_id, + isWarehouse: true, + project: 'warehouse', + }; service.findScopedRelation = async () => relation; - service.ensureWarehouseSubject = () => {}; service.getApiInterfaceType = async () => interfaceType; service.getRelationIncludes = () => []; service.serializeRelation = result => ({ @@ -258,4 +271,97 @@ describe('test/app/service/systems/store_warehouse.saveApiConfig.test.js', () => assert.equal(transaction.committed, false); assert.equal(transaction.rolledBack, true); }); + + it('should store warehouse open api as store open api and use default callback url', async () => { + const { service, capture, transaction } = createSaveApiConfigHarness({ + interfaceTypeId: 3, + interfaceCode: 'OPEN_API_WAREHOUSE', + interfaceCategory: 'OPEN_API', + storeInterfaceType: { + id: 2, + interface_code: 'OPEN_API', + interface_name: '货主开放接口', + interface_category: 'OPEN_API', + }, + config: { + openapi: { + defaultCallbackUrl: ' https://callback.example.com/openapi ', + }, + }, + }); + + const result = await service.saveApiConfig({ + id: 88, + interface_type_id: 3, + app_name: '货主接口配置', + callback_url: 'https://ignored.example.com/hook', + }); + + assert.equal(capture.interfaceTypeFindOneArgs.length, 1); + assert.equal(capture.interfaceTypeFindOneArgs[0].where.interface_code, 'OPEN_API'); + assert.equal(capture.apiAppCreatePayload.interface_type_id, 2); + assert.equal(capture.apiAppCreatePayload.callback_url, 'https://callback.example.com/openapi'); + assert.equal(result.data.api_config.interface_type_id, 2); + assert.equal(transaction.committed, true); + }); + + it('should not write callback_url when default callback url is not configured', async () => { + const { service, capture } = createSaveApiConfigHarness({ + interfaceTypeId: 2, + interfaceCode: 'OPEN_API', + interfaceCategory: 'OPEN_API', + }); + + await service.saveApiConfig({ + id: 88, + interface_type_id: 2, + app_name: '无默认回调地址', + callback_url: 'https://ignored.example.com/hook', + }); + + assert.equal(capture.apiAppCreatePayload.callback_url, null); + }); + + it('should allow store subject to save contract api config', async () => { + const { service, capture, transaction } = createSaveApiConfigHarness({ + interfaceTypeId: 2, + interfaceCode: 'OPEN_API', + interfaceCategory: 'OPEN_API', + currentSubject: { id: 1000000, isWarehouse: false, project: 'store' }, + }); + + await service.saveApiConfig({ + id: 88, + interface_type_id: 2, + app_name: '货主自建开放接口', + }); + + assert.equal(Number(capture.apiAppCreatePayload.interface_type_id), 2); + assert.equal(transaction.committed, true); + assert.equal(transaction.rolledBack, false); + }); + + it('should fail when store open api interface type is missing', async () => { + const { service, capture, transaction } = createSaveApiConfigHarness({ + interfaceTypeId: 3, + interfaceCode: 'OPEN_API_WAREHOUSE', + interfaceCategory: 'OPEN_API', + }); + + await assert.rejects(async () => { + await service.saveApiConfig({ + id: 88, + interface_type_id: 3, + app_name: '缺失货主开放接口类型', + }); + }, error => { + assert.equal(Number(error.code), 404); + assert.match(String(error.message || ''), /货主开放接口类型/); + return true; + }); + + assert.equal(capture.apiAppCreatePayload, null); + assert.equal(transaction.committed, false); + assert.equal(transaction.rolledBack, true); + }); }); diff --git a/test/support/order_service_test_helper.js b/test/support/order_service_test_helper.js index b8e09ea..c83d89b 100644 --- a/test/support/order_service_test_helper.js +++ b/test/support/order_service_test_helper.js @@ -57,6 +57,15 @@ function matchesWhere(row, where) { return row[fieldName] !== condition[Sequelize.Op.ne]; } + if (Object.prototype.hasOwnProperty.call(condition, Sequelize.Op.is)) { + const expected = condition[Sequelize.Op.is]; + const actual = row[fieldName]; + if (expected === null) { + return actual === null || actual === undefined; + } + return actual === expected; + } + if (Object.prototype.hasOwnProperty.call(condition, Sequelize.Op.in)) { const values = condition[Sequelize.Op.in]; return Array.isArray(values) && values.includes(row[fieldName]);