Compare commits
No commits in common. "0a6e82e00a796cdd89978599c0d4295b2c4591bd" and "e3eff20aaa3ed2cbe5e5b1990f44abcee8e8e50c" have entirely different histories.
0a6e82e00a
...
e3eff20aaa
@ -21,12 +21,6 @@ const CALLBACK_FUNCTIONS = [
|
||||
description: '按运单号批量查询是否已揽收:请求 { waybill_codes: [...] },'
|
||||
+ '外部返回 [{ waybill_code, is_galaxy_receive: 1|0 }],回写 wms_order_express.is_galaxy_receive',
|
||||
},
|
||||
{
|
||||
method: 'waybill.getTrace',
|
||||
name: '运单物流轨迹查询',
|
||||
description: '按运单号查询物流轨迹(实时回源,不落库):请求 { waybill_codes: [运单号] },'
|
||||
+ '外部返回 [{ waybillNo, trace: { opTime, outBizCode, memo, opOrgCityName, weight, scanType } }]',
|
||||
},
|
||||
];
|
||||
|
||||
/** method 合法值集合(供管理端 create/update 校验) */
|
||||
|
||||
@ -1,522 +0,0 @@
|
||||
'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<Object>} 默认返回 { 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<Object>} { 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<Object>} 响应。
|
||||
*/
|
||||
request(options) {
|
||||
return defaultClient.request(options);
|
||||
},
|
||||
/**
|
||||
* 用默认客户端做驱动式调用(兼容 execute({ url, body }))。
|
||||
* @param {Object} [request={}] 请求参数。
|
||||
* @return {Promise<Object>} 类 fetch 响应(支持 text() / json())。
|
||||
*/
|
||||
execute(request) {
|
||||
return defaultClient.execute(request);
|
||||
},
|
||||
/**
|
||||
* 默认客户端实例。
|
||||
* @return {JdClient} 实例。
|
||||
*/
|
||||
get client() {
|
||||
return defaultClient;
|
||||
},
|
||||
};
|
||||
@ -66,48 +66,23 @@ 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 下为 <sn> 子节点,而 buildXmlNode 对标量数组统一输出 <item>
|
||||
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 => {
|
||||
// 先修正 snList 内的 <item>,否则会被下面的 item→orderLine 替换误伤
|
||||
const withSnList = this.replaceDeliveryConfirmSnListTags(block);
|
||||
return this.replaceXmlTagsWithString(withSnList, 'item', 'orderLine');
|
||||
return this.replaceXmlTagsWithString(block, '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, (match, attributes = '', inner = '') => {
|
||||
// buildXmlNode 把 packages.package 数组序列化成 <package><item>…</item></package>,
|
||||
// 奇门要求 <packages><package>…</package></packages>:去掉数组容器,再把每个 <item> 改名为 <package>,
|
||||
// 否则一单多运单号(多个包裹)时标签会错位成 <item>/</package>
|
||||
const withoutContainer = String(inner)
|
||||
.replace(/^\s*<\s*package\s*>/, '')
|
||||
.replace(/<\s*\/\s*package\s*>\s*$/, '');
|
||||
|
||||
// <items> 下的 <item> 是包裹内商品明细,必须保留原名;先占位保护,改名后再还原
|
||||
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 `<packages${attributes}>${restored}</packages>`;
|
||||
return String(xmlString || '').replace(packagesBlockRegex, block => {
|
||||
return block
|
||||
// 去掉 buildXmlNode 为数组元素添加的 <item> 包装器:<package><item> → <package>
|
||||
.replace(/<\s*package\s*>\s*<\s*item\s*>/gi, '<package>')
|
||||
// 去掉对应的 </item> 包装器闭合,输出标准格式 XML(不再做交错标签变换)
|
||||
.replace(/<\s*\/\s*item\s*>\s*<\s*\/\s*package\s*>/gi, '</package>');
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@ -3,12 +3,12 @@
|
||||
/**
|
||||
* B2B 订单作业明细表 Model。
|
||||
*
|
||||
* 对应数据库表 `wms_order_b2b`,与发货单(订单)分表 wms_order_delivery_% 一对一,
|
||||
* 记录 B2B 订单的备货/提货作业信息:总箱数、提货车牌、备货备注、备货用时、
|
||||
* 备货完成时间、是否提货等。
|
||||
* 对应数据库表 `wms_order_b2b`,与发货单(订单)分表 wms_order_delivery_% 一对一
|
||||
* (order_id 关联分表 id),记录 B2B 订单的提货作业信息:
|
||||
* 总箱数、提货车牌、备货备注、备货用时、是否提货等。
|
||||
*
|
||||
* 不分表(不按仓库分表),关联读统一使用 warehouse_id + order_id(分表 id 按仓库
|
||||
* 各自发号,跨仓可能重叠,故不单独依赖 order_id)。取消 B2B 时物理删除行,不做软删除。
|
||||
* 不分表(不按仓库分表),通过 warehouse_id/store_id 维度隔离,
|
||||
* 落表方式类似 wms_order_express(运单号表)。
|
||||
* @param {import('egg').Application} app - Egg 应用实例
|
||||
*/
|
||||
module.exports = app => {
|
||||
@ -32,6 +32,16 @@ module.exports = app => {
|
||||
allowNull: false,
|
||||
comment: '仓库ID',
|
||||
},
|
||||
store_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '货主ID',
|
||||
},
|
||||
delivery_order_code: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '发货单号快照',
|
||||
},
|
||||
total_box_count: {
|
||||
type: INTEGER(11),
|
||||
allowNull: false,
|
||||
@ -54,17 +64,18 @@ module.exports = app => {
|
||||
defaultValue: 0,
|
||||
comment: '备货用时(秒)',
|
||||
},
|
||||
prep_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '备货完成时间',
|
||||
},
|
||||
is_picked_up: {
|
||||
type: ENUM('Y', 'N'),
|
||||
allowNull: false,
|
||||
defaultValue: 'N',
|
||||
comment: '是否提货:Y=已提货 N=未提货',
|
||||
},
|
||||
is_print: {
|
||||
type: ENUM('Y', 'N'),
|
||||
allowNull: false,
|
||||
defaultValue: 'N',
|
||||
comment: '是否打印:Y=已打印 N=未打印',
|
||||
},
|
||||
picked_up_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
@ -75,15 +86,37 @@ module.exports = app => {
|
||||
allowNull: false,
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '更新时间',
|
||||
},
|
||||
deleted_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '软删除时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_order_b2b',
|
||||
comment: 'B2B订单作业明细表',
|
||||
timestamps: false,
|
||||
indexes: [
|
||||
{
|
||||
name: 'uk_warehouse_order',
|
||||
name: 'uk_order_id',
|
||||
unique: true,
|
||||
fields: [ 'warehouse_id', 'order_id' ],
|
||||
fields: [ 'order_id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_warehouse_id',
|
||||
fields: [ 'warehouse_id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_store_id',
|
||||
fields: [ 'store_id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_delivery_order_code',
|
||||
fields: [ 'delivery_order_code' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_pickup_plate_number',
|
||||
@ -93,6 +126,14 @@ module.exports = app => {
|
||||
name: 'idx_is_picked_up',
|
||||
fields: [ 'is_picked_up' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_is_print',
|
||||
fields: [ 'is_print' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_deleted_at',
|
||||
fields: [ 'deleted_at' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
|
||||
@ -288,12 +288,6 @@ 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,
|
||||
|
||||
@ -26,7 +26,6 @@ const AUTO_INCREMENT_SAFE_MARGIN = 50;
|
||||
* 剔除从 current 继承来的同名后缀索引,改用自身版本,避免同一张表维护两份功能重叠的索引。
|
||||
*
|
||||
* 带 `_list_logistics_code_` 前缀的是「物流公司编码等值过滤 + 排序」变体(见 buildListSortIndexes),
|
||||
* 带 `_list_is_b2b_` 前缀的是「B2B 标记等值过滤 + 排序」变体(B2B 域列表专用),
|
||||
* 同样需要按分表类型区分版本,故一并登记后缀。
|
||||
*/
|
||||
const LIST_SORT_INDEX_SUFFIXES = Object.freeze([
|
||||
@ -34,8 +33,6 @@ const LIST_SORT_INDEX_SUFFIXES = Object.freeze([
|
||||
'_list_delivery_time',
|
||||
'_list_logistics_code_updated_at',
|
||||
'_list_logistics_code_delivery_time',
|
||||
'_list_is_b2b_updated_at',
|
||||
'_list_is_b2b_delivery_time',
|
||||
]);
|
||||
|
||||
const TABLE_PATTERNS = Object.freeze([
|
||||
@ -596,20 +593,6 @@ function buildListSortIndexes(warehouseId, type) {
|
||||
});
|
||||
}
|
||||
|
||||
// B2B 列表(order.pendingOrder2b.list / order.deliveryOrder2b.list)恒定带
|
||||
// is_b2b='Y' 等值条件,索引形态同上:等值列插在 scopeFields 与排序列之间,
|
||||
// 让「B2B 过滤 + 排序 + 分页」命中同一索引,避免把整表 B2B 行捞出后 filesort。
|
||||
// B2B 列表只查 current / dispatch 分表,history / outsourced 不声明该索引,
|
||||
// 避免在归档表上补建无查询场景的索引。
|
||||
if (modelType === MANAGED_TYPES.CURRENT || dispatchType) {
|
||||
for (const sortField of sortFields) {
|
||||
indexes.push({
|
||||
name: `${namePrefix}_list_is_b2b_${sortField}`,
|
||||
fields: [ ...scopeFields, 'is_b2b', sortField, 'id' ],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return indexes;
|
||||
}
|
||||
|
||||
|
||||
@ -1,120 +0,0 @@
|
||||
// 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;
|
||||
};
|
||||
@ -1,113 +0,0 @@
|
||||
// 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;
|
||||
};
|
||||
@ -30,7 +30,7 @@ module.exports = app => {
|
||||
strategy_type: {
|
||||
type: TINYINT,
|
||||
allowNull: false,
|
||||
comment: '策略类型:1-散单 2-团购 3-SN(序列号管理,固定先拣后分)',
|
||||
comment: '策略类型:1-散单 2-团购',
|
||||
},
|
||||
status: {
|
||||
type: TINYINT,
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { STRING, BIGINT, DECIMAL, TEXT, DATE, CHAR, INTEGER, ENUM, TINYINT, JSON } = app.Sequelize;
|
||||
const { STRING, BIGINT, DECIMAL, TEXT, DATE, CHAR, INTEGER, ENUM, TINYINT } = app.Sequelize;
|
||||
|
||||
const StockWarehouse = app.model.define('stock_warehouse', {
|
||||
id: {
|
||||
@ -115,12 +115,6 @@ 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',
|
||||
|
||||
@ -40,7 +40,6 @@ 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',
|
||||
@ -52,42 +51,6 @@ const ORDER_LIST_BASE_ATTRIBUTES = [
|
||||
'store_id',
|
||||
];
|
||||
|
||||
const ORDER_B2B_DETAIL_ATTRIBUTES = Object.freeze([
|
||||
'order_id',
|
||||
'total_box_count',
|
||||
'pickup_plate_number',
|
||||
'prep_remark',
|
||||
'prep_duration_seconds',
|
||||
'is_picked_up',
|
||||
'picked_up_at',
|
||||
'created_at',
|
||||
'prep_at',
|
||||
]);
|
||||
|
||||
/** B2B 作业明细空值(副表无对应行时的占位输出) */
|
||||
const ORDER_B2B_DETAIL_EMPTY = Object.freeze({
|
||||
total_box_count: 0,
|
||||
pickup_plate_number: null,
|
||||
prep_remark: null,
|
||||
prep_duration_seconds: 0,
|
||||
is_picked_up: 'N',
|
||||
picked_up_at: null,
|
||||
created_at: null,
|
||||
prep_at: null,
|
||||
});
|
||||
|
||||
/** B2B 作业明细可筛选字段(仅 B2B 域列表开放,避免污染普通订单列表口径) */
|
||||
const ORDER_B2B_DETAIL_FILTER_FIELDS = Object.freeze([
|
||||
'total_box_count',
|
||||
'pickup_plate_number',
|
||||
'prep_remark',
|
||||
'prep_duration_seconds',
|
||||
'is_picked_up',
|
||||
'picked_up_at',
|
||||
'created_at',
|
||||
'prep_at',
|
||||
]);
|
||||
|
||||
const ORDER_WEIGHT_TYPE_LABELS = Object.freeze({
|
||||
0: '常规',
|
||||
1: '轻货',
|
||||
@ -646,7 +609,6 @@ 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',
|
||||
};
|
||||
}
|
||||
|
||||
@ -1272,183 +1234,6 @@ 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<number[]>} 命中的订单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)。
|
||||
@ -1923,26 +1708,12 @@ class OrderBaseService extends MainService {
|
||||
|
||||
/**
|
||||
* 查询模块列表。
|
||||
*
|
||||
* 默认排除 B2B 订单(is_b2b='Y',NULL 存量行视为非 B2B),B2B 域列表通过
|
||||
* options.fixedWhere 指定 is_b2b 条件时不追加默认排除。
|
||||
*
|
||||
* @param {string} moduleName 模块名称。
|
||||
* @param {Object} data 请求体。
|
||||
* @param {Object} [options] 查询选项。
|
||||
* @param {Object} [options.fixedWhere] 强制附加的筛选条件,与请求 where 取 AND,
|
||||
* 不可被请求中的同名字段覆盖(用于 B2B 等固定域列表)。
|
||||
* @param {boolean} [options.b2bDetailFilter=false] 是否支持用 wms_order_b2b 作业明细字段
|
||||
* (total_box_count / pickup_plate_number / prep_remark / prep_duration_seconds /
|
||||
* is_picked_up / picked_up_at / created_at / prep_at)作为筛选条件。
|
||||
* @return {Promise<Object>} 列表与分页信息。
|
||||
*/
|
||||
async listByModule(moduleName = 'order', data = {}, options = {}) {
|
||||
async listByModule(moduleName = 'order', data = {}) {
|
||||
const requestData = this.isPlainObject(data) ? data : {};
|
||||
const normalizedOptions = this.isPlainObject(options) ? options : {};
|
||||
const fixedWhere = this.isPlainObject(normalizedOptions.fixedWhere)
|
||||
? normalizedOptions.fixedWhere
|
||||
: null;
|
||||
const contextWarehouseId = this.getWarehouseId();
|
||||
const { page, pageSize } = this.normalizePagination(requestData.pagination || requestData);
|
||||
const { where } = this.prepareWhereContext(requestData, {
|
||||
@ -1957,12 +1728,7 @@ 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 { where: whereAfterSnOrder, isSnOrder } = this.extractSnOrderVirtualFilter(whereAfterWaveScope);
|
||||
const { where: whereAfterSnCode, snCodes } = this.extractSnCodeVirtualFilter(whereAfterSnOrder);
|
||||
const { where: whereAfterB2bDetail, b2bDetailFilters } = normalizedOptions.b2bDetailFilter === true
|
||||
? this.extractB2bDetailVirtualFilter(whereAfterSnCode)
|
||||
: { where: whereAfterSnCode, b2bDetailFilters: null };
|
||||
const mergedWhere = this.mergeWhereObjects(this.getDefaultWhere(moduleName), whereAfterB2bDetail);
|
||||
const mergedWhere = this.mergeWhereObjects(this.getDefaultWhere(moduleName), whereAfterWaveScope);
|
||||
let queryWhere = this.buildWhere(mergedWhere, contextWarehouseId, {
|
||||
specialFieldMap: {
|
||||
quickWhere: {
|
||||
@ -1971,22 +1737,6 @@ class OrderBaseService extends MainService {
|
||||
},
|
||||
});
|
||||
|
||||
if (fixedWhere) {
|
||||
queryWhere = this.appendConditionToWhere(queryWhere, fixedWhere);
|
||||
}
|
||||
|
||||
// 非 B2B 域列表:默认排除 B2B 订单(B2B 域列表由 fixedWhere 指定 is_b2b='Y')
|
||||
if (!fixedWhere || !Object.prototype.hasOwnProperty.call(fixedWhere, 'is_b2b')) {
|
||||
queryWhere = this.appendConditionToWhere(queryWhere, this.buildExcludeB2bCondition());
|
||||
}
|
||||
|
||||
if (b2bDetailFilters) {
|
||||
const b2bOrderIds = await this.findOrderIdsByB2bDetailFilters(b2bDetailFilters, contextWarehouseId);
|
||||
if (b2bOrderIds !== null) {
|
||||
queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, b2bOrderIds);
|
||||
}
|
||||
}
|
||||
|
||||
if (expressNumbers.length > 0) {
|
||||
const orderIds = await this.findOrderIdsByExpressNumbers(expressNumbers, contextWarehouseId);
|
||||
queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, orderIds);
|
||||
@ -2012,16 +1762,6 @@ 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;
|
||||
@ -2097,175 +1837,6 @@ class OrderBaseService extends MainService {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 为订单列表行附加 B2B 作业明细字段(副表 wms_order_b2b)。
|
||||
*
|
||||
* 关联条件固定为 warehouse_id + order_id(分表 id 按仓库发号,不能只按 order_id 关联);
|
||||
* 无副表行时输出空值占位,保证响应字段结构稳定。附加字段:
|
||||
* total_box_count / pickup_plate_number / prep_remark / prep_duration_seconds /
|
||||
* is_picked_up / picked_up_at / created_at(副表创建时间) / prep_at。
|
||||
*
|
||||
* @param {Array<Object>} list 订单列表行(需含 id)。
|
||||
* @param {number|string|null} [warehouseId=null] 仓库ID,缺省取当前上下文。
|
||||
* @return {Promise<Array<Object>>} 附加 B2B 作业明细后的列表。
|
||||
*/
|
||||
async attachB2bJobDetail(list = [], warehouseId = null) {
|
||||
const rows = Array.isArray(list) ? list : [];
|
||||
if (rows.length === 0) {
|
||||
return rows;
|
||||
}
|
||||
|
||||
const normalizedWarehouseId = Number(warehouseId ?? this.getWarehouseId() ?? 0);
|
||||
const b2bModel = this.ctx.model && this.ctx.model.OrderB2b;
|
||||
const detailMap = new Map();
|
||||
|
||||
if (Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0
|
||||
&& b2bModel && typeof b2bModel.findAll === 'function') {
|
||||
const orderIds = [ ...new Set(rows
|
||||
.map(row => Number(row && row.id || 0))
|
||||
.filter(id => Number.isInteger(id) && id > 0)) ];
|
||||
|
||||
if (orderIds.length > 0) {
|
||||
const detailRows = await b2bModel.findAll({
|
||||
where: {
|
||||
warehouse_id: normalizedWarehouseId,
|
||||
order_id: { [this.app.Sequelize.Op.in]: orderIds },
|
||||
},
|
||||
attributes: [ ...ORDER_B2B_DETAIL_ATTRIBUTES ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
for (const detail of (Array.isArray(detailRows) ? detailRows : [])) {
|
||||
const orderId = Number(detail && detail.order_id || 0);
|
||||
if (Number.isInteger(orderId) && orderId > 0) {
|
||||
detailMap.set(orderId, detail);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return rows.map(row => {
|
||||
const detail = detailMap.get(Number(row && row.id || 0));
|
||||
if (!detail) {
|
||||
return { ...row, ...ORDER_B2B_DETAIL_EMPTY };
|
||||
}
|
||||
|
||||
return {
|
||||
...row,
|
||||
total_box_count: Number(detail.total_box_count || 0),
|
||||
pickup_plate_number: detail.pickup_plate_number ?? null,
|
||||
prep_remark: detail.prep_remark ?? null,
|
||||
prep_duration_seconds: Number(detail.prep_duration_seconds || 0),
|
||||
is_picked_up: String(detail.is_picked_up || 'N').trim() === 'Y' ? 'Y' : 'N',
|
||||
picked_up_at: detail.picked_up_at ?? null,
|
||||
created_at: detail.created_at ?? null,
|
||||
prep_at: detail.prep_at ?? null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造"排除 B2B 订单"条件(is_b2b 为 NULL 的存量行视为非 B2B)。
|
||||
* @return {Object} Sequelize 条件。
|
||||
*/
|
||||
buildExcludeB2bCondition() {
|
||||
const { Op } = this.app.Sequelize;
|
||||
return {
|
||||
is_b2b: {
|
||||
[Op.or]: [
|
||||
{ [Op.is]: null },
|
||||
'N',
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 where 中提取 B2B 作业明细筛选条件(仅 B2B 域列表使用)。
|
||||
*
|
||||
* @param {Object} [where={}] 已解析的 where 条件。
|
||||
* @return {{ where: Object, b2bDetailFilters: (Object|null) }} 剩余 where 与作业明细筛选条件。
|
||||
*/
|
||||
extractB2bDetailVirtualFilter(where = {}) {
|
||||
const source = this.isPlainObject(where) ? where : {};
|
||||
const rest = {};
|
||||
const filters = {};
|
||||
|
||||
for (const [ fieldName, condition ] of Object.entries(source)) {
|
||||
if (!ORDER_B2B_DETAIL_FILTER_FIELDS.includes(fieldName)) {
|
||||
rest[fieldName] = condition;
|
||||
continue;
|
||||
}
|
||||
|
||||
const conditionValue = this.isPlainObject(condition) && Object.prototype.hasOwnProperty.call(condition, 'value')
|
||||
? condition.value
|
||||
: condition;
|
||||
if (conditionValue === undefined || conditionValue === null || conditionValue === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
filters[fieldName] = condition;
|
||||
}
|
||||
|
||||
return {
|
||||
where: rest,
|
||||
b2bDetailFilters: Object.keys(filters).length > 0 ? filters : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 B2B 作业明细筛选条件查询命中的订单ID。
|
||||
*
|
||||
* 关联条件固定为 warehouse_id + order_id;无有效条件时返回 null(表示不过滤),
|
||||
* 有条件下未命中时返回空数组(下游展开为空列表)。
|
||||
*
|
||||
* @param {Object} filters 作业明细筛选条件。
|
||||
* @param {number|string|null} [warehouseId=null] 仓库ID,缺省取当前上下文。
|
||||
* @return {Promise<number[]|null>} 命中订单ID列表,或 null(无有效条件)。
|
||||
*/
|
||||
async findOrderIdsByB2bDetailFilters(filters = {}, warehouseId = null) {
|
||||
const { Sequelize } = this.app;
|
||||
const { Op } = Sequelize;
|
||||
const b2bModel = this.ctx.model && this.ctx.model.OrderB2b;
|
||||
const normalizedWarehouseId = Number(warehouseId ?? this.getWarehouseId() ?? 0);
|
||||
|
||||
if (!this.isPlainObject(filters) || Object.keys(filters).length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!b2bModel || typeof b2bModel.findAll !== 'function'
|
||||
|| !Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const parsed = parseWhereConditions({
|
||||
where: this.normalizeWhereInput({ where: filters }),
|
||||
app: this.app,
|
||||
});
|
||||
|
||||
if (!parsed.ok) {
|
||||
throw new Error(`B2B 作业明细筛选条件解析失败: ${parsed.reason}`);
|
||||
}
|
||||
|
||||
const conditions = Array.isArray(parsed.result.dynamicConditions) ? parsed.result.dynamicConditions : [];
|
||||
if (conditions.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const rows = await b2bModel.findAll({
|
||||
where: {
|
||||
warehouse_id: normalizedWarehouseId,
|
||||
[Op.and]: conditions,
|
||||
},
|
||||
attributes: [ 'order_id' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
return [ ...new Set((Array.isArray(rows) ? rows : [])
|
||||
.map(row => Number(row && row.order_id || 0))
|
||||
.filter(orderId => Number.isInteger(orderId) && orderId > 0)) ];
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询订单详情。
|
||||
*
|
||||
|
||||
@ -1,47 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const OrderBaseService = require('./base');
|
||||
|
||||
/** B2B 列表强制条件 */
|
||||
const B2B_FIXED_WHERE = Object.freeze({ is_b2b: 'Y' });
|
||||
|
||||
/**
|
||||
* B2B 配送订单系统方法。
|
||||
*
|
||||
* 查询条件与 order.deliveryOrder.list 完全一致(dispatch 分表 + dispatch_lane=m4),
|
||||
* 仅额外强制 is_b2b='Y',用于 B2B 订单的配送域列表。
|
||||
*/
|
||||
class DeliveryOrder2bService extends OrderBaseService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'list';
|
||||
const _noNeedLog = 'list';
|
||||
const _noNeedAuth = 'list';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
/**
|
||||
* B2B 配送订单列表。
|
||||
*
|
||||
* 在 order.deliveryOrder.list 的基础上强制 is_b2b='Y',并附加 wms_order_b2b 作业明细字段
|
||||
* (total_box_count / pickup_plate_number / prep_remark / prep_duration_seconds /
|
||||
* is_picked_up / picked_up_at / created_at / prep_at)。
|
||||
*
|
||||
* @param {Object} data 请求体(与 order.deliveryOrder.list 一致)。
|
||||
* @return {Promise<Object>} 列表与分页信息。
|
||||
*/
|
||||
async list(data = {}) {
|
||||
const warehouseId = this.getWarehouseId();
|
||||
const result = await this.listByModule('deliveryOrder', data, {
|
||||
fixedWhere: B2B_FIXED_WHERE,
|
||||
b2bDetailFilter: true,
|
||||
});
|
||||
return {
|
||||
...result,
|
||||
list: await this.attachB2bJobDetail(result.list, warehouseId),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = DeliveryOrder2bService;
|
||||
@ -22,8 +22,7 @@ class OrderIndexService extends OrderBaseService {
|
||||
/**
|
||||
* 订单转 B2B 订单。
|
||||
*
|
||||
* 仅限待处理表中处于待处理阶段(step in [1,2,3])、未取消、未拣货、未复核、
|
||||
* 未锁定、未拦截的订单(打印状态不限制);不符合条件跳过。
|
||||
* 仅限待处理表中未打印、未锁定、未拦截的订单;不符合条件跳过。
|
||||
* 事务内:订单表 is_b2b 置 Y + 写入 wms_order_b2b 作业明细,提交后写操作日志。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
@ -70,8 +69,8 @@ class OrderIndexService extends OrderBaseService {
|
||||
/**
|
||||
* 取消 B2B 出库:订单流转回正常订单。
|
||||
*
|
||||
* 仅限待处理表中 is_b2b=Y 且未锁定、未拦截的订单(打印状态不限制);
|
||||
* 不符合条件跳过。事务内:订单表 is_b2b 置回 N + B2B 作业明细物理删除,
|
||||
* 仅限待处理表中 is_b2b=Y 且未打印、未锁定、未拦截、B2B 面单未打印的订单;
|
||||
* 不符合条件跳过。事务内:订单表 is_b2b 置回 N + B2B 作业明细软删除,
|
||||
* 提交后写操作日志。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
|
||||
@ -2077,87 +2077,6 @@ 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>|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: [] };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步待处理订单(异步模式)。
|
||||
*
|
||||
@ -2270,7 +2189,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';
|
||||
|
||||
@ -3874,7 +3793,6 @@ 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 };
|
||||
@ -6992,19 +6910,11 @@ class PendingOrderService extends OrderBaseService {
|
||||
&& contractConfig.policy_config
|
||||
&& contractConfig.policy_config.auto_sync_back === 1
|
||||
) {
|
||||
// SN 订单自动回传会被拦截并置异常,自动触发场景静默跳过
|
||||
const autoSyncFilter = await this.filterAutoSyncSnOrderIds({
|
||||
orderIds: [ orderId ],
|
||||
warehouseId: Number(order.warehouse_id) || warehouseId,
|
||||
source: 'manualWaybill',
|
||||
this.syncOrderIds({ orderIds: [ orderId ] }).catch(err => {
|
||||
this.ctx.logger.error(
|
||||
`[auto_sync_back] manualWaybill 自动同步失败: ${err.message}`
|
||||
);
|
||||
});
|
||||
if (autoSyncFilter.orderIds.length > 0) {
|
||||
this.syncOrderIds({ orderIds: autoSyncFilter.orderIds }).catch(err => {
|
||||
this.ctx.logger.error(
|
||||
`[auto_sync_back] manualWaybill 自动同步失败: ${err.message}`
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
|
||||
@ -1,47 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const OrderBaseService = require('./base');
|
||||
|
||||
/** B2B 列表强制条件 */
|
||||
const B2B_FIXED_WHERE = Object.freeze({ is_b2b: 'Y' });
|
||||
|
||||
/**
|
||||
* B2B 待处理订单系统方法。
|
||||
*
|
||||
* 查询条件与 order.pendingOrder.list 完全一致(current 分表 + 模块默认 where),
|
||||
* 仅额外强制 is_b2b='Y',用于 B2B 备货/提货作业的独立列表。
|
||||
*/
|
||||
class PendingOrder2bService extends OrderBaseService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'list';
|
||||
const _noNeedLog = 'list';
|
||||
const _noNeedAuth = 'list';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
/**
|
||||
* B2B 待处理订单列表。
|
||||
*
|
||||
* 在 order.pendingOrder.list 的基础上强制 is_b2b='Y',并附加 wms_order_b2b 作业明细字段
|
||||
* (total_box_count / pickup_plate_number / prep_remark / prep_duration_seconds /
|
||||
* is_picked_up / picked_up_at / created_at / prep_at)。
|
||||
*
|
||||
* @param {Object} data 请求体(与 order.pendingOrder.list 一致)。
|
||||
* @return {Promise<Object>} 列表与分页信息。
|
||||
*/
|
||||
async list(data = {}) {
|
||||
const warehouseId = this.getWarehouseId();
|
||||
const result = await this.listByModule('pendingOrder', data, {
|
||||
fixedWhere: B2B_FIXED_WHERE,
|
||||
b2bDetailFilter: true,
|
||||
});
|
||||
return {
|
||||
...result,
|
||||
list: await this.attachB2bJobDetail(result.list, warehouseId),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = PendingOrder2bService;
|
||||
@ -866,10 +866,6 @@ 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(),
|
||||
@ -1422,35 +1418,6 @@ 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) {
|
||||
@ -1580,8 +1547,6 @@ 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(),
|
||||
@ -1737,50 +1702,21 @@ 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);
|
||||
|
||||
// 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;
|
||||
if (affectedRows <= 0) {
|
||||
throw new 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();
|
||||
@ -1861,180 +1797,15 @@ 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<void>} 无返回值。
|
||||
*/
|
||||
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<Object>} 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。
|
||||
@ -2091,7 +1862,6 @@ class RecheckOrderService extends OrderBaseService {
|
||||
'intercept_status',
|
||||
'pick_status',
|
||||
'recheck_status',
|
||||
'has_sn_item',
|
||||
],
|
||||
raw: true,
|
||||
});
|
||||
@ -2128,11 +1898,6 @@ 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))
|
||||
@ -3843,7 +3608,6 @@ 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}
|
||||
@ -3894,7 +3658,6 @@ 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', {
|
||||
@ -4394,7 +4157,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', 'has_sn_item',
|
||||
'pick_status', 'recheck_status', 'wave_id', 'wave_no',
|
||||
],
|
||||
raw: true,
|
||||
});
|
||||
@ -4572,7 +4335,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', 'has_sn_item',
|
||||
'pick_status', 'recheck_status', 'wave_id', 'wave_no',
|
||||
],
|
||||
raw: true,
|
||||
});
|
||||
@ -4993,11 +4756,6 @@ class RecheckOrderService extends OrderBaseService {
|
||||
// 校验订单是否允许复核(拣货已完成且未被拦截)
|
||||
this.assertOrderCanRecheck(order);
|
||||
|
||||
// SN 订单必须逐单提交 SN 码,快捷复核没有 SN 采集入口,直接拒绝避免绕过 SN 校验
|
||||
if (this.isSnOrderRow(order)) {
|
||||
throw new Error('SN订单需在单订单复核中提交SN码,不支持快捷复核');
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
|
||||
// 更新订单复核状态
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -562,8 +562,6 @@ 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({
|
||||
@ -611,8 +609,6 @@ 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) {
|
||||
|
||||
@ -4,11 +4,6 @@ const MainService = require('../../main');
|
||||
|
||||
const WAYBILL_EXPORT_TASK_CACHE_KEY_PREFIX = 'waybill_export_task_';
|
||||
const WAYBILL_RECEIVE_TASK_CACHE_KEY_PREFIX = 'waybill_receive_task_';
|
||||
/** 轨迹查询所依赖的出站回调 method */
|
||||
const WAYBILL_TRACE_EVENT = 'waybill.getTrace';
|
||||
/** 轨迹查询外部接口未配置时的失败提示 */
|
||||
const WAYBILL_TRACE_NOT_CONFIGURED_MESSAGE =
|
||||
'如需查询运单物流轨迹,到【设置】->【基础设置】->【API开放接口】配置相应的外部访问接口';
|
||||
/** 揽收状态查询所依赖的出站回调 method */
|
||||
const WAYBILL_RECEIVE_EVENT = 'waybill.getreceive';
|
||||
/** 仓库未配置外部接口时的失败提示(直接失败,不进入任务流程) */
|
||||
@ -28,9 +23,9 @@ class WaybillWarehouseService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'list,detail,export,exportTaskProgress,updateReceive,updateReceiveTaskProgress,getTrace';
|
||||
const _noNeedRight = 'list,detail,export,exportTaskProgress,updateReceive,updateReceiveTaskProgress';
|
||||
const _noNeedLog = '';
|
||||
const _noNeedAuth = 'list,detail,export,exportTaskProgress,updateReceive,updateReceiveTaskProgress,getTrace';
|
||||
const _noNeedAuth = 'list,detail,export,exportTaskProgress,updateReceive,updateReceiveTaskProgress';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
@ -488,26 +483,6 @@ class WaybillWarehouseService extends MainService {
|
||||
return String(first && first.appKey || '').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析仓库承接 waybill.getTrace 的 API 应用 AppKey(按 id 升序取首个)。
|
||||
* 返回空字符串表示仓库未配置轨迹查询外部接口。
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @return {Promise<string>} 目标应用 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 请求体。
|
||||
@ -617,66 +592,6 @@ class WaybillWarehouseService extends MainService {
|
||||
async getReceiveTaskProgress(taskId = '') {
|
||||
return await this.getTaskProgress(taskId, WAYBILL_RECEIVE_TASK_CACHE_KEY_PREFIX);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询单个运单的全部物流轨迹(仓库侧)。
|
||||
*
|
||||
* 全部回源:实时调用外部访问接口 `waybill.getTrace` 查询,不做本地存储。
|
||||
* 一次返回该运单号下的所有轨迹(不分页),按操作时间倒序排列(最新的在前)。
|
||||
* 命中轨迹(非空)时顺带把该运单 `is_galaxy_receive` 置为 Y(只升不降)。
|
||||
*
|
||||
* @param {Object} data 请求参数。
|
||||
* @param {string} [data.waybillCode] 运单号(兼容 waybill_code)。
|
||||
* @return {Promise<Object>} { waybill_code, total, list, received_updated }。
|
||||
*/
|
||||
async getTrace(data = {}) {
|
||||
try {
|
||||
const safeData = this.isPlainObject(data) ? data : {};
|
||||
const waybillCode = String(safeData.waybillCode || safeData.waybill_code || '').trim();
|
||||
if (!waybillCode) {
|
||||
return this.fail('运单号不能为空');
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
const fetched = await this.service.systems.waybill.fetchTracesByWaybill({
|
||||
warehouseId,
|
||||
waybillCode,
|
||||
appKey,
|
||||
});
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WaybillWarehouseService;
|
||||
|
||||
@ -1115,8 +1115,6 @@ 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(),
|
||||
};
|
||||
@ -1696,22 +1694,18 @@ 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', 'is_sn_mgmt' ],
|
||||
attributes: [ 'id', 'gross_weight', 'prohibited_id' ],
|
||||
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);
|
||||
@ -1864,7 +1858,6 @@ 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,
|
||||
@ -2353,7 +2346,7 @@ class DeliveryOrderService extends Service {
|
||||
id: orderId,
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
attributes: [ 'id', 'wave_id', 'step', 'status', 'outbound_status', 'lock_status', 'has_sn_item', 'is_b2b' ],
|
||||
attributes: [ 'id', 'wave_id', 'step', 'status', 'outbound_status', 'lock_status' ],
|
||||
transaction,
|
||||
lock: transaction.LOCK.UPDATE,
|
||||
});
|
||||
@ -2368,18 +2361,6 @@ class DeliveryOrderService extends Service {
|
||||
return false;
|
||||
}
|
||||
|
||||
// B2B 订单不参与波次抓取,自动加团时静默跳过(NULL 视为非 B2B,兼容存量行)
|
||||
if (String(orderRow.is_b2b || '').trim() === 'Y') {
|
||||
await transaction.commit();
|
||||
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();
|
||||
@ -2503,23 +2484,15 @@ 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: { [Op.in]: [ 1, 2, 3 ] },
|
||||
status: { [Op.ne]: 'cancel' },
|
||||
outbound_status: { [Op.ne]: 'padding' },
|
||||
step: { [ctx.app.Sequelize.Op.in]: [ 1, 2, 3 ] },
|
||||
status: { [ctx.app.Sequelize.Op.ne]: 'cancel' },
|
||||
outbound_status: { [ctx.app.Sequelize.Op.ne]: 'padding' },
|
||||
lock_status: 'none',
|
||||
sys_logistics_code: structure.logisticsName,
|
||||
// 自动加团同样不抓取 B2B 订单(NULL 视为非 B2B,兼容存量行)
|
||||
is_b2b: { [Op.or]: [{ [Op.is]: null }, 'N' ] },
|
||||
// 团购排除 SN(序列号管理)订单
|
||||
[Op.or]: [
|
||||
{ has_sn_item: { [Op.is]: null } },
|
||||
{ has_sn_item: { [Op.ne]: 'Y' } },
|
||||
],
|
||||
};
|
||||
where[structure.itemPartType] = structure.itemPart;
|
||||
|
||||
@ -2561,7 +2534,7 @@ class DeliveryOrderService extends Service {
|
||||
context.warehouseId,
|
||||
'B',
|
||||
minGroupOrderFetchQuantity,
|
||||
{ maxFetchQuantity: maxWaveQuantity, excludeSnOrders: true }
|
||||
{ maxFetchQuantity: maxWaveQuantity }
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@ -1885,25 +1885,17 @@ class ExpressPlatformService extends MainService {
|
||||
.filter(Boolean);
|
||||
|
||||
if (syncedOrderIds.length > 0) {
|
||||
// SN 订单自动回传会被拦截并置异常,自动触发场景静默跳过
|
||||
const autoSyncFilter = await this.ctx.service.systemMethods.order.pendingOrder.filterAutoSyncSnOrderIds({
|
||||
// 异步调用,不阻塞主流程
|
||||
// 显式传仓库上下文:Qimen 创建订单等链路 ctx.user 为空,
|
||||
// 不传会导致 syncOrderIds 因"缺少仓库上下文"静默失败
|
||||
this.ctx.service.systemMethods.order.pendingOrder.syncOrderIds({
|
||||
orderIds: syncedOrderIds,
|
||||
warehouseId,
|
||||
source: 'polyapi',
|
||||
}).catch(err => {
|
||||
this.ctx.logger.error(
|
||||
`[auto_sync_back] polyapi 自动同步失败: ${err.message}`
|
||||
);
|
||||
});
|
||||
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}`
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -2260,25 +2252,17 @@ class ExpressPlatformService extends MainService {
|
||||
.filter(Boolean);
|
||||
|
||||
if (syncedOrderIds.length > 0) {
|
||||
// SN 订单自动回传会被拦截并置异常,自动触发场景静默跳过
|
||||
const autoSyncFilter = await this.ctx.service.systemMethods.order.pendingOrder.filterAutoSyncSnOrderIds({
|
||||
// 异步调用,不阻塞主流程
|
||||
// 显式传仓库上下文:Qimen 创建订单等链路 ctx.user 为空,
|
||||
// 不传会导致 syncOrderIds 因"缺少仓库上下文"静默失败
|
||||
this.ctx.service.systemMethods.order.pendingOrder.syncOrderIds({
|
||||
orderIds: syncedOrderIds,
|
||||
warehouseId,
|
||||
source: 'cainiao',
|
||||
}).catch(err => {
|
||||
this.ctx.logger.error(
|
||||
`[auto_sync_back] cainiao 自动同步失败: ${err.message}`
|
||||
);
|
||||
});
|
||||
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}`
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -2928,25 +2912,17 @@ class ExpressPlatformService extends MainService {
|
||||
.filter(Boolean);
|
||||
|
||||
if (syncedOrderIds.length > 0) {
|
||||
// SN 订单自动回传会被拦截并置异常,自动触发场景静默跳过
|
||||
const autoSyncFilter = await this.ctx.service.systemMethods.order.pendingOrder.filterAutoSyncSnOrderIds({
|
||||
// 异步调用,不阻塞主流程
|
||||
// 显式传仓库上下文:Qimen 创建订单等链路 ctx.user 为空,
|
||||
// 不传会导致 syncOrderIds 因"缺少仓库上下文"静默失败
|
||||
this.ctx.service.systemMethods.order.pendingOrder.syncOrderIds({
|
||||
orderIds: syncedOrderIds,
|
||||
warehouseId,
|
||||
source: 'pdd',
|
||||
}).catch(err => {
|
||||
this.ctx.logger.error(
|
||||
`[auto_sync_back] pdd 自动同步失败: ${err.message}`
|
||||
);
|
||||
});
|
||||
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}`
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -22,7 +22,6 @@ class operationLogService extends Service {
|
||||
* @param {string|number} params.businessId 业务ID。
|
||||
* @param {string} params.operationCode 操作编码。
|
||||
* @param {Object} [params.operator={}] 操作人信息。
|
||||
* @param {string} [params.changeSummary=''] 变更描述(extras.message 缺省时作为日志说明落库)。
|
||||
* @param {Object} [params.extras={}] 扩展字段。
|
||||
* @param {Object|null} [params.beforeChanges=null] 操作前快照。
|
||||
* @return {Object} 可直接落库的日志数据。
|
||||
@ -35,7 +34,6 @@ class operationLogService extends Service {
|
||||
operationCode,
|
||||
operator = {},
|
||||
beforeChanges = null,
|
||||
changeSummary = '',
|
||||
extras = {},
|
||||
} = params;
|
||||
|
||||
@ -51,8 +49,7 @@ class operationLogService extends Service {
|
||||
warehouse_id: extras.warehouseId ?? null,
|
||||
before_changes: beforeChanges,
|
||||
platform_code: ctx.user?.platform_code || 'SYSTEM',
|
||||
// 日志说明:优先 extras.message;调用方只传 changeSummary 时回退使用,避免前端"操作说明"为空
|
||||
message: extras.message || changeSummary || null,
|
||||
message: extras.message || null,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@ -11,8 +11,6 @@ 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;
|
||||
@ -196,138 +194,6 @@ async function buildOrderWaybillCodeMapInternal(service, orderIds = [], warehous
|
||||
return waybillCodeMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析单个订单明细回传用的 snList:优先使用明细上已有的 sn_list,其次用 SN 表数据。
|
||||
*
|
||||
* @param {Object} orderItem 订单明细记录。
|
||||
* @param {Map<number, string[]>} 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<Object>} orderItems 订单明细记录。
|
||||
* @return {Promise<Map<number, string[]>>} 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());
|
||||
@ -391,7 +257,6 @@ 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 : []) {
|
||||
@ -400,12 +265,6 @@ 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(),
|
||||
@ -421,8 +280,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: snPayload.snList,
|
||||
qrCode: snPayload.qrCode,
|
||||
snList: Array.isArray(orderItem.sn_list) ? orderItem.sn_list.slice() : [],
|
||||
qrCode: String(orderItem.qr_code || '').trim(),
|
||||
});
|
||||
}
|
||||
|
||||
@ -2660,7 +2519,6 @@ 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, '发货单缺少奇门货主编码');
|
||||
|
||||
@ -1,8 +1,7 @@
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../main');
|
||||
const Sequelize = require('sequelize');
|
||||
const { Op } = Sequelize;
|
||||
const { Op } = require('sequelize');
|
||||
|
||||
const OUTBOUND_STATUS = 'fin';
|
||||
const OUTBOUND_STEP = 4;
|
||||
@ -201,7 +200,7 @@ class OrderAutoOutboundService extends MainService {
|
||||
* 扫描仓库下命中任一自动出库规则的订单ID。
|
||||
*
|
||||
* 逐条规则查询(规则内条件 AND),命中即纳入结果;订单ID 去重并保留首个命中的规则下标。
|
||||
* 需要称重的规则通过关联 EXISTS 子查询(订单表驱动、快递表按 order_id 点查)约束。
|
||||
* 需要称重的规则先取称重订单ID(同仓库只查一次,跨规则复用)。
|
||||
*
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @param {Array<Object>} rules 自动化出库规则数组。
|
||||
@ -225,6 +224,7 @@ class OrderAutoOutboundService extends MainService {
|
||||
const ruleList = Array.isArray(rules) ? rules : [];
|
||||
const orderIds = [];
|
||||
const ruleIndexById = new Map();
|
||||
let weighOrderIds = null;
|
||||
|
||||
for (let index = 0; index < ruleList.length; index += 1) {
|
||||
const remaining = limit - orderIds.length;
|
||||
@ -236,14 +236,13 @@ class OrderAutoOutboundService extends MainService {
|
||||
const where = this.buildAutoOutboundWhere(rule);
|
||||
|
||||
if (rule.require_weigh) {
|
||||
const weighCondition = this.buildWeighExistsCondition(orderModel, warehouseId);
|
||||
if (!weighCondition) {
|
||||
ctx.logger.warn(
|
||||
`[auto-outbound] 仓库 ${warehouseId} 缺少订单快递模型或仓库ID非法,跳过「需已称重」规则${index + 1}`
|
||||
);
|
||||
if (weighOrderIds === null) {
|
||||
weighOrderIds = await this.findOrderIdsWithWeigh(warehouseId);
|
||||
}
|
||||
if (weighOrderIds.length === 0) {
|
||||
continue;
|
||||
}
|
||||
where[Op.and] = [ ...(Array.isArray(where[Op.and]) ? where[Op.and] : []), weighCondition ];
|
||||
where.id = { [Op.in]: weighOrderIds };
|
||||
}
|
||||
|
||||
const orders = await orderModel.findAll({
|
||||
@ -401,82 +400,31 @@ class OrderAutoOutboundService extends MainService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造「已称重」半连接条件(关联 EXISTS 子查询)。
|
||||
* 查找有称重记录的订单ID列表。
|
||||
*
|
||||
* `wms_order_express.weighing_weight` 无索引且历史命中率极高,若先捞出全量称重订单ID
|
||||
* 再用 `id IN (...)` 约束,会全表扫描快递大表,并把百万级订单ID 塞进 SQL 与内存。
|
||||
* 改为关联 EXISTS 后由订单表驱动,快递表按 order_id 唯一索引逐行点查。
|
||||
*
|
||||
* @param {Object} orderModel 当前仓库的订单模型(Sequelize 模型)。
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @return {Object|null} Sequelize literal 条件;模型缺失或仓库ID非法时返回 null。
|
||||
* @return {Promise<Array<number>>} 订单ID列表。
|
||||
*/
|
||||
buildWeighExistsCondition(orderModel, warehouseId) {
|
||||
async findOrderIdsWithWeigh(warehouseId) {
|
||||
const { ctx } = this;
|
||||
const { OrderExpress } = ctx.model;
|
||||
|
||||
if (!OrderExpress) {
|
||||
return null;
|
||||
return [];
|
||||
}
|
||||
|
||||
const safeWarehouseId = Number(warehouseId);
|
||||
if (!Number.isInteger(safeWarehouseId) || safeWarehouseId <= 0) {
|
||||
return null;
|
||||
}
|
||||
const rows = await OrderExpress.findAll({
|
||||
where: {
|
||||
warehouse_id: warehouseId,
|
||||
weighing_weight: { [Op.gt]: 0 },
|
||||
},
|
||||
attributes: [ 'order_id' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const orderTableRef = this.buildSqlTableRef(orderModel);
|
||||
const expressTableRef = this.buildSqlTableRef(OrderExpress);
|
||||
if (!orderTableRef || !expressTableRef) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Sequelize.literal(
|
||||
`EXISTS (SELECT 1 FROM ${expressTableRef}`
|
||||
+ ` WHERE ${expressTableRef}.\`order_id\` = ${orderTableRef}.\`id\``
|
||||
+ ` AND ${expressTableRef}.\`warehouse_id\` = ${safeWarehouseId}`
|
||||
+ ` AND ${expressTableRef}.\`weighing_weight\` > 0)`
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 把模型解析为 SQL 中可直接引用的表名(含 schema)。
|
||||
*
|
||||
* @param {Object} model Sequelize 模型。
|
||||
* @return {string|null} 形如 `table` 或 `schema`.`table` 的表引用;无法解析时返回 null。
|
||||
*/
|
||||
buildSqlTableRef(model) {
|
||||
if (!model) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const raw = typeof model.getTableName === 'function' ? model.getTableName() : model;
|
||||
const tableName = typeof raw === 'string' ? raw : (raw && raw.tableName);
|
||||
const schema = raw && typeof raw === 'object' ? raw.schema : null;
|
||||
const safeTable = this.quoteSqlIdentifier(tableName);
|
||||
|
||||
if (!safeTable) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (schema) {
|
||||
const safeSchema = this.quoteSqlIdentifier(schema);
|
||||
return safeSchema ? `${safeSchema}.${safeTable}` : null;
|
||||
}
|
||||
|
||||
return safeTable;
|
||||
}
|
||||
|
||||
/**
|
||||
* 转义 SQL 标识符(仅允许字母、数字、下划线与 $,避免拼接注入)。
|
||||
*
|
||||
* @param {string} name 标识符。
|
||||
* @return {string|null} 反引号包裹的标识符;非法时返回 null。
|
||||
*/
|
||||
quoteSqlIdentifier(name) {
|
||||
if (typeof name !== 'string' || !/^[A-Za-z0-9_$]+$/.test(name)) {
|
||||
return null;
|
||||
}
|
||||
return `\`${name}\``;
|
||||
return rows
|
||||
.map(row => Number(row.order_id))
|
||||
.filter(id => Number.isFinite(id) && id > 0);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@ -9,22 +9,6 @@ const ORDER_B2B_CANCEL_OPERATION_CODE = 'ORDER_B2B_CANCEL';
|
||||
/** 单次转换订单数上限 */
|
||||
const ORDER_B2B_CONVERT_BATCH_LIMIT = 200;
|
||||
|
||||
/**
|
||||
* 允许转 B2B 的订单步骤白名单。
|
||||
*
|
||||
* 仅待处理阶段(1 已审核 / 2 处理中 / 3 驳回异常)可转;4 配送中(含已提交出库)、
|
||||
* 5 已完成、9 已关闭等已离开待处理阶段的订单一律拒绝,避免误转已配送/已关闭订单。
|
||||
*/
|
||||
const ORDER_B2B_CONVERT_ALLOWED_STEPS = new Set([ 1, 2, 3 ]);
|
||||
|
||||
/** 非白名单步骤的拒绝文案 */
|
||||
const ORDER_B2B_CONVERT_STEP_SKIP_REASONS = Object.freeze({
|
||||
0: '订单待审核,不允许转B2B',
|
||||
4: '订单已提交出库,不允许转B2B',
|
||||
5: '订单已完成,不允许转B2B',
|
||||
9: '订单已关闭,不允许转B2B',
|
||||
});
|
||||
|
||||
/**
|
||||
* B2B 订单业务服务。
|
||||
*
|
||||
@ -34,19 +18,16 @@ class OrderB2bService extends Service {
|
||||
/**
|
||||
* 将待处理订单批量转为 B2B 订单。
|
||||
*
|
||||
* 仅限待处理表(current 分表)中处于待处理阶段(step in [1,2,3])、未取消、
|
||||
* 未拣货、未复核、未锁定、未拦截的订单(打印状态不限制);不符合条件的订单跳过(计入 skipped),不报错。
|
||||
* 已在波次中的订单(含库内抓取进波次的订单)转换成功后会在同一事务内从波次摘除
|
||||
* (清空波次字段、重排 wave_index、回写波次统计);若波次存在进行中的拣货任务则跳过转换。
|
||||
* 事务内完成 is_b2b 置 Y 与 wms_order_b2b 明细写入;操作日志在事务提交后写入。
|
||||
* 仅限待处理表(current 分表)中未打印、未锁定、未拦截的订单;
|
||||
* 不符合条件的订单跳过(计入 skipped),不报错。事务内完成
|
||||
* is_b2b 置 Y 与 wms_order_b2b 明细写入;操作日志在事务提交后写入。
|
||||
*
|
||||
* @param {Object} params 转换参数。
|
||||
* @param {number|string} params.warehouseId 仓库ID。
|
||||
* @param {Array<number>} params.orderIds 订单ID数组。
|
||||
* @param {Object|null} [params.operator=null] 操作人 { id, name }。
|
||||
* @return {Promise<Object>} { converted_order_ids, converted_count, skipped_order_ids,
|
||||
* skipped_count, skipped_reasons, not_found_order_ids, removed_from_wave_order_ids,
|
||||
* affected_wave_ids, emptied_wave_ids, active_pick_task_wave_ids }
|
||||
* skipped_count, skipped_reasons, not_found_order_ids }
|
||||
*/
|
||||
async convertOrdersToB2b(params = {}) {
|
||||
const { ctx, app } = this;
|
||||
@ -77,18 +58,13 @@ class OrderB2bService extends Service {
|
||||
const transaction = await ctx.model.transaction();
|
||||
const convertedRows = [];
|
||||
const skippedReasons = [];
|
||||
const waveRemovalLogItems = [];
|
||||
let waveDetachResult = null;
|
||||
let notFoundOrderIds = [];
|
||||
let notConvertedWaveIds = [];
|
||||
|
||||
try {
|
||||
const lockRows = await orderModel.findAll({
|
||||
attributes: [
|
||||
'id', 'delivery_order_code', 'step', 'status',
|
||||
'pick_status', 'recheck_status',
|
||||
'id', 'delivery_order_code', 'store_id', 'step',
|
||||
'print_status', 'lock_status', 'intercept_status', 'is_b2b',
|
||||
'wave_id', 'wave_no',
|
||||
],
|
||||
where: {
|
||||
id: { [Op.in]: normalizedOrderIds },
|
||||
@ -121,46 +97,6 @@ class OrderB2bService extends Service {
|
||||
convertedRows.push(row);
|
||||
}
|
||||
|
||||
// 已在波次中的订单:波次存在进行中的拣货任务时无法安全摘除,跳过转换
|
||||
const waveBoundRows = convertedRows.filter(row => Number(row && row.wave_id || 0) > 0);
|
||||
if (waveBoundRows.length > 0) {
|
||||
const waveIds = [ ...new Set(waveBoundRows.map(row => Number(row.wave_id))) ];
|
||||
const activeWaveRows = await ctx.model.query(`
|
||||
SELECT DISTINCT ptw.wave_id
|
||||
FROM wms_wave_pick_task_wave ptw
|
||||
INNER JOIN wms_wave_pick_task pt ON pt.id = ptw.task_id
|
||||
WHERE ptw.wave_id IN (:waveIds)
|
||||
AND pt.status IN (0, 1)
|
||||
`, {
|
||||
replacements: { waveIds },
|
||||
type: ctx.model.QueryTypes.SELECT,
|
||||
transaction,
|
||||
});
|
||||
const activeWaveIdSet = new Set((Array.isArray(activeWaveRows) ? activeWaveRows : [])
|
||||
.map(row => Number(row && row.wave_id || 0))
|
||||
.filter(waveId => Number.isInteger(waveId) && waveId > 0));
|
||||
|
||||
if (activeWaveIdSet.size > 0) {
|
||||
notConvertedWaveIds = [ ...activeWaveIdSet ].sort((a, b) => a - b);
|
||||
const retainedRows = [];
|
||||
for (const row of convertedRows) {
|
||||
const waveId = Number(row && row.wave_id || 0);
|
||||
if (waveId > 0 && activeWaveIdSet.has(waveId)) {
|
||||
skippedReasons.push({
|
||||
order_id: Number(row.id),
|
||||
delivery_order_code: String(row.delivery_order_code || '').trim(),
|
||||
reason: '订单所在波次存在进行中的拣货任务,不允许转B2B',
|
||||
});
|
||||
continue;
|
||||
}
|
||||
retainedRows.push(row);
|
||||
}
|
||||
|
||||
convertedRows.length = 0;
|
||||
convertedRows.push(...retainedRows);
|
||||
}
|
||||
}
|
||||
|
||||
if (convertedRows.length > 0) {
|
||||
const convertedOrderIds = convertedRows.map(row => Number(row.id));
|
||||
const now = new Date();
|
||||
@ -176,58 +112,43 @@ class OrderB2bService extends Service {
|
||||
}
|
||||
);
|
||||
|
||||
// 写入 B2B 作业明细(uk_warehouse_order 唯一):
|
||||
// 正常流程为创建新行;并发/重复转换命中同一行时重置作业字段(取消 B2B 为物理删除,无历史行恢复)
|
||||
// 写入 B2B 作业明细(uk_order_id 唯一):
|
||||
// 首次转换创建新行;二次转换(存在历史软删除行)恢复同一行并重置作业字段
|
||||
const b2bModel = ctx.model.OrderB2b;
|
||||
for (const row of convertedRows) {
|
||||
const orderId = Number(row.id);
|
||||
const baseFields = {
|
||||
warehouse_id: normalizedWarehouseId,
|
||||
order_id: orderId,
|
||||
store_id: Number(row.store_id || 0) > 0 ? Number(row.store_id) : null,
|
||||
delivery_order_code: String(row.delivery_order_code || '').trim(),
|
||||
updated_at: now,
|
||||
};
|
||||
const existing = await b2bModel.findOne({
|
||||
where: {
|
||||
warehouse_id: normalizedWarehouseId,
|
||||
order_id: orderId,
|
||||
},
|
||||
where: { order_id: orderId },
|
||||
paranoid: false,
|
||||
transaction,
|
||||
});
|
||||
if (existing) {
|
||||
// 恢复历史行并重置作业字段(取消 B2B 后的旧作业数据不再有效)
|
||||
await existing.update({
|
||||
deleted_at: null,
|
||||
total_box_count: 0,
|
||||
pickup_plate_number: null,
|
||||
prep_remark: null,
|
||||
prep_duration_seconds: 0,
|
||||
prep_at: null,
|
||||
is_picked_up: 'N',
|
||||
picked_up_at: null,
|
||||
is_print: 'N',
|
||||
...baseFields,
|
||||
}, { transaction });
|
||||
}, { transaction, paranoid: false });
|
||||
} else {
|
||||
await b2bModel.create({
|
||||
order_id: orderId,
|
||||
...baseFields,
|
||||
created_at: now,
|
||||
}, { transaction });
|
||||
}
|
||||
}
|
||||
|
||||
// 已在波次中的订单(含库内抓取进波次的订单):转 B2B 后必须从波次摘除,
|
||||
// 清空波次字段、重排 wave_index、回写波次统计(空波次置 wave_status=-1)
|
||||
const waveBoundConvertedRows = convertedRows.filter(row => Number(row && row.wave_id || 0) > 0);
|
||||
if (waveBoundConvertedRows.length > 0) {
|
||||
waveDetachResult = await ctx.service.systemMethods.order.wave.detachOrdersFromWavesInTransaction({
|
||||
warehouseId: normalizedWarehouseId,
|
||||
orderIds: waveBoundConvertedRows.map(row => Number(row.id)),
|
||||
orderModel,
|
||||
transaction,
|
||||
});
|
||||
for (const orderId of waveDetachResult.removed_order_ids) {
|
||||
waveRemovalLogItems.push({
|
||||
orderId,
|
||||
waveNo: String(waveDetachResult.wave_no_map.get(orderId) || '').trim(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await transaction.commit();
|
||||
@ -250,7 +171,6 @@ class OrderB2bService extends Service {
|
||||
warehouseId: normalizedWarehouseId,
|
||||
orderId: Number(row.id),
|
||||
orderNo: String(row.delivery_order_code || '').trim(),
|
||||
message: '订单转为B2B订单',
|
||||
},
|
||||
beforeChanges: null,
|
||||
});
|
||||
@ -259,30 +179,6 @@ class OrderB2bService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
// 波次摘除日志在事务提交后写入,失败不影响主流程
|
||||
for (const item of waveRemovalLogItems) {
|
||||
try {
|
||||
await ctx.service.systems.operationLog.createOperationLog({
|
||||
businessType: 'order',
|
||||
businessId: Number(item.orderId),
|
||||
operationCode: 'ORDER_WAVE_REMOVE',
|
||||
operationAction: 'UPDATE',
|
||||
changeSummary: `订单从波次 ${item.waveNo || '未知波次'} 中移除(转B2B)`,
|
||||
operator,
|
||||
extras: {
|
||||
warehouseId: normalizedWarehouseId,
|
||||
orderId: Number(item.orderId),
|
||||
waveNo: item.waveNo,
|
||||
reason: 'convertToB2b',
|
||||
message: `订单从波次 ${item.waveNo || '未知波次'} 中移除(转B2B)`,
|
||||
},
|
||||
beforeChanges: null,
|
||||
});
|
||||
} catch (error) {
|
||||
ctx.logger.warn(`[orderB2b.convertOrdersToB2b] 写入波次移除日志失败,不影响业务, orderId=${item.orderId}, error=${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
const skippedOrderIds = [ ...new Set(skippedReasons.map(item => item.order_id)) ];
|
||||
return {
|
||||
converted_order_ids: [ ...new Set(convertedRows.map(row => Number(row.id))) ],
|
||||
@ -291,43 +187,25 @@ class OrderB2bService extends Service {
|
||||
skipped_count: skippedOrderIds.length,
|
||||
skipped_reasons: skippedReasons,
|
||||
not_found_order_ids: notFoundOrderIds,
|
||||
removed_from_wave_order_ids: waveDetachResult ? waveDetachResult.removed_order_ids : [],
|
||||
affected_wave_ids: waveDetachResult ? waveDetachResult.affected_wave_ids : [],
|
||||
emptied_wave_ids: waveDetachResult ? waveDetachResult.emptied_wave_ids : [],
|
||||
active_pick_task_wave_ids: notConvertedWaveIds,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断订单是否满足转 B2B 条件,返回跳过原因;可转换时返回空串。
|
||||
*
|
||||
* 条件:非已取消(status != cancel)、处于待处理阶段(step in [1,2,3])、
|
||||
* 未拣货(pick_status != fin)、未复核(recheck_status != fin)、
|
||||
* 条件:待处理(step != 0)、未打印(print_status != fin)、
|
||||
* 未锁定(lock_status = none)、未拦截(intercept_status = none)、未转 B2B(is_b2b != Y)。
|
||||
* 打印状态不参与校验:已打印(print_status = fin)的订单同样允许转 B2B。
|
||||
*
|
||||
* @param {Object} row 订单行。
|
||||
* @return {string} 跳过原因,可转换返回空字符串。
|
||||
*/
|
||||
resolveConvertSkipReason(row = {}) {
|
||||
// 已取消订单即使仍停留在待处理步骤也不允许转 B2B
|
||||
if (String(row && row.status || '').trim() === 'cancel') {
|
||||
return '订单已取消,不允许转B2B';
|
||||
if (Number(row && row.step || 0) === 0) {
|
||||
return '订单待审核,不允许转B2B';
|
||||
}
|
||||
|
||||
// 仅待处理阶段可转:4 配送中/已提交出库、5 已完成、9 已关闭一律拒绝
|
||||
const step = Number(row && row.step || 0);
|
||||
if (!ORDER_B2B_CONVERT_ALLOWED_STEPS.has(step)) {
|
||||
return ORDER_B2B_CONVERT_STEP_SKIP_REASONS[step] || `订单当前步骤(${step})不允许转B2B`;
|
||||
}
|
||||
|
||||
// 已进入作业流程的订单不允许转 B2B:拣货/复核完成后订单实物已分拣、单据已核对
|
||||
if (String(row && row.pick_status || '').trim() === 'fin') {
|
||||
return '订单已拣货,不允许转B2B';
|
||||
}
|
||||
|
||||
if (String(row && row.recheck_status || '').trim() === 'fin') {
|
||||
return '订单已复核,不允许转B2B';
|
||||
if (String(row && row.print_status || '').trim() === 'fin') {
|
||||
return '订单已打印,不允许转B2B';
|
||||
}
|
||||
|
||||
if (String(row && row.lock_status || 'none').trim() !== 'none') {
|
||||
@ -348,8 +226,9 @@ class OrderB2bService extends Service {
|
||||
/**
|
||||
* 取消 B2B 出库:将 B2B 订单流转回正常订单。
|
||||
*
|
||||
* 仅限待处理表(current 分表)中 is_b2b=Y 且未锁定、未拦截的订单(打印状态不限制);
|
||||
* 不符合条件的订单跳过,不报错。事务内完成 is_b2b 置回 N 与 B2B 作业明细物理删除;
|
||||
* 仅限待处理表(current 分表)中 is_b2b=Y 且未打印、未锁定、未拦截、
|
||||
* B2B 面单未打印(wms_order_b2b.is_print=N)的订单;不符合条件的订单跳过,
|
||||
* 不报错。事务内完成 is_b2b 置回 N 与 B2B 作业明细软删除;
|
||||
* 操作日志在事务提交后写入。
|
||||
*
|
||||
* @param {Object} params 取消参数。
|
||||
@ -393,7 +272,7 @@ class OrderB2bService extends Service {
|
||||
try {
|
||||
const lockRows = await orderModel.findAll({
|
||||
attributes: [
|
||||
'id', 'delivery_order_code', 'step',
|
||||
'id', 'delivery_order_code', 'store_id', 'step',
|
||||
'print_status', 'lock_status', 'intercept_status', 'is_b2b',
|
||||
],
|
||||
where: {
|
||||
@ -408,13 +287,26 @@ class OrderB2bService extends Service {
|
||||
const rowMap = new Map((Array.isArray(lockRows) ? lockRows : []).map(row => [ Number(row && row.id || 0), row ]));
|
||||
notFoundOrderIds = normalizedOrderIds.filter(orderId => !rowMap.has(orderId));
|
||||
|
||||
// B2B 作业明细打印状态(is_print):已打印 B2B 面单的订单不允许取消
|
||||
const b2bRows = await ctx.model.OrderB2b.findAll({
|
||||
where: {
|
||||
order_id: { [Op.in]: normalizedOrderIds },
|
||||
deleted_at: null,
|
||||
},
|
||||
attributes: [ 'order_id', 'is_print' ],
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
const b2bPrintMap = new Map((Array.isArray(b2bRows) ? b2bRows : [])
|
||||
.map(row => [ Number(row && row.order_id || 0), String(row && row.is_print || 'N').trim() ]));
|
||||
|
||||
for (const orderId of normalizedOrderIds) {
|
||||
const row = rowMap.get(orderId);
|
||||
if (!row) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const skipReason = this.resolveCancelSkipReason(row);
|
||||
const skipReason = this.resolveCancelSkipReason(row, b2bPrintMap.get(orderId));
|
||||
if (skipReason) {
|
||||
skippedReasons.push({
|
||||
order_id: orderId,
|
||||
@ -442,14 +334,17 @@ class OrderB2bService extends Service {
|
||||
}
|
||||
);
|
||||
|
||||
// B2B 作业明细物理删除(不保留历史),关联条件固定为 warehouse_id + order_id
|
||||
await ctx.model.OrderB2b.destroy({
|
||||
where: {
|
||||
warehouse_id: normalizedWarehouseId,
|
||||
order_id: { [Op.in]: canceledOrderIds },
|
||||
},
|
||||
transaction,
|
||||
});
|
||||
// B2B 作业明细软删除(保留历史)
|
||||
await ctx.model.OrderB2b.update(
|
||||
{ deleted_at: now, updated_at: now },
|
||||
{
|
||||
where: {
|
||||
order_id: { [Op.in]: canceledOrderIds },
|
||||
deleted_at: null,
|
||||
},
|
||||
transaction,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
await transaction.commit();
|
||||
@ -472,7 +367,6 @@ class OrderB2bService extends Service {
|
||||
warehouseId: normalizedWarehouseId,
|
||||
orderId: Number(row.id),
|
||||
orderNo: String(row.delivery_order_code || '').trim(),
|
||||
message: '取消B2B出库,订单流转回正常订单',
|
||||
},
|
||||
beforeChanges: null,
|
||||
});
|
||||
@ -495,13 +389,15 @@ class OrderB2bService extends Service {
|
||||
/**
|
||||
* 判断 B2B 订单是否满足取消条件,返回跳过原因;可取消时返回空串。
|
||||
*
|
||||
* 条件:待处理(step != 0)、是 B2B(is_b2b = Y)、未锁定(lock_status = none)、
|
||||
* 未拦截(intercept_status = none)。打印状态不参与校验。
|
||||
* 条件:待处理(step != 0)、是 B2B(is_b2b = Y)、未打印(print_status != fin)、
|
||||
* 未锁定(lock_status = none)、未拦截(intercept_status = none)、
|
||||
* B2B 面单未打印(is_print != Y)。
|
||||
*
|
||||
* @param {Object} row 订单行。
|
||||
* @param {string} b2bIsPrint B2B 作业明细打印状态(无明细行时为空串,视为未打印)。
|
||||
* @return {string} 跳过原因,可取消返回空字符串。
|
||||
*/
|
||||
resolveCancelSkipReason(row = {}) {
|
||||
resolveCancelSkipReason(row = {}, b2bIsPrint = '') {
|
||||
if (Number(row && row.step || 0) === 0) {
|
||||
return '订单待审核,不允许取消B2B';
|
||||
}
|
||||
@ -510,6 +406,10 @@ class OrderB2bService extends Service {
|
||||
return '订单不是B2B订单';
|
||||
}
|
||||
|
||||
if (String(row && row.print_status || '').trim() === 'fin') {
|
||||
return '订单已打印,不允许取消B2B';
|
||||
}
|
||||
|
||||
if (String(row && row.lock_status || 'none').trim() !== 'none') {
|
||||
return '订单已锁定,不允许取消B2B';
|
||||
}
|
||||
@ -518,6 +418,10 @@ class OrderB2bService extends Service {
|
||||
return '订单已拦截,不允许取消B2B';
|
||||
}
|
||||
|
||||
if (String(b2bIsPrint || '').trim() === 'Y') {
|
||||
return 'B2B面单已打印,不允许取消B2B';
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
@ -14,8 +14,6 @@ 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',
|
||||
@ -57,8 +55,6 @@ 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 },
|
||||
@ -112,8 +108,6 @@ 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 },
|
||||
@ -400,26 +394,12 @@ class OrderExportService extends OrderBaseService {
|
||||
* @param {Map<number, string>} [context.imageUrlMap] stockId → 商品图片URL的映射。
|
||||
* @param {Map<number, Array<Object>>} [context.expressMap] 订单ID → 运单行列表的映射。
|
||||
* @param {Map<number, string>} [context.packageMaterialMap] package_material_id → 包材编码的映射。
|
||||
* @param {Set<number>} [context.snStockIdSet] 启用序列号管理的 stockId 集合(用于统计 SN 码数量)。
|
||||
* @param {Map<number, string[]>} [context.snCodesByOrderMap] 订单ID → 已登记 SN 码列表(订单级汇总)。
|
||||
* @param {Map<number, Map<number, string[]>>} [context.snCodesByItemMap] 订单ID → (明细ID → 已登记 SN 码列表)。
|
||||
* @param {string} [mode='waybill'] 导出模式:'waybill' 或 'item'。
|
||||
* @return {Array<Object>} 导出行数组。
|
||||
*/
|
||||
mapOrderExportRow(orderRow = {}, context = {}, mode = 'waybill') {
|
||||
const safeOrderRow = this.isPlainObject(orderRow) ? orderRow : {};
|
||||
const {
|
||||
itemsMap,
|
||||
storeRemarkMap,
|
||||
stockNameMap,
|
||||
barcodeMap,
|
||||
imageUrlMap,
|
||||
expressMap,
|
||||
packageMaterialMap,
|
||||
snStockIdSet,
|
||||
snCodesByOrderMap,
|
||||
snCodesByItemMap,
|
||||
} = context;
|
||||
const { itemsMap, storeRemarkMap, stockNameMap, barcodeMap, imageUrlMap, expressMap, packageMaterialMap } = 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();
|
||||
@ -461,35 +441,6 @@ 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);
|
||||
@ -522,8 +473,6 @@ 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),
|
||||
@ -564,7 +513,6 @@ 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,
|
||||
@ -584,8 +532,6 @@ 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,
|
||||
@ -625,8 +571,6 @@ 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),
|
||||
@ -757,7 +701,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: [ 'id', 'order_id', 'item_name', 'plan_qty', 'stock_id' ],
|
||||
attributes: [ 'order_id', 'item_name', 'plan_qty', 'stock_id' ],
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
});
|
||||
@ -775,87 +719,6 @@ 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();
|
||||
@ -987,7 +850,7 @@ class OrderExportService extends OrderBaseService {
|
||||
}
|
||||
}
|
||||
|
||||
const exportContext = { itemsMap, storeRemarkMap, stockNameMap, barcodeMap, imageUrlMap, expressMap, packageMaterialMap, snStockIdSet, snCodesByOrderMap, snCodesByItemMap };
|
||||
const exportContext = { itemsMap, storeRemarkMap, stockNameMap, barcodeMap, imageUrlMap, expressMap, packageMaterialMap };
|
||||
|
||||
const exportRows = [];
|
||||
for (const row of rowsWithWaveIndex) {
|
||||
|
||||
@ -329,7 +329,7 @@ class OrderExpressService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 散单称重前置校验:开启「散单称重是否需要打包」时,打包中或已打包订单允许称重。
|
||||
* 散单称重前置校验:开启「散单称重是否需要打包」时,未打包订单禁止称重。
|
||||
*
|
||||
* 适用范围:订单波次范围 wave_scope 不属于 1(大团购)/ 3(小团购)时生效,
|
||||
* 即未分配波次、散单、单品单件等按散单处理的订单;团购订单不校验。
|
||||
@ -337,7 +337,7 @@ class OrderExpressService extends Service {
|
||||
*
|
||||
* @param {number} orderId 订单ID。
|
||||
* @param {number|null} warehouseId 仓库ID,缺失时跳过校验。
|
||||
* @return {Promise<void>} 无返回值;未打包或打包异常时抛出业务异常。
|
||||
* @return {Promise<void>} 无返回值;未打包时抛出业务异常。
|
||||
*/
|
||||
async assertSingleOrderPackedForWeigh(orderId, warehouseId) {
|
||||
const normalizedWarehouseId = Number(warehouseId || 0);
|
||||
@ -361,17 +361,18 @@ class OrderExpressService extends Service {
|
||||
}
|
||||
|
||||
const packStatus = String(orderRow.pack_status || '').trim();
|
||||
if (packStatus !== 'fin' && packStatus !== 'padding') {
|
||||
throw this.createBusinessError(this.buildWeighPackBlockedMessage(), 400);
|
||||
if (packStatus !== 'fin') {
|
||||
throw this.createBusinessError(this.buildWeighPackBlockedMessage(packStatus), 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造「散单称重需先打包」拦截文案,供各称重入口复用(保证提示语一致)。
|
||||
* @return {string} 拦截提示文案。
|
||||
* @param {string} packStatus 打包状态原值。
|
||||
* @return {string} 拦截提示文案:打包中(padding)返回「订单打包中」,其余未完成状态返回「订单未打包」。
|
||||
*/
|
||||
buildWeighPackBlockedMessage() {
|
||||
return '订单未打包';
|
||||
buildWeighPackBlockedMessage(packStatus) {
|
||||
return packStatus === 'padding' ? '订单打包中' : '订单未打包';
|
||||
}
|
||||
|
||||
/**
|
||||
@ -1123,7 +1124,7 @@ class OrderExpressService extends Service {
|
||||
* @return {Promise<{order_id:number, waybill_code:string, weighing_weight:number, items_weight:number}>} 更新结果。
|
||||
*/
|
||||
async _updateSingleOrderWeight(orderId, waybillCode, weight, warehouseId) {
|
||||
// 散单称重前置校验:开启「散单称重是否需要打包」后,仅打包中或已打包订单允许称重
|
||||
// 散单称重前置校验:开启「散单称重是否需要打包」后,未打包订单禁止称重
|
||||
await this.assertSingleOrderPackedForWeigh(orderId, warehouseId);
|
||||
|
||||
const rows = await this.findValidOrderExpressRows(orderId, warehouseId);
|
||||
|
||||
@ -1,713 +0,0 @@
|
||||
'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<string, string[]>} 仓库商品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<string, string[]>} 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<Object[]>} 订单明细列表。
|
||||
*/
|
||||
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<Set<number>>} 启用了序列号管理的仓库商品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<number>} snStockIdSet 序列号管理商品ID集合。
|
||||
* @return {Map<string, Object[]>} 仓库商品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<string, Object[]>} params.stockItemMap 序列号管理商品 -> 明细。
|
||||
* @param {Map<string, string[]>} 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<string, Object[]>} params.stockItemMap 序列号管理商品 -> 明细。
|
||||
* @param {Map<string, string[]>} params.codesByStock 提交的 SN(商品ID -> SN 列表)。
|
||||
* @return {Map<string, string[]>} 订单明细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<string, string[]>} 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<void>} 无返回值,命中已发货 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;
|
||||
@ -10,8 +10,6 @@ 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' ]);
|
||||
|
||||
/**
|
||||
* 规范化块状日志的输出值。
|
||||
@ -1661,10 +1659,6 @@ 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<Object>} 同步结果。
|
||||
*/
|
||||
@ -1672,7 +1666,7 @@ class OrderStorageAllocationService extends MainService {
|
||||
const { ctx } = this;
|
||||
const unallocatedPostStatus = 'none';
|
||||
const fastFailReason = '快递状态未分配,禁止同步';
|
||||
const snBatchForbiddenReason = 'SN订单SN明细未齐套或未复核完成,不允许回传';
|
||||
const snBatchForbiddenReason = 'SN订单不支持批量回传,请改用单订单回传';
|
||||
const requestData = data && typeof data === 'object' ? data : {};
|
||||
const normalizeNumber = (value, defaultValue = 0) => {
|
||||
const numericValue = Number(value);
|
||||
@ -1831,17 +1825,13 @@ class OrderStorageAllocationService extends MainService {
|
||||
orderMap.set(Number(plainOrder.id), plainOrder);
|
||||
}
|
||||
|
||||
// SN(序列号管理)订单回传前置校验:通过订单明细 stock_id 反查 stock_warehouse.is_sn_mgmt,
|
||||
// 只有「每个序列号明细的 SN 数量齐套」且「订单已复核」时才允许回传;
|
||||
// 齐套但未复核、或已复核但 SN 未齐套,一律标记快速失败,避免把缺 SN 的发货单回传平台。
|
||||
// SN 管理订单不允许走批量回传:通过订单明细 stock_id 反查 stock_warehouse.is_sn_mgmt。
|
||||
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({
|
||||
@ -1850,7 +1840,7 @@ class OrderStorageAllocationService extends MainService {
|
||||
[ctx.app.Sequelize.Op.in]: existingOrderIds,
|
||||
},
|
||||
},
|
||||
attributes: [ 'id', 'order_id', 'stock_id', 'plan_qty' ],
|
||||
attributes: [ 'order_id', 'stock_id' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
@ -1875,88 +1865,11 @@ 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) {
|
||||
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);
|
||||
}
|
||||
if (snStockIdSet.has(stockId) && orderId > 0) {
|
||||
snOrderIdSet.add(orderId);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1997,8 +1910,8 @@ class OrderStorageAllocationService extends MainService {
|
||||
continue;
|
||||
}
|
||||
|
||||
// SN 订单仅在「SN 明细未齐套」或「未复核完成」时拦截,齐套且已复核允许回传
|
||||
if (snBlockedOrderIdSet.has(orderId)) {
|
||||
// SN 管理订单不允许走批量回传,标记为跳过,不阻断其他订单
|
||||
if (snOrderIdSet.has(orderId)) {
|
||||
fastFailedOrders.push({
|
||||
order_id: orderId,
|
||||
status: 'failed',
|
||||
|
||||
@ -367,7 +367,7 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([
|
||||
type: 'flag',
|
||||
default: false,
|
||||
required: false,
|
||||
description: '开启后散单称重(订单波次范围 wave_scope 非 1 大团购 / 3 小团购)须处于打包中或已打包(pack_status=padding/fin);未打包或打包异常时拒绝称重并返回错误,默认 false(关闭)',
|
||||
description: '开启后散单称重(订单波次范围 wave_scope 非 1 大团购 / 3 小团购)前必须已打包完成(pack_status=fin),未打包时拒绝称重并返回错误,默认 false(关闭)',
|
||||
}),
|
||||
Object.freeze({
|
||||
key: 'stock_warning_enabled',
|
||||
|
||||
@ -1,235 +0,0 @@
|
||||
'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;
|
||||
@ -3086,7 +3086,7 @@ class stockStoreService extends Service {
|
||||
*/
|
||||
async getInfo(data) {
|
||||
const {
|
||||
ctx, service,
|
||||
ctx,
|
||||
} = this;
|
||||
const {
|
||||
id,
|
||||
@ -3106,7 +3106,6 @@ class stockStoreService extends Service {
|
||||
'is_batch_mgmt',
|
||||
'is_shelf_life_mgmt',
|
||||
'is_sn_mgmt',
|
||||
'sn_code_rules',
|
||||
'need_recheck',
|
||||
'goods_code',
|
||||
'item_code',
|
||||
@ -3143,8 +3142,6 @@ 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';
|
||||
@ -3179,7 +3176,6 @@ 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;
|
||||
@ -3187,12 +3183,6 @@ 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 ],
|
||||
@ -3280,7 +3270,6 @@ class stockStoreService extends Service {
|
||||
outbound_min_days,
|
||||
remaining_threshold_days,
|
||||
warning_quantity,
|
||||
...(normalizedSnCodeRules !== undefined && { sn_code_rules: normalizedSnCodeRules }),
|
||||
updated_at: new Date(),
|
||||
};
|
||||
// 5. 清除空值
|
||||
@ -3357,16 +3346,10 @@ 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);
|
||||
@ -3417,7 +3400,6 @@ class stockStoreService extends Service {
|
||||
box_height,
|
||||
box_volume,
|
||||
box_remark,
|
||||
sn_code_rules: normalizedSnCodeRules,
|
||||
updated_at: new Date(),
|
||||
};
|
||||
const transaction = await ctx.model.transaction();
|
||||
|
||||
@ -6,10 +6,6 @@ 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 时间值
|
||||
@ -477,7 +473,15 @@ class StorageReportService extends Service {
|
||||
}
|
||||
)
|
||||
: [],
|
||||
this.loadOrderDeliveryRows(normalizedOrderIds, warehouseId, orderWarehouseMap),
|
||||
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,
|
||||
}
|
||||
)
|
||||
: [],
|
||||
normalizedOrderIds.length > 0
|
||||
? (async () => {
|
||||
// 强制同仓校验:读取 wms_order_express 必须同时带订单ID与仓库ID,
|
||||
@ -575,155 +579,30 @@ 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<Array<Object>>} 命中的发货单记录
|
||||
*/
|
||||
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<Object>, 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, uniqueToken = '') {
|
||||
buildExportFilename(startTime, endTime) {
|
||||
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}${suffix}.xlsx`;
|
||||
return `库存报表_${startToken}_${endToken}.xlsx`;
|
||||
}
|
||||
|
||||
if (startToken) {
|
||||
return `库存报表_${startToken}${suffix}.xlsx`;
|
||||
return `库存报表_${startToken}.xlsx`;
|
||||
}
|
||||
|
||||
if (endToken) {
|
||||
return `库存报表_${endToken}${suffix}.xlsx`;
|
||||
return `库存报表_${endToken}.xlsx`;
|
||||
}
|
||||
|
||||
return `库存报表_${todayToken}${suffix}.xlsx`;
|
||||
return `库存报表_${todayToken}.xlsx`;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -920,8 +799,7 @@ class StorageReportService extends Service {
|
||||
// 明细游标分页:按主键 id 升序分批拉取(id 自增序≈插入序),
|
||||
// 流式写入 ExcelJS stream,避免一次性把全部明细与单元格留在内存。
|
||||
const detailBatchSize = 5000;
|
||||
// 文件名带时间戳:同一时间范围重复导出会覆盖同名对象,CDN/浏览器会继续命中旧文件
|
||||
const filename = this.buildExportFilename(startTime, endTime, Date.now());
|
||||
const filename = this.buildExportFilename(startTime, endTime);
|
||||
let tempDir = null;
|
||||
let workbook = null;
|
||||
let currentCount = 0;
|
||||
@ -1120,7 +998,7 @@ class StorageReportService extends Service {
|
||||
batch_no: item.batch_no || '',
|
||||
inventory_type: item.inventory_type || '',
|
||||
order_type: item.order_type || '',
|
||||
order_no: String(orderDelivery.delivery_order_code || item.order_no || '').trim(),
|
||||
order_no: item.order_no || '',
|
||||
order_id: orderId,
|
||||
receiving_id: toNumber(item.receiving_id),
|
||||
entry_order_id: entryOrderId,
|
||||
|
||||
@ -10,10 +10,6 @@ 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: '已通过',
|
||||
@ -1106,74 +1102,6 @@ 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<Object>} 接口类型对象。
|
||||
* @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 解析客户标识。
|
||||
*
|
||||
@ -2823,11 +2751,9 @@ class SettingStoreWarehouseService extends Service {
|
||||
contract_id: Number(relation.id || 0),
|
||||
};
|
||||
if (interfaceTypeId) {
|
||||
// 签约关系级配置没有仓库开放接口,传 3 时按货主开放接口过滤
|
||||
const interfaceType = await this.resolveContractApiInterfaceType(
|
||||
{ interface_type_id: interfaceTypeId },
|
||||
{ allowDisabled: true }
|
||||
);
|
||||
const interfaceType = await this.getApiInterfaceType({ interface_type_id: interfaceTypeId }, {
|
||||
allowDisabled: true,
|
||||
});
|
||||
where.interface_type_id = Number(interfaceType.id || 0);
|
||||
}
|
||||
|
||||
@ -2888,9 +2814,6 @@ class SettingStoreWarehouseService extends Service {
|
||||
/**
|
||||
* 保存接口配置。
|
||||
*
|
||||
* 签约关系级配置统一按货主开放接口维护:传入仓库开放接口(interface_type_id=3)时按货主开放接口落库,
|
||||
* 回调地址不再取入参,统一使用 config.openapi.defaultCallbackUrl。
|
||||
*
|
||||
* @param {Object} [data={}] 请求参数。
|
||||
* @return {Promise<Object>} 接口响应对象。
|
||||
*/
|
||||
@ -2901,7 +2824,8 @@ class SettingStoreWarehouseService extends Service {
|
||||
try {
|
||||
const currentSubject = await this.getCurrentSubject();
|
||||
const relation = await this.findScopedRelation(data, currentSubject, transaction);
|
||||
const interfaceType = await this.resolveContractApiInterfaceType(data, { transaction });
|
||||
this.ensureWarehouseSubject(currentSubject, '接口配置');
|
||||
const interfaceType = await this.getApiInterfaceType(data, { transaction, requireId: true });
|
||||
const isOpenApi = interfaceType.interface_category === 'OPEN_API';
|
||||
const isQimenWms = interfaceType.interface_category === 'QM_WMS';
|
||||
|
||||
@ -3020,7 +2944,7 @@ class SettingStoreWarehouseService extends Service {
|
||||
contact_person: contactPerson || null,
|
||||
contact_phone: contactPhone || null,
|
||||
email,
|
||||
callback_url: this.getDefaultApiCallbackUrl(),
|
||||
callback_url: this.normalizeText(data.callback_url || data.callbackUrl, 'callback_url', 500) || null,
|
||||
is_enabled: isEnabled,
|
||||
};
|
||||
|
||||
|
||||
@ -22,12 +22,6 @@ const WAYBILL_RECEIVE_FLAGS = [ 'Y', 'N' ];
|
||||
*/
|
||||
const WAYBILL_RECEIVE_SIGN_MODE = 'simple';
|
||||
|
||||
/** 出站回调 method:查询运单物流轨迹 */
|
||||
const WAYBILL_TRACE_EVENT = 'waybill.getTrace';
|
||||
|
||||
/** 轨迹查询回调签名模式:与揽收查询一致(仓库通知协议) */
|
||||
const WAYBILL_TRACE_SIGN_MODE = WAYBILL_RECEIVE_SIGN_MODE;
|
||||
|
||||
/**
|
||||
* 业务逻辑层:waybill(运单号快速查询)。
|
||||
*/
|
||||
@ -1258,7 +1252,6 @@ 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`。
|
||||
@ -1313,17 +1306,13 @@ 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.map(code => queryCodeMap.get(code) || code) },
|
||||
request: { waybill_codes: batch },
|
||||
signMode: WAYBILL_RECEIVE_SIGN_MODE,
|
||||
});
|
||||
|
||||
@ -1352,7 +1341,7 @@ class WaybillService extends MainService {
|
||||
}
|
||||
} else {
|
||||
for (const row of this.extractReceiveRows(result.response)) {
|
||||
const code = this.stripWaybillCodeSuffix(String(row && (row.waybill_code || row.waybillCode) || '').trim());
|
||||
const code = String(row && (row.waybill_code || row.waybillCode) || '').trim();
|
||||
if (!code) continue;
|
||||
const flag = this.normalizeReceiveFlag(row.is_galaxy_receive);
|
||||
if (!flag) {
|
||||
@ -1476,108 +1465,6 @@ 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<string>} options.waybillCodes 原始运单号列表。
|
||||
* @return {Promise<Map<string, string>>} 原始运单号 → 出站查询运单号。
|
||||
*/
|
||||
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。
|
||||
@ -1643,267 +1530,6 @@ class WaybillService extends MainService {
|
||||
if ([ '0', 'N', 'NO', 'FALSE' ].includes(text)) return 'N';
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 实时查询单个运单的物流轨迹(出站回调 waybill.getTrace)。
|
||||
*
|
||||
* 纯回源:不落库、不读本地表;请求与 `waybill.getreceive` 一致
|
||||
* (`{ request: { waybill_codes: [waybillCode] } }`,运单号同样会补寄件电话后四位
|
||||
* `运单号|后四位`),响应兼容
|
||||
* `[{ waybillNo, trace }]` / `{ waybillNo, trace }` / `{ code, data: [...] }`。
|
||||
*
|
||||
* @param {Object} options 查询参数。
|
||||
* @param {number} options.warehouseId 仓库 ID(仅用于日志与揽收联动)。
|
||||
* @param {string} options.waybillCode 运单号。
|
||||
* @param {string} [options.appKey] 指定目标应用 AppKey,不传则按仓库订阅关系解析。
|
||||
* @return {Promise<{success: boolean, traces: Array<Object>, app_key: string, empty: boolean, reason?: string, error?: string}>} 轨迹列表。
|
||||
*/
|
||||
async fetchTracesByWaybill({ warehouseId, waybillCode, appKey = '' } = {}) {
|
||||
const { ctx } = this;
|
||||
const normalizedWarehouseId = Number(warehouseId) || 0;
|
||||
const normalizedCode = String(waybillCode || '').trim();
|
||||
|
||||
if (!normalizedCode) {
|
||||
return { success: false, traces: [], app_key: '', empty: false, reason: '运单号不能为空' };
|
||||
}
|
||||
if (!normalizedWarehouseId) {
|
||||
return { success: false, traces: [], app_key: '', empty: false, reason: '缺少仓库ID' };
|
||||
}
|
||||
|
||||
const targetAppKey = String(appKey || '').trim()
|
||||
|| await this.resolveTraceQueryAppKey(normalizedWarehouseId);
|
||||
if (!targetAppKey) {
|
||||
return {
|
||||
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 { success: false, traces: [], app_key: targetAppKey, empty: false, reason: 'OpenAPI 回调服务不可用' };
|
||||
}
|
||||
|
||||
const queryCodeMap = await this.buildWaybillQueryCodeMap({
|
||||
warehouseId: normalizedWarehouseId,
|
||||
waybillCodes: [ normalizedCode ],
|
||||
});
|
||||
|
||||
const result = await callbackService.sendByAppKey({
|
||||
appKey: targetAppKey,
|
||||
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 {
|
||||
success: true,
|
||||
traces,
|
||||
app_key: targetAppKey,
|
||||
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。
|
||||
* @return {Promise<string>} 目标应用 AppKey,无承接应用时返回空字符串。
|
||||
*/
|
||||
async resolveTraceQueryAppKey(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();
|
||||
}
|
||||
|
||||
/**
|
||||
* 从回调响应中提取轨迹行,兼容裸数组、单个对象与 { code, data: [...] } 包装。
|
||||
* @param {*} response 回调响应体。
|
||||
* @return {Array<Object>} 轨迹行列表(每行含 waybillNo + trace)。
|
||||
*/
|
||||
extractTraceRows(response) {
|
||||
if (Array.isArray(response)) return response;
|
||||
if (!response || typeof response !== 'object') return [];
|
||||
if (Array.isArray(response.data)) return response.data;
|
||||
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 [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一单个运单的轨迹列表:trace 支持对象或数组,另兼容 traces / traceList。
|
||||
* @param {Object} row 外部返回的单行。
|
||||
* @return {Array<Object>} 轨迹对象数组。
|
||||
*/
|
||||
normalizeTraceList(row) {
|
||||
if (!row || typeof row !== 'object') return [];
|
||||
const candidates = [ row.trace, row.traces, row.traceList, row.trace_list ];
|
||||
const list = [];
|
||||
for (const item of candidates) {
|
||||
if (Array.isArray(item)) {
|
||||
list.push(...item.filter(one => one && typeof one === 'object'));
|
||||
} else if (item && typeof item === 'object') {
|
||||
list.push(item);
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析轨迹重量:外部可能返回数字或字符串(如 "0.99"),统一转保留 3 位小数的数字。
|
||||
* @param {*} value 外部返回值。
|
||||
* @return {number} 重量,非法值返回 0。
|
||||
*/
|
||||
parseTraceWeight(value) {
|
||||
if (value === undefined || value === null || value === '') return 0;
|
||||
const num = Number(String(value).trim().replace(/,/g, ''));
|
||||
if (!Number.isFinite(num)) return 0;
|
||||
return Math.round(num * 1000) / 1000;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析轨迹操作时间:支持 'YYYY-MM-DD HH:mm:ss' 与 ISO 字符串,非法值返回 null。
|
||||
* @param {*} value 外部返回值。
|
||||
* @return {Date|null} 解析后的时间。
|
||||
*/
|
||||
parseTraceTime(value) {
|
||||
const text = String(value === undefined || value === null ? '' : value).trim();
|
||||
if (!text) return null;
|
||||
const normalized = text.includes('T') ? text : text.replace(' ', 'T');
|
||||
const date = new Date(normalized);
|
||||
return Number.isNaN(date.getTime()) ? null : date;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按轨迹把运单标记为已揽收(is_galaxy_receive='Y')。
|
||||
* 仅把非 Y(含 NULL)的行升级为 Y,已为 Y 的不重复更新;按仓库隔离。
|
||||
*
|
||||
* @param {Object} options 参数。
|
||||
* @param {number} options.warehouseId 仓库 ID。
|
||||
* @param {Array<string>} options.waybillCodes 有轨迹的运单号。
|
||||
* @return {Promise<number>} 实际更新行数。
|
||||
*/
|
||||
async markReceiveByTraces({ warehouseId, waybillCodes = [] } = {}) {
|
||||
const { ctx } = this;
|
||||
const { Op } = this.app.Sequelize;
|
||||
const codes = [ ...new Set((waybillCodes || []).map(code => String(code || '').trim()).filter(Boolean)) ];
|
||||
if (codes.length === 0) return 0;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WaybillService;
|
||||
|
||||
@ -1833,8 +1833,8 @@ class WorkbenchService extends Service {
|
||||
|
||||
/**
|
||||
* 散单称重前置校验(工作台):开启仓库配置「散单称重是否需要打包」后,
|
||||
* 波次范围(wave_scope)非 1(大团购)/ 3(小团购)的订单,打包中或已打包
|
||||
* (pack_status = padding/fin)时允许称重。
|
||||
* 波次范围(wave_scope)非 1(大团购)/ 3(小团购)的订单未打包完成
|
||||
* (pack_status != fin)时禁止称重。
|
||||
*
|
||||
* 配置读取与提示文案复用 systems/order_express,避免多处判定逻辑漂移;
|
||||
* 当前订单行已含 wave_scope/pack_status,故无需重复查询订单表。
|
||||
@ -1842,7 +1842,7 @@ class WorkbenchService extends Service {
|
||||
*
|
||||
* @param {Object} orderRow 订单行(需包含 wave_scope/pack_status)
|
||||
* @param {number} warehouseId 仓库ID
|
||||
* @return {Promise<void>} 无返回值;未打包或打包异常时抛出错误
|
||||
* @return {Promise<void>} 无返回值;未打包时抛出错误
|
||||
*/
|
||||
async _assertSingleWeighPackedForWeigh(orderRow, warehouseId) {
|
||||
const waveScope = Number((orderRow && orderRow.wave_scope) || 0);
|
||||
@ -1863,13 +1863,13 @@ class WorkbenchService extends Service {
|
||||
}
|
||||
|
||||
const packStatus = String((orderRow && orderRow.pack_status) || '').trim();
|
||||
if (packStatus === 'fin' || packStatus === 'padding') {
|
||||
if (packStatus === 'fin') {
|
||||
return;
|
||||
}
|
||||
|
||||
const message = typeof orderExpressService.buildWeighPackBlockedMessage === 'function'
|
||||
? orderExpressService.buildWeighPackBlockedMessage()
|
||||
: '订单未打包';
|
||||
? orderExpressService.buildWeighPackBlockedMessage(packStatus)
|
||||
: (packStatus === 'padding' ? '订单打包中' : '订单未打包');
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
|
||||
@ -64,13 +64,6 @@ 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
|
||||
|
||||
@ -76,8 +76,6 @@
|
||||
| `pack_task` | `waybill_code` | 打包任务(打包状态、打包人、打包时间) |
|
||||
| `package_material` | `package_material_id` ↔ `id` | 包材详情 |
|
||||
|
||||
> **轨迹不落库(2026-11-11 调整)**:物流轨迹改为**全部实时回源**,`wms_order_express_trace` 表与模型已删除(迁移 `20261111205500-drop-wms-order-express-trace.js`)。轨迹查询不再有本地表,也不再存在 1:N 关联。
|
||||
|
||||
### 2.3 索引评估
|
||||
|
||||
当前 `wms_order_express` 表的索引不足以支撑运单列表场景的高频查询:
|
||||
@ -214,15 +212,14 @@ POST /system { method: "waybill.warehouse.list", ... }
|
||||
| 4 | `waybill.warehouse.exportTaskProgress` | 运单导出任务进度查询 | ✓ | ✗ |
|
||||
| 5 | `waybill.warehouse.updateReceive` | 批量更新运单是否揽收(走出站回调 `waybill.getreceive`,异步任务) | ✓ | ✗ |
|
||||
| 6 | `waybill.warehouse.updateReceiveTaskProgress` | 揽收状态更新任务进度查询 | ✓ | ✗ |
|
||||
| 7 | `waybill.warehouse.getTrace` | 查询单个运单的全部物流轨迹(实时回源,不分页) | ✓ | ✗ |
|
||||
|
||||
> **预留接口(本期不实现)**:
|
||||
>
|
||||
> | # | method | 描述 |
|
||||
> |---|--------|------|
|
||||
> | 8 | `waybill.store.list` | 运单列表-货主侧(按 store_id 隔离) |
|
||||
> | 9 | `waybill.store.detail` | 运单详情-货主侧 |
|
||||
> | 10 | `waybill.store.export` | 运单导出-货主侧 |
|
||||
> | 7 | `waybill.store.list` | 运单列表-货主侧(按 store_id 隔离) |
|
||||
> | 8 | `waybill.store.detail` | 运单详情-货主侧 |
|
||||
> | 9 | `waybill.store.export` | 运单导出-货主侧 |
|
||||
|
||||
---
|
||||
|
||||
@ -585,57 +582,6 @@ waybill.warehouse.updateReceive(入口层:参数校验 + 接口配置预检
|
||||
|
||||
---
|
||||
|
||||
### 3.9 `waybill.warehouse.getTrace` — 查询运单物流轨迹(仓库侧,实时回源)
|
||||
|
||||
**功能说明**:按运单号**实时**调用外部访问接口 `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.getTrace(入口层:参数校验 + 接口配置预检)
|
||||
→ systems/waybill.js#fetchTracesByWaybill(单运单实时查询 + 归一排序)
|
||||
→ openapi/callback.js#sendByAppKey(event = waybill.getTrace,signMode=simple)
|
||||
→ systems/waybill.js#markReceiveByTraces(命中轨迹则置 is_galaxy_receive=Y)
|
||||
```
|
||||
|
||||
#### 请求 / 响应
|
||||
|
||||
```json
|
||||
{ "method": "waybill.warehouse.getTrace", "waybillCode": "770358128188071" }
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"waybill_code": "770358128188071",
|
||||
"total": 2,
|
||||
"received_updated": 1,
|
||||
"list": [
|
||||
{
|
||||
"op_time": "2026-11-11 10:43:00",
|
||||
"out_biz_code": "770358128188071_510902_1794255999000_120",
|
||||
"memo": "【广州市】快件已发往 山东济南转运中心",
|
||||
"op_org_city_name": "广州市",
|
||||
"weight": 0.99,
|
||||
"scan_type": "收件",
|
||||
"raw_data": { "opTime": "2026-11-11 10:43:00" }
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### 外部接口约定(`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` 升序)
|
||||
|
||||
---
|
||||
|
||||
## 四、`methods/system.json` 变更
|
||||
|
||||
在 `methods.groups[]` 中新增 `waybill.warehouse` group:
|
||||
|
||||
@ -1,137 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 创建运单物流轨迹表 wms_order_express_trace。
|
||||
*
|
||||
* 与 wms_order_express 关联:一个运单(express_id)对应多条轨迹(1:N),
|
||||
* 轨迹由外部快递/轨迹接口回传(如奇门 taobao.qimen.trace.query 的 traces 节点)。
|
||||
*
|
||||
* 字段口径(与外部返回的轨迹行同名转下划线):
|
||||
* op_time opTime 操作时间
|
||||
* out_biz_code outBizCode 外部业务码(可能是拼接串,如 770358128188071_510180_1794262553000_210)
|
||||
* memo memo 轨迹描述,如【广州市】快件已发往 山东济南转运中心
|
||||
* op_org_city_name opOrgCityName 操作机构所在城市
|
||||
* weight weight 重量(来源原值,单位以对接方为准)
|
||||
* scan_type scanType 扫描类型,如 发件 / 到件 / 派件 / 签收
|
||||
* raw_data 原始报文 JSON,便于后续新增字段时不改表结构
|
||||
*
|
||||
* 关联与隔离:
|
||||
* express_id / waybill_code / order_id 冗余落库,便于「按运单」「按订单」直接查询;
|
||||
* warehouse_id 做仓库隔离,避免跨仓串读。
|
||||
*
|
||||
* 幂等去重:uk_express_op_scan(express_id + op_time + scan_type)保证重复回传不落重复行。
|
||||
*
|
||||
* 索引:
|
||||
* uk_express_op_scan(express_id, op_time, scan_type 唯一)
|
||||
* idx_waybill_code(waybill_code, op_time)
|
||||
* idx_order_id(order_id)
|
||||
* idx_warehouse_op_time(warehouse_id, op_time)
|
||||
*/
|
||||
|
||||
const TABLE_NAME = 'wms_order_express_trace';
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
const { BIGINT, STRING, INTEGER, DATE, JSON: JSON_TYPE } = Sequelize;
|
||||
|
||||
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: '操作时间(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: INTEGER(11),
|
||||
allowNull: true,
|
||||
defaultValue: 0,
|
||||
comment: '重量(weight,来源原值)',
|
||||
},
|
||||
scan_type: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '扫描类型(scanType),如 发件/到件/派件/签收',
|
||||
},
|
||||
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: '软删除时间',
|
||||
},
|
||||
}, {
|
||||
// 与主表 wms_order_express 保持一致(utf8mb4_general_ci),避免轨迹描述含 4 字节字符时写入失败
|
||||
charset: 'utf8mb4',
|
||||
collate: 'utf8mb4_general_ci',
|
||||
comment: '运单物流轨迹表(1 运单 : N 轨迹)',
|
||||
});
|
||||
|
||||
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' });
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.dropTable(TABLE_NAME);
|
||||
},
|
||||
};
|
||||
@ -1,75 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* wms_order_express_trace.weight 由 INT 改为 DECIMAL(10,3)。
|
||||
*
|
||||
* 背景:外部轨迹接口返回的 weight 为带小数的字符串(如 "0.99"),
|
||||
* 原 INT 列会把 0.99 四舍五入/截断为 1 或 0,丢失精度。
|
||||
*
|
||||
* 变更:INT(11) DEFAULT 0 → DECIMAL(10,3) DEFAULT 0(保留原可空性与注释)。
|
||||
*
|
||||
* 注意:MySQL 不支持 INT→DECIMAL 的 INPLACE 变更,只能 COPY(重建表)。
|
||||
* 该表为 2026-11-11 新建(轨迹尚在接入期,数据量小),重建代价可接受。
|
||||
* 幂等:已是 decimal 时跳过。
|
||||
*/
|
||||
|
||||
const TABLE_NAME = 'wms_order_express_trace';
|
||||
const COLUMN_NAME = 'weight';
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
const { sequelize } = queryInterface;
|
||||
const [ rows ] = await sequelize.query(
|
||||
'SELECT COLUMN_TYPE AS columnType, IS_NULLABLE AS isNullable, '
|
||||
+ 'COLUMN_DEFAULT AS columnDefault, COLUMN_COMMENT AS columnComment '
|
||||
+ 'FROM INFORMATION_SCHEMA.COLUMNS '
|
||||
+ 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?',
|
||||
{ replacements: [ TABLE_NAME, COLUMN_NAME ] }
|
||||
);
|
||||
|
||||
const column = (rows || [])[0];
|
||||
if (!column) {
|
||||
console.log(`[${COLUMN_NAME}] skip: ${TABLE_NAME}.${COLUMN_NAME} 列不存在`);
|
||||
return;
|
||||
}
|
||||
if (String(column.columnType || '').toLowerCase().startsWith('decimal')) {
|
||||
console.log(`[${COLUMN_NAME}] skip: 已是 DECIMAL(${column.columnType})`);
|
||||
return;
|
||||
}
|
||||
|
||||
const nullable = String(column.isNullable).toUpperCase() === 'YES' ? 'NULL' : 'NOT NULL';
|
||||
const defaultValue = column.columnDefault === null || column.columnDefault === undefined
|
||||
? ''
|
||||
: ` DEFAULT ${Number(column.columnDefault) || 0}`;
|
||||
const comment = String(column.columnComment || '').replace(/'/g, "''");
|
||||
|
||||
await sequelize.query(
|
||||
`ALTER TABLE \`${TABLE_NAME}\` MODIFY COLUMN \`${COLUMN_NAME}\` `
|
||||
+ `DECIMAL(10,3) ${nullable}${defaultValue} COMMENT '${comment}'`
|
||||
);
|
||||
console.log(`[${COLUMN_NAME}] changed to DECIMAL(10,3) on ${TABLE_NAME}`);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
const { sequelize } = queryInterface;
|
||||
const [ rows ] = await sequelize.query(
|
||||
'SELECT COLUMN_TYPE AS columnType, IS_NULLABLE AS isNullable, '
|
||||
+ 'COLUMN_DEFAULT AS columnDefault, COLUMN_COMMENT AS columnComment '
|
||||
+ 'FROM INFORMATION_SCHEMA.COLUMNS '
|
||||
+ 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?',
|
||||
{ replacements: [ TABLE_NAME, COLUMN_NAME ] }
|
||||
);
|
||||
|
||||
const column = (rows || [])[0];
|
||||
if (!column) return;
|
||||
if (!String(column.columnType || '').toLowerCase().startsWith('decimal')) return;
|
||||
|
||||
const nullable = String(column.isNullable).toUpperCase() === 'YES' ? 'NULL' : 'NOT NULL';
|
||||
const comment = String(column.columnComment || '').replace(/'/g, "''");
|
||||
await sequelize.query(
|
||||
`ALTER TABLE \`${TABLE_NAME}\` MODIFY COLUMN \`${COLUMN_NAME}\` `
|
||||
+ `INT(11) ${nullable} DEFAULT 0 COMMENT '${comment}'`
|
||||
);
|
||||
console.log(`[${COLUMN_NAME}] reverted to INT(11)`);
|
||||
},
|
||||
};
|
||||
@ -1,74 +0,0 @@
|
||||
'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)`);
|
||||
},
|
||||
};
|
||||
@ -1,102 +0,0 @@
|
||||
'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<string[]>} 分表名列表。
|
||||
*/
|
||||
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<boolean>} 是否存在。
|
||||
*/
|
||||
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<void>} 无返回值。
|
||||
*/
|
||||
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<void>} 无返回值。
|
||||
*/
|
||||
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));
|
||||
},
|
||||
};
|
||||
@ -1,194 +0,0 @@
|
||||
'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<string[]>} 分表名列表。
|
||||
*/
|
||||
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<boolean>} 是否存在。
|
||||
*/
|
||||
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<boolean>} 是否存在。
|
||||
*/
|
||||
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<void>} 无返回值。
|
||||
*/
|
||||
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<void>} 无返回值。
|
||||
*/
|
||||
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));
|
||||
},
|
||||
};
|
||||
@ -1,71 +0,0 @@
|
||||
'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<number>} 当前字符长度,取不到时返回 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<void>} 无返回值。
|
||||
*/
|
||||
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<void>} 无返回值。
|
||||
*/
|
||||
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编码',
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
@ -1,68 +0,0 @@
|
||||
'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<boolean>} 是否存在。
|
||||
*/
|
||||
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<void>} 无返回值。
|
||||
*/
|
||||
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<void>} 无返回值。
|
||||
*/
|
||||
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}`);
|
||||
},
|
||||
};
|
||||
@ -1,160 +0,0 @@
|
||||
'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<boolean>} 是否存在。
|
||||
*/
|
||||
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<boolean>} 是否存在。
|
||||
*/
|
||||
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<string[]>} 分表名列表。
|
||||
*/
|
||||
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<Object[]>} 每张分表的回填条数。
|
||||
*/
|
||||
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<void>} 无返回值。
|
||||
*/
|
||||
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<void>} 无返回值。
|
||||
*/
|
||||
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(' | '));
|
||||
},
|
||||
};
|
||||
@ -1,202 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* wms_order_b2b 精简重构。
|
||||
*
|
||||
* 变更内容:
|
||||
* 1. 新增 prep_at(备货完成时间)。
|
||||
* 2. 移除 is_print / updated_at / deleted_at / delivery_order_code / store_id:
|
||||
* - is_print 随 B2B 面单打印能力下线而废弃;打印限制改由订单主表 print_status 决定(且已放开)。
|
||||
* - updated_at / deleted_at 移除后作业明细不再软删除。
|
||||
* - delivery_order_code / store_id 为快照冗余字段,关联读统一走 warehouse_id + order_id。
|
||||
* 3. 唯一键 uk_order_id 改为 uk_warehouse_order(warehouse_id, order_id):
|
||||
* 分表 id 按仓库各自发号,跨仓可能重叠,只按 order_id 唯一会误伤。
|
||||
* 4. 取消 B2B 由软删除改为物理删除:迁移时先清掉历史软删除行,避免移除 deleted_at 后"复活"。
|
||||
*
|
||||
* 幂等:所有列/索引变更前都做存在性判断,重复执行安全。
|
||||
* ⚠ 数据不可逆:删除的列与历史软删除行不会保留。
|
||||
*/
|
||||
|
||||
const TABLE_NAME = 'wms_order_b2b';
|
||||
|
||||
/** 需要移除的列 */
|
||||
const DROP_COLUMNS = [ 'is_print', 'updated_at', 'deleted_at', 'delivery_order_code', 'store_id' ];
|
||||
|
||||
/** 需要移除的索引 */
|
||||
const DROP_INDEXES = [ 'uk_order_id', 'idx_warehouse_id', 'idx_store_id', 'idx_delivery_order_code', 'idx_is_print', 'idx_deleted_at' ];
|
||||
|
||||
/**
|
||||
* 判断索引是否存在。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {string} indexName 索引名。
|
||||
* @return {Promise<boolean>} 是否存在。
|
||||
*/
|
||||
async function indexExists(queryInterface, indexName) {
|
||||
const indexes = await queryInterface.showIndex(TABLE_NAME);
|
||||
return (Array.isArray(indexes) ? indexes : []).some(index => {
|
||||
const name = String(index && (index.name || index.Key_name || index.key_name) || '');
|
||||
return name.toLowerCase() === String(indexName).toLowerCase();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全删除索引(不存在则跳过)。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {string} indexName 索引名。
|
||||
* @param {Array<Object>} log 执行日志。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async function dropIndexIfExists(queryInterface, indexName, log) {
|
||||
if (!(await indexExists(queryInterface, indexName))) {
|
||||
log.push({ action: 'skip-drop-index', indexName, reason: 'not-exists' });
|
||||
return;
|
||||
}
|
||||
await queryInterface.removeIndex(TABLE_NAME, indexName);
|
||||
log.push({ action: 'drop-index', indexName });
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全删除列(不存在则跳过)。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {string} columnName 列名。
|
||||
* @param {Object} columns describeTable 结果。
|
||||
* @param {Array<Object>} log 执行日志。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async function dropColumnIfExists(queryInterface, columnName, columns, log) {
|
||||
if (!Object.prototype.hasOwnProperty.call(columns, columnName)) {
|
||||
log.push({ action: 'skip-drop-column', columnName, reason: 'not-exists' });
|
||||
return;
|
||||
}
|
||||
await queryInterface.removeColumn(TABLE_NAME, columnName);
|
||||
log.push({ action: 'drop-column', columnName });
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 执行迁移。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {Object} Sequelize Sequelize 类型集合。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
const { DATE } = Sequelize;
|
||||
const log = [];
|
||||
const query = queryInterface.sequelize;
|
||||
|
||||
let columns = await queryInterface.describeTable(TABLE_NAME);
|
||||
if (!columns || Object.keys(columns).length === 0) {
|
||||
throw new Error(`表 ${TABLE_NAME} 不存在,无法执行重构迁移`);
|
||||
}
|
||||
|
||||
// 1. 历史软删除行清理(deleted_at 即将被移除,不清掉会变成"有效行")
|
||||
if (Object.prototype.hasOwnProperty.call(columns, 'deleted_at')) {
|
||||
const [ deletedRows ] = await query.query(`DELETE FROM ${TABLE_NAME} WHERE deleted_at IS NOT NULL`);
|
||||
log.push({ action: 'delete-soft-deleted-rows', affected: Number(deletedRows && deletedRows.affectedRows || 0) });
|
||||
}
|
||||
|
||||
// 2. 同仓同单重复行清理(保留 id 最大的一行),为新唯一键让路
|
||||
if (Object.prototype.hasOwnProperty.call(columns, 'warehouse_id')
|
||||
&& Object.prototype.hasOwnProperty.call(columns, 'order_id')) {
|
||||
const [ dedupeRows ] = await query.query(`
|
||||
DELETE t FROM ${TABLE_NAME} t
|
||||
INNER JOIN ${TABLE_NAME} keep
|
||||
ON keep.warehouse_id = t.warehouse_id
|
||||
AND keep.order_id = t.order_id
|
||||
AND keep.id > t.id
|
||||
`);
|
||||
log.push({ action: 'delete-duplicate-rows', affected: Number(dedupeRows && dedupeRows.affectedRows || 0) });
|
||||
}
|
||||
|
||||
// 3. 新增 prep_at
|
||||
if (!Object.prototype.hasOwnProperty.call(columns, 'prep_at')) {
|
||||
await queryInterface.addColumn(TABLE_NAME, 'prep_at', {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '备货完成时间',
|
||||
});
|
||||
log.push({ action: 'add-column', columnName: 'prep_at' });
|
||||
} else {
|
||||
log.push({ action: 'skip-add-column', columnName: 'prep_at', reason: 'exists' });
|
||||
}
|
||||
|
||||
// 4. 删除废弃索引(含旧唯一键与冗余 warehouse_id 索引)
|
||||
for (const indexName of DROP_INDEXES) {
|
||||
await dropIndexIfExists(queryInterface, indexName, log);
|
||||
}
|
||||
|
||||
// 5. 建立新的复合唯一键
|
||||
if (!(await indexExists(queryInterface, 'uk_warehouse_order'))) {
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'order_id' ], {
|
||||
name: 'uk_warehouse_order',
|
||||
unique: true,
|
||||
});
|
||||
log.push({ action: 'add-index', indexName: 'uk_warehouse_order' });
|
||||
} else {
|
||||
log.push({ action: 'skip-add-index', indexName: 'uk_warehouse_order', reason: 'exists' });
|
||||
}
|
||||
|
||||
// 6. 删除废弃列
|
||||
columns = await queryInterface.describeTable(TABLE_NAME);
|
||||
for (const columnName of DROP_COLUMNS) {
|
||||
await dropColumnIfExists(queryInterface, columnName, columns, log);
|
||||
}
|
||||
|
||||
console.log('[20261115180000-refactor-wms-order-b2b] up results:', JSON.stringify(log));
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚迁移:恢复被移除的列与索引(历史数据不可恢复)。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {Object} Sequelize Sequelize 类型集合。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async down(queryInterface, Sequelize) {
|
||||
const { DATE, ENUM, STRING, BIGINT } = Sequelize;
|
||||
const log = [];
|
||||
|
||||
let columns = await queryInterface.describeTable(TABLE_NAME);
|
||||
|
||||
await dropIndexIfExists(queryInterface, 'uk_warehouse_order', log);
|
||||
|
||||
const restoreColumns = [
|
||||
[ 'store_id', { type: BIGINT(20).UNSIGNED, allowNull: true, comment: '货主ID' }],
|
||||
[ 'delivery_order_code', { type: STRING(50), allowNull: true, comment: '发货单号快照' }],
|
||||
[ 'is_print', { type: ENUM('Y', 'N'), allowNull: false, defaultValue: 'N', comment: '是否打印:Y=已打印 N=未打印' }],
|
||||
[ 'updated_at', { type: DATE, allowNull: true, comment: '更新时间' }],
|
||||
[ 'deleted_at', { type: DATE, allowNull: true, comment: '软删除时间' }],
|
||||
];
|
||||
|
||||
for (const [ columnName, definition ] of restoreColumns) {
|
||||
if (Object.prototype.hasOwnProperty.call(columns, columnName)) {
|
||||
log.push({ action: 'skip-add-column', columnName, reason: 'exists' });
|
||||
continue;
|
||||
}
|
||||
await queryInterface.addColumn(TABLE_NAME, columnName, definition);
|
||||
log.push({ action: 'add-column', columnName });
|
||||
}
|
||||
|
||||
const restoreIndexes = [
|
||||
[ 'uk_order_id', [ 'order_id' ], true ],
|
||||
[ 'idx_warehouse_id', [ 'warehouse_id' ], false ],
|
||||
[ 'idx_store_id', [ 'store_id' ], false ],
|
||||
[ 'idx_delivery_order_code', [ 'delivery_order_code' ], false ],
|
||||
[ 'idx_is_print', [ 'is_print' ], false ],
|
||||
[ 'idx_deleted_at', [ 'deleted_at' ], false ],
|
||||
];
|
||||
|
||||
for (const [ indexName, fields, unique ] of restoreIndexes) {
|
||||
if (await indexExists(queryInterface, indexName)) {
|
||||
log.push({ action: 'skip-add-index', indexName, reason: 'exists' });
|
||||
continue;
|
||||
}
|
||||
await queryInterface.addIndex(TABLE_NAME, fields, { name: indexName, unique });
|
||||
log.push({ action: 'add-index', indexName });
|
||||
}
|
||||
|
||||
columns = await queryInterface.describeTable(TABLE_NAME);
|
||||
await dropColumnIfExists(queryInterface, 'prep_at', columns, log);
|
||||
|
||||
console.log('[20261115180000-refactor-wms-order-b2b] down results:', JSON.stringify(log));
|
||||
},
|
||||
};
|
||||
@ -39,8 +39,6 @@ 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` |
|
||||
@ -358,7 +356,6 @@ 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: {...} }`):
|
||||
@ -366,48 +363,15 @@ app_key=APP2024011514301234&method=entryorder.confirm×tamp=1758047400&v=1.0
|
||||
```json
|
||||
{
|
||||
"request": {
|
||||
"waybill_codes": [ "YT1234567890|8000" ]
|
||||
"waybill_codes": [ "YT1234567890" ]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> 无寄件电话后四位可补时,`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`),跨仓不串写
|
||||
|
||||
### 3.7 waybill.getTrace(查询型回调:物流轨迹)
|
||||
|
||||
- label:运单物流轨迹查询
|
||||
- description:按运单号查询物流轨迹;消费外部响应并直接返回给调用方(**不落库**)
|
||||
- 注册位置:`app/lib/callback_functions.js#CALLBACK_FUNCTIONS`
|
||||
- 实现:`app/service/systems/waybill.js#fetchTracesByWaybill`;业务入口 `waybill.warehouse.getTrace`(单运单、实时回源)
|
||||
- 入参:`{ request: { waybill_codes: ["770358128188071"] } }`(单运单),运单号同样按 3.6 的规则补寄件电话后四位(`运单号|后四位`);签名同样为 `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: [...] }` 包装、单个对象返回;响应行 `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 已统一为秒)
|
||||
|
||||
`timestamp` 已统一为**秒级(10 位字符串)**规范值:`String(Math.floor(Date.now() / 1000))`。
|
||||
|
||||
@ -195,9 +195,7 @@ report.generate(method 层,异步任务,入参 report_id)
|
||||
|
||||
与订单导出 item 模式的差异:不含 `item_image`(商品图片)列,另附加 3 列——
|
||||
`source_order_codes`(平台交易单号,位置紧跟「外部单号」)、`intercept_notice_time`(通知拦截时间)、
|
||||
`intercept_confirm_time`(库内确定拦截时间),订单导出无这 3 列;
|
||||
另外订单导出 item 模式新增了 `sn_quantity`(SN码数量,明细中启用序列号管理商品的 plan_qty)与
|
||||
`sn_codes`(SN码,该商品行复核时登记的 SN 列表),waybill 模式新增 `sn_codes_summary`(SN码汇总,订单级),本报表未启用这些列。配置示例:
|
||||
`intercept_confirm_time`(库内确定拦截时间),订单导出无这 3 列。配置示例:
|
||||
|
||||
```json
|
||||
// report.definition.save(新增拦截明细报表)
|
||||
|
||||
@ -1,611 +1,4 @@
|
||||
[
|
||||
{
|
||||
"version": "0.3.360",
|
||||
"date": "2026-11-15",
|
||||
"type": "updated",
|
||||
"summary": "B2B 列表支持作业明细筛选;其余订单列表统一排除 B2B 订单",
|
||||
"methods": [
|
||||
"order.list",
|
||||
"order.reviewOrder.list",
|
||||
"order.pendingOrder.list",
|
||||
"order.pendingOrder2b.list",
|
||||
"order.outboundOrder.list",
|
||||
"order.expectionOrder.list",
|
||||
"order.entrustOrder.list",
|
||||
"order.deliveryOrder.list",
|
||||
"order.deliveryOrder2b.list",
|
||||
"order.deliveryExpectionOrder.list",
|
||||
"order.archiveOrder.list",
|
||||
"order.wave.waveStrategyFallbackOrderList"
|
||||
],
|
||||
"notes": [
|
||||
"B2B 列表筛选:order.pendingOrder2b.list / order.deliveryOrder2b.list 的 where 新增 8 个作业明细字段(total_box_count / pickup_plate_number / prep_remark / prep_duration_seconds / is_picked_up / picked_up_at / created_at / prep_at),内部按 warehouse_id + order_id 查 wms_order_b2b 取命中 order_id 后以 id IN (...) 回填,未命中返回空列表;该筛选仅这两个接口开放,不影响普通订单列表。",
|
||||
"B2B 排除: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 / order.wave.waveStrategyFallbackOrderList 在模块默认条件之上统一追加 (is_b2b IS NULL OR is_b2b = 'N'),B2B 订单不再出现在这些列表中;NULL 存量行按非 B2B 处理。",
|
||||
"实现位置:app/service/systemMethods/order/base.js#listByModule(fixedWhere 含 is_b2b 时视为 B2B 域列表,不再追加排除条件)、#extractB2bDetailVirtualFilter / #findOrderIdsByB2bDetailFilters、#buildExcludeB2bCondition;app/service/systemMethods/order/wave.js#waveStrategyFallbackOrderList 单独追加排除条件。",
|
||||
"不在本次口径内:order.export 走独立表位查询(getOrderModelByTableType),不经过 listByModule,导出仍按原口径取数。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.359",
|
||||
"date": "2026-11-15",
|
||||
"type": "updated",
|
||||
"summary": "B2B 作业明细表重构:列表带出作业字段、取消改物理删除、移除冗余字段并新增 prep_at",
|
||||
"methods": [
|
||||
"order.pendingOrder2b.list",
|
||||
"order.deliveryOrder2b.list",
|
||||
"order.convertToB2b",
|
||||
"order.cancelB2b"
|
||||
],
|
||||
"notes": [
|
||||
"数据库迁移 20261115180000-refactor-wms-order-b2b.js(已在开发库与生产库执行):wms_order_b2b 新增 prep_at(备货完成时间);移除 is_print / updated_at / deleted_at / delivery_order_code / store_id;唯一键 uk_order_id 改为 uk_warehouse_order(warehouse_id, order_id);迁移前先清空历史软删除行与同仓同单重复行。",
|
||||
"关联口径:wms_order_b2b 与订单分表的关联读统一使用 warehouse_id + order_id(分表 id 按仓库发号,跨仓可能重叠,不能只按 order_id)。",
|
||||
"列表变更:order.pendingOrder2b.list / order.deliveryOrder2b.list 的列表行新增 total_box_count、pickup_plate_number、prep_remark、prep_duration_seconds、prep_at、is_picked_up、picked_up_at、created_at 8 个作业明细字段,无明细行时输出空值占位(0 / N / null)。",
|
||||
"转换变更:order.convertToB2b 写作业明细改为 (warehouse_id, order_id) 唯一键,不再写 store_id / delivery_order_code / updated_at,已存在同仓同单行时重置作业字段(含 prep_at)。",
|
||||
"取消变更:order.cancelB2b 由软删除改为物理删除;随 is_print 字段移除,取消不再校验「B2B面单已打印」,skipped_reasons 枚举同步删除该原因。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.358",
|
||||
"date": "2026-11-15",
|
||||
"type": "updated",
|
||||
"summary": "order.cancelB2b 取消「已打印不允许取消」限制,并补齐接口文档",
|
||||
"methods": [
|
||||
"order.cancelB2b"
|
||||
],
|
||||
"notes": [
|
||||
"变更:删除 print_status=fin 的拦截,已打印(含打印中)的订单同样允许取消 B2B,不再返回「订单已打印,不允许取消B2B」。",
|
||||
"保留不变的拦截:step=0(待审核)、非 B2B(is_b2b != Y)、已锁定、已拦截、B2B 面单已打印(wms_order_b2b.is_print = Y,当前无逻辑置 Y,实际不触发)。",
|
||||
"实现位置:app/service/systems/order_b2b.js#resolveCancelSkipReason;查询列 print_status 保留(不参与校验)。",
|
||||
"补文档:该接口此前已实现但未登记接口文档,本次一并补齐(入参别名、响应字段、跳过原因枚举、错误码、权限口径与波次/落库行为)。",
|
||||
"文档中如实标注现状差异:cancelB2b 的 step 仅排除 0(step 4/5/9 可取消)、未校验 pick_status / recheck_status,与 convertToB2b 的白名单口径不一致。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.357",
|
||||
"date": "2026-11-15",
|
||||
"type": "updated",
|
||||
"summary": "order.convertToB2b 取消「已打印不允许转 B2B」限制",
|
||||
"methods": [
|
||||
"order.convertToB2b"
|
||||
],
|
||||
"notes": [
|
||||
"变更:删除 print_status=fin 的拦截,已打印(含打印中)的订单同样允许转 B2B,不再返回「订单已打印,不允许转B2B」。",
|
||||
"保留不变的拦截:已取消(status=cancel)、step 白名单(仅 1/2/3)、已拣货(pick_status=fin)、已复核(recheck_status=fin)、已锁定、已拦截、已是 B2B、所在波次存在进行中的拣货任务。",
|
||||
"实现位置:app/service/systems/order_b2b.js#resolveConvertSkipReason;查询列 print_status 保留(不参与校验,仅便于排查)。",
|
||||
"关联提醒:order.cancelB2b 目前仍拦截「订单已打印,不允许取消B2B」,因此已打印订单转 B2B 后无法通过取消接口回退,如需对称放行需另行调整。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.356",
|
||||
"date": "2026-11-15",
|
||||
"type": "updated",
|
||||
"summary": "order.convertToB2b 转换时自动把订单从波次摘除(含库内抓取订单),拣货任务进行中则跳过",
|
||||
"methods": [
|
||||
"order.convertToB2b",
|
||||
"order.wave.batchRemoveOrders"
|
||||
],
|
||||
"notes": [
|
||||
"新行为:已在波次中的订单转 B2B 成功后,在同一事务内从波次摘除——订单 wave_id/wave_no/wave_scope/wave_strategy_version/wave_scan_result 清零,重排 wms_order_wave_index,回写 wms_wave_batch.total_orders / processed_orders,剩余 0 单的波次置 wave_status=-1。团购/散单抓取与库内抓取进入波次的订单一视同仁。",
|
||||
"保护逻辑:波次存在进行中的拣货任务(wms_wave_pick_task.status in (0,1))时该订单不转换,skipped_reasons 返回「订单所在波次存在进行中的拣货任务,不允许转B2B」,波次 ID 通过 active_pick_task_wave_ids 返回;与 order.wave.batchRemoveOrders 的既有保护口径一致。",
|
||||
"响应新增字段:removed_from_wave_order_ids / affected_wave_ids / emptied_wave_ids / active_pick_task_wave_ids;入参结构不变。",
|
||||
"实现:app/service/systemMethods/order/wave.js 新增 detachOrdersFromWavesInTransaction(事务内复用),order.wave.batchRemoveOrders 同步改为复用该方法,行为与改造前等价;app/service/systems/order_b2b.js#convertOrdersToB2b 增加 wave_id/wave_no 查询列、活动拣货任务预检、摘除调用与 ORDER_WAVE_REMOVE 操作日志(提交后写入,失败不影响主流程)。",
|
||||
"本次未触发波次策略快速重扫(enqueueWaveStrategyQuickScanPostOrderChange):被摘除的订单已是 B2B,策略扫描侧本身已排除 B2B,无需为其重扫。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.355",
|
||||
"date": "2026-11-15",
|
||||
"type": "updated",
|
||||
"summary": "order.convertToB2b 增加已拣货/已复核订单拦截",
|
||||
"methods": [
|
||||
"order.convertToB2b"
|
||||
],
|
||||
"notes": [
|
||||
"新增准入校验:pick_status=fin(拣货已完成)返回「订单已拣货,不允许转B2B」,recheck_status=fin(复核已完成)返回「订单已复核,不允许转B2B」,避免把已进入作业流程的订单改成 B2B。",
|
||||
"实现位置:app/service/systems/order_b2b.js#resolveConvertSkipReason;查询列新增 pick_status、recheck_status。校验顺序:已取消 → 步骤白名单 → 已拣货 → 已复核 → 已打印 → 已锁定 → 已拦截 → 已是 B2B。",
|
||||
"拣货中(pick_status=padding)与拣货异常(pick_status=error)按本次需求不拦截,仍允许转换;如需一并拦截需另行调整。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.354",
|
||||
"date": "2026-11-15",
|
||||
"type": "updated",
|
||||
"summary": "波次抓取类接口统一声明排除 B2B 订单,并修复自动加团链路未排除 B2B 的问题",
|
||||
"methods": [
|
||||
"order.wave.fetch",
|
||||
"order.wave.groupFetch",
|
||||
"order.wave.singleFetch",
|
||||
"order.wave.groupOrderFetchList",
|
||||
"order.wave.singleOrderFetchList",
|
||||
"order.wave.fetchableOrderCount",
|
||||
"order.wave.waveStrategyFetchPda",
|
||||
"order.wave.waveStrategyFetchAdmin",
|
||||
"order.wave.waveStrategyQuickScan"
|
||||
],
|
||||
"notes": [
|
||||
"代码侧核查结论:波次抓取的候选取数已全部带 (is_b2b IS NULL OR is_b2b = 'N') 条件,覆盖 buildFetchWhere(团购/散单抓取、异步 fetch 任务、自动加团新建波次)、groupOrderFetchList / singleOrderFetchList / fetchableOrderCount、策略候选 SQL(getWaveStrategyFetchCandidateOrders、selectWaveStrategyFetchOrdersBySkuLimit、第一池同结构合并)、快速扫描 where(buildWaveStrategyQuickScanOrderWhere)与 singleFetchByIds。",
|
||||
"本次修复的缺口:app/service/systems/delivery_order.js 自动加团链路——appendOrderToWave 查询订单未带 is_b2b 且无 B2B 校验,导致 B2B 订单可能被自动加入已存在的\"自动加团中\"波次;countCandidateGroupOrders 候选计数未排除 B2B,导致开新团的候选数量被 B2B 订单污染。",
|
||||
"修复方式:appendOrderToWave 查询属性增加 is_b2b 并在锁校验后静默跳过 is_b2b=Y 的订单;countCandidateGroupOrders 的 where 增加 is_b2b 排除条件。NULL 存量行按非 B2B 处理,不影响历史数据。",
|
||||
"本轮仅补充上述 9 个抓取类接口的 B2B 排除口径说明,接口入参/响应结构未变更。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.353",
|
||||
"date": "2026-11-15",
|
||||
"type": "updated",
|
||||
"summary": "order.convertToB2b 收紧准入:禁止转换已取消与已配送/已出库订单",
|
||||
"methods": [
|
||||
"order.convertToB2b"
|
||||
],
|
||||
"notes": [
|
||||
"问题:原准入只判断 step != 0,导致 step=4(配送中/已提交出库)、step=5(已完成)、step=9(已关闭,含取消单)只要未打印/未锁定/未拦截就会被转成 B2B,可能把已取消或已配送的订单误转。",
|
||||
"现改为步骤白名单:仅 step in [1,2,3] 可转;0 返回「订单待审核」、4 返回「订单已提交出库」、5 返回「订单已完成」、9 返回「订单已关闭」、其它步骤返回「订单当前步骤(N)不允许转B2B」。",
|
||||
"新增 status='cancel' 校验并置于校验链首位(已取消订单即使 step 仍在 [1,2,3] 也拒绝),返回「订单已取消,不允许转B2B」。",
|
||||
"实现位置:app/service/systems/order_b2b.js#resolveConvertSkipReason;查询列新增 status 字段。行为上仍然只跳过不报错,跳过原因通过 skipped_reasons 返回。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.352",
|
||||
"date": "2026-11-15",
|
||||
"type": "added",
|
||||
"summary": "补充 order.convertToB2b 接口文档(订单转 B2B)",
|
||||
"methods": [
|
||||
"order.convertToB2b"
|
||||
],
|
||||
"notes": [
|
||||
"该接口此前已实现(app/service/systemMethods/order/index.js#convertToB2b → app/service/systems/order_b2b.js#convertOrdersToB2b),但未登记接口文档,本次补齐。",
|
||||
"入参支持 ids / order_ids / orderIds / id / order_id / orderId 六种键名,单值或数组均可,单次最多 200 个;仓库取自登录上下文,仅能转换本仓 current 分表内的订单。",
|
||||
"准入条件:step != 0、print_status != 'fin'、lock_status = 'none'、intercept_status = 'none'、is_b2b != 'Y';不满足只跳过并在 skipped_reasons 返回原因,不在 current 分表中的订单进 not_found_order_ids。",
|
||||
"文档中已明确 step 口径现状:只排除 step=0,step=4/5/9(含已取消单)同样可转换,且未校验 outbound_status='padding' 与 wave_id。",
|
||||
"参数错误(订单ID为空 / 超过 200 个)返回 HTTP 200 但响应体 flag=failure、code=400;缺少仓库上下文抛错,HTTP 500。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.351",
|
||||
"date": "2026-11-15",
|
||||
"type": "added",
|
||||
"summary": "新增 B2B 订单列表接口 order.pendingOrder2b.list 与 order.deliveryOrder2b.list",
|
||||
"methods": [
|
||||
"order.pendingOrder2b.list",
|
||||
"order.deliveryOrder2b.list"
|
||||
],
|
||||
"notes": [
|
||||
"两个接口复用 order.pendingOrder.list / order.deliveryOrder.list 的全部查询条件与响应结构,仅额外强制 is_b2b='Y'。",
|
||||
"固定条件通过 listByModule 的 fixedWhere 选项以 AND 方式附加,请求 where 传入同名 is_b2b 条件无法覆盖(传入 N 只会得到空列表)。",
|
||||
"wms_order_delivery 各分表新增 is_b2b 列表索引:idx_{wh}_{type}_list_is_b2b_updated_at (warehouse_id, [dispatch_lane,] is_b2b, updated_at, id) 与 ..._list_is_b2b_delivery_time (warehouse_id, [dispatch_lane,] is_b2b, delivery_time, id),dispatch 分表版本携带 dispatch_lane;history / outsourced 分表不声明该索引。索引由订单工厂表结构漂移同步在部署后首次访问分表时自动补建(ALTER TABLE ADD INDEX),无需手工迁移。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"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 输出 <sn> 子节点,多包裹 packages 正确闭合",
|
||||
"methods": [
|
||||
"order.pendingOrder.syncOrderIds"
|
||||
],
|
||||
"notes": [
|
||||
"orderLines[].snList 现按奇门规范输出 <snList><sn>SN码</sn>…</snList>;此前 XML 生成器对标量数组统一用 <item> 包裹,再被 orderLines 内的 item→orderLine 替换,实际发出的是 <snList><orderLine>…</orderLine></snList>。",
|
||||
"packages 修正:一单多运单号(多个包裹)时,第二个及之后包裹此前会被序列化成 <item> 并导致 </item>/</package> 错位;现输出标准 <packages><package>…<items><item>…</item></items></package></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",
|
||||
"type": "updated",
|
||||
"summary": "适配轨迹接口返回调整:trace 为空数组(暂无轨迹)不再计为失败,新增 result.empty;weight 支持字符串小数并改为 DECIMAL(10,3) 落库",
|
||||
"methods": [
|
||||
"waybill.warehouse.updateTrace",
|
||||
"waybill.warehouse.updateTraceTaskProgress",
|
||||
"waybill.warehouse.getTrace"
|
||||
],
|
||||
"notes": [
|
||||
"背景:外部轨迹接口对暂无轨迹的运单返回 trace: [](如刚下单未揽收),原实现按「轨迹内容为空」计入 failed,导致整单任务被误判失败。",
|
||||
"现口径:trace 为空数组 → 运单号写入 result.empty,不落库、不计 failed;任务状态仍为 success,提示语为「更新完成:新增 X 条轨迹,更新 Y 条,无轨迹 Z 单,失败 N 单」。",
|
||||
"weight:外部返回可能是字符串小数(如 \"0.99\"),新增 parseTraceWeight 统一转数字并保留 3 位小数;非法值按 0 处理。",
|
||||
"数据库:wms_order_express_trace.weight 由 INT(11) 改为 DECIMAL(10,3)(迁移 20261111203500,已执行开发库与生产库);MySQL 不支持 INT→DECIMAL 的 INPLACE 变更,该表为新建、数据量小,重建代价可接受。",
|
||||
"getTrace 返回值不变,weight 现为小数(如 0.99)。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.326",
|
||||
"date": "2026-11-11",
|
||||
"type": "added",
|
||||
"summary": "新增运单轨迹查询:waybill.warehouse.getTrace 按运单号一次返回全部物流轨迹(不分页,按操作时间倒序),只读查询 wms_order_express_trace 并按仓库隔离",
|
||||
"methods": [
|
||||
"waybill.warehouse.getTrace"
|
||||
],
|
||||
"notes": [
|
||||
"定位:与 waybill.warehouse.updateTrace(拉取并落库)互补,本方法只读本地已落库轨迹,不触发外部接口调用。",
|
||||
"入参:waybillCode(必填,兼容 waybill_code 下划线别名),单个运单精确匹配。",
|
||||
"返回:{ waybill_code, total, list };list 按 op_time DESC, id DESC 排序,字段含 op_time(YYYY-MM-DD HH:mm:ss)、out_biz_code、memo、op_org_city_name、weight、scan_type、raw_data。",
|
||||
"仓库隔离:查询固定带 warehouse_id = ctx.user.store_id;无数据返回 success + total=0 + list=[]。",
|
||||
"代码依据:app/service/systemMethods/waybill/warehouse.js#getTrace,app/service/systems/waybill.js#listTracesByWaybill。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.325",
|
||||
"date": "2026-11-11",
|
||||
"type": "added",
|
||||
"summary": "新增运单物流轨迹批量更新:waybill.warehouse.updateTrace 与 waybill.warehouse.updateTraceTaskProgress,链路走 OpenAPI 出站回调 waybill.getTrace(入参同 waybill.getreceive,单批 10 单),结果按 (express_id, op_time, scan_type) 幂等落库 wms_order_express_trace",
|
||||
"methods": [
|
||||
"waybill.warehouse.updateTrace",
|
||||
"waybill.warehouse.updateTraceTaskProgress"
|
||||
],
|
||||
"notes": [
|
||||
"回调方法注册:app/lib/callback_functions.js#CALLBACK_FUNCTIONS 新增 waybill.getTrace(名称「运单物流轨迹查询」),管理端 apiApp.listCallbackFunctions 可拉取并勾选。",
|
||||
"入参:与 waybill.warehouse.updateReceive 完全一致,支持 waybillCodes(优先)或 where(与 waybill.warehouse.list 同口径,不含分页/排序,上限 5000 条)。",
|
||||
"请求体:{ request: { waybill_codes: [...] } },单批最多 10 个运单号;签名口径与 waybill.getreceive 一致(MD5(appSecret + timestamp + bodyJson))。",
|
||||
"响应解析:[{ waybillNo, trace: {...} }],兼容 trace 为数组、traces 数组、traceList 与 { code, data: [...] } 包装。",
|
||||
"落库:wms_order_express_trace,字段映射 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) 保证重复回传不产生重复行,命中时更新轨迹文案等字段。",
|
||||
"任务:task_id 前缀 waybill_trace_,Redis 缓存键前缀 waybill_trace_task_;状态流转 submitted → running → success/failed,result 返回 { total, matched, inserted, updated, not_found, failed }。",
|
||||
"前置校验:仓库下无应用承接 waybill.getTrace 时直接失败并提示「如需更新运单物流轨迹信息,到【设置】->【基础设置】->【API开放接口】配置相应的外部访问接口」,不创建任务。",
|
||||
"代码依据:app/service/systemMethods/waybill/warehouse.js#updateTrace/#updateTraceTaskProgress,app/service/systems/waybill.js#queryTraces/#saveTraces。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.324",
|
||||
"date": "2026-11-11",
|
||||
@ -13495,24 +12888,5 @@
|
||||
"代码变更: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"
|
||||
}
|
||||
]
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -9,12 +9,7 @@ function buildRequestXml(payload = {}) {
|
||||
const packages = Array.isArray(request.packages?.package) ? request.packages.package : [];
|
||||
|
||||
const serializedLines = orderLines
|
||||
.map(line => {
|
||||
const snListXml = Array.isArray(line.snList) && line.snList.length > 0
|
||||
? `<snList>${line.snList.map(sn => `<item>${sn}</item>`).join('')}</snList>`
|
||||
: '';
|
||||
return ` <item><orderLineNo>${line.orderLineNo || ''}</orderLineNo><itemCode>${line.itemCode || ''}</itemCode>${snListXml}</item>`;
|
||||
})
|
||||
.map(line => ` <item><orderLineNo>${line.orderLineNo || ''}</orderLineNo><itemCode>${line.itemCode || ''}</itemCode></item>`)
|
||||
.join('\n');
|
||||
|
||||
const serializedPackages = packages
|
||||
@ -121,76 +116,6 @@ describe('test/app/lib/qimen_client.test.js', () => {
|
||||
assert.doesNotMatch(sentXml, /<orderLine>\s*<orderLine>/);
|
||||
});
|
||||
|
||||
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: '<response><flag>success</flag><code>200</code><message>ok</message></response>',
|
||||
};
|
||||
};
|
||||
|
||||
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, /<snList>\s*<sn>SN-A<\/sn>\s*<sn>SN-B<\/sn>\s*<\/snList>/);
|
||||
assert.doesNotMatch(sentXml, /<snList>\s*<orderLine>/);
|
||||
});
|
||||
|
||||
it('should omit customerId and costomer_id when customerId is null', async () => {
|
||||
const app = {
|
||||
config: {
|
||||
|
||||
@ -142,10 +142,6 @@ 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,
|
||||
}));
|
||||
},
|
||||
|
||||
@ -291,38 +287,4 @@ 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, []);
|
||||
});
|
||||
});
|
||||
|
||||
@ -1,7 +1,6 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const { Op } = require('sequelize');
|
||||
|
||||
const WaveService = require('../../../../../app/service/systemMethods/order/wave');
|
||||
|
||||
@ -50,11 +49,6 @@ function createHarness(options = {}) {
|
||||
user: {
|
||||
store_id: warehouseId,
|
||||
},
|
||||
logger: {
|
||||
info() {},
|
||||
warn() {},
|
||||
error() {},
|
||||
},
|
||||
model: {
|
||||
QueryTypes: {
|
||||
SELECT: 'SELECT',
|
||||
@ -69,9 +63,6 @@ function createHarness(options = {}) {
|
||||
},
|
||||
},
|
||||
async query(sql, queryOptions) {
|
||||
if (options.countError) {
|
||||
throw options.countError;
|
||||
}
|
||||
captures.querySql = String(sql || '');
|
||||
captures.queryOptions = queryOptions;
|
||||
return matchedRows;
|
||||
@ -207,123 +198,4 @@ 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\)/
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@ -28,7 +28,6 @@ function createCainiaoHarness(options = {}) {
|
||||
operationLogCreateOperationLogs: 0,
|
||||
operationLogPayloads: [],
|
||||
getContractConfigCalls: [],
|
||||
filterAutoSyncSnOrderIdsCalls: [],
|
||||
syncOrderIdsCalls: [],
|
||||
};
|
||||
|
||||
@ -144,15 +143,6 @@ 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' };
|
||||
@ -380,12 +370,6 @@ 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 ],
|
||||
@ -393,15 +377,6 @@ 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 } },
|
||||
|
||||
@ -22,7 +22,6 @@ function createPddHarness(options = {}) {
|
||||
printQuantityLogCreate: 0,
|
||||
operationLogCreateOperationLogs: 0,
|
||||
getContractConfigCalls: [],
|
||||
filterAutoSyncSnOrderIdsCalls: [],
|
||||
syncOrderIdsCalls: [],
|
||||
};
|
||||
|
||||
@ -39,9 +38,6 @@ function createPddHarness(options = {}) {
|
||||
or: 'or',
|
||||
},
|
||||
},
|
||||
async setCacheAsync() {
|
||||
// no-op in tests
|
||||
},
|
||||
},
|
||||
model: {
|
||||
async transaction(callback) {
|
||||
@ -110,15 +106,6 @@ 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' };
|
||||
@ -252,9 +239,6 @@ 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 ],
|
||||
@ -262,15 +246,6 @@ 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 } },
|
||||
|
||||
@ -49,7 +49,6 @@ function createPolyapiHarness(options = {}) {
|
||||
getWaybillAsyncOrderDeliveryModel: 0,
|
||||
getWaybillAsyncOrderDeliveryModelArgs: [],
|
||||
getContractConfigCalls: [],
|
||||
filterAutoSyncSnOrderIdsCalls: [],
|
||||
syncOrderIdsCalls: [],
|
||||
callSequence: [],
|
||||
};
|
||||
@ -277,15 +276,6 @@ 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' };
|
||||
@ -538,12 +528,6 @@ 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 ],
|
||||
@ -551,15 +535,6 @@ 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 } },
|
||||
|
||||
@ -9,9 +9,8 @@ function createHarness(options = {}) {
|
||||
const outboundCalls = [];
|
||||
const noticeCalls = [];
|
||||
const transactionCalls = [];
|
||||
const callbackCalls = [];
|
||||
const orderRows = Array.isArray(options.orderRows)
|
||||
? options.orderRows.map(item => ({ from_key: 'APP-KEY-1', ...item }))
|
||||
? options.orderRows.map(item => ({ ...item }))
|
||||
: [
|
||||
{
|
||||
id: 1,
|
||||
@ -25,7 +24,6 @@ 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)
|
||||
@ -86,10 +84,6 @@ function createHarness(options = {}) {
|
||||
async transaction(callback) {
|
||||
const transaction = {
|
||||
id: `tx-${transactionCalls.length + 1}`,
|
||||
LOCK: {
|
||||
UPDATE: 'UPDATE',
|
||||
SHARE: 'SHARE',
|
||||
},
|
||||
};
|
||||
transactionCalls.push({ transaction });
|
||||
|
||||
@ -168,26 +162,6 @@ 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,
|
||||
@ -228,25 +202,6 @@ 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() {},
|
||||
@ -264,7 +219,6 @@ function createHarness(options = {}) {
|
||||
outboundCalls,
|
||||
noticeCalls,
|
||||
transactionCalls,
|
||||
callbackCalls,
|
||||
};
|
||||
}
|
||||
|
||||
@ -320,114 +274,6 @@ 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() {
|
||||
@ -765,7 +611,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, callbackCalls } = createHarness();
|
||||
const { service, outboundCalls } = createHarness();
|
||||
|
||||
const result = await service.syncApiOrders({
|
||||
create_channel: 'API',
|
||||
@ -787,46 +633,11 @@ 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);
|
||||
|
||||
// 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' },
|
||||
],
|
||||
assert.deepEqual(outboundCalls[0].meta, {
|
||||
orderId: 1,
|
||||
orderNo: 'DO-1001',
|
||||
orderItemId: 101,
|
||||
});
|
||||
|
||||
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 () => {
|
||||
|
||||
@ -82,7 +82,7 @@ function createSummaryList() {
|
||||
];
|
||||
}
|
||||
|
||||
function createHarness({ detailRows = [], summaryList = [], orderLocations = null, orderDeliveryRows = [] } = {}) {
|
||||
function createHarness({ detailRows = [], summaryList = [] } = {}) {
|
||||
const captured = {
|
||||
queries: [],
|
||||
upload: null,
|
||||
@ -147,34 +147,11 @@ function createHarness({ detailRows = [], summaryList = [], orderLocations = nul
|
||||
.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: '测试货主' }];
|
||||
@ -296,59 +273,4 @@ 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', '无发货单记录时回退流水单据号');
|
||||
});
|
||||
});
|
||||
|
||||
@ -17,7 +17,6 @@ function createListApiConfigHarness(options = {}) {
|
||||
const capture = {
|
||||
apiAppFindAllArgs: [],
|
||||
qimenAppFindAllArgs: [],
|
||||
interfaceTypeFindOneArgs: [],
|
||||
};
|
||||
|
||||
const rows = options.rows || [];
|
||||
@ -51,14 +50,7 @@ function createListApiConfigHarness(options = {}) {
|
||||
return qimenApps.filter(item => appKeys.includes(item.app_key));
|
||||
},
|
||||
},
|
||||
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;
|
||||
},
|
||||
},
|
||||
InterfaceType: {},
|
||||
},
|
||||
logger: {
|
||||
info() {},
|
||||
@ -137,21 +129,4 @@ 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);
|
||||
});
|
||||
});
|
||||
|
||||
@ -13,12 +13,8 @@ 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),
|
||||
@ -26,7 +22,6 @@ function createSaveApiConfigHarness(options = {}) {
|
||||
const capture = {
|
||||
qimenAppFindOneArgs: [],
|
||||
apiAppFindOneArgs: [],
|
||||
interfaceTypeFindOneArgs: [],
|
||||
apiAppCreatePayload: null,
|
||||
apiAppUpdatePayload: null,
|
||||
operationLogPayload: null,
|
||||
@ -49,8 +44,8 @@ function createSaveApiConfigHarness(options = {}) {
|
||||
persistedConfig = {
|
||||
...options.existingConfig,
|
||||
interface_type: {
|
||||
id: effectiveInterfaceType.id,
|
||||
interface_category: effectiveInterfaceType.interface_category,
|
||||
id: interfaceType.id,
|
||||
interface_category: interfaceType.interface_category,
|
||||
},
|
||||
};
|
||||
existingConfig = {
|
||||
@ -61,8 +56,8 @@ function createSaveApiConfigHarness(options = {}) {
|
||||
...persistedConfig,
|
||||
...payload,
|
||||
interface_type: {
|
||||
id: effectiveInterfaceType.id,
|
||||
interface_category: effectiveInterfaceType.interface_category,
|
||||
id: interfaceType.id,
|
||||
interface_category: interfaceType.interface_category,
|
||||
},
|
||||
};
|
||||
return this;
|
||||
@ -72,7 +67,7 @@ function createSaveApiConfigHarness(options = {}) {
|
||||
|
||||
const ctx = {
|
||||
app: {
|
||||
config: options.config || {},
|
||||
config: {},
|
||||
Sequelize,
|
||||
},
|
||||
user: {
|
||||
@ -102,8 +97,8 @@ function createSaveApiConfigHarness(options = {}) {
|
||||
id: Number(options.createdConfigId || 321),
|
||||
...payload,
|
||||
interface_type: {
|
||||
id: effectiveInterfaceType.id,
|
||||
interface_category: effectiveInterfaceType.interface_category,
|
||||
id: interfaceType.id,
|
||||
interface_category: interfaceType.interface_category,
|
||||
},
|
||||
};
|
||||
return {
|
||||
@ -117,12 +112,7 @@ function createSaveApiConfigHarness(options = {}) {
|
||||
};
|
||||
},
|
||||
},
|
||||
InterfaceType: {
|
||||
async findOne(args = {}) {
|
||||
capture.interfaceTypeFindOneArgs.push(args);
|
||||
return options.storeInterfaceType || null;
|
||||
},
|
||||
},
|
||||
InterfaceType: {},
|
||||
StoreWarehouse: {
|
||||
async findByPk(id) {
|
||||
return {
|
||||
@ -151,12 +141,9 @@ function createSaveApiConfigHarness(options = {}) {
|
||||
ctx.app.model = ctx.model;
|
||||
|
||||
const service = new StoreWarehouseService(ctx);
|
||||
service.getCurrentSubject = async () => options.currentSubject || {
|
||||
id: relation.warehouse_id,
|
||||
isWarehouse: true,
|
||||
project: 'warehouse',
|
||||
};
|
||||
service.getCurrentSubject = async () => ({ role: 'warehouse' });
|
||||
service.findScopedRelation = async () => relation;
|
||||
service.ensureWarehouseSubject = () => {};
|
||||
service.getApiInterfaceType = async () => interfaceType;
|
||||
service.getRelationIncludes = () => [];
|
||||
service.serializeRelation = result => ({
|
||||
@ -271,97 +258,4 @@ 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);
|
||||
});
|
||||
});
|
||||
|
||||
@ -57,15 +57,6 @@ 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]);
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user