chore: commit all current workspace changes
This commit is contained in:
parent
37a8e152a6
commit
0ffe290a21
1
.github/agents/文档.agent.md
vendored
1
.github/agents/文档.agent.md
vendored
@ -63,6 +63,7 @@ node .\script\tmp-struct-system-params.cjs
|
||||
## 推荐工作流
|
||||
|
||||
1. 先定位代码真实实现与调用链
|
||||
2. 在temp/apiDoc/目录下先备份对应的时间的json文档方便后续对比和回档,自动归档人工回档都在这个目录下进行
|
||||
2. 如 system 入参结构变化,可先执行 `node .\script\tmp-struct-system-params.cjs`
|
||||
3. 按 `docs/api-doc-update-workflow.md` 生成固定 spec JSON
|
||||
4. 先执行 `npm run doc:api:update -- --spec=<path> --dry-run`
|
||||
|
||||
2
.github/agents/调度.agent.md
vendored
2
.github/agents/调度.agent.md
vendored
@ -3,7 +3,7 @@ name: wms-dispatcher-agent
|
||||
description: "Use when the user asks about 任务委派、任务分派、调度、router、triage、多领域排障、不确定该找哪个 agent,或需要把问题分给 数据库/Redis/发布/开发/测试/文档 等模块。专用于 WMS 任务分诊与委派。"
|
||||
argument-hint: "描述你的目标或问题,例如:帮我判断这是数据库、测试还是缓存问题并分派、这个线上异常该交给谁处理。"
|
||||
tools: ['read', 'search', 'agent', 'todo']
|
||||
model: GPT-5.4 mini (copilot)
|
||||
model: Claude Opus 4.6 (copilot)
|
||||
---
|
||||
|
||||
# WMS 调度代理(`wms-dispatcher-agent`)
|
||||
|
||||
5
app.js
5
app.js
@ -1,7 +1,7 @@
|
||||
// app.js
|
||||
const path = require('path');
|
||||
const LocalFileWriter = require('./app/lib/file_writer');
|
||||
const ensureOrderDeliverySelfCheck = require('./app/lib/order_delivery_selfcheck');
|
||||
const QimenClient = require('./app/lib/qimen_client');
|
||||
|
||||
/**
|
||||
* 挂载应用级扩展能力。
|
||||
@ -13,8 +13,10 @@ module.exports = app => {
|
||||
global.APP_ROOT = path.resolve(__dirname, './');
|
||||
app.appRoot = global.APP_ROOT;
|
||||
app.fileWriter = new LocalFileWriter(app);
|
||||
app.qimenClient = new QimenClient(app);
|
||||
app.logger.info('✅ Application 扩展能力已加载');
|
||||
app.logger.info('✅ fileWriter 已挂载到 app.fileWriter');
|
||||
app.logger.info('✅ qimenClient 已挂载到 app.qimenClient');
|
||||
// 初始化工厂
|
||||
app.beforeStart(async () => {
|
||||
const OrderDeliveryFactory = require('./app/model/order_delivery_factory');
|
||||
@ -32,7 +34,6 @@ module.exports = app => {
|
||||
app.OrderItemsFactory = OrderItemsFactory(app);
|
||||
app.model.OrderItemsFactory = app.OrderItemsFactory;
|
||||
app.logger.info('✅ 工厂类初始化完成');
|
||||
// await ensureOrderDeliverySelfCheck(app);
|
||||
} catch (error) {
|
||||
app.logger.error('❌ 工厂类初始化失败:', error);
|
||||
}
|
||||
|
||||
@ -443,6 +443,28 @@ function normalizeGroups(docData) {
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析文档对应的统一入口路径,优先使用文档内声明的 http.path。
|
||||
* @param {object} docData 文档 JSON 数据。
|
||||
* @return {string} 统一入口路径。
|
||||
*/
|
||||
function resolveDocEntryPath(docData) {
|
||||
const httpPath = String(docData?.http?.path || '').trim();
|
||||
if (httpPath.startsWith('/')) {
|
||||
return httpPath;
|
||||
}
|
||||
|
||||
if (docData?.module === 'qimen') {
|
||||
return '/qimen';
|
||||
}
|
||||
|
||||
if (docData?.module === 'gateway') {
|
||||
return '/internal/v1/gateway';
|
||||
}
|
||||
|
||||
return '/system';
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染键值表格。
|
||||
* @param {Array<object>} items 数据项列表。
|
||||
@ -512,9 +534,14 @@ function renderMethodCard(item, entryPath, moduleName) {
|
||||
const methodName = item.method || item.name || 'unknown';
|
||||
const description = item.description || '';
|
||||
const isQimen = moduleName === 'qimen';
|
||||
const isOpenapi = moduleName === 'openapi';
|
||||
const queryHint = isQimen
|
||||
? 'app_key=xxx&method=...&v=2.0&format=json&sign_method=md5&sign=xxx×tamp=1700000000'
|
||||
: `method=${methodName}&v=1.0×tamp=1700000000`;
|
||||
: isOpenapi
|
||||
? `app_key=&method=${methodName}&v=1.0×tamp=1700000000`
|
||||
: `method=${methodName}&v=1.0×tamp=1700000000`;
|
||||
const queryLabel = isOpenapi ? 'Query 参数(自动生成)' : 'Query 参数';
|
||||
const queryReadonlyAttr = isOpenapi ? ' readonly data-auto-generated="true" aria-label="自动生成"' : '';
|
||||
|
||||
return `<section class="method-card" id="${escapeHtml(methodName)}" data-method="${escapeHtml(methodName)}" data-desc="${escapeHtml(description)}" data-module="${escapeHtml(moduleName || '')}" data-endpoint="${escapeHtml(entryPath)}" data-login-required="${item.isNeedLogin ? 'true' : 'false'}">
|
||||
<div class="method-header">
|
||||
@ -584,8 +611,13 @@ function renderMethodCard(item, entryPath, moduleName) {
|
||||
<details class="debug-panel">
|
||||
<summary>在线调试</summary>
|
||||
<div class="debug-form">
|
||||
<label>Query 参数</label>
|
||||
<input class="req-query" type="text" placeholder="${escapeHtml(queryHint)}" />
|
||||
<label>${queryLabel}</label>
|
||||
<input class="req-query" type="text" placeholder="${escapeHtml(queryHint)}"${queryReadonlyAttr} />
|
||||
|
||||
${isOpenapi ? `<label>app_key(仅 openapi 页面本地保存)</label>
|
||||
<input class="req-app-key" type="text" placeholder="请输入 app_key" autocomplete="off" />
|
||||
<label>self_app_secret(仅本地签名计算,不会发送)</label>
|
||||
<input class="req-self-app-secret" type="password" placeholder="请输入 self_app_secret" autocomplete="off" />` : ''}
|
||||
|
||||
<label>Body (JSON)</label>
|
||||
<textarea class="req-body" rows="6" placeholder='{}'></textarea>
|
||||
@ -1043,8 +1075,11 @@ function renderHtmlPage({
|
||||
</main>
|
||||
<script>
|
||||
(function() {
|
||||
var DOC_NAME = ${JSON.stringify(docName)};
|
||||
var IS_OPENAPI_DOC = DOC_NAME === 'openapi';
|
||||
var AUTH_KEY = 'wms_docs_global_auth';
|
||||
var HEADER_STORE_KEY = 'wms_docs_global_headers_' + ${JSON.stringify(docName)};
|
||||
var OPENAPI_APP_KEY_STORE_KEY = 'wms_docs_openapi_app_key';
|
||||
var authInput = document.getElementById('globalAuth');
|
||||
var clearBtn = document.getElementById('clearAuthBtn');
|
||||
var searchInput = document.getElementById('methodSearch');
|
||||
@ -1056,6 +1091,7 @@ function renderHtmlPage({
|
||||
var resourcePreview = document.getElementById('docResourcePreview');
|
||||
var changesUrl = ${JSON.stringify(changesUrl)};
|
||||
var rawUrl = ${JSON.stringify(rawUrl)};
|
||||
var defaultEntryPath = ${JSON.stringify(entryPath)};
|
||||
|
||||
function openWindowHref(target) {
|
||||
var href = target && target.getAttribute('data-window-href');
|
||||
@ -1074,6 +1110,296 @@ function renderHtmlPage({
|
||||
return Math.floor(Date.now() / 1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算字符串 MD5(小写十六进制)。
|
||||
* @param {string} value 待计算字符串。
|
||||
* @return {string} MD5 结果。
|
||||
*/
|
||||
function md5(value) {
|
||||
function add32(a, b) {
|
||||
return (a + b) & 0xFFFFFFFF;
|
||||
}
|
||||
|
||||
function cmn(q, a, b, x, s, t) {
|
||||
a = add32(add32(a, q), add32(x, t));
|
||||
return add32((a << s) | (a >>> (32 - s)), b);
|
||||
}
|
||||
|
||||
function ff(a, b, c, d, x, s, t) {
|
||||
return cmn((b & c) | ((~b) & d), a, b, x, s, t);
|
||||
}
|
||||
|
||||
function gg(a, b, c, d, x, s, t) {
|
||||
return cmn((b & d) | (c & (~d)), a, b, x, s, t);
|
||||
}
|
||||
|
||||
function hh(a, b, c, d, x, s, t) {
|
||||
return cmn(b ^ c ^ d, a, b, x, s, t);
|
||||
}
|
||||
|
||||
function ii(a, b, c, d, x, s, t) {
|
||||
return cmn(c ^ (b | (~d)), a, b, x, s, t);
|
||||
}
|
||||
|
||||
function md5cycle(state, block) {
|
||||
var a = state[0];
|
||||
var b = state[1];
|
||||
var c = state[2];
|
||||
var d = state[3];
|
||||
|
||||
a = ff(a, b, c, d, block[0], 7, -680876936);
|
||||
d = ff(d, a, b, c, block[1], 12, -389564586);
|
||||
c = ff(c, d, a, b, block[2], 17, 606105819);
|
||||
b = ff(b, c, d, a, block[3], 22, -1044525330);
|
||||
a = ff(a, b, c, d, block[4], 7, -176418897);
|
||||
d = ff(d, a, b, c, block[5], 12, 1200080426);
|
||||
c = ff(c, d, a, b, block[6], 17, -1473231341);
|
||||
b = ff(b, c, d, a, block[7], 22, -45705983);
|
||||
a = ff(a, b, c, d, block[8], 7, 1770035416);
|
||||
d = ff(d, a, b, c, block[9], 12, -1958414417);
|
||||
c = ff(c, d, a, b, block[10], 17, -42063);
|
||||
b = ff(b, c, d, a, block[11], 22, -1990404162);
|
||||
a = ff(a, b, c, d, block[12], 7, 1804603682);
|
||||
d = ff(d, a, b, c, block[13], 12, -40341101);
|
||||
c = ff(c, d, a, b, block[14], 17, -1502002290);
|
||||
b = ff(b, c, d, a, block[15], 22, 1236535329);
|
||||
|
||||
a = gg(a, b, c, d, block[1], 5, -165796510);
|
||||
d = gg(d, a, b, c, block[6], 9, -1069501632);
|
||||
c = gg(c, d, a, b, block[11], 14, 643717713);
|
||||
b = gg(b, c, d, a, block[0], 20, -373897302);
|
||||
a = gg(a, b, c, d, block[5], 5, -701558691);
|
||||
d = gg(d, a, b, c, block[10], 9, 38016083);
|
||||
c = gg(c, d, a, b, block[15], 14, -660478335);
|
||||
b = gg(b, c, d, a, block[4], 20, -405537848);
|
||||
a = gg(a, b, c, d, block[9], 5, 568446438);
|
||||
d = gg(d, a, b, c, block[14], 9, -1019803690);
|
||||
c = gg(c, d, a, b, block[3], 14, -187363961);
|
||||
b = gg(b, c, d, a, block[8], 20, 1163531501);
|
||||
a = gg(a, b, c, d, block[13], 5, -1444681467);
|
||||
d = gg(d, a, b, c, block[2], 9, -51403784);
|
||||
c = gg(c, d, a, b, block[7], 14, 1735328473);
|
||||
b = gg(b, c, d, a, block[12], 20, -1926607734);
|
||||
|
||||
a = hh(a, b, c, d, block[5], 4, -378558);
|
||||
d = hh(d, a, b, c, block[8], 11, -2022574463);
|
||||
c = hh(c, d, a, b, block[11], 16, 1839030562);
|
||||
b = hh(b, c, d, a, block[14], 23, -35309556);
|
||||
a = hh(a, b, c, d, block[1], 4, -1530992060);
|
||||
d = hh(d, a, b, c, block[4], 11, 1272893353);
|
||||
c = hh(c, d, a, b, block[7], 16, -155497632);
|
||||
b = hh(b, c, d, a, block[10], 23, -1094730640);
|
||||
a = hh(a, b, c, d, block[13], 4, 681279174);
|
||||
d = hh(d, a, b, c, block[0], 11, -358537222);
|
||||
c = hh(c, d, a, b, block[3], 16, -722521979);
|
||||
b = hh(b, c, d, a, block[6], 23, 76029189);
|
||||
a = hh(a, b, c, d, block[9], 4, -640364487);
|
||||
d = hh(d, a, b, c, block[12], 11, -421815835);
|
||||
c = hh(c, d, a, b, block[15], 16, 530742520);
|
||||
b = hh(b, c, d, a, block[2], 23, -995338651);
|
||||
|
||||
a = ii(a, b, c, d, block[0], 6, -198630844);
|
||||
d = ii(d, a, b, c, block[7], 10, 1126891415);
|
||||
c = ii(c, d, a, b, block[14], 15, -1416354905);
|
||||
b = ii(b, c, d, a, block[5], 21, -57434055);
|
||||
a = ii(a, b, c, d, block[12], 6, 1700485571);
|
||||
d = ii(d, a, b, c, block[3], 10, -1894986606);
|
||||
c = ii(c, d, a, b, block[10], 15, -1051523);
|
||||
b = ii(b, c, d, a, block[1], 21, -2054922799);
|
||||
a = ii(a, b, c, d, block[8], 6, 1873313359);
|
||||
d = ii(d, a, b, c, block[15], 10, -30611744);
|
||||
c = ii(c, d, a, b, block[6], 15, -1560198380);
|
||||
b = ii(b, c, d, a, block[13], 21, 1309151649);
|
||||
a = ii(a, b, c, d, block[4], 6, -145523070);
|
||||
d = ii(d, a, b, c, block[11], 10, -1120210379);
|
||||
c = ii(c, d, a, b, block[2], 15, 718787259);
|
||||
b = ii(b, c, d, a, block[9], 21, -343485551);
|
||||
|
||||
state[0] = add32(a, state[0]);
|
||||
state[1] = add32(b, state[1]);
|
||||
state[2] = add32(c, state[2]);
|
||||
state[3] = add32(d, state[3]);
|
||||
}
|
||||
|
||||
function md5blk(str) {
|
||||
var block = [];
|
||||
for (var i = 0; i < 64; i += 4) {
|
||||
block[i >> 2] = str.charCodeAt(i)
|
||||
+ (str.charCodeAt(i + 1) << 8)
|
||||
+ (str.charCodeAt(i + 2) << 16)
|
||||
+ (str.charCodeAt(i + 3) << 24);
|
||||
}
|
||||
return block;
|
||||
}
|
||||
|
||||
function md51(str) {
|
||||
var state = [ 1732584193, -271733879, -1732584194, 271733878 ];
|
||||
var i;
|
||||
for (i = 64; i <= str.length; i += 64) {
|
||||
md5cycle(state, md5blk(str.substring(i - 64, i)));
|
||||
}
|
||||
str = str.substring(i - 64);
|
||||
var tail = new Array(16).fill(0);
|
||||
for (i = 0; i < str.length; i += 1) {
|
||||
tail[i >> 2] |= str.charCodeAt(i) << ((i % 4) << 3);
|
||||
}
|
||||
tail[i >> 2] |= 0x80 << ((i % 4) << 3);
|
||||
if (i > 55) {
|
||||
md5cycle(state, tail);
|
||||
tail = new Array(16).fill(0);
|
||||
}
|
||||
tail[14] = str.length * 8;
|
||||
md5cycle(state, tail);
|
||||
return state;
|
||||
}
|
||||
|
||||
function rhex(n) {
|
||||
var hex = '0123456789abcdef';
|
||||
var output = '';
|
||||
for (var j = 0; j < 4; j += 1) {
|
||||
output += hex.charAt((n >> (j * 8 + 4)) & 0x0F) + hex.charAt((n >> (j * 8)) & 0x0F);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
function hex(x) {
|
||||
return x.map(rhex).join('');
|
||||
}
|
||||
|
||||
return hex(md51(unescape(encodeURIComponent(String(value || '')))));
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断输入是否为普通对象。
|
||||
* @param {*} value 任意值。
|
||||
* @return {boolean} 是否为普通对象。
|
||||
*/
|
||||
function isPlainObject(value) {
|
||||
return Object.prototype.toString.call(value) === '[object Object]';
|
||||
}
|
||||
|
||||
/**
|
||||
* 以稳定顺序序列化对象,用于签名。
|
||||
* @param {*} value 待序列化值。
|
||||
* @return {string} 序列化字符串。
|
||||
*/
|
||||
function stableStringify(value) {
|
||||
if (value === undefined) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if (value === null || typeof value !== 'object') {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
return '[' + value.map(function(item) {
|
||||
return stableStringify(item);
|
||||
}).join(',') + ']';
|
||||
}
|
||||
|
||||
if (!isPlainObject(value)) {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
var keys = Object.keys(value).sort();
|
||||
return '{' + keys.map(function(key) {
|
||||
return JSON.stringify(key) + ':' + stableStringify(value[key]);
|
||||
}).join(',') + '}';
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 query 字符串解析为对象。
|
||||
* @param {string} queryText query 文本。
|
||||
* @return {Object} query 对象。
|
||||
*/
|
||||
function parseQueryString(queryText) {
|
||||
var result = {};
|
||||
var raw = String(queryText || '').trim();
|
||||
if (raw.startsWith('?')) {
|
||||
raw = raw.slice(1);
|
||||
}
|
||||
if (!raw) {
|
||||
return result;
|
||||
}
|
||||
|
||||
raw.split('&').forEach(function(part) {
|
||||
if (!part) {
|
||||
return;
|
||||
}
|
||||
|
||||
var eqIndex = part.indexOf('=');
|
||||
var rawKey = eqIndex >= 0 ? part.slice(0, eqIndex) : part;
|
||||
var rawValue = eqIndex >= 0 ? part.slice(eqIndex + 1) : '';
|
||||
var key = decodeURIComponent(rawKey || '').trim();
|
||||
if (!key) {
|
||||
return;
|
||||
}
|
||||
|
||||
var value = decodeURIComponent(rawValue || '');
|
||||
result[key] = value;
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 query 对象按 key 排序后编码为字符串。
|
||||
* @param {Object} params query 对象。
|
||||
* @return {string} query 字符串。
|
||||
*/
|
||||
function buildSortedQueryString(params) {
|
||||
return Object.keys(params || {}).filter(function(key) {
|
||||
return params[key] !== undefined;
|
||||
}).sort().map(function(key) {
|
||||
return encodeURIComponent(key) + '=' + encodeURIComponent(String(params[key] == null ? '' : params[key]));
|
||||
}).join('&');
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建参与签名的 canonical query。
|
||||
* @param {Object} queryParams query 对象。
|
||||
* @return {string} canonical query。
|
||||
*/
|
||||
function buildCanonicalQuery(queryParams) {
|
||||
var ignoredSet = {
|
||||
sign: true,
|
||||
signature: true,
|
||||
};
|
||||
|
||||
return Object.keys(queryParams || {}).filter(function(key) {
|
||||
return !ignoredSet[String(key).toLowerCase()] && queryParams[key] !== undefined;
|
||||
}).sort().map(function(key) {
|
||||
return key + '=' + String(queryParams[key] == null ? '' : queryParams[key]);
|
||||
}).join('&');
|
||||
}
|
||||
|
||||
/**
|
||||
* 对 openapi 请求计算签名并回填 sign 字段。
|
||||
* @param {string} queryText 原始 query 文本。
|
||||
* @param {Object} requestBody 已解析的 body 对象。
|
||||
* @param {string} selfAppSecret 本地输入密钥。
|
||||
* @return {{ queryText: string, sign: string, bodySign: string }} 签名结果。
|
||||
*/
|
||||
function applyOpenapiSign(queryText, requestBody, selfAppSecret) {
|
||||
var normalizedSecret = String(selfAppSecret || '').trim();
|
||||
if (!normalizedSecret) {
|
||||
throw new Error('openapi 签名失败: self_app_secret 不能为空');
|
||||
}
|
||||
|
||||
var queryParams = parseQueryString(queryText);
|
||||
var canonicalQuery = buildCanonicalQuery(queryParams);
|
||||
var bodySign = md5(stableStringify(requestBody));
|
||||
var sign = md5(canonicalQuery + normalizedSecret + bodySign);
|
||||
queryParams.sign = sign;
|
||||
|
||||
return {
|
||||
queryText: buildSortedQueryString(queryParams),
|
||||
sign: sign,
|
||||
bodySign: bodySign,
|
||||
};
|
||||
}
|
||||
|
||||
function formatPretty(text) {
|
||||
try {
|
||||
return JSON.stringify(JSON.parse(text), null, 2);
|
||||
@ -1101,6 +1427,11 @@ function renderHtmlPage({
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成在线调试默认 Query 字符串。
|
||||
* @param {HTMLElement} card 接口卡片节点。
|
||||
* @return {string} 默认 Query 参数。
|
||||
*/
|
||||
function buildDefaultQuery(card) {
|
||||
var moduleName = card.getAttribute('data-module') || '';
|
||||
var methodName = card.getAttribute('data-method') || '';
|
||||
@ -1108,16 +1439,39 @@ function renderHtmlPage({
|
||||
return 'app_key=&method=' + encodeURIComponent(methodName)
|
||||
+ '&v=2.0&format=json&sign_method=md5&sign=×tamp=' + nowTimestamp();
|
||||
}
|
||||
if (moduleName === 'openapi') {
|
||||
return buildOpenapiQuery(card, '');
|
||||
}
|
||||
return 'method=' + encodeURIComponent(methodName) + '&v=1.0×tamp=' + nowTimestamp();
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 openapi method 与 app_key 生成 query 展示值。
|
||||
* @param {HTMLElement} card 接口卡片节点。
|
||||
* @param {string} appKey openapi app_key。
|
||||
* @return {string} 生成后的 query。
|
||||
*/
|
||||
function buildOpenapiQuery(card, appKey) {
|
||||
var methodName = card.getAttribute('data-method') || '';
|
||||
return 'app_key=' + encodeURIComponent(String(appKey || '').trim())
|
||||
+ '&method=' + encodeURIComponent(methodName)
|
||||
+ '&v=1.0×tamp=' + nowTimestamp();
|
||||
}
|
||||
|
||||
function initDefaultQueries() {
|
||||
var cards = document.querySelectorAll('.method-card');
|
||||
cards.forEach(function(card) {
|
||||
var queryInput = card.querySelector('.req-query');
|
||||
var bodyInput = card.querySelector('.req-body');
|
||||
if (queryInput && !queryInput.value.trim()) {
|
||||
queryInput.value = buildDefaultQuery(card);
|
||||
var moduleName = card.getAttribute('data-module') || '';
|
||||
if (queryInput) {
|
||||
if (moduleName === 'openapi') {
|
||||
var appKeyInput = card.querySelector('.req-app-key');
|
||||
var openapiAppKey = (appKeyInput && appKeyInput.value.trim()) || '';
|
||||
queryInput.value = buildOpenapiQuery(card, openapiAppKey);
|
||||
} else if (!queryInput.value.trim()) {
|
||||
queryInput.value = buildDefaultQuery(card);
|
||||
}
|
||||
}
|
||||
if (bodyInput && !bodyInput.value.trim()) {
|
||||
bodyInput.value = '{}';
|
||||
@ -1125,6 +1479,59 @@ function renderHtmlPage({
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 刷新 openapi 页面所有卡片的只读 query 展示。
|
||||
* @param {string} appKey 当前 app_key。
|
||||
* @return {void}
|
||||
*/
|
||||
function refreshOpenapiQueryDisplays(appKey) {
|
||||
if (!IS_OPENAPI_DOC) {
|
||||
return;
|
||||
}
|
||||
|
||||
var cards = document.querySelectorAll('.method-card[data-module="openapi"]');
|
||||
cards.forEach(function(card) {
|
||||
var queryInput = card.querySelector('.req-query');
|
||||
if (!queryInput) {
|
||||
return;
|
||||
}
|
||||
|
||||
queryInput.value = buildOpenapiQuery(card, appKey);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载 openapi 专用 app_key,并绑定输入变化自动持久化。
|
||||
* @return {void}
|
||||
*/
|
||||
function initOpenapiAppKeyInputs() {
|
||||
if (!IS_OPENAPI_DOC) {
|
||||
return;
|
||||
}
|
||||
|
||||
var appKeyInputs = document.querySelectorAll('.req-app-key');
|
||||
if (!appKeyInputs.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
var storedAppKey = localStorage.getItem(OPENAPI_APP_KEY_STORE_KEY) || '';
|
||||
appKeyInputs.forEach(function(input) {
|
||||
input.value = storedAppKey;
|
||||
input.addEventListener('input', function() {
|
||||
var value = input.value.trim();
|
||||
localStorage.setItem(OPENAPI_APP_KEY_STORE_KEY, value);
|
||||
appKeyInputs.forEach(function(otherInput) {
|
||||
if (otherInput !== input) {
|
||||
otherInput.value = value;
|
||||
}
|
||||
});
|
||||
refreshOpenapiQueryDisplays(value);
|
||||
});
|
||||
});
|
||||
|
||||
refreshOpenapiQueryDisplays(storedAppKey);
|
||||
}
|
||||
|
||||
function normalizeText(text) {
|
||||
return String(text || '').toLowerCase();
|
||||
}
|
||||
@ -1250,6 +1657,7 @@ function renderHtmlPage({
|
||||
}
|
||||
|
||||
loadGlobalHeaders();
|
||||
initOpenapiAppKeyInputs();
|
||||
|
||||
if (searchInput) {
|
||||
searchInput.addEventListener('input', function() {
|
||||
@ -1321,14 +1729,51 @@ function renderHtmlPage({
|
||||
var queryInput = card.querySelector('.req-query');
|
||||
var bodyInput = card.querySelector('.req-body');
|
||||
var resultEl = card.querySelector('.req-result');
|
||||
var endpoint = card.getAttribute('data-endpoint') || '/system';
|
||||
var endpoint = card.getAttribute('data-endpoint') || defaultEntryPath;
|
||||
var moduleName = card.getAttribute('data-module') || '';
|
||||
var loginRequired = card.getAttribute('data-login-required') === 'true';
|
||||
|
||||
var query = (queryInput && queryInput.value.trim()) || '';
|
||||
var url = query ? (endpoint + '?' + query) : endpoint;
|
||||
var auth = (authInput && authInput.value.trim()) || localStorage.getItem(AUTH_KEY) || '';
|
||||
var rawBody = (bodyInput && bodyInput.value.trim()) || '{}';
|
||||
var globalHeaderData = collectGlobalHeaders();
|
||||
var requestBody = null;
|
||||
|
||||
try {
|
||||
requestBody = JSON.parse(rawBody);
|
||||
} catch (error) {
|
||||
if (resultEl) {
|
||||
resultEl.textContent = '请求已阻止: Body 必须是合法 JSON。';
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (moduleName === 'openapi') {
|
||||
var appKeyInput = card.querySelector('.req-app-key');
|
||||
var openapiAppKey = (appKeyInput && appKeyInput.value.trim()) || '';
|
||||
query = buildOpenapiQuery(card, openapiAppKey);
|
||||
if (queryInput) {
|
||||
queryInput.value = query;
|
||||
}
|
||||
|
||||
var selfSecretInput = card.querySelector('.req-self-app-secret');
|
||||
var selfAppSecret = (selfSecretInput && selfSecretInput.value.trim()) || '';
|
||||
|
||||
try {
|
||||
var signed = applyOpenapiSign(query, requestBody, selfAppSecret);
|
||||
query = signed.queryText;
|
||||
if (queryInput) {
|
||||
queryInput.value = query;
|
||||
}
|
||||
} catch (error) {
|
||||
if (resultEl) {
|
||||
resultEl.textContent = error.message;
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
var url = query ? (endpoint + '?' + query) : endpoint;
|
||||
|
||||
var headers = {
|
||||
'Content-Type': 'application/json',
|
||||
@ -1552,6 +1997,11 @@ class DocsController extends Controller {
|
||||
.sort();
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染指定 API 文档详情页。
|
||||
* @param {string} docName 文档名称(不含 .json 后缀)。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async renderDoc(docName) {
|
||||
const { ctx, app } = this;
|
||||
|
||||
@ -1571,9 +2021,7 @@ class DocsController extends Controller {
|
||||
|
||||
const docData = JSON.parse(content);
|
||||
const groups = normalizeGroups(docData);
|
||||
const entryPath = docData.module === 'qimen'
|
||||
? '/qimen'
|
||||
: (docData.module === 'gateway' ? '/internal/v1/gateway' : '/system');
|
||||
const entryPath = resolveDocEntryPath(docData);
|
||||
const html = renderHtmlPage({
|
||||
docName,
|
||||
docData,
|
||||
|
||||
56
app/controller/openapi.js
Normal file
56
app/controller/openapi.js
Normal file
@ -0,0 +1,56 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
const { toSuccess, toFailure } = require('../lib/api_response');
|
||||
|
||||
class OpenapiController extends Controller {
|
||||
/**
|
||||
* 输出 openapi 统一失败响应。
|
||||
* @param {number} httpStatus HTTP 状态码。
|
||||
* @param {string} message 错误消息。
|
||||
* @param {number} [code=httpStatus] 业务错误码。
|
||||
* @return {void} 无返回值。
|
||||
*/
|
||||
writeFailureResponse(httpStatus, message, code = httpStatus) {
|
||||
const { ctx } = this;
|
||||
ctx.status = httpStatus;
|
||||
ctx.body = toFailure({
|
||||
message,
|
||||
httpStatus,
|
||||
code,
|
||||
});
|
||||
ctx.type = 'application/json';
|
||||
}
|
||||
|
||||
/**
|
||||
* OpenAPI 统一入口,仅负责转发到 openapi service 并输出标准响应。
|
||||
* @return {Promise<void>} 无返回值,结果写入 ctx.body。
|
||||
*/
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
|
||||
try {
|
||||
const result = await ctx.service.openapi.processRequest();
|
||||
if (result.ok) {
|
||||
ctx.status = Number(result.httpStatus) || 200;
|
||||
ctx.body = toSuccess(result.data, result.message || 'ok');
|
||||
ctx.type = 'application/json';
|
||||
return;
|
||||
}
|
||||
|
||||
this.writeFailureResponse(
|
||||
Number(result.httpStatus) || 500,
|
||||
String(result.message || '请求失败'),
|
||||
Number(result.code) || Number(result.httpStatus) || 500
|
||||
);
|
||||
ctx.type = 'application/json';
|
||||
return;
|
||||
} catch (error) {
|
||||
const message = String(error && error.message || '请求失败');
|
||||
this.writeFailureResponse(500, `接口错误: ${message}`, 500);
|
||||
ctx.type = 'application/json';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = OpenapiController;
|
||||
@ -314,6 +314,34 @@ module.exports = {
|
||||
|
||||
setLocalCacheValue(this, cacheKey, data, ttl);
|
||||
},
|
||||
/**
|
||||
* 删除缓存。
|
||||
*
|
||||
* Redis 可用时优先删除 Redis;无论 Redis 是否可用,都会同步清理进程内缓存。
|
||||
*
|
||||
* @param {string} cacheKey 缓存键。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async delCacheAsync(cacheKey) {
|
||||
if (!cacheKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
const cacheRedis = getRedisCacheClient(this);
|
||||
|
||||
if (cacheRedis && typeof cacheRedis.del === 'function') {
|
||||
try {
|
||||
await cacheRedis.del(cacheKey);
|
||||
} catch (error) {
|
||||
const logger = getCacheLogger(this);
|
||||
if (logger && typeof logger.warn === 'function') {
|
||||
logger.warn('[CacheRedisDeleteError] Redis 删除缓存失败', error.message, cacheKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
deleteLocalCacheValue(this, cacheKey);
|
||||
},
|
||||
/**
|
||||
* 读取缓存。
|
||||
*
|
||||
|
||||
193
app/lib/api_sign.js
Normal file
193
app/lib/api_sign.js
Normal file
@ -0,0 +1,193 @@
|
||||
'use strict';
|
||||
|
||||
const crypto = require('crypto');
|
||||
|
||||
const DEFAULT_IGNORE_KEYS = [ 'sign', 'signature' ];
|
||||
|
||||
/**
|
||||
* 判断输入是否为普通对象。
|
||||
* @param {*} value 任意输入值。
|
||||
* @return {boolean} 是否为普通对象。
|
||||
*/
|
||||
function isPlainObject(value) {
|
||||
return Object.prototype.toString.call(value) === '[object Object]';
|
||||
}
|
||||
|
||||
/**
|
||||
* 将忽略字段列表归一化为小写集合。
|
||||
* @param {string[]} [ignoreKeys=[]] 忽略字段数组。
|
||||
* @return {Set<string>} 小写忽略字段集合。
|
||||
*/
|
||||
function normalizeIgnoreKeySet(ignoreKeys = []) {
|
||||
const rawKeys = Array.isArray(ignoreKeys)
|
||||
? ignoreKeys
|
||||
: [];
|
||||
|
||||
return new Set(rawKeys.map(key => String(key).toLowerCase()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 对任意值做稳定序列化,确保对象键顺序固定。
|
||||
* @param {*} value 待序列化值。
|
||||
* @return {string} 稳定序列化后的字符串。
|
||||
*/
|
||||
function stableStringify(value) {
|
||||
if (value === undefined) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if (value === null || typeof value !== 'object') {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
const serializedItems = value.map(item => stableStringify(item));
|
||||
return `[${serializedItems.join(',')}]`;
|
||||
}
|
||||
|
||||
if (!isPlainObject(value)) {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
const keys = Object.keys(value).sort();
|
||||
const serializedFields = keys.map(key => `${JSON.stringify(key)}:${stableStringify(value[key])}`);
|
||||
return `{${serializedFields.join(',')}}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化参数值为可拼接字符串。
|
||||
* @param {*} value 参数值。
|
||||
* @return {string} 归一化后的字符串。
|
||||
*/
|
||||
function normalizeParamValue(value) {
|
||||
if (value === undefined || value === null) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if (typeof value === 'object') {
|
||||
return stableStringify(value);
|
||||
}
|
||||
|
||||
return String(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建按 key 字母序排列的 query 参数串。
|
||||
* @param {Object} [params={}] 请求 query 参数对象。
|
||||
* @param {string[]} [ignoreKeys=[]] 需要忽略的字段名列表。
|
||||
* @return {string} 规范化后的 query 串,格式为 key=value&key2=value2。
|
||||
*/
|
||||
function buildCanonicalQuery(params = {}, ignoreKeys = []) {
|
||||
if (!isPlainObject(params)) {
|
||||
throw new Error('query 参数必须是对象');
|
||||
}
|
||||
|
||||
const ignoreKeySet = normalizeIgnoreKeySet(ignoreKeys);
|
||||
const keys = Object.keys(params)
|
||||
.filter(key => !ignoreKeySet.has(String(key).toLowerCase()))
|
||||
.filter(key => params[key] !== undefined)
|
||||
.sort();
|
||||
|
||||
return keys.map(key => `${key}=${normalizeParamValue(params[key])}`).join('&');
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建请求体签名,算法为 md5(稳定序列化后的 body)。
|
||||
* @param {*} body 请求体,可为对象、数组、字符串或空值。
|
||||
* @return {string} 小写十六进制 body 签名。
|
||||
*/
|
||||
function buildBodySign(body) {
|
||||
const serializedBody = typeof body === 'string'
|
||||
? body
|
||||
: stableStringify(body);
|
||||
|
||||
return crypto.createHash('md5').update(serializedBody, 'utf8').digest('hex').toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算请求签名。
|
||||
* 参与签名字符串 = canonicalQuery + selfAppSecret + bodySign。
|
||||
* 最终签名 = md5(参与签名字符串)。
|
||||
* @param {Object} options 签名参数。
|
||||
* @param {Object} [options.query={}] 请求 query 参数。
|
||||
* @param {*} [options.body] 请求体。
|
||||
* @param {string} options.selfAppSecret 密钥。
|
||||
* @param {string[]} [options.ignoreKeys] 需要忽略的 query 字段。
|
||||
* @return {{ canonicalQuery: string, bodySign: string, sign: string }} 计算结果。
|
||||
*/
|
||||
function signRequest({ query = {}, body, selfAppSecret, ignoreKeys } = {}) {
|
||||
const normalizedSecret = String(selfAppSecret || '').trim();
|
||||
if (!normalizedSecret) {
|
||||
throw new Error('selfAppSecret 不能为空');
|
||||
}
|
||||
|
||||
const mergedIgnoreKeys = [ ...DEFAULT_IGNORE_KEYS, ...(Array.isArray(ignoreKeys) ? ignoreKeys : []) ];
|
||||
const canonicalQuery = buildCanonicalQuery(query, mergedIgnoreKeys);
|
||||
const bodySign = buildBodySign(body);
|
||||
const signText = `${canonicalQuery}${normalizedSecret}${bodySign}`;
|
||||
const sign = crypto.createHash('md5').update(signText, 'utf8').digest('hex').toLowerCase();
|
||||
|
||||
return {
|
||||
canonicalQuery,
|
||||
bodySign,
|
||||
sign,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证请求签名。
|
||||
* @param {Object} options 验签参数。
|
||||
* @param {Object} [options.query={}] 请求 query 参数。
|
||||
* @param {*} [options.body] 请求体。
|
||||
* @param {string} options.providedSign 调用方提供的签名。
|
||||
* @param {string} options.selfAppSecret 密钥。
|
||||
* @param {string[]} [options.ignoreKeys] 需要忽略的 query 字段。
|
||||
* @return {{ ok: boolean, expectedSign: string, providedSign: string, message: string }} 验签结果。
|
||||
*/
|
||||
function verifyRequestSign({ query = {}, body, providedSign, selfAppSecret, ignoreKeys } = {}) {
|
||||
const normalizedProvidedSign = String(providedSign || '').trim().toLowerCase();
|
||||
if (!normalizedProvidedSign) {
|
||||
return {
|
||||
ok: false,
|
||||
expectedSign: '',
|
||||
providedSign: '',
|
||||
message: 'providedSign 不能为空',
|
||||
};
|
||||
}
|
||||
|
||||
let expected;
|
||||
try {
|
||||
expected = signRequest({ query, body, selfAppSecret, ignoreKeys }).sign;
|
||||
} catch (error) {
|
||||
return {
|
||||
ok: false,
|
||||
expectedSign: '',
|
||||
providedSign: normalizedProvidedSign,
|
||||
message: error.message,
|
||||
};
|
||||
}
|
||||
|
||||
if (expected !== normalizedProvidedSign) {
|
||||
return {
|
||||
ok: false,
|
||||
expectedSign: expected,
|
||||
providedSign: normalizedProvidedSign,
|
||||
message: '签名不匹配',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
expectedSign: expected,
|
||||
providedSign: normalizedProvidedSign,
|
||||
message: '签名验证通过',
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
DEFAULT_IGNORE_KEYS,
|
||||
buildCanonicalQuery,
|
||||
buildBodySign,
|
||||
signRequest,
|
||||
verifyRequestSign,
|
||||
};
|
||||
@ -6,6 +6,7 @@ const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
|
||||
const DEFAULT_MAX_FILE_SIZE = 100 * 1024 * 1024;
|
||||
const DEFAULT_MAX_FILE_LINES = 2000;
|
||||
const DEFAULT_MAX_CONSUME_RECORDS_PER_WINDOW = 1000;
|
||||
const DEFAULT_WRITE_WINDOW_SECONDS = 1;
|
||||
const DEFAULT_MAX_WRITE_RECORDS_PER_WINDOW = 2000;
|
||||
@ -28,6 +29,7 @@ class LocalFileWriter {
|
||||
this.config = app.config.fileWriter || {};
|
||||
this.baseDir = path.resolve(this.config.baseDir || path.join(app.baseDir, 'runtime', 'file-writer'));
|
||||
this.maxFileSize = this.normalizeSize(this.config.maxFileSize, DEFAULT_MAX_FILE_SIZE);
|
||||
this.maxFileLines = this.normalizePositiveInteger(this.config.maxFileLines, DEFAULT_MAX_FILE_LINES);
|
||||
this.maxConsumeRecordsPerWindow = this.normalizePositiveInteger(
|
||||
this.config.maxConsumeRecordsPerWindow
|
||||
?? this.config.maxConsumeRecordsPerRun
|
||||
@ -121,10 +123,14 @@ class LocalFileWriter {
|
||||
const payload = `${jsonLine}\n`;
|
||||
const payloadSize = Buffer.byteLength(payload);
|
||||
|
||||
if (partitionState.currentSize > 0 && partitionState.currentSize + payloadSize > this.maxFileSize) {
|
||||
if (
|
||||
partitionState.currentLineCount >= this.maxFileLines
|
||||
|| (partitionState.currentSize > 0 && partitionState.currentSize + payloadSize > this.maxFileSize)
|
||||
) {
|
||||
partitionState.sequence += 1;
|
||||
partitionState.currentFilePath = this.buildDataFilePath(partitionState, partitionState.sequence);
|
||||
partitionState.currentSize = 0;
|
||||
partitionState.currentLineCount = 0;
|
||||
}
|
||||
|
||||
await this.ensureParentDirectory(partitionState.partitionDir);
|
||||
@ -138,6 +144,7 @@ class LocalFileWriter {
|
||||
}
|
||||
|
||||
partitionState.currentSize += payloadSize;
|
||||
partitionState.currentLineCount += 1;
|
||||
await this.maybeCleanup();
|
||||
|
||||
return {
|
||||
@ -145,6 +152,7 @@ class LocalFileWriter {
|
||||
dateKey: partitionState.dateKey,
|
||||
filePath: partitionState.currentFilePath,
|
||||
size: partitionState.currentSize,
|
||||
lineCount: partitionState.currentLineCount,
|
||||
bytesWritten: payloadSize,
|
||||
sequence: partitionState.sequence,
|
||||
machineId: this.machineId,
|
||||
@ -825,17 +833,86 @@ class LocalFileWriter {
|
||||
filePrefix: partitionInfo.filePrefix,
|
||||
sequence: 1,
|
||||
currentSize: 0,
|
||||
currentLineCount: 0,
|
||||
currentFilePath: this.buildDataFilePath({
|
||||
partitionDir: partitionInfo.partitionDir,
|
||||
filePrefix: partitionInfo.filePrefix,
|
||||
}, 1),
|
||||
};
|
||||
|
||||
const latestDataFileState = await this.loadLatestDataFileState(partitionInfo.partitionDir, partitionInfo.filePrefix);
|
||||
if (latestDataFileState) {
|
||||
state.sequence = latestDataFileState.sequence;
|
||||
state.currentSize = latestDataFileState.currentSize;
|
||||
state.currentLineCount = latestDataFileState.currentLineCount;
|
||||
state.currentFilePath = latestDataFileState.currentFilePath;
|
||||
}
|
||||
|
||||
this.evictOldestStateIfNeeded();
|
||||
this.stateMap.set(stateKey, state);
|
||||
return state;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取分区中最新数据文件的大小与行数,用于恢复写入状态。
|
||||
* @param {string} partitionDir 分区目录。
|
||||
* @param {string} filePrefix 文件前缀。
|
||||
* @return {Promise<Object|null>} 最新文件状态。
|
||||
*/
|
||||
async loadLatestDataFileState(partitionDir, filePrefix) {
|
||||
const dataFiles = await this.collectDataFiles(partitionDir);
|
||||
if (dataFiles.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
dataFiles.sort((left, right) => this.compareDataFileSortKey(left.sortKey, right.sortKey));
|
||||
const latestFile = dataFiles[dataFiles.length - 1];
|
||||
const stat = await fsp.stat(latestFile.filePath);
|
||||
const currentLineCount = await this.countFileLines(latestFile.filePath);
|
||||
|
||||
return {
|
||||
filePrefix,
|
||||
sequence: latestFile.sortKey.sequence > 0 ? latestFile.sortKey.sequence : 1,
|
||||
currentFilePath: latestFile.filePath,
|
||||
currentSize: stat.size,
|
||||
currentLineCount,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 统计文件中的行数。
|
||||
* @param {string} filePath 文件路径。
|
||||
* @return {Promise<number>} 行数。
|
||||
*/
|
||||
async countFileLines(filePath) {
|
||||
let lineCount = 0;
|
||||
let lastByte = null;
|
||||
const stream = fs.createReadStream(filePath);
|
||||
|
||||
try {
|
||||
for await (const chunk of stream) {
|
||||
lastByte = chunk.length > 0 ? chunk[chunk.length - 1] : lastByte;
|
||||
for (let i = 0; i < chunk.length; i += 1) {
|
||||
if (chunk[i] === 0x0A) {
|
||||
lineCount += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
stream.destroy();
|
||||
}
|
||||
|
||||
if (lineCount === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (lastByte !== 0x0A) {
|
||||
lineCount += 1;
|
||||
}
|
||||
|
||||
return lineCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* 逐行读取 JSON Lines 文件,并返回每行的精确字节偏移。
|
||||
* @param {string} filePath 文件路径。
|
||||
|
||||
@ -1,19 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 在应用启动阶段触发订单发货表的 managed table schema 自检。
|
||||
* @param {import('egg').Application} app 应用实例。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
module.exports = async app => {
|
||||
if (!app || !app.OrderDeliveryFactory) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof app.OrderDeliveryFactory.ensureManagedTableSchemas !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
await app.OrderDeliveryFactory.ensureManagedTableSchemas();
|
||||
app.logger.info('✅ 订单工厂目标表自检完成');
|
||||
};
|
||||
@ -97,13 +97,19 @@ class PoloApiClient {
|
||||
* @return {Promise<object|null>} 数据库中的配置记录。
|
||||
*/
|
||||
async _loadConfigFromDatabase(platid) {
|
||||
if (!this.ctx.app || !this.ctx.app.model || !this.ctx.app.model.ExpressPlatform || typeof this.ctx.app.model.ExpressPlatform.findOne !== 'function') {
|
||||
if (!this.ctx.app || !this.ctx.app.model || typeof this.ctx.app.model.query !== 'function') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return await this.ctx.app.model.ExpressPlatform.findOne({
|
||||
where: { platid },
|
||||
});
|
||||
const rows = await this.ctx.app.model.query(
|
||||
'SELECT id, interface_url, platform_code, interface_name, platid, appkey, app_secret, token, version FROM wms_express_platform WHERE platid = :platid LIMIT 1',
|
||||
{
|
||||
replacements: { platid },
|
||||
type: this.ctx.app.model.QueryTypes.SELECT,
|
||||
}
|
||||
);
|
||||
|
||||
return Array.isArray(rows) && rows.length > 0 ? rows[0] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -139,17 +145,16 @@ class PoloApiClient {
|
||||
async request(options = {}) {
|
||||
const {
|
||||
method,
|
||||
platid,
|
||||
bizcontent = {},
|
||||
config = {},
|
||||
token,
|
||||
} = options;
|
||||
|
||||
let config = await this.getConfig(platid);
|
||||
if (!config) {
|
||||
// throw new Error('未找到 polyapi 配置');
|
||||
config = await this.getConfig(633);
|
||||
}
|
||||
|
||||
const signMap = this._buildSignMap(config, method, platid, bizcontent);
|
||||
const configWithToken = { ...config, token: token || config.token };
|
||||
const signMap = this._buildSignMap(configWithToken, method, config.platid, bizcontent);
|
||||
const signText = this._getSignText(signMap, config.app_secret);
|
||||
const sign = this._md5(signText.toLowerCase());
|
||||
const formBody = this._encodeForm({ ...signMap, sign });
|
||||
@ -162,10 +167,56 @@ class PoloApiClient {
|
||||
},
|
||||
content: formBody,
|
||||
});
|
||||
|
||||
return response && response.data !== undefined ? response.data : null;
|
||||
let result;
|
||||
if (Buffer.isBuffer(response.data)) {
|
||||
// 如果是 Buffer,转字符串再解析
|
||||
const str = response.data.toString('utf8');
|
||||
result = JSON.parse(str);
|
||||
} else if (typeof response.data === 'string') {
|
||||
result = JSON.parse(response.data);
|
||||
} else {
|
||||
result = response.data;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
async get(options = {}) {
|
||||
const {
|
||||
method,
|
||||
bizcontent = {},
|
||||
config = {},
|
||||
token,
|
||||
} = options;
|
||||
if (!config) {
|
||||
// throw new Error('未找到 polyapi 配置');
|
||||
config = await this.getConfig(633);
|
||||
}
|
||||
const configWithToken = { ...config, token: token || config.token };
|
||||
const signMap = this._buildSignMap(configWithToken, method, config.platid, bizcontent);
|
||||
const signText = this._getSignText(signMap, config.app_secret);
|
||||
const sign = this._md5(signText.toLowerCase());
|
||||
const formBody = this._encodeForm({ ...signMap, sign });
|
||||
const requestUrl = `http://39.98.7.126/OpenApi/Do?${formBody}`;
|
||||
|
||||
const response = await this.ctx.curl(requestUrl, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
|
||||
},
|
||||
});
|
||||
let result;
|
||||
if (Buffer.isBuffer(response.data)) {
|
||||
// 如果是 Buffer,转字符串再解析
|
||||
const str = response.data.toString('utf8');
|
||||
console.log("菠萝派平台接口响应原始数据",str)
|
||||
result = JSON.parse(str);
|
||||
} else if (typeof response.data === 'string') {
|
||||
result = JSON.parse(response.data);
|
||||
} else {
|
||||
result = response.data;
|
||||
}
|
||||
return result;
|
||||
|
||||
}
|
||||
// ── 内部方法 ──
|
||||
|
||||
/**
|
||||
|
||||
216
app/lib/qimen_client.js
Normal file
216
app/lib/qimen_client.js
Normal file
@ -0,0 +1,216 @@
|
||||
'use strict';
|
||||
|
||||
const https = require('https');
|
||||
const http = require('http');
|
||||
|
||||
class QimenClient {
|
||||
constructor(app) {
|
||||
this.app = app;
|
||||
}
|
||||
|
||||
resolveRuntime(runtime = {}) {
|
||||
const ctx = runtime.ctx || {};
|
||||
const qimenService = ctx.service && ctx.service.qimen ? ctx.service.qimen : null;
|
||||
const signService = ctx.service && ctx.service.systems && ctx.service.systems.sign ? ctx.service.systems.sign : null;
|
||||
|
||||
return {
|
||||
ctx,
|
||||
qimenLogId: runtime.qimenLogId ?? ctx.qimenLogId ?? null,
|
||||
toXml: runtime.toXml || (signService && typeof signService.toXml === 'function'
|
||||
? signService.toXml.bind(signService)
|
||||
: qimenService && typeof qimenService.formatResponse === 'function'
|
||||
? qimenService.formatResponse.bind(qimenService)
|
||||
: null),
|
||||
parseXmlToArray: runtime.parseXmlToArray || (qimenService && typeof qimenService.parseXmlToArray === 'function'
|
||||
? qimenService.parseXmlToArray.bind(qimenService)
|
||||
: null),
|
||||
saveQimenLog: runtime.saveQimenLog || (qimenService && typeof qimenService.saveQimenLog === 'function'
|
||||
? qimenService.saveQimenLog.bind(qimenService)
|
||||
: async () => null),
|
||||
signTopRequest: runtime.signTopRequest || (signService && typeof signService.signTopRequest === 'function'
|
||||
? signService.signTopRequest.bind(signService)
|
||||
: null),
|
||||
formatDate: runtime.formatDate || ctx.app?.formatDate || this.app.formatDate || (date => (date && typeof date.toISOString === 'function' ? date.toISOString() : String(date))),
|
||||
};
|
||||
}
|
||||
|
||||
normalizeRequestPayload(data) {
|
||||
if (!data || typeof data !== 'object' || Array.isArray(data)) {
|
||||
return { request: data };
|
||||
}
|
||||
|
||||
if (Object.prototype.hasOwnProperty.call(data, 'request')) {
|
||||
return data;
|
||||
}
|
||||
|
||||
return { request: data };
|
||||
}
|
||||
|
||||
replaceXmlTagsWithString(xmlString, oldTag, newTag) {
|
||||
const startTagRegex = new RegExp(`<\s*${oldTag}(\s+[^>]*)?>`, 'gi');
|
||||
const endTagRegex = new RegExp(`<\s*/\s*${oldTag}\s*>`, 'gi');
|
||||
const selfClosingRegex = new RegExp(`<\s*${oldTag}(\s+[^>]*)?\s*/>`, 'gi');
|
||||
|
||||
return xmlString
|
||||
.replace(startTagRegex, (match, attributes = '') => `<${newTag}${attributes}>`)
|
||||
.replace(endTagRegex, `</${newTag}>`)
|
||||
.replace(selfClosingRegex, (match, attributes = '') => `<${newTag}${attributes}/>`);
|
||||
}
|
||||
|
||||
addSign(baseQueryParams, sign) {
|
||||
return Object.assign({}, baseQueryParams, { sign });
|
||||
}
|
||||
|
||||
getQueryParams(method, appKey, version, customerId, formatDate) {
|
||||
return {
|
||||
method,
|
||||
format: 'xml',
|
||||
app_key: appKey,
|
||||
v: version,
|
||||
sign_method: 'md5',
|
||||
customerId,
|
||||
timestamp: formatDate(new Date()),
|
||||
};
|
||||
}
|
||||
|
||||
generateUrlWithParams(baseUrl, params) {
|
||||
if (!params || Object.keys(params).length === 0) {
|
||||
return baseUrl;
|
||||
}
|
||||
|
||||
const queryString = Object.keys(params)
|
||||
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
|
||||
.join('&');
|
||||
|
||||
const separator = baseUrl.includes('?') ? '&' : '?';
|
||||
return `${baseUrl}${separator}${queryString}`;
|
||||
}
|
||||
|
||||
async send(method, customerId, data, runtime = {}) {
|
||||
const helpers = this.resolveRuntime(runtime);
|
||||
|
||||
if (!helpers.toXml) {
|
||||
throw new Error('缺少奇门 XML 转换器');
|
||||
}
|
||||
|
||||
if (!helpers.parseXmlToArray) {
|
||||
throw new Error('缺少奇门响应解析器');
|
||||
}
|
||||
|
||||
if (!helpers.signTopRequest) {
|
||||
throw new Error('缺少奇门签名器');
|
||||
}
|
||||
|
||||
const wmsAppKey = this.app.config.qimen.appKey;
|
||||
const baseQueryParams = this.getQueryParams(method, wmsAppKey, '2.0', customerId, helpers.formatDate);
|
||||
const baseUrl = 'http://qimen.api.taobao.com/router/qimen/service';
|
||||
const requestPayload = this.normalizeRequestPayload(data);
|
||||
const xmlData = await helpers.toXml(requestPayload);
|
||||
const queryData = this.replaceXmlTagsWithString(xmlData, 'item', 'orderLine');
|
||||
const sign = await helpers.signTopRequest(baseQueryParams, queryData, this.app.config.qimen.security, 'md5');
|
||||
const queryParams = this.addSign(baseQueryParams, sign);
|
||||
const url = this.generateUrlWithParams(baseUrl, queryParams);
|
||||
const logData = {
|
||||
from_key: this.app.config.qimen.appKey,
|
||||
to_key: wmsAppKey,
|
||||
method,
|
||||
sign,
|
||||
costomer_id: customerId,
|
||||
v: '2.0',
|
||||
url,
|
||||
created_at: new Date(),
|
||||
body: '',
|
||||
result: '',
|
||||
use_time: 0,
|
||||
};
|
||||
const result = await this.sendRequest(url, queryData, logData, helpers);
|
||||
const xmlArray = await helpers.parseXmlToArray(result.res);
|
||||
return { queryId: result.queryId, xmlArray };
|
||||
}
|
||||
|
||||
async sendRequest(url, requestData, logData = {}, runtime = {}) {
|
||||
const helpers = this.resolveRuntime(runtime);
|
||||
const startTime = Date.now();
|
||||
const { ctx } = helpers;
|
||||
const requestLogData = Object.assign({
|
||||
body: requestData,
|
||||
result: '',
|
||||
log_id: helpers.qimenLogId,
|
||||
}, logData);
|
||||
|
||||
requestLogData.body = requestLogData.body || requestData;
|
||||
requestLogData.result = requestLogData.result || '';
|
||||
requestLogData.log_id = requestLogData.log_id || helpers.qimenLogId || null;
|
||||
|
||||
const httpquery = url.indexOf('https://') > -1 ? https : http;
|
||||
let requestXml;
|
||||
|
||||
try {
|
||||
if (typeof requestData === 'string') {
|
||||
requestXml = requestData;
|
||||
if (requestXml.trim() === '') {
|
||||
throw new Error('请求数据为空字符串');
|
||||
}
|
||||
} else {
|
||||
requestXml = await helpers.toXml(requestData);
|
||||
}
|
||||
|
||||
if (!requestXml || requestXml.trim() === '') {
|
||||
throw new Error('XML内容为空');
|
||||
}
|
||||
} catch (error) {
|
||||
requestLogData.result = error.stack || `${error.name || 'Error'}: ${error.message || String(error)}`;
|
||||
await helpers.saveQimenLog(requestLogData, startTime);
|
||||
throw error;
|
||||
}
|
||||
|
||||
const header = {
|
||||
'Content-Type': 'application/xml',
|
||||
'Content-Length': Buffer.byteLength(requestXml, 'utf8'),
|
||||
'User-Agent': 'EggJS Client',
|
||||
};
|
||||
|
||||
const options = {
|
||||
method: 'POST',
|
||||
headers: header,
|
||||
};
|
||||
|
||||
let res;
|
||||
try {
|
||||
res = await new Promise((resolve, reject) => {
|
||||
let req;
|
||||
try {
|
||||
req = httpquery.request(url, options, response => {
|
||||
let datas = '';
|
||||
response.on('data', chunk => {
|
||||
datas += chunk;
|
||||
});
|
||||
response.on('end', () => {
|
||||
resolve(datas);
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
|
||||
req.on('error', error => {
|
||||
reject(error);
|
||||
});
|
||||
|
||||
req.write(requestXml);
|
||||
req.end();
|
||||
});
|
||||
} catch (error) {
|
||||
requestLogData.result = error.stack || `${error.name || 'Error'}: ${error.message || String(error)}`;
|
||||
await helpers.saveQimenLog(requestLogData, startTime);
|
||||
throw error;
|
||||
}
|
||||
|
||||
requestLogData.result = res;
|
||||
const queryId = await helpers.saveQimenLog(requestLogData, startTime);
|
||||
return { queryId, res };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = QimenClient;
|
||||
@ -15,21 +15,29 @@ module.exports = app => {
|
||||
allowNull: true,
|
||||
comment: '快递名称',
|
||||
},
|
||||
polyapi_code: {
|
||||
KS: {
|
||||
type: STRING(255),
|
||||
field: 'KS',
|
||||
allowNull: true,
|
||||
comment: '聚合接口编码',
|
||||
comment: '快手编码',
|
||||
},
|
||||
polyapi_extra_info: {
|
||||
type: JSON,
|
||||
allowNull: true,
|
||||
comment: '聚合接口扩展信息',
|
||||
},
|
||||
pdd_code: {
|
||||
PDD: {
|
||||
field: 'PDD',
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '拼多多编码',
|
||||
},
|
||||
DYXD: {
|
||||
field: 'DYXD',
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '抖音编码',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_express',
|
||||
freezeTableName: true,
|
||||
|
||||
@ -18,24 +18,24 @@ module.exports = app => {
|
||||
},
|
||||
express_code: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
allowNull: false,
|
||||
comment: '快递编码',
|
||||
},
|
||||
platform_code: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: '平台编码',
|
||||
},
|
||||
sys_express_code: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: '系统快递编码',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '仓库编码',
|
||||
},
|
||||
platform_code: {
|
||||
type: STRING(20),
|
||||
allowNull: true,
|
||||
comment: '平台id',
|
||||
},
|
||||
express_platform_id: {
|
||||
type: INTEGER(11),
|
||||
allowNull: true,
|
||||
comment: '快递接口id',
|
||||
},
|
||||
sender_name: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
@ -108,11 +108,26 @@ module.exports = app => {
|
||||
allowNull: true,
|
||||
comment: '产品编码',
|
||||
},
|
||||
weight_type: {
|
||||
type: INTEGER(10),
|
||||
allowNull: true,
|
||||
comment: '重量类型',
|
||||
},
|
||||
shop_name: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '平台店铺',
|
||||
},
|
||||
address:{
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '地址',
|
||||
},
|
||||
town_name: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '寄件人街道',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_express_interface',
|
||||
freezeTableName: true,
|
||||
@ -128,5 +143,24 @@ module.exports = app => {
|
||||
],
|
||||
});
|
||||
|
||||
/**
|
||||
* 定义快递接口与系统快递的关联关系。
|
||||
*
|
||||
* 说明:`wms_express_interface.express_code` 对应 `wms_express.code`。
|
||||
*/
|
||||
ExpressInterface.associate = function() {
|
||||
const { Express } = app.model;
|
||||
|
||||
if (Express && typeof ExpressInterface.belongsTo === 'function') {
|
||||
ExpressInterface.belongsTo(Express, {
|
||||
foreignKey: 'express_code',
|
||||
targetKey: 'code',
|
||||
as: 'express',
|
||||
constraints: false,
|
||||
});
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
return ExpressInterface;
|
||||
};
|
||||
|
||||
@ -1,75 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { INTEGER, STRING } = app.Sequelize;
|
||||
|
||||
const ExpressPlatform = app.model.define('express_platform', {
|
||||
id: {
|
||||
type: INTEGER(10),
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '接口ID',
|
||||
},
|
||||
interface_url: {
|
||||
type: STRING(500),
|
||||
allowNull: false,
|
||||
comment: '外部接口URL',
|
||||
},
|
||||
platform_code: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: '平台代码,用于应用分流',
|
||||
},
|
||||
interface_name: {
|
||||
type: STRING(200),
|
||||
allowNull: false,
|
||||
comment: '接口名称',
|
||||
},
|
||||
platid: {
|
||||
type: STRING(20),
|
||||
allowNull: true,
|
||||
comment: '菠萝派平台id',
|
||||
},
|
||||
appkey: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '应用Key',
|
||||
},
|
||||
app_secret: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
field: 'app_secret',
|
||||
comment: '应用密钥',
|
||||
},
|
||||
token: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '访问令牌',
|
||||
},
|
||||
version: {
|
||||
type: STRING(20),
|
||||
allowNull: true,
|
||||
comment: '接口版本',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_express_platform',
|
||||
freezeTableName: true,
|
||||
underscored: true,
|
||||
timestamps: false,
|
||||
paranoid: false,
|
||||
comment: '快递外部接口配置表',
|
||||
indexes: [
|
||||
{
|
||||
name: 'idx_platform_code',
|
||||
fields: [ 'platform_code' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_interface_name',
|
||||
fields: [ 'interface_name' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return ExpressPlatform;
|
||||
};
|
||||
@ -1,7 +1,7 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { INTEGER, STRING, BIGINT } = app.Sequelize;
|
||||
const { INTEGER, STRING, BIGINT, DATE } = app.Sequelize;
|
||||
|
||||
const ExpressSetting = app.model.define('express_setting', {
|
||||
id: {
|
||||
@ -31,6 +31,11 @@ module.exports = app => {
|
||||
allowNull: false,
|
||||
comment: '仓库主体ID',
|
||||
},
|
||||
deleted_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '删除时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_express_setting',
|
||||
freezeTableName: true,
|
||||
@ -43,8 +48,8 @@ module.exports = app => {
|
||||
fields: [ 'express_code' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_warehouse_id',
|
||||
fields: [ 'warehouse_id' ],
|
||||
name: 'idx_warehouse_deleted_at',
|
||||
fields: [ 'warehouse_id', 'deleted_at' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
@ -39,6 +39,7 @@ module.exports = app => {
|
||||
Object.freeze({ code: 'all', name: '全部事件', business: 'all', description: '订阅后接收所有通知事件' }),
|
||||
Object.freeze({ code: '*', name: '全部事件(兼容别名)', business: 'all', description: '兼容旧配置,等价于 all' }),
|
||||
Object.freeze({ code: 'receiving_completed', name: '收货完成', business: 'receiving', description: '收货单完成后的通知' }),
|
||||
Object.freeze({ code: 'order_sync_completed', name: '订单同步完成', business: 'order', description: '本地创建入口同步完成后的通知' }),
|
||||
Object.freeze({ code: 'order_cancel_intercepted', name: '订单取消拦截', business: 'order', description: '订单取消失败并触发拦截执行后的通知' }),
|
||||
Object.freeze({
|
||||
code: 'store_warehouse_print_quantity_adjusted',
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { STRING, INTEGER, BIGINT, DATE, ENUM, JSON } = app.Sequelize;
|
||||
const { STRING, INTEGER, BIGINT, DATE, ENUM, JSON, TEXT } = app.Sequelize;
|
||||
|
||||
const OperationLog = app.model.define('operation_log', {
|
||||
id: {
|
||||
@ -69,6 +69,11 @@ module.exports = app => {
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间',
|
||||
},
|
||||
message: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '日志信息',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_operation_log', // 数据库中的实际表名
|
||||
timestamps: false, // 不使用默认的 createdAt 和 updatedAt
|
||||
|
||||
@ -6,25 +6,26 @@ module.exports = app => {
|
||||
|
||||
// 状态机枚举定义
|
||||
const StatusEnum = {
|
||||
STATUS: [ 'pedding', 'created', 'cancel', 'error' ],
|
||||
SYNC_STATUS: [ 'padding', 'fin', 'error' ],
|
||||
POST_STATUS: [ 'padding', 'fin', 'timeout', 'error', 'none' ],
|
||||
STORAGE_STATUS: [ 'padding', 'fin', 'error', 'none' ],
|
||||
PICK_STATUS: [ 'padding', 'fin', 'error', 'none' ],
|
||||
PACK_STATUS: [ 'none', 'padding', 'fin', 'error' ],
|
||||
INSPECTION_STATUS: [ 'none', 'padding', 'running', 'fin', 'error' ],
|
||||
PRINT_STATUS: [ 'none', 'padding', 'fin', 'error' ],
|
||||
CLAIM_STATUS: [ 'none', 'padding', 'fin', 'error' ],
|
||||
OUTBOUND_STATUS: [ 'none', 'padding', 'fin', 'timeout', 'error' ],
|
||||
LOCK_STATUS: [ 'none', 'warehouse', 'store' ],
|
||||
STATUS: ['pedding', 'created', 'cancel', 'error'],
|
||||
SYNC_STATUS: ['padding', 'fin', 'error'],
|
||||
POST_STATUS: ['padding', 'fin', 'timeout', 'error', 'none'],
|
||||
STORAGE_STATUS: ['padding', 'fin', 'error', 'none'],
|
||||
PICK_STATUS: ['padding', 'fin', 'error', 'none'],
|
||||
PACK_STATUS: ['none', 'padding', 'fin', 'error'],
|
||||
SENDED_STATUS: ['none', 'padding', 'fin', 'error'],
|
||||
INSPECTION_STATUS: ['none', 'padding', 'running', 'fin', 'error'],
|
||||
PRINT_STATUS: ['none', 'padding', 'fin', 'error'],
|
||||
CLAIM_STATUS: ['none', 'padding', 'fin', 'error'],
|
||||
OUTBOUND_STATUS: ['none', 'padding', 'fin', 'timeout', 'error'],
|
||||
LOCK_STATUS: ['none', 'warehouse', 'store'],
|
||||
INTERCEPT_STATUS: [
|
||||
'none', 'requesting', 'requested', 'intercepting',
|
||||
'intercepted_in_transit', 'intercepted_at_warehouse',
|
||||
'returning', 'returned', 'delivered_by_mistake',
|
||||
'timeout', 'cancelled', 'failed', 'exception',
|
||||
],
|
||||
URGENCY: [ 'Y', 'N' ],
|
||||
INVOICE: [ 'Y', 'N' ],
|
||||
URGENCY: ['Y', 'N'],
|
||||
INVOICE: ['Y', 'N'],
|
||||
};
|
||||
|
||||
// 基础模型定义
|
||||
@ -60,7 +61,7 @@ module.exports = app => {
|
||||
comment: '仓库编码',
|
||||
},
|
||||
order_flag: {
|
||||
type: STRING(200),
|
||||
type: TEXT('long'),
|
||||
allowNull: true,
|
||||
comment: '订单标记',
|
||||
},
|
||||
@ -74,6 +75,17 @@ module.exports = app => {
|
||||
allowNull: true,
|
||||
comment: '来源平台名称',
|
||||
},
|
||||
create_channel: {
|
||||
type: STRING(20),
|
||||
allowNull: false,
|
||||
defaultValue: 'MANUAL',
|
||||
comment: '创建来源渠道',
|
||||
},
|
||||
source_order_codes: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '来源订单号集合',
|
||||
},
|
||||
sys_platform_code: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
@ -219,6 +231,12 @@ module.exports = app => {
|
||||
allowNull: true,
|
||||
comment: '发货服务类型',
|
||||
},
|
||||
weight_type: {
|
||||
type: INTEGER(11),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '重量类型:0常规、1轻货、2重货、3冷链',
|
||||
},
|
||||
is_urgency: {
|
||||
type: ENUM(...StatusEnum.URGENCY),
|
||||
allowNull: true,
|
||||
@ -288,7 +306,7 @@ module.exports = app => {
|
||||
comment: '镇',
|
||||
},
|
||||
detail_address: {
|
||||
type: STRING(255),
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '详细地址',
|
||||
},
|
||||
@ -394,6 +412,12 @@ module.exports = app => {
|
||||
defaultValue: 'none',
|
||||
comment: '打包状态机',
|
||||
},
|
||||
sended_status: {
|
||||
type: ENUM(...StatusEnum.SENDED_STATUS),
|
||||
allowNull: true,
|
||||
defaultValue: 'none',
|
||||
comment: '发货状态机',
|
||||
},
|
||||
inspection_status: {
|
||||
type: ENUM(...StatusEnum.INSPECTION_STATUS),
|
||||
allowNull: true,
|
||||
@ -446,16 +470,16 @@ module.exports = app => {
|
||||
indexes: [
|
||||
{
|
||||
name: 'idx_current_store_id',
|
||||
fields: [ 'store_id' ],
|
||||
fields: ['store_id'],
|
||||
},
|
||||
{
|
||||
name: 'idx_current_warehouse_id',
|
||||
fields: [ 'warehouse_id' ],
|
||||
fields: ['warehouse_id'],
|
||||
},
|
||||
{
|
||||
name: 'idx_current_delivery_code',
|
||||
unique: true,
|
||||
fields: [ 'delivery_order_code', 'store_id', 'warehouse_id' ],
|
||||
fields: ['delivery_order_code', 'store_id', 'warehouse_id'],
|
||||
},
|
||||
{
|
||||
name: 'idx_items',
|
||||
@ -463,15 +487,15 @@ module.exports = app => {
|
||||
},
|
||||
{
|
||||
name: 'idx_items_hash',
|
||||
fields: [ 'items_hash' ],
|
||||
fields: ['items_hash'],
|
||||
},
|
||||
{
|
||||
name: 'idx_hash_crc',
|
||||
fields: [ 'items_hash', 'items_crc', 'warehouse_id' ],
|
||||
fields: ['items_hash', 'items_crc', 'warehouse_id'],
|
||||
},
|
||||
{
|
||||
name: 'wave_id',
|
||||
fields: [ 'status', 'wave_id' ],
|
||||
fields: ['status', 'wave_id'],
|
||||
},
|
||||
// 状态机索引
|
||||
{
|
||||
|
||||
@ -245,7 +245,6 @@ module.exports = app => {
|
||||
|
||||
try {
|
||||
const DynamicModel = this.buildManagedModel(warehouseIdStr, modelType, tableName);
|
||||
|
||||
await this.ensureManagedTableSchema(tableName, modelType, warehouseIdStr, DynamicModel);
|
||||
|
||||
// 设置关联关系
|
||||
@ -335,7 +334,7 @@ module.exports = app => {
|
||||
*/
|
||||
async getDispatchTableName(warehouseId) {
|
||||
const warehouseIdStr = await ensureShardWarehouseId(this.app, warehouseId);
|
||||
return `wms_order_delivery_dispatch_${warehouseIdStr}`;
|
||||
return `wms_order_delivery_${warehouseIdStr}_dispatch`;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -616,6 +615,7 @@ module.exports = app => {
|
||||
* @param {Object} [DynamicModel] 已构建的动态模型。
|
||||
* @return {Promise<boolean>} 是否执行了同步。
|
||||
*/
|
||||
|
||||
async ensureManagedTableSchema(tableName, type, warehouseId, DynamicModel = null) {
|
||||
const modelType = this.resolveModelType(type);
|
||||
const dynamicModel = DynamicModel || this.buildManagedModel(warehouseId, modelType, tableName);
|
||||
@ -636,23 +636,6 @@ module.exports = app => {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 扫描并同步订单工厂管理的目标表。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async ensureManagedTableSchemas() {
|
||||
const tableNames = await this.listManagedTableNames();
|
||||
|
||||
for (const tableName of tableNames) {
|
||||
const parsed = parseManagedTableName(tableName);
|
||||
if (!parsed) {
|
||||
continue;
|
||||
}
|
||||
|
||||
await this.ensureManagedTableSchema(tableName, parsed.type, parsed.warehouseId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前库中已存在的订单工厂目标表。
|
||||
* @return {Promise<Array<string>>} 目标表名列表。
|
||||
|
||||
@ -10,7 +10,7 @@ const MANAGED_TYPES = Object.freeze({
|
||||
const TABLE_PATTERNS = Object.freeze([
|
||||
{
|
||||
type: MANAGED_TYPES.DISPATCH,
|
||||
pattern: /^wms_order_delivery_dispatch_(\d+)$/,
|
||||
pattern: /^wms_order_delivery_(\d+)_dispatch$/,
|
||||
},
|
||||
{
|
||||
type: MANAGED_TYPES.HISTORY,
|
||||
@ -307,7 +307,7 @@ function buildTableName(warehouseId, type) {
|
||||
const modelType = normalizeManagedType(type);
|
||||
|
||||
if (isDispatchType(modelType)) {
|
||||
return `wms_order_delivery_dispatch_${warehouseId}`;
|
||||
return `wms_order_delivery_${warehouseId}_dispatch`;
|
||||
}
|
||||
|
||||
if (isOutsourcedType(modelType)) {
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, DATE, ENUM, INTEGER, TINYINT } = app.Sequelize;
|
||||
const { BIGINT, STRING, DATE, ENUM, INTEGER, TINYINT, TEXT } = app.Sequelize;
|
||||
|
||||
const OrderExpress = app.model.define('order_express', {
|
||||
id: {
|
||||
@ -87,6 +87,31 @@ module.exports = app => {
|
||||
allowNull: true,
|
||||
comment: '重试次数',
|
||||
},
|
||||
printinfo: {
|
||||
type: TEXT('long'),
|
||||
allowNull: true,
|
||||
comment: '打印信息',
|
||||
},
|
||||
signature: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '签名信息',
|
||||
},
|
||||
encryptprintinfo: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '加密打印信息',
|
||||
},
|
||||
encryptedtoken:{
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '加密令牌',
|
||||
},
|
||||
warehouse_id:{
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '仓库ID',
|
||||
}
|
||||
}, {
|
||||
tableName: 'wms_order_express',
|
||||
freezeTableName: true,
|
||||
|
||||
@ -185,7 +185,7 @@ module.exports = app => {
|
||||
try {
|
||||
const DynamicModel = this.buildDynamicModel(warehouseId, type, tableName);
|
||||
|
||||
await this.ensureManagedTableSchema(tableName, type, warehouseId, DynamicModel);
|
||||
// await this.ensureManagedTableSchema(tableName, type, warehouseId, DynamicModel);
|
||||
|
||||
// 复制关联关系
|
||||
this.copyAssociations(this.app.model.OrderItems, DynamicModel);
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { STRING } = app.Sequelize;
|
||||
const { STRING, INTEGER } = app.Sequelize;
|
||||
|
||||
const Platform = app.model.define('platform', {
|
||||
code: {
|
||||
@ -12,14 +12,54 @@ module.exports = app => {
|
||||
},
|
||||
name: {
|
||||
type: STRING(255),
|
||||
allowNull: false,
|
||||
allowNull: true,
|
||||
comment: '平台名称',
|
||||
},
|
||||
default_express_interface: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: '默认快递接口',
|
||||
interface_url: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '接口地址',
|
||||
},
|
||||
platform_code: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '平台编码',
|
||||
},
|
||||
platid: {
|
||||
type: INTEGER(11),
|
||||
allowNull: true,
|
||||
comment: '平台ID',
|
||||
},
|
||||
appkey: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '应用Key',
|
||||
},
|
||||
app_secret: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '应用密钥',
|
||||
},
|
||||
token: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '访问令牌',
|
||||
},
|
||||
version: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '接口版本',
|
||||
},
|
||||
shoptype: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '店铺类型',
|
||||
},
|
||||
ordersource:{
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '订单来源',
|
||||
}
|
||||
}, {
|
||||
tableName: 'wms_platform',
|
||||
freezeTableName: true,
|
||||
@ -28,8 +68,5 @@ module.exports = app => {
|
||||
comment: '平台表',
|
||||
});
|
||||
|
||||
// 移除 associate 方法,稍后在单独的初始化文件中定义关联
|
||||
// 或者在控制器中动态定义关联
|
||||
|
||||
return Platform;
|
||||
};
|
||||
|
||||
@ -57,6 +57,16 @@ module.exports = app => {
|
||||
required: false,
|
||||
description: '是否允许该货主在当前仓库下锁定超过可用库存',
|
||||
}),
|
||||
Object.freeze({
|
||||
key: 'express_quota',
|
||||
name: '快递号额度',
|
||||
type: 'integer',
|
||||
default: 0,
|
||||
required: false,
|
||||
description: '允许在快递余额之外额外分配的快递号数量',
|
||||
min: 0,
|
||||
max: 1000000,
|
||||
}),
|
||||
Object.freeze({
|
||||
key: 'need_order_approval',
|
||||
name: '推送订单需审批',
|
||||
@ -112,6 +122,86 @@ module.exports = app => {
|
||||
description: '补充说明该货主在仓库内的特殊约束',
|
||||
maxLength: 200,
|
||||
}),
|
||||
Object.freeze({
|
||||
key: 'use_store_sender_info',
|
||||
name: '是否使用货主发货信息',
|
||||
type: 'flag',
|
||||
default: 1,
|
||||
required: false,
|
||||
description: '控制面单分配时是否优先使用货主在当前仓下配置的发件信息',
|
||||
}),
|
||||
Object.freeze({
|
||||
key: 'shop_name',
|
||||
name: '店铺名称',
|
||||
type: 'string',
|
||||
default: '',
|
||||
required: false,
|
||||
description: '货主在当前仓下的店铺名称',
|
||||
maxLength: 100,
|
||||
}),
|
||||
Object.freeze({
|
||||
key: 'sender_name',
|
||||
name: '发件人姓名',
|
||||
type: 'string',
|
||||
default: '',
|
||||
required: false,
|
||||
description: '货主在当前仓下的默认发件人姓名',
|
||||
maxLength: 50,
|
||||
}),
|
||||
Object.freeze({
|
||||
key: 'sender_tel',
|
||||
name: '发件人电话',
|
||||
type: 'string',
|
||||
default: '',
|
||||
required: false,
|
||||
description: '货主在当前仓下的默认发件人联系电话',
|
||||
maxLength: 20,
|
||||
}),
|
||||
Object.freeze({
|
||||
key: 'province_name',
|
||||
name: '省份',
|
||||
type: 'string',
|
||||
default: '',
|
||||
required: false,
|
||||
description: '货主在当前仓下的发件省份',
|
||||
maxLength: 50,
|
||||
}),
|
||||
Object.freeze({
|
||||
key: 'city_name',
|
||||
name: '城市',
|
||||
type: 'string',
|
||||
default: '',
|
||||
required: false,
|
||||
description: '货主在当前仓下的发件城市',
|
||||
maxLength: 50,
|
||||
}),
|
||||
Object.freeze({
|
||||
key: 'district_name',
|
||||
name: '区/县',
|
||||
type: 'string',
|
||||
default: '',
|
||||
required: false,
|
||||
description: '货主在当前仓下的发件区/县',
|
||||
maxLength: 50,
|
||||
}),
|
||||
Object.freeze({
|
||||
key: 'town_name',
|
||||
name: '镇/街道',
|
||||
type: 'string',
|
||||
default: '',
|
||||
required: false,
|
||||
description: '货主在当前仓下的发件镇/街道',
|
||||
maxLength: 50,
|
||||
}),
|
||||
Object.freeze({
|
||||
key: 'address',
|
||||
name: '详细地址',
|
||||
type: 'string',
|
||||
default: '',
|
||||
required: false,
|
||||
description: '货主在当前仓下的发件详细地址',
|
||||
maxLength: 200,
|
||||
}),
|
||||
]);
|
||||
const POLICY_CONFIG_FIELD_MAP = Object.freeze(POLICY_CONFIG_FIELDS.reduce((result, field) => {
|
||||
result[field.key] = field;
|
||||
@ -356,10 +446,15 @@ module.exports = app => {
|
||||
comment: '申请时间',
|
||||
},
|
||||
print_quantity: {
|
||||
type: BIGINT(12),
|
||||
type: INTEGER(11),
|
||||
allowNull: false,
|
||||
comment: '面单余额',
|
||||
},
|
||||
print_quantity_locked: {
|
||||
type: INTEGER(11),
|
||||
allowNull: false,
|
||||
comment: '面单锁定余额',
|
||||
},
|
||||
review_time: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, TEXT, DATE } = app.Sequelize;
|
||||
const { BIGINT, STRING, TEXT, DATE, INTEGER } = app.Sequelize;
|
||||
|
||||
const StoreWarehousePrintQuantityLog = app.model.define('store_warehouse_print_quantity_log', {
|
||||
id: {
|
||||
@ -59,12 +59,17 @@ module.exports = app => {
|
||||
comment: '本次变更数量,整数,可正可负',
|
||||
},
|
||||
balance_before: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
type: INTEGER(11),
|
||||
allowNull: false,
|
||||
comment: '本次变更数量,整数,可正可负',
|
||||
},
|
||||
balance_before: {
|
||||
type: INTEGER(11),
|
||||
allowNull: false,
|
||||
comment: '变更前余额',
|
||||
},
|
||||
balance_after: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
type: INTEGER(11),
|
||||
allowNull: false,
|
||||
comment: '变更后余额',
|
||||
},
|
||||
|
||||
@ -24,6 +24,9 @@ module.exports = app => {
|
||||
router.get('/api/docs/:docName/changes', controller.docs.changes);
|
||||
router.get('/api/docs/:docName', controller.docs.detail);
|
||||
|
||||
// OpenAPI 入口
|
||||
router.post('/openapi', controller.openapi.index);
|
||||
|
||||
// 打印模板
|
||||
router.get('/template/xml/:id', controller.template.xml);
|
||||
|
||||
|
||||
@ -31,7 +31,9 @@ class testServer extends Service {
|
||||
},
|
||||
});
|
||||
if (entryOrder) {
|
||||
const body = await this.ctx.service.systems.qimenQuery.sendRequest(entryOrder.url, entryOrder.body);
|
||||
const body = await this.app.qimenClient.sendRequest(entryOrder.url, entryOrder.body, {}, {
|
||||
ctx: this.ctx,
|
||||
});
|
||||
return { body };
|
||||
}
|
||||
throw new Error('无历史请求数据');
|
||||
|
||||
238
app/service/openapi.js
Normal file
238
app/service/openapi.js
Normal file
@ -0,0 +1,238 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
|
||||
class OpenapiService extends Service {
|
||||
/**
|
||||
* 解析 openapi method,拆分为服务路径与动作名。
|
||||
* @param {string} methodName method 名称。
|
||||
* @return {{ servicePath: string, actionName: string }} 解析结果。
|
||||
*/
|
||||
resolveOpenapiMethod(methodName = '') {
|
||||
const method = String(methodName || '').trim();
|
||||
const parts = method.split('.').filter(Boolean);
|
||||
const actionName = parts.pop() || '';
|
||||
const servicePath = parts.join('.');
|
||||
|
||||
return {
|
||||
servicePath,
|
||||
actionName,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据服务路径查找 openapiMethods 下的目标服务。
|
||||
* @param {string} servicePath 服务路径。
|
||||
* @return {Object|null} 目标服务实例。
|
||||
*/
|
||||
getOpenapiMethodService(servicePath = '') {
|
||||
const { ctx } = this;
|
||||
const pathSegments = String(servicePath || '').split('.').filter(Boolean);
|
||||
let methodService = ctx.service.openapiMethods;
|
||||
|
||||
if (pathSegments.length === 0) {
|
||||
return methodService;
|
||||
}
|
||||
|
||||
for (const segment of pathSegments) {
|
||||
methodService = methodService && methodService[segment];
|
||||
}
|
||||
|
||||
return methodService || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分发 openapi method 到 openapiMethods 目录。
|
||||
* @param {string} methodName method 名称。
|
||||
* @param {Object} body 请求体。
|
||||
* @param {Object} query 请求 query。
|
||||
* @return {Promise<Object>} method 执行结果。
|
||||
*/
|
||||
async dispatchOpenapiMethod(methodName, body, query) {
|
||||
const { servicePath, actionName } = this.resolveOpenapiMethod(methodName);
|
||||
const methodService = this.getOpenapiMethodService(servicePath);
|
||||
|
||||
if (!methodService || typeof methodService[actionName] !== 'function') {
|
||||
return {
|
||||
ok: false,
|
||||
httpStatus: 400,
|
||||
code: 400,
|
||||
message: `openapi method 不存在: ${methodName}`,
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
|
||||
const methodResult = await methodService[actionName]({
|
||||
body,
|
||||
query,
|
||||
});
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
httpStatus: 200,
|
||||
code: 1,
|
||||
message: 'ok',
|
||||
data: methodResult,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验 openapi 基础 query 参数,仅校验 method/v/timestamp。
|
||||
* @param {Object} query 请求 query 参数。
|
||||
* @return {boolean} 是否通过基础参数校验。
|
||||
*/
|
||||
validateOpenapiParams(query) {
|
||||
const requiredFields = [ 'method', 'v', 'timestamp' ];
|
||||
for (const field of requiredFields) {
|
||||
if (!query || !query[field]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof query.method !== 'string' || !query.method.includes('.')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取并解析 JSON 请求体,采用 rawBody 优先策略。
|
||||
* @return {Promise<Object>} 解析后的 JSON 对象。
|
||||
*/
|
||||
async parseJsonBody() {
|
||||
const { ctx } = this;
|
||||
let jsonData = '';
|
||||
|
||||
if (ctx.request.rawBody) {
|
||||
jsonData = ctx.request.rawBody;
|
||||
} else if (ctx.request.body !== undefined) {
|
||||
jsonData = typeof ctx.request.body === 'string'
|
||||
? ctx.request.body
|
||||
: JSON.stringify(ctx.request.body);
|
||||
} else {
|
||||
jsonData = await new Promise((resolve, reject) => {
|
||||
let data = '';
|
||||
ctx.req.on('data', chunk => {
|
||||
data += chunk;
|
||||
});
|
||||
ctx.req.on('end', () => {
|
||||
resolve(data);
|
||||
});
|
||||
ctx.req.on('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
jsonData = jsonData ? String(jsonData) : '';
|
||||
if (!jsonData || jsonData.trim() === '') {
|
||||
return {
|
||||
ok: false,
|
||||
httpStatus: 400,
|
||||
code: 400,
|
||||
message: 'json数据为空',
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(jsonData);
|
||||
} catch (error) {
|
||||
return {
|
||||
ok: false,
|
||||
httpStatus: 400,
|
||||
code: 400,
|
||||
message: 'json数据解析错误',
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取并归一化 openapi 所需的 appKey 与 sign。
|
||||
* @param {Object} query 请求 query 参数。
|
||||
* @return {{ appKey: string, providedSign: string }} 归一化后的关键信息。
|
||||
*/
|
||||
normalizeSignFields(query = {}) {
|
||||
const appKey = String(query.app_key || query.appkey || query.self_app_key || '').trim();
|
||||
const providedSign = String(query.sign || query.signature || '').trim();
|
||||
|
||||
return {
|
||||
appKey,
|
||||
providedSign,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理 openapi 请求并返回统一结果。
|
||||
* @return {Promise<Object>} 统一结果对象。
|
||||
*/
|
||||
async processRequest() {
|
||||
const { ctx } = this;
|
||||
const query = ctx.query || {};
|
||||
|
||||
if (!this.validateOpenapiParams(query)) {
|
||||
return {
|
||||
ok: false,
|
||||
httpStatus: 400,
|
||||
code: 400,
|
||||
message: '参数缺失或错误: method/v/timestamp',
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
|
||||
const body = await this.parseJsonBody();
|
||||
if (body && body.ok === false) {
|
||||
return body;
|
||||
}
|
||||
|
||||
const { appKey, providedSign } = this.normalizeSignFields(query);
|
||||
if (!appKey) {
|
||||
return {
|
||||
ok: false,
|
||||
httpStatus: 400,
|
||||
code: 400,
|
||||
message: '参数缺失或错误: app_key',
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
|
||||
const { systems: systemsService } = ctx.service;
|
||||
const apiSignService = systemsService.apiSign;
|
||||
let appConfig;
|
||||
try {
|
||||
appConfig = await apiSignService.getApiAppSecretByAppKey(appKey);
|
||||
} catch (error) {
|
||||
return {
|
||||
ok: false,
|
||||
httpStatus: 401,
|
||||
code: 401,
|
||||
message: `app_key 校验失败: ${error.message}`,
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
|
||||
const verifyResult = await apiSignService.verifyRequestSignByAppKey({
|
||||
appKey,
|
||||
query,
|
||||
body,
|
||||
providedSign,
|
||||
});
|
||||
|
||||
if (!verifyResult.ok) {
|
||||
return {
|
||||
ok: false,
|
||||
httpStatus: 401,
|
||||
code: 401,
|
||||
message: `签名校验失败: ${verifyResult.message}`,
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
|
||||
return await this.dispatchOpenapiMethod(query.method, body, {
|
||||
...query,
|
||||
app_key: appConfig.appKey,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = OpenapiService;
|
||||
35
app/service/openapiMethods/index.js
Normal file
35
app/service/openapiMethods/index.js
Normal file
@ -0,0 +1,35 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
|
||||
class OpenapiMethodsIndexService extends Service {
|
||||
/**
|
||||
* openapi index.ping 健康探活方法。
|
||||
* @param {Object} payload 调用参数。
|
||||
* @param {Object} payload.query 请求 query 数据。
|
||||
* @return {Promise<Object>} 探活结果。
|
||||
*/
|
||||
async ping(payload = {}) {
|
||||
const { query = {} } = payload;
|
||||
return {
|
||||
pong: true,
|
||||
method: query.method || 'index.ping',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* openapiMethods 入口健康检查。
|
||||
* @param {Object} payload 调用参数。
|
||||
* @return {Promise<Object>} 健康检查结果。
|
||||
*/
|
||||
async health(payload = {}) {
|
||||
const { query = {} } = payload;
|
||||
return {
|
||||
module: 'openapiMethods',
|
||||
status: 'ok',
|
||||
method: query.method || '',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = OpenapiMethodsIndexService;
|
||||
23
app/service/openapiMethods/ping.js
Normal file
23
app/service/openapiMethods/ping.js
Normal file
@ -0,0 +1,23 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
|
||||
class OpenapiMethodsPingService extends Service {
|
||||
/**
|
||||
* openapi ping 示例方法,回显请求体。
|
||||
* @param {Object} payload 调用参数。
|
||||
* @param {Object} payload.body 请求体数据。
|
||||
* @param {Object} payload.query 请求 query 数据。
|
||||
* @return {Promise<Object>} 回显结果。
|
||||
*/
|
||||
async echo(payload = {}) {
|
||||
const { body = {}, query = {} } = payload;
|
||||
return {
|
||||
pong: true,
|
||||
method: query.method || '',
|
||||
body,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = OpenapiMethodsPingService;
|
||||
@ -417,9 +417,18 @@ class indexService extends MainService {
|
||||
});
|
||||
return this.success('ok', { list, total: list.length, code: 200 });
|
||||
}
|
||||
async getExpressList() {
|
||||
/**
|
||||
* 获取快递列表。
|
||||
*
|
||||
* @param {Object} data 请求参数
|
||||
* @param {boolean} [data.systemOnly] 是否仅返回系统基础快递列表
|
||||
* @return {Promise<Object>} 返回结果
|
||||
*/
|
||||
async getExpressList(data) {
|
||||
const { service } = this;
|
||||
const result = await service.systems.express.getExpressList();
|
||||
const { systemOnly } = data || {};
|
||||
const isSystemOnly = [ true, 1, '1', 'true' ].includes(systemOnly);
|
||||
const result = await service.systems.express.getExpressList(isSystemOnly);
|
||||
return this.success('ok', { data: result, code: 200 });
|
||||
}
|
||||
|
||||
@ -437,9 +446,20 @@ class indexService extends MainService {
|
||||
return this.success('ok', { data: result, code: 200 });
|
||||
}
|
||||
|
||||
async getPlatformList() {
|
||||
/**
|
||||
* 获取平台列表。
|
||||
*
|
||||
* @param {Object} data 请求参数
|
||||
* @param {boolean} [data.systemOnly] 是否仅返回系统基础平台列表
|
||||
* @param {boolean} [data.full] 是否返回全量字段
|
||||
* @return {Promise<Object>} 返回结果
|
||||
*/
|
||||
async getPlatformList(data) {
|
||||
const { service } = this;
|
||||
const result = await service.systems.platform.getPlatformList();
|
||||
const { systemOnly, full } = data || {};
|
||||
const isSystemOnly = [ true, 1, '1', 'true' ].includes(systemOnly);
|
||||
const isFull = [ true, 1, '1', 'true' ].includes(full);
|
||||
const result = await service.systems.platform.getPlatformList(isSystemOnly, isFull);
|
||||
return this.success('ok', { data: result, code: 200 });
|
||||
}
|
||||
}
|
||||
|
||||
@ -18,6 +18,37 @@ const REVIEW_STATUS_STEP_MAP = Object.freeze({
|
||||
|
||||
const REVIEW_ORDER_ALLOWED_FIELDS = Object.freeze([ 'ids' ]);
|
||||
const BADGE_COUNT_OVER_LIMIT_VALUE = '99+';
|
||||
|
||||
const ORDER_LIST_BASE_ATTRIBUTES = Object.freeze([
|
||||
'id', 'delivery_order_code', 'pre_delivery_order_code', 'pre_delivery_order_id',
|
||||
'order_type', 'order_flag','source_order_codes',
|
||||
'sys_platform_code', 'sys_platform_name',
|
||||
'create_at',
|
||||
'place_order_time', 'pay_time', 'pay_no', 'service_code',
|
||||
'operator_name', 'operate_time', 'delivery_time',
|
||||
'shop_nick', 'seller_nick', 'buyer_nick',
|
||||
'total_amount', 'item_amount', 'discount_amount', 'freight',
|
||||
'ar_amount', 'got_amount', 'service_fee',
|
||||
'logistics_name',
|
||||
'delivery_type', 'weight_type',
|
||||
'is_urgency', 'invoice_flag', 'status',
|
||||
'name', 'zip_code', 'tel', 'mobile', 'email',
|
||||
'province', 'city', 'area', 'town', 'detail_address',
|
||||
'id_type', 'id_number',
|
||||
'sync_status',
|
||||
'items', 'items_count', 'items_total', 'items_weight',
|
||||
'wave_id',
|
||||
'post_status', 'storage_status', 'pick_status', 'pack_status',
|
||||
'inspection_status', 'print_status', 'claim_status',
|
||||
'outbound_status', 'lock_status', 'intercept_status',
|
||||
]);
|
||||
|
||||
const ORDER_WEIGHT_TYPE_LABELS = Object.freeze({
|
||||
0: '常规',
|
||||
1: '轻货',
|
||||
2: '重货',
|
||||
3: '冷链',
|
||||
});
|
||||
const ORDER_TABLE_TYPE_ALIASES = Object.freeze({
|
||||
current: 'current',
|
||||
history: 'history',
|
||||
@ -57,7 +88,7 @@ const MODULE_CONFIGS = Object.freeze({
|
||||
},
|
||||
step: {
|
||||
operator: 'in',
|
||||
value: [ 1, 2 ],
|
||||
value: [ 1, 2, 3 ],
|
||||
},
|
||||
},
|
||||
},
|
||||
@ -66,11 +97,11 @@ const MODULE_CONFIGS = Object.freeze({
|
||||
defaultWhere: {
|
||||
outbound_status: {
|
||||
operator: 'in',
|
||||
value: [ 'none', 'padding' ],
|
||||
value: [ 'fin', 'padding' ],
|
||||
},
|
||||
step: {
|
||||
operator: 'in',
|
||||
value: [ 1, 2 ],
|
||||
value: [ 4, 9 ],
|
||||
},
|
||||
},
|
||||
},
|
||||
@ -323,6 +354,49 @@ class OrderBaseService extends MainService {
|
||||
return normalizedCount > 99 ? BADGE_COUNT_OVER_LIMIT_VALUE : normalizedCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将订单重量类型转换为中文展示值。
|
||||
* @param {number|string} weightType 重量类型值。
|
||||
* @return {string} 中文重量类型。
|
||||
*/
|
||||
formatWeightTypeLabel(weightType) {
|
||||
if (typeof weightType === 'string') {
|
||||
const trimmedWeightType = weightType.trim();
|
||||
|
||||
if (!trimmedWeightType) {
|
||||
return ORDER_WEIGHT_TYPE_LABELS[0];
|
||||
}
|
||||
|
||||
if (Object.values(ORDER_WEIGHT_TYPE_LABELS).includes(trimmedWeightType)) {
|
||||
return trimmedWeightType;
|
||||
}
|
||||
}
|
||||
|
||||
const normalizedWeightType = Number(weightType);
|
||||
if (Number.isInteger(normalizedWeightType)
|
||||
&& Object.prototype.hasOwnProperty.call(ORDER_WEIGHT_TYPE_LABELS, normalizedWeightType)) {
|
||||
return ORDER_WEIGHT_TYPE_LABELS[normalizedWeightType];
|
||||
}
|
||||
|
||||
return ORDER_WEIGHT_TYPE_LABELS[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范订单列表单行输出,保证重量类型直接返回中文。
|
||||
* @param {Object} order 订单列表行数据。
|
||||
* @return {Object} 规范后的订单列表行数据。
|
||||
*/
|
||||
normalizeOrderListItem(order = {}) {
|
||||
if (!this.isPlainObject(order)) {
|
||||
return order;
|
||||
}
|
||||
|
||||
return {
|
||||
...order,
|
||||
weight_type: this.formatWeightTypeLabel(order.weight_type),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定模块的角标展示值。
|
||||
* @param {string} moduleName 模块名称。
|
||||
@ -738,11 +812,16 @@ class OrderBaseService extends MainService {
|
||||
const model = await this.getOrderModel(moduleName, contextWarehouseId);
|
||||
const order = this.buildListOrder(requestData.sort, moduleName);
|
||||
const offset = (page - 1) * pageSize;
|
||||
const moduleConfig = this.getModuleConfig(moduleName);
|
||||
const listAttributes = moduleConfig.modelType === 'history'
|
||||
? [ ...ORDER_LIST_BASE_ATTRIBUTES, 'archive_time' ]
|
||||
: [ ...ORDER_LIST_BASE_ATTRIBUTES ];
|
||||
|
||||
const [ total, list ] = await Promise.all([
|
||||
model.count({ where: queryWhere }),
|
||||
model.findAll({
|
||||
where: queryWhere,
|
||||
attributes: listAttributes,
|
||||
limit: pageSize,
|
||||
offset,
|
||||
order,
|
||||
@ -750,7 +829,9 @@ class OrderBaseService extends MainService {
|
||||
}),
|
||||
]);
|
||||
|
||||
const normalizedList = await this.attachOrderExpressNumbers(list);
|
||||
const normalizedList = await this.attachOrderExpressNumbers(
|
||||
list.map(order => this.normalizeOrderListItem(order))
|
||||
);
|
||||
|
||||
const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0;
|
||||
|
||||
|
||||
@ -6,9 +6,9 @@ class ExpectionOrderService extends OrderBaseService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'list,expectionOrder';
|
||||
const _noNeedRight = 'list,expectionOrder,resolveException';
|
||||
const _noNeedLog = 'list';
|
||||
const _noNeedAuth = 'list,expectionOrder';
|
||||
const _noNeedAuth = 'list,expectionOrder,resolveException';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
@ -21,6 +21,70 @@ class ExpectionOrderService extends OrderBaseService {
|
||||
return await this.listByModule('expectionOrder', data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将待处理异常订单转回正常待处理状态(step 3 -> 2)。
|
||||
*
|
||||
* 只操作当前仓库的当前订单表,且仅允许 step=3 的订单转出。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {number[]} data.ids 订单ID 数组。
|
||||
* @return {Promise<Object>} 统一 success 包装的更新结果。
|
||||
*/
|
||||
async resolveException(data = {}) {
|
||||
const requestData = this.isPlainObject(data) ? data : {};
|
||||
const warehouseId = this.getWarehouseId();
|
||||
|
||||
if (!Array.isArray(requestData.ids) || requestData.ids.length === 0) {
|
||||
throw new Error('ids 不能为空');
|
||||
}
|
||||
|
||||
const orderIds = Array.from(new Set(requestData.ids.map(v => {
|
||||
const n = Number(v);
|
||||
if (!Number.isInteger(n) || n <= 0) {
|
||||
throw new Error('ids 仅支持正整数数组');
|
||||
}
|
||||
return n;
|
||||
})));
|
||||
|
||||
const model = await this.getOrderModel('order', warehouseId);
|
||||
const where = this.buildOrderWhere(orderIds, warehouseId);
|
||||
where.step = 3;
|
||||
|
||||
const [ affectedRows ] = await model.update({
|
||||
step: 2,
|
||||
updated_at: new Date(),
|
||||
}, { where });
|
||||
|
||||
const count = Number(affectedRows || 0);
|
||||
|
||||
// 记录操作日志
|
||||
try {
|
||||
await this.ctx.service.systems.operationLog.createOperationLog({
|
||||
businessType: 'order',
|
||||
businessId: warehouseId,
|
||||
operationCode: 'ORDER_RESOLVE_EXCEPTION',
|
||||
operator: {
|
||||
id: this.ctx.user?.employees_id || this.ctx.user?.id,
|
||||
name: this.ctx.user?.employees_name || '',
|
||||
},
|
||||
extras: {
|
||||
warehouseId,
|
||||
orderIds,
|
||||
updated_count: count,
|
||||
message: `异常订单转正常:订单ID [${orderIds.join(', ')}],step 3 -> 2,共更新 ${count} 条`,
|
||||
},
|
||||
beforeChanges: null,
|
||||
});
|
||||
} catch (logErr) {
|
||||
this.ctx.logger.warn('[ExpectionOrderService.resolveException] 写入操作日志失败,不影响业务', logErr);
|
||||
}
|
||||
|
||||
return this.success('ok', {
|
||||
updated_count: count,
|
||||
ids: orderIds,
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
module.exports = ExpectionOrderService;
|
||||
|
||||
@ -6,9 +6,9 @@ class OrderIndexService extends OrderBaseService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'list,badgeCount,manualOutboundOrder,detail';
|
||||
const _noNeedLog = 'list,badgeCount,manualOutboundOrder,detail';
|
||||
const _noNeedAuth = 'list,badgeCount,manualOutboundOrder,detail';
|
||||
const _noNeedRight = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,detail';
|
||||
const _noNeedLog = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,detail';
|
||||
const _noNeedAuth = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,detail';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
@ -73,6 +73,38 @@ class OrderIndexService extends OrderBaseService {
|
||||
return badgeCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询订单操作日志。
|
||||
* @param {Object} data 请求体。
|
||||
* @param {string|number} data.id 订单ID。
|
||||
* @param {number} [data.page] 页码。
|
||||
* @param {number} [data.pageSize] 每页数量。
|
||||
* @return {Promise<Object>} 统一 success 包装的分页结果。
|
||||
*/
|
||||
async queryOrderLogs(data = {}) {
|
||||
const { ctx, service } = this;
|
||||
const requestData = data && typeof data === 'object' ? data : {};
|
||||
const { id, page, pageSize } = requestData;
|
||||
|
||||
try {
|
||||
const result = await service.systems.operationLog.queryOrderLogs({
|
||||
id,
|
||||
page,
|
||||
pageSize,
|
||||
warehouseId: ctx.user.store_id,
|
||||
});
|
||||
|
||||
return this.success('ok', {
|
||||
data: result,
|
||||
code: 200,
|
||||
});
|
||||
} catch (e) {
|
||||
return this.success(e.message, {
|
||||
code: 200,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
module.exports = OrderIndexService;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -1,47 +1,3 @@
|
||||
'use strict';
|
||||
|
||||
const OrderBaseService = require('./base');
|
||||
|
||||
/**
|
||||
* 系统方法层:订单储位分配入口。
|
||||
* 仅负责参数归一化与调用底层公共 service。
|
||||
*/
|
||||
class StorageAllocationService extends OrderBaseService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'allocateStorage';
|
||||
const _noNeedLog = 'allocateStorage';
|
||||
const _noNeedAuth = 'allocateStorage';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量分配订单储位。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @return {Promise<Object>} 统一 success 包装。
|
||||
*/
|
||||
async allocateStorage(data = {}) {
|
||||
const { service } = this;
|
||||
const requestData = this.isPlainObject(data) ? data : {};
|
||||
const normalizedData = {
|
||||
allow_storage_location: requestData.allow_storage_location
|
||||
?? requestData.allowStorageLocation
|
||||
?? requestData.is_allow_storage
|
||||
?? requestData.isAllowStorage,
|
||||
order_ids: requestData.order_ids
|
||||
?? requestData.orderIds
|
||||
?? requestData.ids
|
||||
?? requestData.order_id
|
||||
?? requestData.orderId
|
||||
?? requestData.id,
|
||||
warehouse_id: requestData.warehouse_id ?? requestData.warehouseId,
|
||||
};
|
||||
|
||||
const result = await service.systems.orderStorageAllocation.allocateStorage(normalizedData);
|
||||
return this.success('ok', result);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = StorageAllocationService;
|
||||
module.exports = undefined;
|
||||
|
||||
@ -11,9 +11,9 @@ class expressService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'list,listBase,create,checkCodeUnique,update';
|
||||
const _noNeedRight = 'list,listBase,create,checkCodeUnique,update,delete';
|
||||
const _noNeedLog = '*';
|
||||
const _noNeedAuth = 'list,listBase,create,checkCodeUnique,update';
|
||||
const _noNeedAuth = 'list,listBase,create,checkCodeUnique,update,delete';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
@ -166,6 +166,77 @@ class expressService extends MainService {
|
||||
|
||||
return await this.callSystemExpress('update', payload, '更新快递映射失败');
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化删除 ID 列表。
|
||||
*
|
||||
* 优先读取 `ids`,其次兼容单个 `id`、`setting_id`、`settingId`。
|
||||
*
|
||||
* @param {Object} data 请求参数
|
||||
* @return {Array<number>} 删除 ID 列表
|
||||
*/
|
||||
resolveDeleteIds(data = {}) {
|
||||
const {
|
||||
ids,
|
||||
id,
|
||||
setting_id: settingId,
|
||||
settingId: camelSettingId,
|
||||
} = data || {};
|
||||
|
||||
const rawIds = ids !== undefined
|
||||
? ids
|
||||
: (id !== undefined ? id : (settingId !== undefined ? settingId : camelSettingId));
|
||||
|
||||
const values = Array.isArray(rawIds)
|
||||
? rawIds
|
||||
: String(rawIds || '')
|
||||
.split(',')
|
||||
.map(item => item.trim())
|
||||
.filter(Boolean);
|
||||
|
||||
const normalizedIds = [];
|
||||
const seenIds = new Set();
|
||||
|
||||
for (const value of values) {
|
||||
const normalized = Number(value);
|
||||
if (!Number.isInteger(normalized) || normalized <= 0 || seenIds.has(normalized)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
seenIds.add(normalized);
|
||||
normalizedIds.push(normalized);
|
||||
}
|
||||
|
||||
return normalizedIds;
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除快递映射。
|
||||
*
|
||||
* @param {Object} data 请求参数
|
||||
* @return {Promise<Object>} 删除结果
|
||||
*/
|
||||
async delete(data = {}) {
|
||||
const {
|
||||
ids,
|
||||
id,
|
||||
setting_id: settingId,
|
||||
settingId: camelSettingId,
|
||||
...rest
|
||||
} = data || {};
|
||||
|
||||
const payload = {
|
||||
...rest,
|
||||
ids: this.resolveDeleteIds({
|
||||
ids,
|
||||
id,
|
||||
setting_id: settingId,
|
||||
settingId: camelSettingId,
|
||||
}),
|
||||
};
|
||||
|
||||
return await this.callSystemExpress('delete', payload, '删除快递映射失败');
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = expressService;
|
||||
|
||||
@ -11,9 +11,9 @@ class expressInterfaceService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'list,create,update,delete';
|
||||
const _noNeedRight = 'list,listByWarehousePlatformCode,create,update,delete';
|
||||
const _noNeedLog = '*';
|
||||
const _noNeedAuth = 'list,create,update,delete';
|
||||
const _noNeedAuth = 'list,listByWarehousePlatformCode,create,update,delete';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
@ -57,7 +57,6 @@ class expressInterfaceService extends MainService {
|
||||
const pagination = {
|
||||
...(inputPagination && typeof inputPagination === 'object' ? inputPagination : {}),
|
||||
};
|
||||
|
||||
if (page !== undefined) {
|
||||
pagination.page = page;
|
||||
}
|
||||
@ -87,9 +86,6 @@ class expressInterfaceService extends MainService {
|
||||
platform_code: {
|
||||
field: 'platform_code',
|
||||
},
|
||||
express_platform_id: {
|
||||
field: 'express_platform_id',
|
||||
},
|
||||
sender_name: {
|
||||
field: 'sender_name',
|
||||
},
|
||||
@ -123,6 +119,16 @@ class expressInterfaceService extends MainService {
|
||||
return await this.callSystemExpressInterface('list', payload, '获取快递接口列表失败');
|
||||
}
|
||||
|
||||
/**
|
||||
* 按仓库与平台代码查询快递接口全量记录。
|
||||
*
|
||||
* @param {Object} data 请求参数
|
||||
* @return {Promise<Object>} 查询结果
|
||||
*/
|
||||
async listByWarehousePlatformCode(data = {}) {
|
||||
return await this.callSystemExpressInterface('listByWarehousePlatformCode', data, '获取快递接口查询失败');
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建快递接口。
|
||||
*
|
||||
@ -136,7 +142,6 @@ class expressInterfaceService extends MainService {
|
||||
expressCode: camelExpressCode,
|
||||
platform_code: platformCode,
|
||||
platformCode: camelPlatformCode,
|
||||
express_platform_id: expressPlatformId,
|
||||
expressPlatformId: camelExpressPlatformId,
|
||||
...rest
|
||||
} = data || {};
|
||||
@ -154,9 +159,6 @@ class expressInterfaceService extends MainService {
|
||||
if (platformCode !== undefined || camelPlatformCode !== undefined) {
|
||||
payload.platform_code = platformCode !== undefined ? platformCode : camelPlatformCode;
|
||||
}
|
||||
if (expressPlatformId !== undefined || camelExpressPlatformId !== undefined) {
|
||||
payload.express_platform_id = expressPlatformId !== undefined ? expressPlatformId : camelExpressPlatformId;
|
||||
}
|
||||
|
||||
return await this.callSystemExpressInterface('create', payload, '创建快递接口失败');
|
||||
}
|
||||
@ -177,7 +179,6 @@ class expressInterfaceService extends MainService {
|
||||
expressCode: camelExpressCode,
|
||||
platform_code: platformCode,
|
||||
platformCode: camelPlatformCode,
|
||||
express_platform_id: expressPlatformId,
|
||||
expressPlatformId: camelExpressPlatformId,
|
||||
...rest
|
||||
} = data || {};
|
||||
@ -196,9 +197,6 @@ class expressInterfaceService extends MainService {
|
||||
if (platformCode !== undefined || camelPlatformCode !== undefined) {
|
||||
payload.platform_code = platformCode !== undefined ? platformCode : camelPlatformCode;
|
||||
}
|
||||
if (expressPlatformId !== undefined || camelExpressPlatformId !== undefined) {
|
||||
payload.express_platform_id = expressPlatformId !== undefined ? expressPlatformId : camelExpressPlatformId;
|
||||
}
|
||||
|
||||
return await this.callSystemExpressInterface('update', payload, '更新快递接口失败');
|
||||
}
|
||||
|
||||
@ -160,6 +160,49 @@ class platformService extends MainService {
|
||||
return await this.callSystemPlatform('update', payload, '更新平台设置失败');
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化删除 ID 列表。
|
||||
*
|
||||
* 优先读取 `ids`,其次兼容单个 `id`、`setting_id`、`settingId`。
|
||||
*
|
||||
* @param {Object} data 请求参数
|
||||
* @return {Array<number>} 删除 ID 列表
|
||||
*/
|
||||
resolveDeleteIds(data = {}) {
|
||||
const {
|
||||
ids,
|
||||
id,
|
||||
setting_id: settingId,
|
||||
settingId: camelSettingId,
|
||||
} = data || {};
|
||||
|
||||
const rawIds = ids !== undefined
|
||||
? ids
|
||||
: (id !== undefined ? id : (settingId !== undefined ? settingId : camelSettingId));
|
||||
|
||||
const values = Array.isArray(rawIds)
|
||||
? rawIds
|
||||
: String(rawIds || '')
|
||||
.split(',')
|
||||
.map(item => item.trim())
|
||||
.filter(Boolean);
|
||||
|
||||
const normalizedIds = [];
|
||||
const seenIds = new Set();
|
||||
|
||||
for (const value of values) {
|
||||
const normalized = Number(value);
|
||||
if (!Number.isInteger(normalized) || normalized <= 0 || seenIds.has(normalized)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
seenIds.add(normalized);
|
||||
normalizedIds.push(normalized);
|
||||
}
|
||||
|
||||
return normalizedIds;
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除平台设置。
|
||||
*
|
||||
@ -168,15 +211,23 @@ class platformService extends MainService {
|
||||
*/
|
||||
async delete(data = {}) {
|
||||
const {
|
||||
ids,
|
||||
id,
|
||||
setting_id: settingId,
|
||||
settingId: camelSettingId,
|
||||
...rest
|
||||
} = data || {};
|
||||
|
||||
const normalizedIds = this.resolveDeleteIds({
|
||||
ids,
|
||||
id,
|
||||
setting_id: settingId,
|
||||
settingId: camelSettingId,
|
||||
});
|
||||
|
||||
const payload = {
|
||||
...rest,
|
||||
id: id !== undefined ? id : (settingId !== undefined ? settingId : camelSettingId),
|
||||
ids: normalizedIds,
|
||||
};
|
||||
|
||||
return await this.callSystemPlatform('delete', payload, '删除平台设置失败');
|
||||
|
||||
144
app/service/systems/api_sign.js
Normal file
144
app/service/systems/api_sign.js
Normal file
@ -0,0 +1,144 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
const apiSignLib = require('../../lib/api_sign');
|
||||
|
||||
const API_APP_CACHE_PREFIX = 'openapi:api-app';
|
||||
const API_APP_CACHE_TTL_SECONDS = 300;
|
||||
const OPENAPI_INTERFACE_TYPE_ID = 2;
|
||||
|
||||
class ApiSignService extends Service {
|
||||
/**
|
||||
* 构建 API 应用配置缓存键。
|
||||
* @param {string} appKey 开放接口 app_key。
|
||||
* @return {string} 缓存键。
|
||||
*/
|
||||
getApiAppCacheKey(appKey) {
|
||||
return `${API_APP_CACHE_PREFIX}:${String(appKey || '').trim()}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 app_key 查询 API 应用可用配置(带缓存)。
|
||||
* @param {string} appKey 开放接口 app_key。
|
||||
* @return {Promise<Object>} 查询结果,包含应用主键与密钥。
|
||||
*/
|
||||
async getApiAppConfigByAppKey(appKey) {
|
||||
const normalizedAppKey = String(appKey || '').trim();
|
||||
if (!normalizedAppKey) {
|
||||
throw new Error('appKey 不能为空');
|
||||
}
|
||||
|
||||
const cacheKey = this.getApiAppCacheKey(normalizedAppKey);
|
||||
if (this.app && typeof this.app.getCacheAsync === 'function') {
|
||||
try {
|
||||
const cached = await this.app.getCacheAsync(cacheKey);
|
||||
if (cached && typeof cached === 'object') {
|
||||
return cached;
|
||||
}
|
||||
} catch (error) {
|
||||
this.ctx.logger.warn(`[api_sign] 读取缓存失败,降级查库: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
const row = await this.ctx.model.ApiApp.findOne({
|
||||
attributes: [ 'id', 'self_app_key', 'self_app_secret', 'is_enabled', 'interface_type_id' ],
|
||||
where: {
|
||||
self_app_key: normalizedAppKey,
|
||||
},
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (!row) {
|
||||
throw new Error('未找到对应的 API 应用配置');
|
||||
}
|
||||
|
||||
if (Number(row.is_enabled) !== 1) {
|
||||
throw new Error('API 应用已禁用');
|
||||
}
|
||||
|
||||
if (Number(row.interface_type_id) !== OPENAPI_INTERFACE_TYPE_ID) {
|
||||
throw new Error('app_key 无效或不可用');
|
||||
}
|
||||
|
||||
if (!row.self_app_secret) {
|
||||
throw new Error('API 应用缺少 self_app_secret 配置');
|
||||
}
|
||||
|
||||
const appConfig = {
|
||||
id: row.id,
|
||||
appKey: row.self_app_key,
|
||||
selfAppSecret: row.self_app_secret,
|
||||
};
|
||||
|
||||
if (this.app && typeof this.app.setCacheAsync === 'function') {
|
||||
this.app.setCacheAsync(cacheKey, appConfig, API_APP_CACHE_TTL_SECONDS)
|
||||
.catch(error => {
|
||||
this.ctx.logger.warn(`[api_sign] 写入缓存失败: ${error.message}`);
|
||||
});
|
||||
}
|
||||
|
||||
return appConfig;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 app_key 查询 API 应用密钥信息。
|
||||
* @param {string} appKey 开放接口 app_key。
|
||||
* @return {Promise<Object>} 查询结果,包含应用主键与密钥。
|
||||
*/
|
||||
async getApiAppSecretByAppKey(appKey) {
|
||||
return await this.getApiAppConfigByAppKey(appKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用 app_key 读取密钥并执行签名验证。
|
||||
* @param {Object} options 验签参数。
|
||||
* @param {string} options.appKey 开放接口 app_key。
|
||||
* @param {Object} [options.query={}] 请求 query 参数。
|
||||
* @param {*} [options.body] 请求体。
|
||||
* @param {string} options.providedSign 请求中携带的 sign。
|
||||
* @param {string[]} [options.ignoreKeys] 额外忽略的 query 字段。
|
||||
* @return {Promise<Object>} 验签结果。
|
||||
*/
|
||||
async verifyRequestSignByAppKey({ appKey, query = {}, body, providedSign, ignoreKeys } = {}) {
|
||||
let appConfig;
|
||||
try {
|
||||
appConfig = await this.getApiAppSecretByAppKey(appKey);
|
||||
} catch (error) {
|
||||
return {
|
||||
ok: false,
|
||||
code: 'APP_CONFIG_INVALID',
|
||||
message: error.message,
|
||||
};
|
||||
}
|
||||
|
||||
const verifyResult = apiSignLib.verifyRequestSign({
|
||||
query,
|
||||
body,
|
||||
providedSign,
|
||||
selfAppSecret: appConfig.selfAppSecret,
|
||||
ignoreKeys,
|
||||
});
|
||||
|
||||
if (!verifyResult.ok) {
|
||||
return {
|
||||
ok: false,
|
||||
code: 'SIGN_INVALID',
|
||||
message: verifyResult.message,
|
||||
expectedSign: verifyResult.expectedSign,
|
||||
providedSign: verifyResult.providedSign,
|
||||
appId: appConfig.id,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
code: 'OK',
|
||||
message: verifyResult.message,
|
||||
sign: verifyResult.expectedSign,
|
||||
appId: appConfig.id,
|
||||
appKey: appConfig.appKey,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ApiSignService;
|
||||
@ -18,6 +18,12 @@ const DEFAULT_STORE_SUBJECT_CONFIG = Object.freeze({
|
||||
default_platform_code: 'TB',
|
||||
});
|
||||
|
||||
const ORDER_OPERATION_CODES = Object.freeze({
|
||||
CREATE: 'ORDER_CREATE',
|
||||
PLATFORM_FALLBACK: 'ORDER_PLATFORM_FALLBACK',
|
||||
EXPRESS_FALLBACK: 'ORDER_EXPRESS_FALLBACK',
|
||||
});
|
||||
|
||||
const STORE_SUBJECT_CONFIG_CACHE_TTL_SECONDS = 600;
|
||||
|
||||
class DeliveryOrderService extends Service {
|
||||
@ -94,6 +100,86 @@ class DeliveryOrderService extends Service {
|
||||
return String(option.name || option.label || option.code || option.value || '').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录待写入的订单操作日志项。
|
||||
*
|
||||
* @param {Array<Object>} operationLogs 待写入的日志数组。
|
||||
* @param {string} operationCode 操作编码。
|
||||
* @param {string} message 日志内容。
|
||||
* @param {Object} [options={}] 记录选项。
|
||||
* @param {boolean} [options.prepend=false] 是否插入到数组首位。
|
||||
* @return {void}
|
||||
*/
|
||||
appendOrderOperationLog(operationLogs, operationCode, message, options = {}) {
|
||||
if (!Array.isArray(operationLogs)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const logItem = {
|
||||
operationCode,
|
||||
message,
|
||||
};
|
||||
|
||||
if (options && options.prepend) {
|
||||
operationLogs.unshift(logItem);
|
||||
return;
|
||||
}
|
||||
|
||||
operationLogs.push(logItem);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将订单操作日志逐条写入数据库。
|
||||
*
|
||||
* @param {Array<Object>} operationLogs 待写入的日志数组。
|
||||
* @param {number|string} orderId 订单ID。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async flushOrderOperationLogs(operationLogs, orderId) {
|
||||
const { ctx } = this;
|
||||
const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog;
|
||||
|
||||
if (!Array.isArray(operationLogs) || operationLogs.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!operationLogService || typeof operationLogService.createOperationLog !== 'function') {
|
||||
ctx.logger.warn('[DeliveryOrderService.flushOrderOperationLogs] operationLog service unavailable', {
|
||||
orderId,
|
||||
logs: operationLogs.length,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
for (const logItem of operationLogs) {
|
||||
try {
|
||||
const result = await operationLogService.createOperationLog({
|
||||
businessType: 'order',
|
||||
businessId: orderId,
|
||||
operationCode: logItem.operationCode,
|
||||
extras: {
|
||||
message: logItem.message,
|
||||
},
|
||||
});
|
||||
|
||||
if (!result) {
|
||||
ctx.logger.warn('[DeliveryOrderService.flushOrderOperationLogs] 写入操作日志失败,不影响业务', {
|
||||
orderId,
|
||||
operationCode: logItem.operationCode,
|
||||
message: logItem.message,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
ctx.logger.warn('[DeliveryOrderService.flushOrderOperationLogs] 写入操作日志异常,不影响业务', {
|
||||
orderId,
|
||||
operationCode: logItem.operationCode,
|
||||
message: logItem.message,
|
||||
error: error.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 按平台码解析平台列表项,优先基础平台,再匹配平台设置。
|
||||
*
|
||||
@ -148,19 +234,18 @@ class DeliveryOrderService extends Service {
|
||||
* 解析平台快照。
|
||||
*
|
||||
* 优先级:
|
||||
* 1. 直接匹配 wms_platform.code;
|
||||
* 2. 再按 wms_platfrom_setting.code 读取平台映射;
|
||||
* 3. 最后才回退货主默认平台 code。
|
||||
* 1. 先匹配平台列表里的基础平台项;
|
||||
* 2. 再匹配平台列表里的系统设置项。
|
||||
*
|
||||
* @param {string} sourcePlatformCode 外部平台编码。
|
||||
* @param {Object} storeSubjectConfig 货主签约配置。
|
||||
* @param {Object} [info={}] 上下文信息。
|
||||
* @param {Array<Object>} [operationLogs=[]] 待写入的操作日志数组。
|
||||
* @return {Promise<Object>} 平台快照。
|
||||
*/
|
||||
async resolvePlatformSnapshot(sourcePlatformCode, storeSubjectConfig, info = {}) {
|
||||
async resolvePlatformSnapshot(sourcePlatformCode, storeSubjectConfig, info = {}, operationLogs = []) {
|
||||
const platformList = await this.ctx.service.systems.platform.getPlatformList();
|
||||
const externalCode = String(sourcePlatformCode || '').trim();
|
||||
const defaultCode = String(storeSubjectConfig && storeSubjectConfig.default_platform_code || '').trim();
|
||||
const matchedPlatform = this.findPlatformOptionByCode(platformList, externalCode);
|
||||
|
||||
if (matchedPlatform) {
|
||||
@ -170,20 +255,38 @@ class DeliveryOrderService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
const fallbackPlatform = this.findPlatformOptionByCode(platformList, defaultCode);
|
||||
if (fallbackPlatform) {
|
||||
this.ctx.logger.warn('[DeliveryOrderService.prepareOrderData] invalid platform code fallback to store default', {
|
||||
deliveryOrderCode: info.deliveryOrderCode,
|
||||
warehouseId: info.warehouseId,
|
||||
storeId: info.storeId,
|
||||
sourcePlatformCode: externalCode,
|
||||
defaultPlatformCode: defaultCode,
|
||||
});
|
||||
this.ctx.logger.warn('[DeliveryOrderService.prepareOrderData] platform code not found in platform service list', {
|
||||
deliveryOrderCode: info.deliveryOrderCode,
|
||||
warehouseId: info.warehouseId,
|
||||
storeId: info.storeId,
|
||||
sourcePlatformCode: externalCode,
|
||||
});
|
||||
|
||||
return {
|
||||
sysPlatformCode: this.getPlatformSnapshotCode(fallbackPlatform, defaultCode),
|
||||
sysPlatformName: this.getPlatformSnapshotName(fallbackPlatform),
|
||||
};
|
||||
const defaultCode = String(storeSubjectConfig && storeSubjectConfig.default_platform_code || '').trim();
|
||||
const fallbackPlatform = defaultCode ? this.findPlatformOptionByCode(platformList, defaultCode) : null;
|
||||
const fallbackPlatformName = this.getPlatformSnapshotName(fallbackPlatform) || defaultCode;
|
||||
|
||||
if (defaultCode) {
|
||||
this.appendOrderOperationLog(
|
||||
operationLogs,
|
||||
ORDER_OPERATION_CODES.PLATFORM_FALLBACK,
|
||||
`平台编码${externalCode}匹配不到平台,已转为默认平台:${fallbackPlatformName}`
|
||||
);
|
||||
|
||||
if (fallbackPlatform) {
|
||||
this.ctx.logger.warn('[DeliveryOrderService.prepareOrderData] platform code fallback to store default', {
|
||||
deliveryOrderCode: info.deliveryOrderCode,
|
||||
warehouseId: info.warehouseId,
|
||||
storeId: info.storeId,
|
||||
sourcePlatformCode: externalCode,
|
||||
defaultPlatformCode: defaultCode,
|
||||
});
|
||||
|
||||
return {
|
||||
sysPlatformCode: this.getPlatformSnapshotCode(fallbackPlatform, defaultCode),
|
||||
sysPlatformName: fallbackPlatformName,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
this.ctx.logger.warn('[DeliveryOrderService.prepareOrderData] platform default not found in platform service list', {
|
||||
@ -196,7 +299,7 @@ class DeliveryOrderService extends Service {
|
||||
|
||||
return {
|
||||
sysPlatformCode: defaultCode || externalCode,
|
||||
sysPlatformName: '',
|
||||
sysPlatformName: fallbackPlatformName || '',
|
||||
};
|
||||
}
|
||||
|
||||
@ -250,9 +353,10 @@ class DeliveryOrderService extends Service {
|
||||
* @param {string} logisticsCode 外部快递编码。
|
||||
* @param {Object} storeSubjectConfig 货主签约配置。
|
||||
* @param {Object} [info={}] 上下文信息。
|
||||
* @param {Array<Object>} [operationLogs=[]] 待写入的操作日志数组。
|
||||
* @return {Promise<Object>} 快递快照。
|
||||
*/
|
||||
async resolveExpressSnapshot(logisticsCode, storeSubjectConfig, info = {}) {
|
||||
async resolveExpressSnapshot(logisticsCode, storeSubjectConfig, info = {}, operationLogs = []) {
|
||||
const expressList = await this.ctx.service.systems.express.getExpressList();
|
||||
const externalCode = String(logisticsCode || '').trim();
|
||||
const defaultCode = String(storeSubjectConfig && storeSubjectConfig.default_express_code || '').trim();
|
||||
@ -299,6 +403,12 @@ class DeliveryOrderService extends Service {
|
||||
defaultExpressCode: defaultCode,
|
||||
});
|
||||
|
||||
this.appendOrderOperationLog(
|
||||
operationLogs,
|
||||
ORDER_OPERATION_CODES.EXPRESS_FALLBACK,
|
||||
`快递编码${externalCode}匹配不到快递,已转为默认快递:${this.getOptionName(fallbackExpress) || defaultCode}`
|
||||
);
|
||||
|
||||
return {
|
||||
sysLogisticsCode: String(fallbackExpress.express_code || fallbackExpress.code || fallbackExpress.value || defaultCode).trim(),
|
||||
sysLogisticsName: this.getOptionName(fallbackExpress),
|
||||
@ -326,8 +436,9 @@ class DeliveryOrderService extends Service {
|
||||
* @param {Object} info 当前仓库与货主上下文。
|
||||
* @return {Promise<Object>} 创建结果。
|
||||
*/
|
||||
async addOrder(data, info) {
|
||||
async addOrder(data, info, createChannel = '') {
|
||||
const { ctx } = this;
|
||||
const operationLogs = [];
|
||||
let warehouseIdStr;
|
||||
try {
|
||||
warehouseIdStr = normalizeWarehouseShardId(info.warehouseId);
|
||||
@ -341,6 +452,12 @@ class DeliveryOrderService extends Service {
|
||||
info = { ...info, warehouseId: warehouseIdStr };
|
||||
const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseIdStr);
|
||||
const { deliveryOrder, orderLines } = data.request;
|
||||
const normalizedCreateChannel = String(
|
||||
createChannel
|
||||
|| deliveryOrder.createChannel
|
||||
|| deliveryOrder.create_channel
|
||||
|| 'MANUAL'
|
||||
).trim().toUpperCase() || 'MANUAL';
|
||||
|
||||
// 开启事务
|
||||
const transaction = await ctx.model.transaction();
|
||||
@ -374,11 +491,23 @@ class DeliveryOrderService extends Service {
|
||||
|
||||
// 准备订单数据
|
||||
const step = await this.resolveOrderStep(info, transaction);
|
||||
const orderData = await this.prepareOrderData(deliveryOrder, info, step);
|
||||
const orderData = await this.prepareOrderData(
|
||||
deliveryOrder,
|
||||
info,
|
||||
normalizedCreateChannel,
|
||||
step,
|
||||
operationLogs
|
||||
);
|
||||
|
||||
// 创建订单
|
||||
const createdOrder = await DeliveryModel.create(orderData, { transaction });
|
||||
const orderId = createdOrder.id;
|
||||
this.appendOrderOperationLog(
|
||||
operationLogs,
|
||||
ORDER_OPERATION_CODES.CREATE,
|
||||
`订单创建成功,orderId:${orderId}`,
|
||||
{ prepend: true }
|
||||
);
|
||||
|
||||
let itemsInfo = null;
|
||||
// 添加订单明细
|
||||
@ -402,6 +531,7 @@ class DeliveryOrderService extends Service {
|
||||
items_weight: itemsInfo.total_weight || 0, // 总重量
|
||||
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(','),
|
||||
updated_at: new Date(),
|
||||
};
|
||||
|
||||
@ -429,6 +559,8 @@ class DeliveryOrderService extends Service {
|
||||
|
||||
await transaction.commit();
|
||||
|
||||
await this.flushOrderOperationLogs(operationLogs, orderId);
|
||||
|
||||
// 异步处理:订单入队列
|
||||
await this.addOrderToQueue(orderId, info.warehouseId);
|
||||
|
||||
@ -437,10 +569,12 @@ class DeliveryOrderService extends Service {
|
||||
message: '订单创建成功',
|
||||
data: {
|
||||
orderId,
|
||||
step,
|
||||
stats: itemsInfo ? {
|
||||
items_count: itemsInfo.stock_count,
|
||||
items_total: itemsInfo.item_total_count,
|
||||
items_weight: itemsInfo.total_weight,
|
||||
source_order_codes: (itemsInfo.stats && itemsInfo.stats.source_order_codes) || [],
|
||||
} : null,
|
||||
},
|
||||
};
|
||||
@ -541,16 +675,45 @@ class DeliveryOrderService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 标准化订单来源键。
|
||||
*
|
||||
* @param {any} value 来源键原始值。
|
||||
* @return {number|null} 有限整数返回整数值,否则返回 null。
|
||||
*/
|
||||
normalizeOrderFromKey(value) {
|
||||
if (value === null || value === undefined) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (typeof value === 'string' && value.trim() === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const normalizedValue = Number(value);
|
||||
if (Number.isFinite(normalizedValue) && Number.isInteger(normalizedValue)) {
|
||||
return normalizedValue;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 准备订单主表数据。
|
||||
*
|
||||
* @param {Object} deliveryOrder 订单主信息。
|
||||
* @param {Object} info 当前仓库与货主上下文。
|
||||
* @param {number} step 订单步骤。
|
||||
* @param {number} step 订单步骤。
|
||||
* @param {Array<Object>} [operationLogs=[]] 待写入的操作日志数组。
|
||||
* @return {Promise<Object>} 可入库的订单数据。
|
||||
*/
|
||||
async prepareOrderData(deliveryOrder, info, step = DELIVERY_ORDER_STEP.PENDING_REVIEW) {
|
||||
const { service } = this;
|
||||
async prepareOrderData(
|
||||
deliveryOrder,
|
||||
info,
|
||||
createChannel = 'MANUAL',
|
||||
step = DELIVERY_ORDER_STEP.PENDING_REVIEW,
|
||||
operationLogs = []
|
||||
) {
|
||||
const {
|
||||
deliveryOrderCode,
|
||||
preDeliveryOrderCode,
|
||||
@ -589,12 +752,12 @@ class DeliveryOrderService extends Service {
|
||||
deliveryOrderCode,
|
||||
warehouseId: info.warehouseId,
|
||||
storeId: info.storeId,
|
||||
});
|
||||
}, operationLogs);
|
||||
const expressSnapshot = await this.resolveExpressSnapshot(logisticsCode, storeSubjectConfig, {
|
||||
deliveryOrderCode,
|
||||
warehouseId: info.warehouseId,
|
||||
storeId: info.storeId,
|
||||
});
|
||||
}, operationLogs);
|
||||
|
||||
return {
|
||||
delivery_order_code: deliveryOrderCode,
|
||||
@ -605,6 +768,7 @@ class DeliveryOrderService extends Service {
|
||||
order_flag: orderFlag || '',
|
||||
source_platform_code: sourcePlatformCode || '',
|
||||
source_platform_name: sourcePlatformName || '',
|
||||
create_channel: String(createChannel || 'MANUAL').trim().toUpperCase() || 'MANUAL',
|
||||
sys_platform_code: platformSnapshot.sysPlatformCode,
|
||||
sys_platform_name: platformSnapshot.sysPlatformName,
|
||||
create_at: createTime ? new Date(createTime) : new Date(),
|
||||
@ -648,7 +812,7 @@ class DeliveryOrderService extends Service {
|
||||
// 业务关联ID
|
||||
store_id: info.storeId,
|
||||
warehouse_id: info.warehouseId,
|
||||
from_key: info.appKey,
|
||||
from_key: this.normalizeOrderFromKey(info.appKey),
|
||||
};
|
||||
}
|
||||
|
||||
@ -707,13 +871,16 @@ class DeliveryOrderService extends Service {
|
||||
}
|
||||
let wms_stock = null;
|
||||
if (!line.itemId) {
|
||||
// 查找唯一键
|
||||
wms_stock = await app.model.StockStore.findOne({ where: {
|
||||
// 查找唯一键(appKey 为空时不作为条件,兼容内部手动建单场景)
|
||||
const stockWhere = {
|
||||
item_code: line.itemCode,
|
||||
app_key: appKey,
|
||||
warehouse_id: warehouseId,
|
||||
store_id: storeId,
|
||||
}, transaction });
|
||||
};
|
||||
if (appKey) {
|
||||
stockWhere.app_key = appKey;
|
||||
}
|
||||
wms_stock = await app.model.StockStore.findOne({ where: stockWhere, transaction });
|
||||
} else {
|
||||
wms_stock = await app.model.StockStore.findByPk(line.itemId, { transaction });
|
||||
}
|
||||
@ -813,6 +980,7 @@ class DeliveryOrderService extends Service {
|
||||
let total_weight = 0; // 总重量
|
||||
let stock_count = 0; // stock种类数
|
||||
let item_total_count = 0; // 商品总数
|
||||
let source_order_codes = new Set(); // 订单来源去重集合
|
||||
|
||||
if (stockQuantityMap.size > 0) {
|
||||
// 生成结构字符串
|
||||
@ -839,7 +1007,7 @@ class DeliveryOrderService extends Service {
|
||||
const qty = parseInt(quantity) || 0;
|
||||
return sum + (weight * qty);
|
||||
}, 0);
|
||||
|
||||
source_order_codes = new Set(lineData.map(line => line.source_order_code).filter(code => code)); // 订单来源去重集合
|
||||
// 格式化重量(保留2位小数)
|
||||
total_weight = parseFloat(total_weight.toFixed(2));
|
||||
|
||||
@ -880,6 +1048,7 @@ class DeliveryOrderService extends Service {
|
||||
total_items: item_total_count,
|
||||
total_weight,
|
||||
avg_weight_per_item: stock_count > 0 ? (total_weight / item_total_count).toFixed(2) : 0,
|
||||
source_order_codes: Array.from(source_order_codes), // 订单来源去重集合
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@ -799,7 +799,9 @@ class entryOrderService extends Service {
|
||||
orderLines,
|
||||
},
|
||||
};
|
||||
const Result = await this.ctx.service.systems.qimenQuery.send('taobao.qimen.entryorder.confirm', entryOrder.qimen_owner_code, queryData);
|
||||
const Result = await this.app.qimenClient.send('taobao.qimen.entryorder.confirm', entryOrder.qimen_owner_code, queryData, {
|
||||
ctx: this.ctx,
|
||||
});
|
||||
return Result;
|
||||
}
|
||||
async entryorderConfirm(orderId, isCompleted) {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
580
app/service/systems/express_platform.js
Normal file
580
app/service/systems/express_platform.js
Normal file
@ -0,0 +1,580 @@
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../main');
|
||||
|
||||
/**
|
||||
* 快递平台服务类。
|
||||
*
|
||||
* 当前仅保留平台方法出口,后续接入真实平台实现时再补充具体调用逻辑。
|
||||
* 这里的 `data` 统一与上游 `app/service/systems/express.js` 中
|
||||
* `buildWaybillAsyncBizcontentSkeleton` / `buildWaybillAsyncOrderListItem`
|
||||
* 生成的结构对齐,完整形状如下:
|
||||
*
|
||||
* ```js
|
||||
* {
|
||||
* bizcontent: {
|
||||
* platform_code: string,
|
||||
* express_platform_code: string,
|
||||
* store_id: number,
|
||||
* warehouse_id: number,
|
||||
* order_list: [
|
||||
* {
|
||||
* order_id: number,
|
||||
* business_key: number,
|
||||
* sys_platform_code: string,
|
||||
* logistics_code: string,
|
||||
* express_platform_code: string,
|
||||
* route_info: {
|
||||
* source_platform_code: string,
|
||||
* source_platform_name: string,
|
||||
* sys_platform_code: string,
|
||||
* sys_platform_name: string,
|
||||
* logistics_code: string,
|
||||
* logistics_name: string,
|
||||
* sys_logistics_code: string,
|
||||
* sys_logistics_name: string,
|
||||
* express_code: string,
|
||||
* logistics_area_code: string,
|
||||
* },
|
||||
* order_info: {
|
||||
* delivery_order_code: string,
|
||||
* order_type: string,
|
||||
* status: string,
|
||||
* step: number,
|
||||
* order_flag: string,
|
||||
* from_key: string,
|
||||
* create_at: string,
|
||||
* place_order_time: string,
|
||||
* pay_time: string,
|
||||
* operate_time: string,
|
||||
* delivery_time: string,
|
||||
* },
|
||||
* receiver_info: {
|
||||
* name: string,
|
||||
* tel: string,
|
||||
* mobile: string,
|
||||
* email: string,
|
||||
* country_code: string,
|
||||
* province: string,
|
||||
* city: string,
|
||||
* area: string,
|
||||
* town: string,
|
||||
* detail_address: string,
|
||||
* zip_code: string,
|
||||
* },
|
||||
* settlement_info: {
|
||||
* total_amount: number,
|
||||
* item_amount: number,
|
||||
* discount_amount: number,
|
||||
* freight: number,
|
||||
* ar_amount: number,
|
||||
* got_amount: number,
|
||||
* },
|
||||
* items_summary: {
|
||||
* items: Array,
|
||||
* items_count: number,
|
||||
* items_total: number,
|
||||
* items_weight: number,
|
||||
* },
|
||||
* },
|
||||
* ],
|
||||
* platform_payload: {},
|
||||
* },
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @typedef {Object} ExpressPlatformData
|
||||
* @property {ExpressPlatformBizcontent} bizcontent 顶层业务载荷对象。
|
||||
*
|
||||
* @typedef {Object} ExpressPlatformBizcontent
|
||||
* @property {string} platform_code 平台编码。
|
||||
* @property {string} express_platform_code 物流平台编码。
|
||||
* @property {number} store_id 店铺 ID。
|
||||
* @property {number} warehouse_id 仓库 ID。
|
||||
* @property {Array<ExpressPlatformOrderItem>} order_list 订单列表。
|
||||
* @property {Object} platform_payload 平台专属载荷占位对象。
|
||||
*
|
||||
* @typedef {Object} ExpressPlatformOrderItem
|
||||
* @property {number} order_id 订单 ID。
|
||||
* @property {number} business_key 业务主键。
|
||||
* @property {string} sys_platform_code 系统平台编码。
|
||||
* @property {string} logistics_code 物流编码。
|
||||
* @property {string} express_platform_code 订单对应的物流平台编码。
|
||||
* @property {ExpressPlatformRouteInfo} route_info 路由信息块。
|
||||
* @property {ExpressPlatformOrderInfo} order_info 订单信息块。
|
||||
* @property {ExpressPlatformReceiverInfo} receiver_info 收件人信息块。
|
||||
* @property {ExpressPlatformSettlementInfo} settlement_info 结算信息块。
|
||||
* @property {ExpressPlatformItemsSummary} items_summary 商品汇总信息块。
|
||||
*
|
||||
* @typedef {Object} ExpressPlatformRouteInfo
|
||||
* @property {string} source_platform_code 来源平台编码。
|
||||
* @property {string} source_platform_name 来源平台名称。
|
||||
* @property {string} sys_platform_code 系统平台编码。
|
||||
* @property {string} sys_platform_name 系统平台名称。
|
||||
* @property {string} logistics_code 物流编码。
|
||||
* @property {string} logistics_name 物流名称。
|
||||
* @property {string} sys_logistics_code 系统物流编码。
|
||||
* @property {string} sys_logistics_name 系统物流名称。
|
||||
* @property {string} express_code 快递单号或快递编码。
|
||||
* @property {string} logistics_area_code 物流区域编码。
|
||||
*
|
||||
* @typedef {Object} ExpressPlatformOrderInfo
|
||||
* @property {string} delivery_order_code 发货单号。
|
||||
* @property {string} order_type 订单类型。
|
||||
* @property {string} status 订单状态。
|
||||
* @property {number} step 流程步骤。
|
||||
* @property {string} order_flag 订单标记。
|
||||
* @property {string} from_key 来源键。
|
||||
* @property {string} create_at 创建时间。
|
||||
* @property {string} place_order_time 下单时间。
|
||||
* @property {string} pay_time 支付时间。
|
||||
* @property {string} operate_time 操作时间。
|
||||
* @property {string} delivery_time 发货时间。
|
||||
*
|
||||
* @typedef {Object} ExpressPlatformReceiverInfo
|
||||
* @property {string} name 收件人姓名。
|
||||
* @property {string} tel 电话。
|
||||
* @property {string} mobile 手机号。
|
||||
* @property {string} email 邮箱。
|
||||
* @property {string} country_code 国家编码。
|
||||
* @property {string} province 省份。
|
||||
* @property {string} city 城市。
|
||||
* @property {string} area 区县。
|
||||
* @property {string} town 乡镇。
|
||||
* @property {string} detail_address 详细地址。
|
||||
* @property {string} zip_code 邮编。
|
||||
*
|
||||
* @typedef {Object} ExpressPlatformSettlementInfo
|
||||
* @property {number} total_amount 总金额。
|
||||
* @property {number} item_amount 商品金额。
|
||||
* @property {number} discount_amount 优惠金额。
|
||||
* @property {number} freight 运费。
|
||||
* @property {number} ar_amount 应收金额。
|
||||
* @property {number} got_amount 已收金额。
|
||||
*
|
||||
* @typedef {Object} ExpressPlatformItemsSummary
|
||||
* @property {Array} items 商品明细。
|
||||
* @property {number} items_count 商品数量。
|
||||
* @property {number} items_total 商品总额。
|
||||
* @property {number} items_weight 商品总重量。
|
||||
*/
|
||||
class ExpressPlatformService extends MainService {
|
||||
/**
|
||||
* 菠萝派数据处理接口。
|
||||
*
|
||||
* @param {Object} [data={}] 平台业务入参。
|
||||
* @return {Promise<never>} 当前暂未实现,直接抛出异常。
|
||||
*/
|
||||
async polyapi(data = {}) {
|
||||
const { matchedPlatform, listByWarehousePlatformCode, orders } = data;
|
||||
const ExpressList = await this.service.systems.express.loadExpressList();
|
||||
console.log("matchedPlatform", JSON.stringify(matchedPlatform));
|
||||
|
||||
console.log('接收到菠萝派快递接口入参:', JSON.stringify(listByWarehousePlatformCode));
|
||||
|
||||
console.log('接收到菠萝派平台数据处理请求,入参:', JSON.stringify(orders));
|
||||
console.log("ExpressList", JSON.stringify(ExpressList));
|
||||
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
|
||||
const allocatedWaybillMap = new Map();
|
||||
if (orderExpressModel && typeof orderExpressModel.findAll === 'function') {
|
||||
const { Op } = this.app.Sequelize;
|
||||
const orderIdList = Array.from(new Set((Array.isArray(orders) ? orders : [])
|
||||
.map(order => Number(order && order.order_id))
|
||||
.filter(orderId => Number.isFinite(orderId) && orderId > 0)));
|
||||
|
||||
if (orderIdList.length > 0) {
|
||||
const allocatedWaybillRows = await orderExpressModel.findAll({
|
||||
attributes: ['order_id', 'business_key', 'waybill_code'],
|
||||
where: {
|
||||
order_id: {
|
||||
[Op.in]: orderIdList,
|
||||
},
|
||||
},
|
||||
order: [['id', 'ASC']],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
for (const row of Array.isArray(allocatedWaybillRows) ? allocatedWaybillRows : []) {
|
||||
const orderId = Number(row && row.order_id);
|
||||
const businessKey = Number(row && row.business_key);
|
||||
const waybillCode = String(row && row.waybill_code || '').trim();
|
||||
if (!Number.isFinite(orderId) || orderId <= 0 || !Number.isFinite(businessKey) || businessKey <= 0 || !waybillCode) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const waybillKey = `${orderId}:${businessKey}`;
|
||||
if (!allocatedWaybillMap.has(waybillKey)) {
|
||||
allocatedWaybillMap.set(waybillKey, waybillCode);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const Dictionary_bizcontent = {
|
||||
};
|
||||
const Dictionary_result = await this.service.systems.poloApi.request('Differ.JH.LogisticsPlatFeatures', Dictionary_bizcontent, matchedPlatform, listByWarehousePlatformCode.token);
|
||||
console.log('==================\n菠萝派平台字典接口返回结果', JSON.stringify(Dictionary_result));
|
||||
|
||||
const order_bizcontent = {
|
||||
orders: orders.map(order_tmp => {
|
||||
const order = order_tmp.order_delivery;
|
||||
return {
|
||||
orderno: `${order.warehouse_id}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单号必须为字符串
|
||||
plattradeno: order.source_order_codes || order.delivery_order_code || '',
|
||||
ismultiplepieces: order.package_count > 1 ? 1 : 0,
|
||||
logisticno: allocatedWaybillMap.get(`${Number(order.id) || 0}:${Number(order_tmp.business_key) || 0}`) || '',
|
||||
logistictype: order.logistics_code || '',
|
||||
numpackage: order.package_count || 1,
|
||||
businesstype: "JH_Normal",
|
||||
|
||||
businessplat: order.sys_platform_code == "KS" ? order.sys_platform_code : "OTHERS",
|
||||
paymode: listByWarehousePlatformCode.paymode ?? 1,
|
||||
ordertype: listByWarehousePlatformCode.ordertype ?? 'JH_Normal',
|
||||
codpaymoney: order.ar_amount ?? null,
|
||||
packagemoney: order.item_amount ?? null,
|
||||
weight: Number(order.items_weight) || 0,
|
||||
supporpaymoney: order.total_amount ?? null,
|
||||
length: Number(order.length) || 0,
|
||||
width: Number(order.width) || 0,
|
||||
height: Number(order.height) || 0,
|
||||
volume: Number(order.volume) || 0,
|
||||
ispickup: listByWarehousePlatformCode.ispickup ?? 0,
|
||||
producttype: listByWarehousePlatformCode.product_type || '',
|
||||
Sipshopid: listByWarehousePlatformCode.shop_id || '',
|
||||
sys_express_code: listByWarehousePlatformCode.sys_express_code || '',
|
||||
platform_code: listByWarehousePlatformCode.platform_code || '',
|
||||
cpcode: ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code)[listByWarehousePlatformCode.platform_code] || '',
|
||||
logisticsproductname: "JH_02",
|
||||
dmssorting: 0,
|
||||
needencrypt: 1,
|
||||
ordersource: matchedPlatform.ordersource || '',
|
||||
inputsite: listByWarehousePlatformCode.site_code || '',
|
||||
sitecode: listByWarehousePlatformCode.site_code || '',
|
||||
shipperno: listByWarehousePlatformCode.client_id || '',
|
||||
sender: {
|
||||
company: listByWarehousePlatformCode.shop_name || '',
|
||||
name: listByWarehousePlatformCode.sender_name || '',
|
||||
phone: listByWarehousePlatformCode.sender_tel || '',
|
||||
mobile: listByWarehousePlatformCode.sender_tel || '',
|
||||
country: "CN",
|
||||
city: listByWarehousePlatformCode.city_name || '',
|
||||
province: listByWarehousePlatformCode.province_name || '',
|
||||
area: listByWarehousePlatformCode.district_name || '',
|
||||
town: listByWarehousePlatformCode.town_name || '',
|
||||
address: listByWarehousePlatformCode.address || '',
|
||||
}, // 需要实现
|
||||
receiver: {
|
||||
name: order.name || '',
|
||||
company: order.company || '',
|
||||
phone: order.mobile || order.tel || '',
|
||||
mobile: order.mobile || order.tel || '',
|
||||
country: order.country_code || 'CN',
|
||||
province: order.province || '',
|
||||
city: order.city || '',
|
||||
area: order.area || '',
|
||||
town: order.town || '',
|
||||
address: order.detail_address || '',
|
||||
zip: order.zip_code || '',
|
||||
email: order.email || '',
|
||||
|
||||
},
|
||||
goods: (order.orderItems && order.orderItems.map(item => ({
|
||||
productid: item.item_code,
|
||||
cnname: item.item_name || "商品",
|
||||
count: item.plan_qty || 0,
|
||||
}))) || [],
|
||||
Mallmaskid: '',
|
||||
template_url: matchedPlatform.template_url || '',
|
||||
labelformat: listByWarehousePlatformCode.labelformat || '',
|
||||
extraInfo: ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code)?.polyapi_extra_info || '',
|
||||
}
|
||||
}),
|
||||
shoptype: matchedPlatform.shoptype,
|
||||
};
|
||||
//调用菠萝派平台接口进行数据处理
|
||||
console.log('==================\n业务数据', JSON.stringify(order_bizcontent), "\n=========================\n");
|
||||
const result = await this.service.systems.poloApi.request('Differ.JH.Logistics.PostOrder', order_bizcontent, matchedPlatform, listByWarehousePlatformCode.token);
|
||||
console.log('==================\n菠萝派平台接口返回结果', JSON.stringify(result));
|
||||
if (result && result.code !== '10000') {
|
||||
throw new Error(`菠萝派平台接口返回错误信息:${result.submessage},原始错误信息: \`\`\`${JSON.stringify(result)}\`\`\`` || '菠萝派平台接口调用失败');
|
||||
} else if (result && result.code === '10000') {
|
||||
const resolveWaybillCode = item => String(item && (item.waybill_code || item.logisticno) || '').trim();
|
||||
let successUpdates = [];
|
||||
switch (listByWarehousePlatformCode.platform_code) {
|
||||
case 'KS':
|
||||
successUpdates = (result.results || []).map(item => {
|
||||
const [warehouse_id, order_id, business_key] = String(item.orderno || '').split('_');
|
||||
const waybillCode = resolveWaybillCode(item);
|
||||
return {
|
||||
warehouse_id,
|
||||
order_id,
|
||||
business_key,
|
||||
waybill_code: waybillCode,
|
||||
orderExpressValues: {
|
||||
waybill_code: waybillCode,
|
||||
printinfo: item.printinfo,
|
||||
signature: item.signature,
|
||||
encryptprintinfo: item.encryptprintinfo,
|
||||
create_at: new Date(),
|
||||
logistics_code: listByWarehousePlatformCode.logistics_code || '',
|
||||
logistics_interface_id: listByWarehousePlatformCode.id || null,
|
||||
logistics_name: listByWarehousePlatformCode.logistics_name || '',
|
||||
logistics_interface_name: listByWarehousePlatformCode.name || '',
|
||||
platform_code: listByWarehousePlatformCode.platform_code || '',
|
||||
status: 1,
|
||||
retry_count: 0,
|
||||
},
|
||||
orderDeliveryValues: {
|
||||
post_status: 'fin',
|
||||
order_flag: '',
|
||||
},
|
||||
};
|
||||
});
|
||||
break;
|
||||
case 'DYXD':
|
||||
successUpdates = (result.results || []).map(item => {
|
||||
const [warehouse_id, order_id, business_key] = String(item.orderno || '').split('_');
|
||||
const waybillCode = resolveWaybillCode(item);
|
||||
return {
|
||||
warehouse_id,
|
||||
order_id,
|
||||
business_key,
|
||||
waybill_code: waybillCode,
|
||||
orderExpressValues: {
|
||||
waybill_code: waybillCode,
|
||||
signature: item.signature,
|
||||
encryptedtoken: item.encryptedtoken,
|
||||
encryptprintinfo: item.encryptprintinfo,
|
||||
create_at: new Date(),
|
||||
logistics_code: listByWarehousePlatformCode.logistics_code || '',
|
||||
logistics_interface_id: listByWarehousePlatformCode.id || null,
|
||||
logistics_name: listByWarehousePlatformCode.logistics_name || '',
|
||||
logistics_interface_name: listByWarehousePlatformCode.name || '',
|
||||
platform_code: listByWarehousePlatformCode.platform_code || '',
|
||||
status: 1,
|
||||
retry_count: 0,
|
||||
},
|
||||
orderDeliveryValues: {
|
||||
post_status: 'fin',
|
||||
order_flag: '',
|
||||
},
|
||||
};
|
||||
});
|
||||
break;
|
||||
case 'JD':
|
||||
case 'XHS':
|
||||
case 'SPH':
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
const orderMetaMap = new Map();
|
||||
for (const order of Array.isArray(orders) ? orders : []) {
|
||||
const orderDelivery = order && order.order_delivery;
|
||||
const warehouseId = Number(orderDelivery && orderDelivery.warehouse_id) || 0;
|
||||
const orderId = Number(orderDelivery && orderDelivery.id) || 0;
|
||||
const businessKey = Number(order && order.business_key) || 0;
|
||||
if (!warehouseId || !orderId || !businessKey) {
|
||||
continue;
|
||||
}
|
||||
|
||||
orderMetaMap.set(`${warehouseId}_${orderId}_${businessKey}`, {
|
||||
store_id: Number(orderDelivery && orderDelivery.store_id) || 0,
|
||||
warehouse_id: warehouseId,
|
||||
});
|
||||
}
|
||||
|
||||
const settlementRelationMap = new Map();
|
||||
for (const item of successUpdates) {
|
||||
const warehouseId = Number(item.warehouse_id) || 0;
|
||||
const orderId = Number(item.order_id) || 0;
|
||||
const businessKey = Number(item.business_key) || 0;
|
||||
if (!warehouseId || !orderId || !businessKey) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const orderMeta = orderMetaMap.get(`${warehouseId}_${orderId}_${businessKey}`);
|
||||
if (!orderMeta) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const storeId = Number(orderMeta.store_id) || 0;
|
||||
if (!storeId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const relationKey = `${storeId}:${warehouseId}`;
|
||||
const currentRelation = settlementRelationMap.get(relationKey) || {
|
||||
store_id: storeId,
|
||||
warehouse_id: warehouseId,
|
||||
success_count: 0,
|
||||
};
|
||||
currentRelation.success_count += 1;
|
||||
settlementRelationMap.set(relationKey, currentRelation);
|
||||
}
|
||||
|
||||
const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse;
|
||||
if (typeof this.ctx.model.transaction === 'function' && successUpdates.length > 0) {
|
||||
await this.ctx.model.transaction(async transaction => {
|
||||
for (const item of successUpdates) {
|
||||
const warehouseId = Number(item.warehouse_id) || 0;
|
||||
const orderId = Number(item.order_id) || 0;
|
||||
const businessKey = Number(item.business_key) || 0;
|
||||
if (!warehouseId || !orderId || !businessKey) {
|
||||
continue;
|
||||
}
|
||||
|
||||
await this.ctx.model.OrderExpress.update(item.orderExpressValues, {
|
||||
where: {
|
||||
order_id: orderId,
|
||||
business_key: businessKey,
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
transaction,
|
||||
});
|
||||
|
||||
if (item.orderDeliveryValues) {
|
||||
const orderModel = await this.service.systems.express.getWaybillAsyncOrderDeliveryModel(item.warehouse_id);
|
||||
await orderModel.update(item.orderDeliveryValues, {
|
||||
where: {
|
||||
id: orderId,
|
||||
},
|
||||
transaction,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (storeWarehouseModel
|
||||
&& typeof storeWarehouseModel.findAll === 'function'
|
||||
&& settlementRelationMap.size > 0) {
|
||||
const { Op } = this.app.Sequelize;
|
||||
const relationList = Array.from(settlementRelationMap.values());
|
||||
const relationRows = await storeWarehouseModel.findAll({
|
||||
attributes: ['id', 'store_id', 'warehouse_id', 'print_quantity', 'print_quantity_locked'],
|
||||
where: {
|
||||
[Op.or]: relationList.map(item => ({
|
||||
store_id: item.store_id,
|
||||
warehouse_id: item.warehouse_id,
|
||||
})),
|
||||
},
|
||||
raw: true,
|
||||
transaction,
|
||||
lock: transaction.LOCK.UPDATE,
|
||||
});
|
||||
|
||||
const relationRowMap = new Map();
|
||||
for (const row of Array.isArray(relationRows) ? relationRows : []) {
|
||||
const relationKey = `${Number(row && row.store_id) || 0}:${Number(row && row.warehouse_id) || 0}`;
|
||||
if (relationKey !== '0:0') {
|
||||
relationRowMap.set(relationKey, row);
|
||||
}
|
||||
}
|
||||
|
||||
for (const item of relationList) {
|
||||
const relationKey = `${item.store_id}:${item.warehouse_id}`;
|
||||
const row = relationRowMap.get(relationKey);
|
||||
if (!row) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const currentPrintQuantity = Number(row.print_quantity || 0);
|
||||
const currentLockedQuantity = Math.max(0, Number(row.print_quantity_locked || 0));
|
||||
const successCount = Number(item.success_count || 0);
|
||||
if (successCount <= 0) {
|
||||
continue;
|
||||
}
|
||||
const printDecrement = successCount;
|
||||
const lockedDecrement = Math.min(currentLockedQuantity, printDecrement);
|
||||
const nextPrintQuantity = currentPrintQuantity - printDecrement;
|
||||
const nextLockedQuantity = Math.max(0, currentLockedQuantity - lockedDecrement);
|
||||
await storeWarehouseModel.update({
|
||||
print_quantity: nextPrintQuantity,
|
||||
print_quantity_locked: nextLockedQuantity,
|
||||
}, {
|
||||
where: {
|
||||
id: row.id,
|
||||
},
|
||||
transaction,
|
||||
});
|
||||
|
||||
await this.ctx.model.StoreWarehousePrintQuantityLog.create({
|
||||
contract_id: Number(row.id || 0),
|
||||
store_id: Number(row.store_id || 0),
|
||||
warehouse_id: Number(row.warehouse_id || 0),
|
||||
change_type: 'order_deduct',
|
||||
business_type: 'order_express',
|
||||
business_id: null,
|
||||
change_quantity: -printDecrement,
|
||||
balance_before: Math.max(0, currentPrintQuantity),
|
||||
balance_after: Math.max(0, nextPrintQuantity),
|
||||
reason: '获取快递号成功扣减',
|
||||
operator_id: null,
|
||||
created_by: null,
|
||||
}, {
|
||||
transaction,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
for (const item of successUpdates) {
|
||||
const warehouseId = Number(item.warehouse_id) || 0;
|
||||
const orderId = Number(item.order_id) || 0;
|
||||
if (!warehouseId || !orderId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
await this.service.systems.operationLog.createOperationLog({
|
||||
businessType: 'order',
|
||||
businessId: `${orderId}`,
|
||||
operationCode: 'WAYBILL',
|
||||
operatorId: this.ctx.user ? this.ctx.user.id : 'system',
|
||||
operatorName: this.ctx.user ? this.ctx.user.employees_name : '系统',
|
||||
externalLogType: 'API',
|
||||
operator: {
|
||||
id: this.ctx.user ? this.ctx.user.employees_id : '0',
|
||||
name: this.ctx.user ? this.ctx.user.employees_name : '系统',
|
||||
},
|
||||
extras: {
|
||||
message: `订单${orderId}获取快递单成功,单号:${item.waybill_code}`,
|
||||
warehouseId,
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
flag: true,
|
||||
code: 0,
|
||||
message: '菠萝派平台数据处理成功',
|
||||
data: result,
|
||||
};
|
||||
//throw new Error('菠萝派平台接口未实现');
|
||||
}
|
||||
|
||||
/**
|
||||
* 菜鸟数据处理接口。
|
||||
*
|
||||
* @param {Object} [data={}] 平台业务入参。
|
||||
* @return {Promise<never>} 当前暂未实现,直接抛出异常。
|
||||
*/
|
||||
async cainiao(data = {}) {
|
||||
void data;
|
||||
console.log('接收到菜鸟平台数据处理请求,入参:', JSON.stringify(data));
|
||||
throw new Error('菜鸟平台接口未实现');
|
||||
}
|
||||
|
||||
/**
|
||||
* 拼多多数据处理接口。
|
||||
*
|
||||
* @param {Object} [data={}] 平台业务入参。
|
||||
* @return {Promise<never>} 当前暂未实现,直接抛出异常。
|
||||
*/
|
||||
async pdd(data = {}) {
|
||||
void data;
|
||||
console.log('接收到拼多多平台数据处理请求,入参:', JSON.stringify(data));
|
||||
|
||||
throw new Error('拼多多平台接口未实现');
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ExpressPlatformService;
|
||||
@ -1,8 +1,19 @@
|
||||
// app/service/operationLog.js
|
||||
// app/service/systems/operation_log.js
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
|
||||
const OPERATION_LOG_ATTRIBUTES = [
|
||||
'id',
|
||||
'operation_code',
|
||||
'operator_name',
|
||||
'created_at',
|
||||
'external_log_type',
|
||||
'external_log_id',
|
||||
'platform_code',
|
||||
'message',
|
||||
];
|
||||
|
||||
class operationLogService extends Service {
|
||||
/**
|
||||
* 通用操作日志记录方法
|
||||
@ -20,6 +31,8 @@ class operationLogService extends Service {
|
||||
* @param {string} params.extras.externalLogType 外部日志类型
|
||||
* @param {number} params.extras.externalLogId 外部日志ID
|
||||
* @param {number} params.extras.warehouseId 仓库ID
|
||||
* @param {string} params.extras.message 日志信息
|
||||
*
|
||||
*/
|
||||
async createOperationLog(params) {
|
||||
const { ctx } = this;
|
||||
@ -43,6 +56,7 @@ class operationLogService extends Service {
|
||||
warehouse_id: extras.warehouseId || null,
|
||||
before_changes: beforeChanges,
|
||||
platform_code: ctx.user?.platform_code || 'SYSTEM',
|
||||
message: extras.message || null,
|
||||
};
|
||||
|
||||
const result = await ctx.model.OperationLog.create(logData);
|
||||
@ -55,58 +69,97 @@ class operationLogService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
async queryStockLogs(query) {
|
||||
/**
|
||||
* 按业务类型查询操作日志分页数据。
|
||||
* @param {Object} query 查询参数。
|
||||
* @param {string|number} query.id 业务ID。
|
||||
* @param {string|number} query.warehouseId 仓库ID。
|
||||
* @param {number} [query.page=1] 页码。
|
||||
* @param {number} [query.pageSize=20] 每页数量。
|
||||
* @param {string} businessType 业务类型。
|
||||
* @return {Promise<{list: Object[], pagination: Object}>} 分页结果。
|
||||
*/
|
||||
async queryLogsByBusinessType(query = {}, businessType) {
|
||||
const { ctx, app } = this;
|
||||
const requestQuery = query && typeof query === 'object' ? query : {};
|
||||
const {
|
||||
id,
|
||||
warehouseId,
|
||||
page = 1,
|
||||
pageSize = 20,
|
||||
} = requestQuery;
|
||||
|
||||
try {
|
||||
const { ctx, app } = this;
|
||||
const {
|
||||
id,
|
||||
warehouseId,
|
||||
page = 1,
|
||||
pageSize = 20,
|
||||
} = query;
|
||||
const where = {};
|
||||
where.business_type = 'stock';
|
||||
if (!id) {
|
||||
throw new Error('id不能为空');
|
||||
} else {
|
||||
where.business_id = id;
|
||||
}
|
||||
if (!warehouseId) {
|
||||
throw new Error('仓库id不能为空');
|
||||
} else {
|
||||
where.warehouse_id = warehouseId;
|
||||
}
|
||||
const where = {
|
||||
business_type: businessType,
|
||||
};
|
||||
|
||||
const offset = (page - 1) * pageSize;
|
||||
|
||||
const result = await ctx.model.OperationLog.findAndCountAll({
|
||||
where,
|
||||
order: [[ 'created_at', 'DESC' ]],
|
||||
offset,
|
||||
attributes: [ 'id', 'operation_code', 'operator_name', 'created_at', 'external_log_type', 'external_log_id', 'platform_code' ],
|
||||
limit: pageSize,
|
||||
});
|
||||
|
||||
return {
|
||||
list: result.rows.map(item => {
|
||||
const item_tmp = JSON.parse(JSON.stringify(item));
|
||||
item_tmp.operation_name = app.getOperationCodeName(item.operation_code);
|
||||
item_tmp.platform_name = app.getPlatformName(item.platform_code);
|
||||
item_tmp.created_at = app.formatDate(item_tmp.created_at);
|
||||
return item_tmp;
|
||||
}),
|
||||
pagination: {
|
||||
page,
|
||||
pageSize,
|
||||
total: result.count,
|
||||
totalPages: Math.ceil(result.count / pageSize),
|
||||
},
|
||||
};
|
||||
} catch (e) {
|
||||
throw e;
|
||||
if (!id) {
|
||||
throw new Error('id不能为空');
|
||||
}
|
||||
where.business_id = id;
|
||||
|
||||
if (!warehouseId) {
|
||||
throw new Error('仓库id不能为空');
|
||||
}
|
||||
where.warehouse_id = warehouseId;
|
||||
|
||||
const currentPage = Number.parseInt(page, 10) || 1;
|
||||
const currentPageSize = Number.parseInt(pageSize, 10) || 20;
|
||||
const offset = (currentPage - 1) * currentPageSize;
|
||||
|
||||
const result = await ctx.model.OperationLog.findAndCountAll({
|
||||
where,
|
||||
order: [[ 'created_at', 'DESC' ]],
|
||||
offset,
|
||||
attributes: OPERATION_LOG_ATTRIBUTES,
|
||||
limit: currentPageSize,
|
||||
});
|
||||
|
||||
const rows = Array.isArray(result.rows) ? result.rows : [];
|
||||
|
||||
return {
|
||||
list: rows.map(item => {
|
||||
const itemTmp = JSON.parse(JSON.stringify(item));
|
||||
itemTmp.operation_name = app.getOperationCodeName(item.operation_code);
|
||||
itemTmp.platform_name = app.getPlatformName(item.platform_code);
|
||||
itemTmp.created_at = app.formatDate(itemTmp.created_at);
|
||||
return itemTmp;
|
||||
}),
|
||||
pagination: {
|
||||
page: currentPage,
|
||||
pageSize: currentPageSize,
|
||||
total: result.count,
|
||||
totalPages: Math.ceil(result.count / currentPageSize),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询库存操作日志。
|
||||
* @param {Object} query 查询参数。
|
||||
* @param {string|number} query.id 库存业务ID。
|
||||
* @param {string|number} query.warehouseId 仓库ID。
|
||||
* @param {number} [query.page=1] 页码。
|
||||
* @param {number} [query.pageSize=20] 每页数量。
|
||||
* @return {Promise<{list: Object[], pagination: Object}>} 分页结果。
|
||||
*/
|
||||
async queryStockLogs(query = {}) {
|
||||
return await this.queryLogsByBusinessType(query, 'stock');
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询订单操作日志。
|
||||
* @param {Object} query 查询参数。
|
||||
* @param {string|number} query.id 订单ID。
|
||||
* @param {string|number} query.warehouseId 仓库ID。
|
||||
* @param {number} [query.page=1] 页码。
|
||||
* @param {number} [query.pageSize=20] 每页数量。
|
||||
* @return {Promise<{list: Object[], pagination: Object}>} 分页结果。
|
||||
*/
|
||||
async queryOrderLogs(query = {}) {
|
||||
return await this.queryLogsByBusinessType(query, 'order');
|
||||
}
|
||||
|
||||
async getMessageDetail(data) {
|
||||
const { id, type } = data;
|
||||
const { ctx } = this;
|
||||
|
||||
1122
app/service/systems/order_async.js
Normal file
1122
app/service/systems/order_async.js
Normal file
File diff suppressed because it is too large
Load Diff
@ -5,10 +5,12 @@ const MainService = require('../main');
|
||||
const OUTBOUND_STATUS = 'fin';
|
||||
const OUTBOUND_STATUS_TIMEOUT = 'timeout';
|
||||
const OUTBOUND_STEP = 4;
|
||||
const OUTBOUND_SYNC_STEPS = [ OUTBOUND_STEP, 9 ];
|
||||
const DISPATCH_LANE = 'm4';
|
||||
const MAX_BATCH_SIZE = 1000;
|
||||
const CURRENT_TABLE_PATTERN = /^wms_order_delivery_(\d+)$/;
|
||||
const RETRYABLE_DATABASE_ERROR_CODES = new Set([ 1205, 1213, 'ER_LOCK_WAIT_TIMEOUT', 'ER_LOCK_DEADLOCK' ]);
|
||||
const DEFAULT_OUTBOUND_STATUSES = [ OUTBOUND_STATUS, 'padding' ];
|
||||
|
||||
/**
|
||||
* 订单出库后迁移到配送表的同步服务。
|
||||
@ -24,7 +26,7 @@ class OrderDeliveryMigrationService extends MainService {
|
||||
*/
|
||||
async syncOutboundOrdersToDelivery(data = {}) {
|
||||
return this.syncOutboundOrdersByStatus(data, {
|
||||
outboundStatuses: [ OUTBOUND_STATUS ],
|
||||
outboundStatuses: DEFAULT_OUTBOUND_STATUSES,
|
||||
persistTimeoutState: true,
|
||||
});
|
||||
}
|
||||
@ -149,7 +151,7 @@ class OrderDeliveryMigrationService extends MainService {
|
||||
* @param {Array<string>|string} outboundStatuses 目标状态。
|
||||
* @return {Array<string>} 规范化后的状态列表。
|
||||
*/
|
||||
normalizeOutboundStatuses(outboundStatuses = [ OUTBOUND_STATUS ]) {
|
||||
normalizeOutboundStatuses(outboundStatuses = DEFAULT_OUTBOUND_STATUSES) {
|
||||
const candidates = Array.isArray(outboundStatuses)
|
||||
? outboundStatuses
|
||||
: [ outboundStatuses ];
|
||||
@ -158,7 +160,7 @@ class OrderDeliveryMigrationService extends MainService {
|
||||
.map(value => String(value || '').trim())
|
||||
.filter(Boolean)));
|
||||
|
||||
return normalizedStatuses.length > 0 ? normalizedStatuses : [ OUTBOUND_STATUS ];
|
||||
return normalizedStatuses.length > 0 ? normalizedStatuses : DEFAULT_OUTBOUND_STATUSES;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -440,7 +442,9 @@ class OrderDeliveryMigrationService extends MainService {
|
||||
outbound_status: {
|
||||
[Op.in]: outboundStatuses,
|
||||
},
|
||||
step: OUTBOUND_STEP,
|
||||
step: {
|
||||
[Op.in]: OUTBOUND_SYNC_STEPS,
|
||||
},
|
||||
},
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
limit: batchLimit,
|
||||
|
||||
@ -13,6 +13,7 @@ class OrderPendingExceptionService extends OrderBaseService {
|
||||
* @return {Promise<Object>} 更新后的订单信息,包含异常文本与更新数量。
|
||||
*/
|
||||
async markPendingException(data = {}) {
|
||||
console.log('订单转异常', JSON.stringify(data));
|
||||
const requestData = this.isPlainObject(data) ? data : {};
|
||||
const exceptionText = String(
|
||||
requestData.exception_text
|
||||
@ -38,6 +39,30 @@ class OrderPendingExceptionService extends OrderBaseService {
|
||||
order_flag: exceptionText,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 将待处理异常订单恢复为待处理状态。
|
||||
*
|
||||
* 兼容单条与批量入参,支持 id、order_id、ids 三种订单 ID 写法。
|
||||
* 会同步清空订单标记,并将审核状态恢复为待处理状态,对应 inspection_status 为 padding、step 为 2。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @return {Promise<Object>} 更新后的订单信息,包含清理后的订单标记与更新数量。
|
||||
*/
|
||||
async reversePendingException(data = {}) {
|
||||
const requestData = this.isPlainObject(data) ? data : {};
|
||||
|
||||
const result = await this.updateOrderInspectionState(requestData, 'padding', {
|
||||
extraUpdateValues: {
|
||||
order_flag: '',
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
...result,
|
||||
order_flag: '',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = OrderPendingExceptionService;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -19,20 +19,58 @@ class PlatformService extends Service {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取平台表的全量字段列表。
|
||||
*
|
||||
* @return {Array<string>} 平台表字段列表。
|
||||
*/
|
||||
getPlatformFullAttributes() {
|
||||
const rawAttributes = this.ctx && this.ctx.model && this.ctx.model.Platform && this.ctx.model.Platform.rawAttributes;
|
||||
|
||||
if (!rawAttributes || typeof rawAttributes !== 'object') {
|
||||
return [];
|
||||
}
|
||||
|
||||
return Object.keys(rawAttributes);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取平台设置表的全量字段列表。
|
||||
*
|
||||
* @return {Array<string>} 平台设置表字段列表。
|
||||
*/
|
||||
getPlatformSettingFullAttributes() {
|
||||
const rawAttributes = this.ctx && this.ctx.model && this.ctx.model.PlatformSetting && this.ctx.model.PlatformSetting.rawAttributes;
|
||||
|
||||
if (!rawAttributes || typeof rawAttributes !== 'object') {
|
||||
return [];
|
||||
}
|
||||
|
||||
return Object.keys(rawAttributes);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成平台列表缓存键。
|
||||
*
|
||||
* @param {number|string} warehouseId 仓库ID。
|
||||
* @param {boolean} [systemOnly=false] 是否仅返回系统基础平台列表。
|
||||
* @param {boolean} [full=false] 是否返回全量字段。
|
||||
* @return {string} 缓存键。
|
||||
*/
|
||||
getPlatformListCacheKey(warehouseId = 0) {
|
||||
getPlatformListCacheKey(warehouseId = 0, systemOnly = false, full = false) {
|
||||
const isFull = [ true, 1, '1', 'true' ].includes(full);
|
||||
|
||||
if (systemOnly) {
|
||||
return isFull ? 'platform:list:system:full' : 'platform:list:system';
|
||||
}
|
||||
|
||||
const normalizedWarehouseId = Number(warehouseId || 0);
|
||||
|
||||
if (Number.isFinite(normalizedWarehouseId) && normalizedWarehouseId > 0) {
|
||||
return `platform:list:${normalizedWarehouseId}`;
|
||||
return isFull ? `platform:list:${normalizedWarehouseId}:full` : `platform:list:${normalizedWarehouseId}`;
|
||||
}
|
||||
|
||||
return 'platform:list';
|
||||
return isFull ? 'platform:list:full' : 'platform:list';
|
||||
}
|
||||
|
||||
/**
|
||||
@ -74,7 +112,7 @@ class PlatformService extends Service {
|
||||
}
|
||||
|
||||
const name = String(row.name || '').trim();
|
||||
const defaultExpressInterface = String(row.default_express_interface || '').trim();
|
||||
const defaultExpressInterface = String(row.platform_code || '').trim();
|
||||
|
||||
return {
|
||||
code,
|
||||
@ -156,14 +194,54 @@ class PlatformService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化系统平台全量记录。
|
||||
*
|
||||
* @param {Object} row 数据库记录。
|
||||
* @return {Object|null} 规范化后的全量记录。
|
||||
*/
|
||||
normalizeFullPlatformRow(row) {
|
||||
const normalizedRow = this.normalizePlatformRow(row);
|
||||
|
||||
if (!normalizedRow) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
...row,
|
||||
...normalizedRow,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化平台设置全量记录。
|
||||
*
|
||||
* @param {Object} row 数据库记录。
|
||||
* @param {Map<string, Object>} platformMap 系统平台映射。
|
||||
* @return {Object|null} 规范化后的全量记录。
|
||||
*/
|
||||
normalizeFullPlatformSettingRow(row, platformMap) {
|
||||
const normalizedRow = this.normalizePlatformSettingRow(row, platformMap);
|
||||
|
||||
if (!normalizedRow) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
...row,
|
||||
...normalizedRow,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 合并基础平台列表和平台设置列表。
|
||||
*
|
||||
* @param {Array<Object>} platformList 系统平台列表。
|
||||
* @param {Array<Object>} platformSettingList 平台设置列表。
|
||||
* @param full
|
||||
* @return {Array<Object>} 合并后的平台列表。
|
||||
*/
|
||||
buildMergedPlatformList(platformList, platformSettingList) {
|
||||
buildMergedPlatformList(platformList, platformSettingList, full = false) {
|
||||
const mergedList = [];
|
||||
const seenCodeMap = new Set();
|
||||
const normalizedPlatformList = Array.isArray(platformList) ? platformList : [];
|
||||
@ -199,7 +277,9 @@ class PlatformService extends Service {
|
||||
}
|
||||
|
||||
for (const row of Array.isArray(platformSettingList) ? platformSettingList : []) {
|
||||
const mergedItem = this.normalizePlatformSettingRow(row, platformMap);
|
||||
const mergedItem = full
|
||||
? this.normalizeFullPlatformSettingRow(row, platformMap)
|
||||
: this.normalizePlatformSettingRow(row, platformMap);
|
||||
if (!mergedItem || seenCodeMap.has(mergedItem.code)) {
|
||||
continue;
|
||||
}
|
||||
@ -211,32 +291,58 @@ class PlatformService extends Service {
|
||||
return mergedList;
|
||||
}
|
||||
|
||||
async loadPlatformListFromDatabase() {
|
||||
const rows = await this.ctx.model.Platform.findAll({
|
||||
attributes: [ 'code', 'name', 'default_express_interface' ],
|
||||
async loadPlatformListFromDatabase(full = false) {
|
||||
const query = {
|
||||
order: [[ 'code', 'ASC' ]],
|
||||
raw: true,
|
||||
});
|
||||
};
|
||||
|
||||
if (full) {
|
||||
const attributes = this.getPlatformFullAttributes();
|
||||
if (attributes.length > 0) {
|
||||
query.attributes = attributes;
|
||||
}
|
||||
} else {
|
||||
query.attributes = [ 'code', 'name', 'platform_code' ];
|
||||
}
|
||||
|
||||
const rows = await this.ctx.model.Platform.findAll(query);
|
||||
|
||||
if (!Array.isArray(rows)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return rows
|
||||
.map(row => this.normalizePlatformRow(row))
|
||||
.map(row => (full ? this.normalizeFullPlatformRow(row) : this.normalizePlatformRow(row)))
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取系统平台列表。
|
||||
*
|
||||
* 该接口只返回系统基础平台数据,不合并仓库自定义映射。
|
||||
*
|
||||
* @return {Promise<Array>} 系统平台列表。
|
||||
*/
|
||||
async getSystemPlatformList() {
|
||||
return await this.loadPlatformListFromDatabase();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取平台列表。
|
||||
*
|
||||
* 先读取系统平台,再按当前仓库合并平台设置;同一编码只保留一条记录。
|
||||
* 默认先读取系统平台,再按当前仓库合并平台设置;同一编码只保留一条记录。
|
||||
* systemOnly 为 true 时仅返回系统平台列表。
|
||||
*
|
||||
* @param {boolean} [systemOnly=false] 是否仅返回系统基础平台列表。
|
||||
* @param {boolean} [full=false] 是否返回全量字段。
|
||||
* @return {Promise<Array>} 平台列表。
|
||||
*/
|
||||
async getPlatformList() {
|
||||
async getPlatformList(systemOnly = false, full = false) {
|
||||
const warehouseId = this.getCurrentWarehouseId();
|
||||
const cacheKey = this.getPlatformListCacheKey(warehouseId);
|
||||
const isSystemOnly = [ true, 1, '1', 'true' ].includes(systemOnly);
|
||||
const isFull = [ true, 1, '1', 'true' ].includes(full);
|
||||
const cacheKey = this.getPlatformListCacheKey(warehouseId, isSystemOnly, isFull);
|
||||
|
||||
try {
|
||||
const cachedList = await this.app.getCacheAsync(cacheKey);
|
||||
@ -244,12 +350,18 @@ class PlatformService extends Service {
|
||||
return Array.isArray(cachedList) ? cachedList : [];
|
||||
}
|
||||
|
||||
if (isSystemOnly) {
|
||||
const platformList = await this.loadPlatformListFromDatabase(isFull);
|
||||
await this.app.setCacheAsync(cacheKey, platformList, DEFAULT_PLATFORM_LIST_CACHE_TTL_SECONDS);
|
||||
return platformList;
|
||||
}
|
||||
|
||||
const [ platformList, platformSettingList ] = await Promise.all([
|
||||
this.loadPlatformListFromDatabase(),
|
||||
this.loadPlatformSettingListFromDatabase(warehouseId),
|
||||
this.loadPlatformListFromDatabase(isFull),
|
||||
this.loadPlatformSettingListFromDatabase(warehouseId, isFull),
|
||||
]);
|
||||
|
||||
const mergedList = this.buildMergedPlatformList(platformList, platformSettingList);
|
||||
const mergedList = this.buildMergedPlatformList(platformList, platformSettingList, isFull);
|
||||
await this.app.setCacheAsync(cacheKey, mergedList, DEFAULT_PLATFORM_LIST_CACHE_TTL_SECONDS);
|
||||
|
||||
return mergedList;
|
||||
@ -303,7 +415,7 @@ class PlatformService extends Service {
|
||||
{
|
||||
model: this.app.model.Platform,
|
||||
as: 'platform',
|
||||
attributes: [ 'code', 'name', 'default_express_interface' ],
|
||||
attributes: [ 'code', 'name', 'platform_code' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
@ -312,7 +424,7 @@ class PlatformService extends Service {
|
||||
platformInfo = {
|
||||
code: platformSetting.platform.code,
|
||||
name: platformSetting.platform.name,
|
||||
default_express_interface: platformSetting.platform.default_express_interface,
|
||||
default_express_interface: String(platformSetting.platform.platform_code || '').trim(),
|
||||
source: 'setting', // 标记来源
|
||||
setting_id: platformSetting.id,
|
||||
warehouse_id: warehouseId,
|
||||
@ -323,14 +435,14 @@ class PlatformService extends Service {
|
||||
where: {
|
||||
code: platformCode,
|
||||
},
|
||||
attributes: [ 'code', 'name', 'default_express_interface' ],
|
||||
attributes: [ 'code', 'name', 'platform_code' ],
|
||||
});
|
||||
|
||||
if (basePlatform) {
|
||||
platformInfo = {
|
||||
code: basePlatform.code,
|
||||
name: basePlatform.name,
|
||||
default_express_interface: basePlatform.default_express_interface,
|
||||
default_express_interface: String(basePlatform.platform_code || '').trim(),
|
||||
source: 'base', // 标记来源
|
||||
warehouse_id: warehouseId,
|
||||
};
|
||||
@ -413,7 +525,7 @@ class PlatformService extends Service {
|
||||
{
|
||||
model: this.app.model.Platform,
|
||||
as: 'platform',
|
||||
attributes: [ 'code', 'name', 'default_express_interface' ],
|
||||
attributes: [ 'code', 'name', 'platform_code' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
@ -34,6 +34,24 @@ class PoloApiService extends Service {
|
||||
},
|
||||
});
|
||||
}
|
||||
async request(method,bizcontent = {},config = {},token) {
|
||||
console.log('查询菠萝派平台数据,入参bizcontent:', JSON.stringify(bizcontent));
|
||||
return this.client.request({
|
||||
method,
|
||||
bizcontent: bizcontent,
|
||||
config,
|
||||
token
|
||||
});
|
||||
}
|
||||
async get(method,bizcontent = {},config = {},token) {
|
||||
console.log('查询菠萝派平台数据,入参bizcontent:', JSON.stringify(bizcontent));
|
||||
return this.client.get({
|
||||
method,
|
||||
bizcontent: bizcontent,
|
||||
config,
|
||||
token
|
||||
});
|
||||
}
|
||||
/**
|
||||
* 快手取号。
|
||||
*
|
||||
|
||||
25
app/service/systems/print/printData.js
Normal file
25
app/service/systems/print/printData.js
Normal file
@ -0,0 +1,25 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
|
||||
const result = {
|
||||
platform:null,
|
||||
count:0,
|
||||
datas:[],
|
||||
};
|
||||
class PrintDataService extends Service {
|
||||
|
||||
async getPrintData({ printType, orderId }) {
|
||||
const { ctx } = this;
|
||||
switch (printType) {
|
||||
case 'delivery_order': {
|
||||
const deliveryOrderData = await ctx.service.systems.deliveryOrder.getPrintData({ orderId });
|
||||
return deliveryOrderData;
|
||||
}
|
||||
default:
|
||||
return { success: false, error: `不支持的打印类型 ${printType}` };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = PrintDataService;
|
||||
@ -1,182 +1,28 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
const https = require('https');
|
||||
const http = require('http');
|
||||
const QimenClient = require('../../lib/qimen_client');
|
||||
|
||||
class QimenQueryService extends Service {
|
||||
get qimenClient() {
|
||||
if (!this.app.qimenClient) {
|
||||
this.app.qimenClient = new QimenClient(this.app);
|
||||
}
|
||||
|
||||
return this.app.qimenClient;
|
||||
}
|
||||
|
||||
async send(method, customerId, data) {
|
||||
|
||||
try {
|
||||
const wmsAppKey = this.app.config.qimen.appKey;
|
||||
const baseQueryParams = this.getQueryParams(method, wmsAppKey, '2.0', customerId);
|
||||
const baseUrl = 'http://qimen.api.taobao.com/router/qimen/service';
|
||||
const xmlData = await this.ctx.service.systems.sign.toXml(data);
|
||||
const queryData = this.replaceXmlTagsWithString(xmlData, 'item', 'orderLine');
|
||||
const sign = await this.ctx.service.systems.sign.signTopRequest(baseQueryParams, queryData, this.app.config.qimen.security, 'md5');
|
||||
const queryParams = this.addSign(baseQueryParams, sign);
|
||||
const url = this.generateUrlWithParams(baseUrl, queryParams);
|
||||
const logData = {
|
||||
from_key: this.app.config.qimen.appKey,
|
||||
to_key: wmsAppKey,
|
||||
method,
|
||||
sign,
|
||||
costomer_id: customerId,
|
||||
v: '2.0',
|
||||
url,
|
||||
created_at: new Date(),
|
||||
body: '',
|
||||
result: '',
|
||||
use_time: 0,
|
||||
};
|
||||
const result = await this.sendRequest(url, queryData, logData);
|
||||
const xmlArray = await this.ctx.service.qimen.parseXmlToArray(result.res);
|
||||
return { queryId: result.queryId, xmlArray };
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
return this.qimenClient.send(method, customerId, data, {
|
||||
ctx: this.ctx,
|
||||
});
|
||||
}
|
||||
|
||||
replaceXmlTagsWithString(xmlString, oldTag, newTag) {
|
||||
// 匹配开始标签(包括属性)
|
||||
const startTagRegex = new RegExp(`<\\s*${oldTag}(\\s+[^>]*)?>`, 'gi');
|
||||
|
||||
// 匹配结束标签
|
||||
const endTagRegex = new RegExp(`<\\s*/\\s*${oldTag}\\s*>`, 'gi');
|
||||
|
||||
// 匹配自闭合标签
|
||||
const selfClosingRegex = new RegExp(`<\\s*${oldTag}(\\s+[^>]*)?\\s*/>`, 'gi');
|
||||
|
||||
return xmlString
|
||||
.replace(startTagRegex, (match, attributes = '') => {
|
||||
return `<${newTag}${attributes}>`;
|
||||
})
|
||||
.replace(endTagRegex, `</${newTag}>`)
|
||||
.replace(selfClosingRegex, (match, attributes = '') => {
|
||||
return `<${newTag}${attributes}/>`;
|
||||
});
|
||||
}
|
||||
addSign(baseQueryParams, sign) {
|
||||
return Object.assign({}, baseQueryParams, { sign });
|
||||
}
|
||||
getQueryParams(method, app_key, v, customerId) {
|
||||
const param = {
|
||||
method,
|
||||
format: 'xml',
|
||||
app_key,
|
||||
v,
|
||||
sign_method: 'md5',
|
||||
customerId,
|
||||
timestamp: this.app.formatDate(new Date()),
|
||||
};
|
||||
return param;
|
||||
}
|
||||
generateUrlWithParams(baseUrl, params) {
|
||||
if (!params || Object.keys(params).length === 0) {
|
||||
return baseUrl;
|
||||
}
|
||||
|
||||
const queryString = Object.keys(params)
|
||||
.map(key => {
|
||||
const value = params[key];
|
||||
// 对参数进行URL编码
|
||||
return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
|
||||
})
|
||||
.join('&');
|
||||
|
||||
// 检查基础URL是否已包含查询参数
|
||||
const separator = baseUrl.includes('?') ? '&' : '?';
|
||||
return `${baseUrl}${separator}${queryString}`;
|
||||
}
|
||||
/**
|
||||
* 发送奇门请求并在成功或失败时落库日志。
|
||||
* @param {string} url 请求地址。
|
||||
* @param {string} requestData 请求报文。
|
||||
* @param {Object} [logData={}] 日志基础数据。
|
||||
* @return {Promise<{queryId: *, res: string}>} 请求结果。
|
||||
*/
|
||||
async sendRequest(url, requestData, logData = {}) {
|
||||
const startTime = Date.now();
|
||||
const { service } = this;
|
||||
const requestLogData = Object.assign({
|
||||
body: requestData,
|
||||
result: '',
|
||||
log_id: this.ctx.qimenLogId || null,
|
||||
}, logData);
|
||||
requestLogData.body = requestLogData.body || requestData;
|
||||
requestLogData.result = requestLogData.result || '';
|
||||
requestLogData.log_id = requestLogData.log_id || this.ctx.qimenLogId || null;
|
||||
let httpquery = null;
|
||||
if (url.indexOf('https://') > -1) {
|
||||
httpquery = https;
|
||||
} else {
|
||||
httpquery = http;
|
||||
}
|
||||
|
||||
let requestXml;
|
||||
try {
|
||||
// 判断 requestData 是否为字符串,如果是字符串则直接使用,否则进行转换
|
||||
if (typeof requestData === 'string') {
|
||||
requestXml = requestData;
|
||||
|
||||
// 可选:验证字符串是否是有效的XML
|
||||
if (requestXml.trim() === '') {
|
||||
throw new Error('请求数据为空字符串');
|
||||
}
|
||||
} else {
|
||||
requestXml = await this.ctx.service.qimen.formatResponse(requestData);
|
||||
}
|
||||
|
||||
// 最终检查XML是否为空
|
||||
if (!requestXml || requestXml.trim() === '') {
|
||||
throw new Error('XML内容为空');
|
||||
}
|
||||
} catch (error) {
|
||||
requestLogData.result = error.stack || `${error.name || 'Error'}: ${error.message || String(error)}`;
|
||||
await service.qimen.saveQimenLog(requestLogData, startTime);
|
||||
throw error;
|
||||
}
|
||||
const header = {
|
||||
'Content-Type': 'application/xml',
|
||||
'Content-Length': Buffer.byteLength(requestXml, 'utf8'),
|
||||
'User-Agent': 'EggJS Client',
|
||||
};
|
||||
const options = {
|
||||
method: 'POST',
|
||||
headers: header,
|
||||
};
|
||||
let res;
|
||||
try {
|
||||
res = await new Promise((resolve, reject) => {
|
||||
let req;
|
||||
try {
|
||||
req = httpquery.request(url, options, response => {
|
||||
let datas = '';
|
||||
response.on('data', chunk => {
|
||||
datas += chunk;
|
||||
});
|
||||
response.on('end', () => {
|
||||
resolve(datas);
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
|
||||
req.on('error', error => {
|
||||
reject(error);
|
||||
});
|
||||
|
||||
req.write(requestXml);
|
||||
req.end();
|
||||
});
|
||||
} catch (error) {
|
||||
requestLogData.result = error.stack || `${error.name || 'Error'}: ${error.message || String(error)}`;
|
||||
await service.qimen.saveQimenLog(requestLogData, startTime);
|
||||
throw error;
|
||||
}
|
||||
requestLogData.result = res;
|
||||
const queryId = await service.qimen.saveQimenLog(requestLogData, startTime);
|
||||
return { queryId, res };
|
||||
return this.qimenClient.sendRequest(url, requestData, logData, {
|
||||
ctx: this.ctx,
|
||||
});
|
||||
}
|
||||
}
|
||||
module.exports = QimenQueryService;
|
||||
|
||||
module.exports = QimenQueryService;
|
||||
@ -30,6 +30,97 @@ class SettingExpressService extends Service {
|
||||
return storeId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成当前仓库快递列表缓存键。
|
||||
*
|
||||
* @param {number|string} warehouseId 仓库主体ID
|
||||
* @return {string} 缓存键
|
||||
*/
|
||||
getExpressListCacheKey(warehouseId = 0) {
|
||||
const normalizedWarehouseId = Number(warehouseId || 0);
|
||||
|
||||
if (Number.isFinite(normalizedWarehouseId) && normalizedWarehouseId > 0) {
|
||||
return `express:list:${normalizedWarehouseId}`;
|
||||
}
|
||||
|
||||
return 'express:list';
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除指定缓存键。
|
||||
*
|
||||
* @param {string} cacheKey 缓存键
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async deleteCacheByKey(cacheKey) {
|
||||
if (!cacheKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { app } = this;
|
||||
if (app && typeof app.delCacheAsync === 'function') {
|
||||
await app.delCacheAsync(cacheKey);
|
||||
return;
|
||||
}
|
||||
|
||||
if (app && typeof app.setCacheAsync === 'function') {
|
||||
await app.setCacheAsync(cacheKey, null, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理当前仓库快递列表缓存。
|
||||
*
|
||||
* @param {number|string} warehouseId 仓库主体ID
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async clearExpressListCache(warehouseId) {
|
||||
await this.deleteCacheByKey(this.getExpressListCacheKey(warehouseId));
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化删除 ID 列表。
|
||||
*
|
||||
* 优先读取 `ids`,其次兼容单个 `id`、`setting_id`、`settingId`。
|
||||
*
|
||||
* @param {Object} data 请求参数
|
||||
* @return {Array<number>} 删除 ID 列表
|
||||
*/
|
||||
normalizeDeleteIds(data = {}) {
|
||||
const {
|
||||
ids,
|
||||
id,
|
||||
setting_id: settingId,
|
||||
settingId: camelSettingId,
|
||||
} = data || {};
|
||||
|
||||
const rawIds = ids !== undefined
|
||||
? ids
|
||||
: (id !== undefined ? id : (settingId !== undefined ? settingId : camelSettingId));
|
||||
|
||||
const values = Array.isArray(rawIds)
|
||||
? rawIds
|
||||
: String(rawIds || '')
|
||||
.split(',')
|
||||
.map(item => item.trim())
|
||||
.filter(Boolean);
|
||||
|
||||
const normalizedIds = [];
|
||||
const seenIds = new Set();
|
||||
|
||||
for (const value of values) {
|
||||
const normalized = Number(value);
|
||||
if (!Number.isInteger(normalized) || normalized <= 0 || seenIds.has(normalized)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
seenIds.add(normalized);
|
||||
normalizedIds.push(normalized);
|
||||
}
|
||||
|
||||
return normalizedIds;
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化文本值。
|
||||
*
|
||||
@ -196,6 +287,7 @@ class SettingExpressService extends Service {
|
||||
where: {
|
||||
id,
|
||||
warehouse_id: this.getCurrentStoreId(),
|
||||
deleted_at: null,
|
||||
},
|
||||
});
|
||||
|
||||
@ -219,6 +311,7 @@ class SettingExpressService extends Service {
|
||||
const where = {
|
||||
warehouse_id: this.getCurrentStoreId(),
|
||||
code,
|
||||
deleted_at: null,
|
||||
};
|
||||
|
||||
const normalizedExcludeId = Number(excludeId || 0);
|
||||
@ -326,6 +419,9 @@ class SettingExpressService extends Service {
|
||||
{
|
||||
warehouse_id: currentStoreId,
|
||||
},
|
||||
{
|
||||
deleted_at: null,
|
||||
},
|
||||
];
|
||||
|
||||
const dynamicConditions = Array.isArray(parsedResult.dynamicConditions) ? parsedResult.dynamicConditions : [];
|
||||
@ -454,6 +550,8 @@ class SettingExpressService extends Service {
|
||||
express_code: expressInfo.code,
|
||||
});
|
||||
|
||||
await this.clearExpressListCache(currentStoreId);
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
data: this.normalizeSettingRow(created.get ? created.get({ plain: true }) : created, expressMap),
|
||||
@ -467,7 +565,6 @@ class SettingExpressService extends Service {
|
||||
* @return {Promise<Object>} 修改结果
|
||||
*/
|
||||
async update(data = {}) {
|
||||
const { ctx } = this;
|
||||
const id = Number(data.id || data.setting_id || data.settingId || 0);
|
||||
if (!Number.isFinite(id) || id <= 0) {
|
||||
throw this.createError('id 参数不能为空', 400);
|
||||
@ -516,6 +613,8 @@ class SettingExpressService extends Service {
|
||||
|
||||
await setting.update(updates);
|
||||
|
||||
await this.clearExpressListCache(this.getCurrentStoreId());
|
||||
|
||||
if (!expressMap) {
|
||||
expressMap = await this.getSystemExpressMap();
|
||||
}
|
||||
@ -525,6 +624,153 @@ class SettingExpressService extends Service {
|
||||
data: this.normalizeSettingRow(setting.get ? setting.get({ plain: true }) : setting, expressMap),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询批量删除目标记录。
|
||||
*
|
||||
* @param {Array<number>} ids 删除ID列表
|
||||
* @return {Promise<Array<Object>>} 目标记录列表
|
||||
*/
|
||||
async findSettingsForDelete(ids) {
|
||||
const { ctx, app } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
|
||||
return await ctx.model.ExpressSetting.findAll({
|
||||
where: {
|
||||
warehouse_id: this.getCurrentStoreId(),
|
||||
id: {
|
||||
[Op.in]: ids,
|
||||
},
|
||||
},
|
||||
attributes: [ 'id', 'code', 'deleted_at' ],
|
||||
raw: true,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查待删除快递编码是否被当前仓库快递接口引用。
|
||||
*
|
||||
* @param {Array<string>} codes 快递设置编码列表
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async ensureDeleteCodesNotReferenced(codes) {
|
||||
const uniqueCodes = Array.from(new Set(
|
||||
Array.isArray(codes)
|
||||
? codes.map(code => String(code || '').trim()).filter(Boolean)
|
||||
: []
|
||||
));
|
||||
|
||||
if (uniqueCodes.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { ctx, app } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
const referencedRows = await ctx.model.ExpressInterface.findAll({
|
||||
where: {
|
||||
warehouse_id: this.getCurrentStoreId(),
|
||||
express_code: {
|
||||
[Op.in]: uniqueCodes,
|
||||
},
|
||||
},
|
||||
attributes: [ 'id', 'express_code' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (Array.isArray(referencedRows) && referencedRows.length > 0) {
|
||||
const referencedCodes = Array.from(new Set(
|
||||
referencedRows
|
||||
.map(row => String(row && row.express_code || '').trim())
|
||||
.filter(Boolean)
|
||||
));
|
||||
|
||||
throw this.createError(`存在快递接口引用的快递编码,无法删除:${referencedCodes.join('、')}`, 409);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除快递映射。
|
||||
*
|
||||
* @param {Object} data 请求参数
|
||||
* @return {Promise<Object>} 删除结果
|
||||
*/
|
||||
async delete(data = {}) {
|
||||
const { ctx, app } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
const ids = this.normalizeDeleteIds(data);
|
||||
|
||||
if (ids.length === 0) {
|
||||
throw this.createError('ids 参数不能为空', 400);
|
||||
}
|
||||
|
||||
const settings = await this.findSettingsForDelete(ids);
|
||||
if (!Array.isArray(settings) || settings.length !== ids.length) {
|
||||
throw this.createError('快递映射不存在或无权限操作', 404);
|
||||
}
|
||||
|
||||
const settingMap = new Map();
|
||||
for (const setting of settings) {
|
||||
if (!setting || typeof setting !== 'object') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const settingId = Number(setting.id);
|
||||
if (Number.isInteger(settingId) && settingId > 0) {
|
||||
settingMap.set(settingId, setting);
|
||||
}
|
||||
}
|
||||
|
||||
const deletedIds = [];
|
||||
const alreadyDeletedIds = [];
|
||||
const targetCodes = [];
|
||||
|
||||
for (const id of ids) {
|
||||
const setting = settingMap.get(id);
|
||||
if (!setting) {
|
||||
throw this.createError('快递映射不存在或无权限操作', 404);
|
||||
}
|
||||
|
||||
targetCodes.push(String(setting.code || '').trim());
|
||||
|
||||
if (setting.deleted_at) {
|
||||
alreadyDeletedIds.push(id);
|
||||
continue;
|
||||
}
|
||||
|
||||
deletedIds.push(id);
|
||||
}
|
||||
|
||||
await this.ensureDeleteCodesNotReferenced(targetCodes);
|
||||
|
||||
if (deletedIds.length > 0) {
|
||||
await ctx.model.transaction(async transaction => {
|
||||
await ctx.model.ExpressSetting.update({
|
||||
deleted_at: new Date(),
|
||||
}, {
|
||||
where: {
|
||||
warehouse_id: this.getCurrentStoreId(),
|
||||
id: {
|
||||
[Op.in]: deletedIds,
|
||||
},
|
||||
deleted_at: null,
|
||||
},
|
||||
transaction,
|
||||
});
|
||||
});
|
||||
|
||||
await this.clearExpressListCache(this.getCurrentStoreId());
|
||||
}
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
data: {
|
||||
ids,
|
||||
deleted_ids: deletedIds,
|
||||
already_deleted_ids: alreadyDeletedIds,
|
||||
status: 'deleted',
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = SettingExpressService;
|
||||
|
||||
@ -3,6 +3,8 @@
|
||||
const Service = require('egg').Service;
|
||||
const { parseWhereConditions } = require('../../../lib/query_condition_parser');
|
||||
|
||||
const DEFAULT_CACHE_TTL_SECONDS = 600;
|
||||
|
||||
class SettingExpressInterfaceService extends Service {
|
||||
/**
|
||||
* 创建业务错误对象。
|
||||
@ -30,6 +32,70 @@ class SettingExpressInterfaceService extends Service {
|
||||
return storeId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成仓库与平台维度的快递接口缓存键。
|
||||
*
|
||||
* @param {number|string} warehouseId 仓库 ID
|
||||
* @param {string} platformCode 平台代码
|
||||
* @return {string} 缓存键
|
||||
*/
|
||||
getWarehousePlatformCacheKey(warehouseId, platformCode) {
|
||||
const normalizedWarehouseId = Number(warehouseId || 0);
|
||||
const normalizedPlatformCode = String(platformCode || '').trim().toUpperCase();
|
||||
|
||||
return `express_interface:warehouse:${normalizedWarehouseId}:platform:${normalizedPlatformCode}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除指定缓存键。
|
||||
*
|
||||
* @param {string} cacheKey 缓存键
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async deleteCacheByKey(cacheKey) {
|
||||
if (!cacheKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { app } = this;
|
||||
if (app && typeof app.delCacheAsync === 'function') {
|
||||
await app.delCacheAsync(cacheKey);
|
||||
return;
|
||||
}
|
||||
|
||||
if (app && typeof app.setCacheAsync === 'function') {
|
||||
await app.setCacheAsync(cacheKey, null, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理当前仓库与平台维度的快递接口缓存。
|
||||
*
|
||||
* @param {number|string} warehouseId 仓库 ID
|
||||
* @param {string} platformCode 平台代码
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async clearWarehousePlatformCache(warehouseId, platformCode) {
|
||||
await this.deleteCacheByKey(this.getWarehousePlatformCacheKey(warehouseId, platformCode));
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化平台代码。
|
||||
*
|
||||
* @param {string} value 原始值
|
||||
* @param {string} fieldName 字段名称
|
||||
* @param {number} [maxLength=20] 最大长度
|
||||
* @return {string} 规范化后的平台代码
|
||||
*/
|
||||
normalizePlatformCode(value, fieldName, maxLength = 20) {
|
||||
const normalized = this.normalizeText(value, fieldName, maxLength).toUpperCase();
|
||||
if (!normalized) {
|
||||
throw this.createError(`${fieldName} 参数不能为空`, 400);
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化文本值。
|
||||
*
|
||||
@ -173,9 +239,6 @@ class SettingExpressInterfaceService extends Service {
|
||||
platform_code: {
|
||||
field: 'platform_code',
|
||||
},
|
||||
express_platform_id: {
|
||||
field: 'express_platform_id',
|
||||
},
|
||||
sender_name: {
|
||||
field: 'sender_name',
|
||||
},
|
||||
@ -239,6 +302,87 @@ class SettingExpressInterfaceService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取快递接口联查配置。
|
||||
*
|
||||
* @param options
|
||||
* @return {Array<Object>} Sequelize 关联配置,仅保留系统快递关联。
|
||||
*/
|
||||
getInterfaceInclude(options = {}) {
|
||||
const { ctx } = this;
|
||||
const { full = false } = options;
|
||||
|
||||
const include = {
|
||||
model: ctx.model.Express,
|
||||
as: 'express',
|
||||
required: false,
|
||||
};
|
||||
|
||||
if (!full) {
|
||||
include.attributes = [ 'code', 'name' ];
|
||||
}
|
||||
|
||||
return [
|
||||
include,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取快递接口模型的全量字段。
|
||||
*
|
||||
* @return {Array<string>} 模型字段列表
|
||||
*/
|
||||
getInterfaceFullAttributes() {
|
||||
const rawAttributes = this.ctx && this.ctx.model && this.ctx.model.ExpressInterface && this.ctx.model.ExpressInterface.rawAttributes;
|
||||
|
||||
if (!rawAttributes || typeof rawAttributes !== 'object') {
|
||||
return [];
|
||||
}
|
||||
|
||||
return Object.keys(rawAttributes);
|
||||
}
|
||||
|
||||
/**
|
||||
* 复制普通对象或数组,避免缓存对象被外部修改。
|
||||
*
|
||||
* @param {*} value 待复制的值
|
||||
* @return {*} 复制后的值
|
||||
*/
|
||||
clonePlainValue(value) {
|
||||
if (Array.isArray(value)) {
|
||||
return value.map(item => this.clonePlainValue(item));
|
||||
}
|
||||
|
||||
if (value && typeof value === 'object') {
|
||||
const cloned = {};
|
||||
for (const [ key, item ] of Object.entries(value)) {
|
||||
cloned[key] = this.clonePlainValue(item);
|
||||
}
|
||||
return cloned;
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化系统快递记录。
|
||||
*
|
||||
* @param {Object} row 数据库记录
|
||||
* @return {Object|null} 规范化后的系统快递信息
|
||||
*/
|
||||
normalizeExpressRow(row) {
|
||||
if (!row || typeof row !== 'object') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
code: this.normalizeOptionalText(row.code, 'express.code', 50),
|
||||
name: this.normalizeOptionalText(row.name, 'express.name', 255),
|
||||
polyapi_extra_info: row.polyapi_extra_info === undefined ? null : row.polyapi_extra_info,
|
||||
pdd_code: this.normalizeOptionalText(row.pdd_code, 'express.pdd_code', 255),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化快递接口记录。
|
||||
*
|
||||
@ -250,14 +394,15 @@ class SettingExpressInterfaceService extends Service {
|
||||
return null;
|
||||
}
|
||||
|
||||
const express = this.normalizeExpressRow(row.express && typeof row.express === 'object' ? row.express : null);
|
||||
|
||||
return {
|
||||
id: row.id === undefined || row.id === null ? null : Number(row.id),
|
||||
name: this.normalizeOptionalText(row.name, 'name', 255),
|
||||
express_code: this.normalizeOptionalText(row.express_code, 'express_code', 255),
|
||||
warehouse_id: row.warehouse_id === undefined || row.warehouse_id === null ? null : Number(row.warehouse_id),
|
||||
platform_code: this.normalizeOptionalText(row.platform_code, 'platform_code', 20),
|
||||
express_platform_id: row.express_platform_id === undefined || row.express_platform_id === null ? null : Number(row.express_platform_id),
|
||||
sender_name: this.normalizeOptionalText(row.sender_name, 'sender_name', 50),
|
||||
sender_name: this.normalizeOptionalText(row.sender_name, 'sender_name', 50),
|
||||
sender_tel: this.normalizeOptionalText(row.sender_tel, 'sender_tel', 11),
|
||||
weight: row.weight === undefined || row.weight === null ? null : Number(row.weight),
|
||||
token: this.normalizeOptionalText(row.token, 'token', 500),
|
||||
@ -272,6 +417,100 @@ class SettingExpressInterfaceService extends Service {
|
||||
site_code: this.normalizeOptionalText(row.site_code, 'site_code', 255),
|
||||
product_type: this.normalizeOptionalText(row.product_type, 'product_type', 50),
|
||||
shop_name: this.normalizeOptionalText(row.shop_name, 'shop_name', 255),
|
||||
express,
|
||||
express_name: express ? express.name : null,
|
||||
express_polyapi_extra_info: express ? express.polyapi_extra_info : null,
|
||||
express_pdd_code: express ? express.pdd_code : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化快递接口的全量记录。
|
||||
*
|
||||
* @param {Object} row 数据库记录
|
||||
* @return {Object|null} 规范化后的全量记录
|
||||
*/
|
||||
normalizeFullInterfaceRow(row) {
|
||||
if (!row || typeof row !== 'object') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const attributes = this.getInterfaceFullAttributes();
|
||||
const normalized = {};
|
||||
const keys = attributes.length > 0 ? attributes : Object.keys(row);
|
||||
|
||||
for (const key of keys) {
|
||||
if (Object.prototype.hasOwnProperty.call(row, key)) {
|
||||
normalized[key] = this.clonePlainValue(row[key]);
|
||||
}
|
||||
}
|
||||
|
||||
if (Object.prototype.hasOwnProperty.call(row, 'express')) {
|
||||
normalized.express = this.clonePlainValue(row.express);
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化快递接口的全量记录数组,并按 weight / id 排序。
|
||||
*
|
||||
* @param {Array|Object} rows 数据库记录数组或单条记录
|
||||
* @return {Array<Object>} 规范化后的全量记录数组
|
||||
*/
|
||||
normalizeFullInterfaceRows(rows) {
|
||||
const sourceRows = Array.isArray(rows)
|
||||
? rows
|
||||
: rows ? [ rows ] : [];
|
||||
|
||||
return sourceRows
|
||||
.map(row => this.normalizeFullInterfaceRow(row))
|
||||
.filter(row => row)
|
||||
.sort((left, right) => {
|
||||
const leftWeight = left.weight === undefined || left.weight === null
|
||||
? Number.POSITIVE_INFINITY
|
||||
: Number(left.weight);
|
||||
const rightWeight = right.weight === undefined || right.weight === null
|
||||
? Number.POSITIVE_INFINITY
|
||||
: Number(right.weight);
|
||||
|
||||
if (leftWeight !== rightWeight) {
|
||||
return leftWeight - rightWeight;
|
||||
}
|
||||
|
||||
const leftId = left.id === undefined || left.id === null
|
||||
? Number.POSITIVE_INFINITY
|
||||
: Number(left.id);
|
||||
const rightId = right.id === undefined || right.id === null
|
||||
? Number.POSITIVE_INFINITY
|
||||
: Number(right.id);
|
||||
|
||||
return leftId - rightId;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析仓库与平台代码查询条件。
|
||||
*
|
||||
* @param {Object} data 请求参数
|
||||
* @return {Object} 归一化后的仓库与平台信息
|
||||
*/
|
||||
resolveWarehousePlatformTarget(data = {}) {
|
||||
const warehouseValue = data.warehouse_id !== undefined
|
||||
? data.warehouse_id
|
||||
: data.warehouseId;
|
||||
const platformValue = data.platform_code !== undefined
|
||||
? data.platform_code
|
||||
: data.platformCode;
|
||||
|
||||
const warehouseId = warehouseValue === undefined
|
||||
? this.getCurrentStoreId()
|
||||
: this.normalizeInteger(warehouseValue, 'warehouse_id', { min: 1 });
|
||||
const platformCode = this.normalizePlatformCode(platformValue, 'platform_code', 20);
|
||||
|
||||
return {
|
||||
warehouseId,
|
||||
platformCode,
|
||||
};
|
||||
}
|
||||
|
||||
@ -290,6 +529,7 @@ class SettingExpressInterfaceService extends Service {
|
||||
id,
|
||||
warehouse_id: currentStoreId,
|
||||
},
|
||||
include: this.getInterfaceInclude(),
|
||||
});
|
||||
|
||||
if (!setting) {
|
||||
@ -324,6 +564,7 @@ class SettingExpressInterfaceService extends Service {
|
||||
return await ctx.model.ExpressInterface.findOne({
|
||||
where,
|
||||
attributes: [ 'id', 'express_code' ],
|
||||
include: this.getInterfaceInclude(),
|
||||
});
|
||||
}
|
||||
|
||||
@ -331,17 +572,15 @@ class SettingExpressInterfaceService extends Service {
|
||||
* 查找同仓下的平台接口冲突记录。
|
||||
*
|
||||
* @param {string} platformCode 平台代码
|
||||
* @param {number} expressPlatformId 快递接口 ID
|
||||
* @param {number|null} [excludeId=null] 排除的记录 ID
|
||||
* @return {Promise<Object|null>} 冲突记录
|
||||
*/
|
||||
async findInterfaceConflict(platformCode, expressPlatformId, excludeId = null) {
|
||||
async findInterfaceConflict(platformCode, excludeId = null) {
|
||||
const { ctx, app } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
const where = {
|
||||
warehouse_id: this.getCurrentStoreId(),
|
||||
platform_code: platformCode,
|
||||
express_platform_id: expressPlatformId,
|
||||
};
|
||||
|
||||
const normalizedExcludeId = Number(excludeId || 0);
|
||||
@ -353,7 +592,8 @@ class SettingExpressInterfaceService extends Service {
|
||||
|
||||
return await ctx.model.ExpressInterface.findOne({
|
||||
where,
|
||||
attributes: [ 'id', 'platform_code', 'express_platform_id' ],
|
||||
attributes: [ 'id', 'platform_code' ],
|
||||
include: this.getInterfaceInclude(),
|
||||
});
|
||||
}
|
||||
|
||||
@ -380,8 +620,8 @@ class SettingExpressInterfaceService extends Service {
|
||||
* @param {number|null} [excludeId=null] 排除的记录 ID
|
||||
* @return {Promise<boolean>} 是否可用
|
||||
*/
|
||||
async ensureInterfaceAvailable(platformCode, expressPlatformId, excludeId = null) {
|
||||
const conflict = await this.findInterfaceConflict(platformCode, expressPlatformId, excludeId);
|
||||
async ensureInterfaceAvailable(platformCode, excludeId = null) {
|
||||
const conflict = await this.findInterfaceConflict(platformCode, excludeId);
|
||||
if (conflict) {
|
||||
throw this.createError('当前平台和快递接口组合已被使用', 409);
|
||||
}
|
||||
@ -452,8 +692,9 @@ class SettingExpressInterfaceService extends Service {
|
||||
where: {
|
||||
[Op.and]: andConditions,
|
||||
},
|
||||
include: this.getInterfaceInclude(),
|
||||
attributes: [
|
||||
'id', 'name', 'express_code', 'warehouse_id', 'platform_code', 'express_platform_id',
|
||||
'id', 'name', 'express_code', 'warehouse_id', 'platform_code',
|
||||
'sender_name', 'sender_tel', 'weight', 'token', 'viewer', 'client_id', 'is_share',
|
||||
'share_id', 'can_use_count', 'province_name', 'city_name', 'district_name', 'site_code',
|
||||
'product_type', 'shop_name',
|
||||
@ -461,11 +702,11 @@ class SettingExpressInterfaceService extends Service {
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
offset,
|
||||
limit: pageSize,
|
||||
raw: true,
|
||||
distinct: true,
|
||||
});
|
||||
|
||||
const list = Array.isArray(result && result.rows)
|
||||
? result.rows.map(row => this.normalizeInterfaceRow(row)).filter(Boolean)
|
||||
? result.rows.map(row => this.normalizeInterfaceRow(row && typeof row.get === 'function' ? row.get({ plain: true }) : row)).filter(Boolean)
|
||||
: [];
|
||||
|
||||
return {
|
||||
@ -479,6 +720,74 @@ class SettingExpressInterfaceService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 按仓库和平台代码查询快递接口全量记录。
|
||||
*
|
||||
* 该方法会先尝试读取缓存;缓存未命中时查库并回写缓存。
|
||||
*
|
||||
* @param {Object} data 请求参数
|
||||
* @return {Promise<Object>} 查询结果,data 为快递接口数组
|
||||
*/
|
||||
async listByWarehousePlatformCode(data = {}) {
|
||||
const { ctx, app } = this;
|
||||
const { warehouseId, platformCode } = this.resolveWarehousePlatformTarget(data);
|
||||
const cacheKey = this.getWarehousePlatformCacheKey(warehouseId, platformCode);
|
||||
|
||||
if (app && typeof app.getCacheAsync === 'function') {
|
||||
try {
|
||||
const cachedValue = await app.getCacheAsync(cacheKey);
|
||||
if (cachedValue !== null && cachedValue !== undefined) {
|
||||
return {
|
||||
code: 200,
|
||||
data: this.normalizeFullInterfaceRows(cachedValue),
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
if (this.ctx && this.ctx.logger && typeof this.ctx.logger.warn === 'function') {
|
||||
this.ctx.logger.warn('[SettingExpressInterfaceService.listByWarehousePlatformCode] 读取缓存失败', {
|
||||
error: error.message,
|
||||
cacheKey,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const settings = await ctx.model.ExpressInterface.findAll({
|
||||
where: {
|
||||
warehouse_id: warehouseId,
|
||||
platform_code: platformCode,
|
||||
},
|
||||
include: this.getInterfaceInclude({ full: true }),
|
||||
attributes: this.getInterfaceFullAttributes(),
|
||||
order: [[ 'weight', 'ASC' ], [ 'id', 'ASC' ]],
|
||||
});
|
||||
|
||||
const plainSettings = Array.isArray(settings)
|
||||
? settings.map(setting => (setting && typeof setting.get === 'function'
|
||||
? setting.get({ plain: true })
|
||||
: setting))
|
||||
: [];
|
||||
const normalized = this.normalizeFullInterfaceRows(plainSettings);
|
||||
|
||||
if (normalized && app && typeof app.setCacheAsync === 'function') {
|
||||
try {
|
||||
await app.setCacheAsync(cacheKey, normalized, DEFAULT_CACHE_TTL_SECONDS);
|
||||
} catch (error) {
|
||||
if (this.ctx && this.ctx.logger && typeof this.ctx.logger.warn === 'function') {
|
||||
this.ctx.logger.warn('[SettingExpressInterfaceService.listByWarehousePlatformCode] 写入缓存失败', {
|
||||
error: error.message,
|
||||
cacheKey,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
data: normalized,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建快递接口。
|
||||
*
|
||||
@ -492,9 +801,7 @@ class SettingExpressInterfaceService extends Service {
|
||||
const name = this.normalizeText(data.name, 'name', 255);
|
||||
const expressCode = this.normalizeText(data.express_code || data.expressCode, 'express_code', 255).toUpperCase();
|
||||
const platformCode = this.normalizeText(data.platform_code || data.platformCode, 'platform_code', 20).toUpperCase();
|
||||
const expressPlatformId = this.normalizeInteger(data.express_platform_id || data.expressPlatformId, 'express_platform_id', {
|
||||
min: 1,
|
||||
});
|
||||
|
||||
|
||||
if (!name) {
|
||||
throw this.createError('name 参数不能为空', 400);
|
||||
@ -505,19 +812,14 @@ class SettingExpressInterfaceService extends Service {
|
||||
if (!platformCode) {
|
||||
throw this.createError('platform_code 参数不能为空', 400);
|
||||
}
|
||||
if (!expressPlatformId) {
|
||||
throw this.createError('express_platform_id 参数不能为空', 400);
|
||||
}
|
||||
|
||||
await this.ensureCodeAvailable(expressCode);
|
||||
await this.ensureInterfaceAvailable(platformCode, expressPlatformId);
|
||||
await this.ensureInterfaceAvailable(platformCode);
|
||||
|
||||
const payload = {
|
||||
warehouse_id: currentStoreId,
|
||||
name,
|
||||
express_code: expressCode,
|
||||
platform_code: platformCode,
|
||||
express_platform_id: expressPlatformId,
|
||||
sender_name: this.normalizeOptionalText(data.sender_name || data.senderName, 'sender_name', 50),
|
||||
sender_tel: this.normalizeOptionalText(data.sender_tel || data.senderTel, 'sender_tel', 11),
|
||||
weight: this.normalizeInteger(data.weight, 'weight', {
|
||||
@ -544,9 +846,15 @@ class SettingExpressInterfaceService extends Service {
|
||||
};
|
||||
|
||||
const created = await ctx.model.ExpressInterface.create(payload);
|
||||
const plainCreated = created && typeof created.get === 'function'
|
||||
const plainCreatedRow = created && typeof created.get === 'function'
|
||||
? created.get({ plain: true })
|
||||
: created;
|
||||
const createdSetting = await this.findInterfaceById(Number(plainCreatedRow && plainCreatedRow.id));
|
||||
const plainCreated = createdSetting && typeof createdSetting.get === 'function'
|
||||
? createdSetting.get({ plain: true })
|
||||
: createdSetting;
|
||||
|
||||
await this.clearWarehousePlatformCache(currentStoreId, payload.platform_code);
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
@ -572,8 +880,6 @@ class SettingExpressInterfaceService extends Service {
|
||||
|| Object.prototype.hasOwnProperty.call(data, 'expressCode');
|
||||
const hasPlatformCode = Object.prototype.hasOwnProperty.call(data, 'platform_code')
|
||||
|| Object.prototype.hasOwnProperty.call(data, 'platformCode');
|
||||
const hasExpressPlatformId = Object.prototype.hasOwnProperty.call(data, 'express_platform_id')
|
||||
|| Object.prototype.hasOwnProperty.call(data, 'expressPlatformId');
|
||||
const hasSenderName = Object.prototype.hasOwnProperty.call(data, 'sender_name')
|
||||
|| Object.prototype.hasOwnProperty.call(data, 'senderName');
|
||||
const hasSenderTel = Object.prototype.hasOwnProperty.call(data, 'sender_tel')
|
||||
@ -602,7 +908,7 @@ class SettingExpressInterfaceService extends Service {
|
||||
const hasShopName = Object.prototype.hasOwnProperty.call(data, 'shop_name')
|
||||
|| Object.prototype.hasOwnProperty.call(data, 'shopName');
|
||||
|
||||
if (!hasName && !hasExpressCode && !hasPlatformCode && !hasExpressPlatformId && !hasSenderName
|
||||
if (!hasName && !hasExpressCode && !hasPlatformCode && !hasSenderName
|
||||
&& !hasSenderTel && !hasWeight && !hasToken && !hasViewer && !hasClientId && !hasIsShare
|
||||
&& !hasShareId && !hasCanUseCount && !hasProvinceName && !hasCityName && !hasDistrictName
|
||||
&& !hasSiteCode && !hasProductType && !hasShopName) {
|
||||
@ -612,9 +918,6 @@ class SettingExpressInterfaceService extends Service {
|
||||
const updates = {};
|
||||
let nextExpressCode = setting.express_code || '';
|
||||
let nextPlatformCode = setting.platform_code || '';
|
||||
let nextExpressPlatformId = setting.express_platform_id === undefined || setting.express_platform_id === null
|
||||
? null
|
||||
: Number(setting.express_platform_id);
|
||||
|
||||
if (hasName) {
|
||||
const name = this.normalizeText(data.name, 'name', 255);
|
||||
@ -642,17 +945,6 @@ class SettingExpressInterfaceService extends Service {
|
||||
updates.platform_code = platformCode;
|
||||
}
|
||||
|
||||
if (hasExpressPlatformId) {
|
||||
const expressPlatformId = this.normalizeInteger(data.express_platform_id || data.expressPlatformId, 'express_platform_id', {
|
||||
min: 1,
|
||||
});
|
||||
if (!expressPlatformId) {
|
||||
throw this.createError('express_platform_id 参数不能为空', 400);
|
||||
}
|
||||
nextExpressPlatformId = expressPlatformId;
|
||||
updates.express_platform_id = expressPlatformId;
|
||||
}
|
||||
|
||||
if (hasSenderName) {
|
||||
updates.sender_name = this.normalizeOptionalText(data.sender_name || data.senderName, 'sender_name', 50);
|
||||
}
|
||||
@ -724,16 +1016,25 @@ class SettingExpressInterfaceService extends Service {
|
||||
if (Object.prototype.hasOwnProperty.call(updates, 'express_code')) {
|
||||
await this.ensureCodeAvailable(nextExpressCode, id);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(updates, 'platform_code')
|
||||
|| Object.prototype.hasOwnProperty.call(updates, 'express_platform_id')) {
|
||||
await this.ensureInterfaceAvailable(nextPlatformCode, nextExpressPlatformId, id);
|
||||
}
|
||||
|
||||
const previousWarehouseId = Number(setting.warehouse_id || this.getCurrentStoreId());
|
||||
const previousPlatformCode = this.normalizePlatformCode(setting.platform_code, 'platform_code', 20);
|
||||
const nextWarehouseId = previousWarehouseId;
|
||||
const nextCachePlatformCode = Object.prototype.hasOwnProperty.call(updates, 'platform_code')
|
||||
? this.normalizePlatformCode(updates.platform_code, 'platform_code', 20)
|
||||
: previousPlatformCode;
|
||||
|
||||
await setting.update(updates);
|
||||
|
||||
const plainSetting = setting && typeof setting.get === 'function'
|
||||
? setting.get({ plain: true })
|
||||
: setting;
|
||||
await Promise.all(Array.from(new Set([
|
||||
this.getWarehousePlatformCacheKey(previousWarehouseId, previousPlatformCode),
|
||||
this.getWarehousePlatformCacheKey(nextWarehouseId, nextCachePlatformCode),
|
||||
])).map(cacheKey => this.deleteCacheByKey(cacheKey)));
|
||||
|
||||
const refreshedSetting = await this.findInterfaceById(id);
|
||||
const plainSetting = refreshedSetting && typeof refreshedSetting.get === 'function'
|
||||
? refreshedSetting.get({ plain: true })
|
||||
: refreshedSetting;
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
@ -760,6 +1061,8 @@ class SettingExpressInterfaceService extends Service {
|
||||
|
||||
await setting.destroy();
|
||||
|
||||
await this.clearWarehousePlatformCache(plainSetting.warehouse_id, plainSetting.platform_code);
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
data: {
|
||||
|
||||
@ -30,6 +30,134 @@ class SettingPlatformService extends Service {
|
||||
return storeId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化删除 ID 列表。
|
||||
*
|
||||
* 优先读取 `ids`,其次兼容单个 `id`、`setting_id`、`settingId`。
|
||||
*
|
||||
* @param {Object} data 请求参数
|
||||
* @return {Array<number>} 删除 ID 列表
|
||||
*/
|
||||
normalizeDeleteIds(data = {}) {
|
||||
const {
|
||||
ids,
|
||||
id,
|
||||
setting_id: settingId,
|
||||
settingId: camelSettingId,
|
||||
} = data || {};
|
||||
|
||||
const rawIds = ids !== undefined
|
||||
? ids
|
||||
: (id !== undefined ? id : (settingId !== undefined ? settingId : camelSettingId));
|
||||
|
||||
const values = Array.isArray(rawIds)
|
||||
? rawIds
|
||||
: String(rawIds || '')
|
||||
.split(',')
|
||||
.map(item => item.trim())
|
||||
.filter(Boolean);
|
||||
|
||||
const normalizedIds = [];
|
||||
const seenIds = new Set();
|
||||
|
||||
for (const value of values) {
|
||||
const normalized = Number(value);
|
||||
if (!Number.isInteger(normalized) || normalized <= 0 || seenIds.has(normalized)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
seenIds.add(normalized);
|
||||
normalizedIds.push(normalized);
|
||||
}
|
||||
|
||||
return normalizedIds;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成平台列表缓存键。
|
||||
*
|
||||
* @param {number|string} warehouseId 仓库 ID
|
||||
* @return {string} 缓存键
|
||||
*/
|
||||
getPlatformListCacheKey(warehouseId = 0) {
|
||||
const normalizedWarehouseId = Number(warehouseId || 0);
|
||||
if (Number.isFinite(normalizedWarehouseId) && normalizedWarehouseId > 0) {
|
||||
return `platform:list:${normalizedWarehouseId}`;
|
||||
}
|
||||
|
||||
return 'platform:list';
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成平台详情缓存键。
|
||||
*
|
||||
* @param {string} platformCode 平台设置代码
|
||||
* @param {number|string} warehouseId 仓库 ID
|
||||
* @return {string} 缓存键
|
||||
*/
|
||||
getPlatformDetailCacheKey(platformCode, warehouseId) {
|
||||
return `platform_setting_detail:${platformCode}:${warehouseId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成平台存在性缓存键。
|
||||
*
|
||||
* @param {string} platformCode 平台设置代码
|
||||
* @param {number|string} warehouseId 仓库 ID
|
||||
* @return {string} 缓存键
|
||||
*/
|
||||
getPlatformExistsCacheKey(platformCode, warehouseId) {
|
||||
return `platform:${platformCode}:${warehouseId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除指定缓存键。
|
||||
*
|
||||
* @param {string} cacheKey 缓存键
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async deleteCacheByKey(cacheKey) {
|
||||
if (!cacheKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { app } = this;
|
||||
if (app && typeof app.delCacheAsync === 'function') {
|
||||
await app.delCacheAsync(cacheKey);
|
||||
return;
|
||||
}
|
||||
|
||||
if (app && typeof app.setCacheAsync === 'function') {
|
||||
await app.setCacheAsync(cacheKey, null, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理平台列表、详情和存在性缓存。
|
||||
*
|
||||
* @param {number|string} warehouseId 仓库 ID
|
||||
* @param {Array<string>} platformCodes 平台设置代码列表
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async clearPlatformCaches(warehouseId, platformCodes = []) {
|
||||
const normalizedWarehouseId = Number(warehouseId || 0);
|
||||
const uniquePlatformCodes = Array.from(new Set(
|
||||
Array.isArray(platformCodes)
|
||||
? platformCodes.map(code => String(code || '').trim()).filter(Boolean)
|
||||
: []
|
||||
));
|
||||
|
||||
const cacheKeys = [
|
||||
this.getPlatformListCacheKey(normalizedWarehouseId),
|
||||
...uniquePlatformCodes.flatMap(platformCode => [
|
||||
this.getPlatformDetailCacheKey(platformCode, normalizedWarehouseId),
|
||||
this.getPlatformExistsCacheKey(platformCode, normalizedWarehouseId),
|
||||
]),
|
||||
];
|
||||
|
||||
await Promise.all(cacheKeys.map(cacheKey => this.deleteCacheByKey(cacheKey)));
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化必填文本。
|
||||
*
|
||||
@ -268,7 +396,7 @@ class SettingPlatformService extends Service {
|
||||
platform: platform ? {
|
||||
code: this.normalizeOptionalText(platform.code, 'platform.code', 50),
|
||||
name: this.normalizeOptionalText(platform.name, 'platform.name', 255),
|
||||
default_express_interface: this.normalizeOptionalText(platform.default_express_interface, 'platform.default_express_interface', 50),
|
||||
platform_code: this.normalizeOptionalText(platform.platform_code, 'platform.platform_code', 255),
|
||||
} : null,
|
||||
};
|
||||
}
|
||||
@ -292,7 +420,7 @@ class SettingPlatformService extends Service {
|
||||
{
|
||||
model: ctx.model.Platform,
|
||||
as: 'platform',
|
||||
attributes: [ 'code', 'name', 'default_express_interface' ],
|
||||
attributes: [ 'code', 'name', 'platform_code' ],
|
||||
required: false,
|
||||
},
|
||||
],
|
||||
@ -373,7 +501,7 @@ class SettingPlatformService extends Service {
|
||||
where: {
|
||||
code: platformCode,
|
||||
},
|
||||
attributes: [ 'code', 'name', 'default_express_interface' ],
|
||||
attributes: [ 'code', 'name', 'platform_code' ],
|
||||
});
|
||||
|
||||
if (!platform) {
|
||||
@ -471,7 +599,7 @@ class SettingPlatformService extends Service {
|
||||
{
|
||||
model: ctx.model.Platform,
|
||||
as: 'platform',
|
||||
attributes: [ 'code', 'name', 'default_express_interface' ],
|
||||
attributes: [ 'code', 'name', 'platform_code' ],
|
||||
required: false,
|
||||
},
|
||||
],
|
||||
@ -612,25 +740,57 @@ class SettingPlatformService extends Service {
|
||||
* @return {Promise<Object>} 删除结果
|
||||
*/
|
||||
async delete(data = {}) {
|
||||
const id = Number(data.id || data.setting_id || data.settingId || 0);
|
||||
if (!Number.isInteger(id) || id <= 0) {
|
||||
throw this.createError('id 参数不能为空', 400);
|
||||
const ids = this.normalizeDeleteIds(data);
|
||||
if (!Array.isArray(ids) || ids.length === 0) {
|
||||
throw this.createError('ids 参数不能为空', 400);
|
||||
}
|
||||
|
||||
const setting = await this.findSettingById(id);
|
||||
const plainSetting = setting && typeof setting.get === 'function'
|
||||
? setting.get({ plain: true })
|
||||
: setting;
|
||||
const { ctx, app } = this;
|
||||
const currentStoreId = this.getCurrentStoreId();
|
||||
const { Op } = app.Sequelize;
|
||||
|
||||
await setting.destroy();
|
||||
const settings = await ctx.model.PlatformSetting.findAll({
|
||||
where: {
|
||||
warehouse_id: currentStoreId,
|
||||
id: {
|
||||
[Op.in]: ids,
|
||||
},
|
||||
},
|
||||
attributes: [ 'id', 'code', 'warehouse_id' ],
|
||||
});
|
||||
|
||||
if (!Array.isArray(settings) || settings.length !== ids.length) {
|
||||
throw this.createError('平台设置不存在或无权限操作', 404);
|
||||
}
|
||||
|
||||
await ctx.model.PlatformSetting.destroy({
|
||||
where: {
|
||||
warehouse_id: currentStoreId,
|
||||
id: {
|
||||
[Op.in]: ids,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await this.clearPlatformCaches(
|
||||
currentStoreId,
|
||||
settings.map(setting => setting && setting.code).filter(Boolean)
|
||||
);
|
||||
|
||||
const deletedIds = settings.map(setting => Number(setting.id)).filter(id => Number.isInteger(id) && id > 0);
|
||||
const responseData = {
|
||||
ids: deletedIds,
|
||||
warehouse_id: currentStoreId,
|
||||
deleted: true,
|
||||
};
|
||||
|
||||
if (deletedIds.length === 1) {
|
||||
responseData.id = deletedIds[0];
|
||||
}
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
data: {
|
||||
id: Number(plainSetting.id),
|
||||
warehouse_id: Number(plainSetting.warehouse_id),
|
||||
deleted: true,
|
||||
},
|
||||
data: responseData,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@ -423,11 +423,23 @@ class stockStoreService extends Service {
|
||||
app,
|
||||
} = this;
|
||||
const cacheKey = `storages:${itemId}`;
|
||||
try {
|
||||
if (app && typeof app.delCacheAsync === 'function') {
|
||||
try {
|
||||
await app.delCacheAsync(cacheKey);
|
||||
app.logger.debug(`[缓存清理] 商品 ${itemId} 库存缓存已清理`);
|
||||
} catch (error) {
|
||||
app.logger.warn(`[缓存清理失败] 商品 ${itemId}`, error.message);
|
||||
} catch (error) {
|
||||
app.logger.warn(`[缓存清理失败] 商品 ${itemId}`, error.message);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (app && typeof app.setCacheAsync === 'function') {
|
||||
try {
|
||||
await app.setCacheAsync(cacheKey, null, 0);
|
||||
app.logger.debug(`[缓存清理] 商品 ${itemId} 库存缓存已清理`);
|
||||
} catch (error) {
|
||||
app.logger.warn(`[缓存清理失败] 商品 ${itemId}`, error.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -473,7 +485,7 @@ class stockStoreService extends Service {
|
||||
is_valid: 'Y',
|
||||
deleted_at: null,
|
||||
},
|
||||
attributes: [ 'id', 'store_id', 'warehouse_id', 'policy_config' ],
|
||||
attributes: [ 'id', 'store_id', 'warehouse_id' ],
|
||||
transaction,
|
||||
raw: true,
|
||||
});
|
||||
@ -549,112 +561,103 @@ class stockStoreService extends Service {
|
||||
const absQty = Math.abs(lockQty);
|
||||
|
||||
try {
|
||||
// 1. 查询并锁定记录(悲观锁)
|
||||
const stockRecord = await ctx.model.StockWarehouse.findOne({
|
||||
where: {
|
||||
id: stockWarehouseId,
|
||||
is_valid: 'Y',
|
||||
deleted_at: null,
|
||||
},
|
||||
transaction,
|
||||
lock: transaction.LOCK.UPDATE, // 行级锁
|
||||
attributes: [ 'id', 'store_id', 'warehouse_id', 'quantity', 'locked_quantity', 'gross_weight' ],
|
||||
raw: false, // 需要实例以使用方法
|
||||
});
|
||||
return await this._runWithTransaction(transaction, async currentTransaction => {
|
||||
// 1. 查询并锁定记录(悲观锁)
|
||||
const stockRecord = await ctx.model.StockWarehouse.findOne({
|
||||
where: {
|
||||
id: stockWarehouseId,
|
||||
is_valid: 'Y',
|
||||
deleted_at: null,
|
||||
},
|
||||
transaction: currentTransaction,
|
||||
lock: currentTransaction.LOCK.UPDATE,
|
||||
attributes: [ 'id', 'store_id', 'warehouse_id', 'quantity', 'locked_quantity', 'gross_weight' ],
|
||||
raw: false,
|
||||
});
|
||||
|
||||
// 检查记录是否存在
|
||||
if (!stockRecord) {
|
||||
return {
|
||||
success: false,
|
||||
error: `库存记录不存在或已失效 (ID: ${stockWarehouseId})`,
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
if (!stockRecord) {
|
||||
return {
|
||||
success: false,
|
||||
error: `库存记录不存在或已失效 (ID: ${stockWarehouseId})`,
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
|
||||
// 2. 业务规则校验
|
||||
if (isLocking) {
|
||||
// 加锁操作:检查可用库存是否足够
|
||||
const availableQty = stockRecord.quantity - stockRecord.locked_quantity;
|
||||
if (availableQty < absQty) {
|
||||
const policyConfig = await this.getStoreWarehousePolicyConfigByStockId(stockRecord, transaction);
|
||||
if (!policyConfig.allowOversell) {
|
||||
if (isLocking) {
|
||||
const availableQty = stockRecord.quantity - stockRecord.locked_quantity;
|
||||
if (availableQty < absQty) {
|
||||
const policyConfig = await this.getStoreWarehousePolicyConfigByStockId(stockRecord, currentTransaction);
|
||||
if (!policyConfig.allowOversell) {
|
||||
return {
|
||||
success: false,
|
||||
error: `库存不足,可用 ${availableQty},需求 ${absQty}`,
|
||||
data: {
|
||||
available: availableQty,
|
||||
required: absQty,
|
||||
recordId: stockWarehouseId,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (stockRecord.locked_quantity < absQty) {
|
||||
return {
|
||||
success: false,
|
||||
error: `库存不足,可用 ${availableQty},需求 ${absQty}`,
|
||||
data: {
|
||||
available: availableQty,
|
||||
required: absQty,
|
||||
recordId: stockWarehouseId,
|
||||
},
|
||||
error: `释放数量超过已锁定库存,已锁 ${stockRecord.locked_quantity},尝试释放 ${absQty}`,
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
|
||||
const newLocked = stockRecord.locked_quantity - absQty;
|
||||
if (newLocked < 0) {
|
||||
return {
|
||||
success: false,
|
||||
error: `释放后锁定库存为负值: ${newLocked}`,
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 减锁操作:检查已锁定库存是否足够释放
|
||||
if (stockRecord.locked_quantity < absQty) {
|
||||
return {
|
||||
success: false,
|
||||
error: `释放数量超过已锁定库存,已锁 ${stockRecord.locked_quantity},尝试释放 ${absQty}`,
|
||||
data: null,
|
||||
};
|
||||
|
||||
if (isLocking) {
|
||||
await stockRecord.increment('locked_quantity', {
|
||||
by: absQty,
|
||||
transaction: currentTransaction,
|
||||
silent: true,
|
||||
});
|
||||
app.logger.info(
|
||||
`[库存锁定] ID: ${stockWarehouseId}, 增加锁定: +${absQty}, 锁定后: ${stockRecord.locked_quantity + absQty}`
|
||||
);
|
||||
} else {
|
||||
await stockRecord.decrement('locked_quantity', {
|
||||
by: absQty,
|
||||
transaction: currentTransaction,
|
||||
silent: true,
|
||||
});
|
||||
app.logger.info(
|
||||
`[库存释放] ID: ${stockWarehouseId}, 减少锁定: -${absQty}, 锁定后: ${stockRecord.locked_quantity - absQty}`
|
||||
);
|
||||
}
|
||||
|
||||
// 检查释放后锁定数是否为负
|
||||
const newLocked = stockRecord.locked_quantity - absQty;
|
||||
if (newLocked < 0) {
|
||||
return {
|
||||
success: false,
|
||||
error: `释放后锁定库存为负值: ${newLocked}`,
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 执行锁定/释放操作
|
||||
if (isLocking) {
|
||||
// 加锁:增加 locked_quantity
|
||||
await stockRecord.increment('locked_quantity', {
|
||||
by: absQty,
|
||||
transaction,
|
||||
silent: true,
|
||||
await stockRecord.reload({
|
||||
transaction: currentTransaction,
|
||||
});
|
||||
app.logger.info(
|
||||
`[库存锁定] ID: ${stockWarehouseId}, 增加锁定: +${absQty}, 锁定后: ${stockRecord.locked_quantity + absQty}`
|
||||
);
|
||||
} else {
|
||||
// 减锁:减少 locked_quantity(确保不小于0)
|
||||
await stockRecord.decrement('locked_quantity', {
|
||||
by: absQty,
|
||||
transaction,
|
||||
silent: true,
|
||||
});
|
||||
app.logger.info(
|
||||
`[库存释放] ID: ${stockWarehouseId}, 减少锁定: -${absQty}, 锁定后: ${stockRecord.locked_quantity - absQty}`
|
||||
);
|
||||
}
|
||||
|
||||
// 4. 获取更新后的数据(可选)
|
||||
await stockRecord.reload({
|
||||
transaction,
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
id: stockWarehouseId,
|
||||
action: isLocking ? 'lock' : 'unlock',
|
||||
quantity: absQty,
|
||||
beforeLocked: isLocking ? stockRecord.locked_quantity - absQty : stockRecord.locked_quantity +
|
||||
absQty,
|
||||
afterLocked: stockRecord.locked_quantity,
|
||||
totalQuantity: stockRecord.quantity,
|
||||
available: stockRecord.quantity - stockRecord.locked_quantity,
|
||||
updatedAt: stockRecord.update_at,
|
||||
},
|
||||
error: null,
|
||||
};
|
||||
});
|
||||
|
||||
// 5. 返回成功结果
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
id: stockWarehouseId,
|
||||
action: isLocking ? 'lock' : 'unlock',
|
||||
quantity: absQty,
|
||||
beforeLocked: isLocking ? stockRecord.locked_quantity - absQty : stockRecord.locked_quantity +
|
||||
absQty,
|
||||
afterLocked: stockRecord.locked_quantity,
|
||||
totalQuantity: stockRecord.quantity,
|
||||
available: stockRecord.quantity - stockRecord.locked_quantity,
|
||||
updatedAt: stockRecord.update_at,
|
||||
},
|
||||
error: null,
|
||||
};
|
||||
|
||||
} catch (error) {
|
||||
app.logger.error('[lockItemStorages] 系统异常', {
|
||||
stockWarehouseId,
|
||||
@ -785,6 +788,8 @@ class stockStoreService extends Service {
|
||||
after: afterQuantity,
|
||||
});
|
||||
|
||||
await this.clearItemStorageCache(itemId);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
@ -978,6 +983,8 @@ class stockStoreService extends Service {
|
||||
afterLocked: afterLockedQuantity,
|
||||
});
|
||||
|
||||
await this.clearItemStorageCache(itemId);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
@ -2843,6 +2850,7 @@ class stockStoreService extends Service {
|
||||
'shelf_life_days', 'remaining_threshold_days',
|
||||
'is_batch_mgmt',
|
||||
'is_shelf_life_mgmt',
|
||||
'gross_weight',
|
||||
],
|
||||
order: [[ 'create_at', 'DESC' ]],
|
||||
limit: 50,
|
||||
|
||||
@ -115,40 +115,99 @@ class IndexService extends Service {
|
||||
|
||||
async updateQuantity(id, quantityChange, lockedChange = 0, options = {}) {
|
||||
const { ctx } = this;
|
||||
const storage = await ctx.model.Storage.findByPk(id, {
|
||||
transaction: options.transaction,
|
||||
});
|
||||
const applyUpdate = async transaction => {
|
||||
const storage = await ctx.model.Storage.findByPk(id, {
|
||||
transaction,
|
||||
lock: transaction ? transaction.LOCK.UPDATE : undefined,
|
||||
});
|
||||
|
||||
if (!storage) {
|
||||
throw new Error('库存记录不存在');
|
||||
}
|
||||
if (!storage) {
|
||||
throw new Error('库存记录不存在');
|
||||
}
|
||||
|
||||
const newQuantity = storage.quantity + quantityChange;
|
||||
const newLocked = storage.locked_quantity + lockedChange;
|
||||
const newQuantity = storage.quantity + quantityChange;
|
||||
const newLocked = storage.locked_quantity + lockedChange;
|
||||
|
||||
if (newQuantity < 0) {
|
||||
throw new Error('库存数量不能为负数');
|
||||
}
|
||||
if (newQuantity < 0) {
|
||||
throw new Error('库存数量不能为负数');
|
||||
}
|
||||
|
||||
if (newLocked < 0 || newLocked > newQuantity) {
|
||||
throw new Error('锁定数量无效');
|
||||
}
|
||||
if (newLocked < 0 || newLocked > newQuantity) {
|
||||
throw new Error('锁定数量无效');
|
||||
}
|
||||
|
||||
const updateData = {
|
||||
quantity: newQuantity,
|
||||
locked_quantity: newLocked,
|
||||
available_quantity: newQuantity - newLocked,
|
||||
updated_at: new Date(),
|
||||
const updateData = {
|
||||
quantity: newQuantity,
|
||||
locked_quantity: newLocked,
|
||||
available_quantity: newQuantity - newLocked,
|
||||
updated_at: new Date(),
|
||||
};
|
||||
|
||||
await storage.update(updateData, {
|
||||
transaction,
|
||||
});
|
||||
return storage;
|
||||
};
|
||||
|
||||
await storage.update(updateData, {
|
||||
transaction: options.transaction,
|
||||
if (options.transaction) {
|
||||
return await applyUpdate(options.transaction);
|
||||
}
|
||||
|
||||
return await ctx.model.transaction(async transaction => {
|
||||
return await applyUpdate(transaction);
|
||||
});
|
||||
return storage;
|
||||
}
|
||||
|
||||
/**
|
||||
* 锁定指定库存记录的可用数量。
|
||||
*
|
||||
* @param {number} id 库存记录 ID。
|
||||
* @param {number} quantity 需要锁定的数量。
|
||||
* @param {Object} [options={}] 执行上下文与事务参数。
|
||||
* @param {Object} [options.transaction] Sequelize 事务对象。
|
||||
* @param {string} [options.source] 调用来源标识。
|
||||
* @param {string} [options.caller] 调用方标识。
|
||||
* @param {string} [options.from] 来源模块标识。
|
||||
* @param {string} [options.action] 操作标识。
|
||||
* @return {Promise<Object>} 更新后的库存记录。
|
||||
*/
|
||||
async lockQuantity(id, quantity, options = {}) {
|
||||
return await this.updateQuantity(id, 0, quantity, options);
|
||||
const callContext = {
|
||||
hasTransaction: Boolean(options && options.transaction),
|
||||
source: options && (options.source || options.caller || options.from || options.action) || null,
|
||||
optionKeys: options && typeof options === 'object'
|
||||
? Object.keys(options).filter(key => key !== 'transaction')
|
||||
: [],
|
||||
};
|
||||
|
||||
console.log('[StorageService.lockQuantity] 开始锁定库存', {
|
||||
id,
|
||||
quantity,
|
||||
callContext,
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await this.updateQuantity(id, 0, quantity, options);
|
||||
|
||||
console.log('[StorageService.lockQuantity] 锁定库存成功', {
|
||||
id,
|
||||
quantity,
|
||||
callContext,
|
||||
storageId: result && result.id,
|
||||
locked_quantity: result && result.locked_quantity,
|
||||
available_quantity: result && result.available_quantity,
|
||||
});
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
console.log('[StorageService.lockQuantity] 锁定库存失败', {
|
||||
id,
|
||||
quantity,
|
||||
callContext,
|
||||
error,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async unlockQuantity(id, quantity, options = {}) {
|
||||
|
||||
@ -69,7 +69,7 @@ class ReceivingService extends Service {
|
||||
},
|
||||
order: [],
|
||||
attributes: {
|
||||
exclude: [ 'deleted_at' ],
|
||||
exclude: ['deleted_at'],
|
||||
},
|
||||
};
|
||||
|
||||
@ -115,7 +115,7 @@ class ReceivingService extends Service {
|
||||
parsedResult = parsed.result;
|
||||
}
|
||||
|
||||
const dynamicConditions = [ ...(parsedResult.dynamicConditions || []) ];
|
||||
const dynamicConditions = [...(parsedResult.dynamicConditions || [])];
|
||||
const quickWhereRaw = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere)
|
||||
|| normalizedWhere.quickWhere;
|
||||
|
||||
@ -153,14 +153,14 @@ class ReceivingService extends Service {
|
||||
];
|
||||
const actualSortField = validSortFields.includes(sortField) ? sortField : 'create_at';
|
||||
const actualSortOrder = sortOrder.toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
|
||||
queryOptions.order.push([ actualSortField, actualSortOrder ]);
|
||||
queryOptions.order.push([actualSortField, actualSortOrder]);
|
||||
|
||||
const offset = (page - 1) * pageSize;
|
||||
const include = [
|
||||
{
|
||||
model: ctx.model.StoreWarehouse,
|
||||
as: 'store',
|
||||
attributes: [ 'store_remask' ],
|
||||
attributes: ['store_remask'],
|
||||
where: {
|
||||
use_status: 1,
|
||||
warehouse_id: ctx.user.store_id,
|
||||
@ -170,12 +170,12 @@ class ReceivingService extends Service {
|
||||
{
|
||||
model: ctx.model.AccountStoreEmployee,
|
||||
as: 'creator',
|
||||
attributes: [ 'real_name' ],
|
||||
attributes: ['real_name'],
|
||||
required: true,
|
||||
},
|
||||
];
|
||||
|
||||
const [ total, data ] = await Promise.all([
|
||||
const [total, data] = await Promise.all([
|
||||
ctx.model.Receiving.count({
|
||||
where: queryOptions.where,
|
||||
include,
|
||||
@ -209,7 +209,7 @@ class ReceivingService extends Service {
|
||||
{
|
||||
model: ctx.model.File,
|
||||
as: 'file',
|
||||
attributes: [ 'file_url' ],
|
||||
attributes: ['file_url'],
|
||||
required: true,
|
||||
},
|
||||
],
|
||||
@ -341,7 +341,7 @@ class ReceivingService extends Service {
|
||||
include: [{
|
||||
model: ctx.model.File,
|
||||
as: 'file',
|
||||
attributes: [ 'file_url' ],
|
||||
attributes: ['file_url'],
|
||||
required: true,
|
||||
}],
|
||||
});
|
||||
@ -372,7 +372,7 @@ class ReceivingService extends Service {
|
||||
include: [{
|
||||
model: ctx.model.File,
|
||||
as: 'file',
|
||||
attributes: [ 'file_url' ],
|
||||
attributes: ['file_url'],
|
||||
required: true,
|
||||
}],
|
||||
});
|
||||
@ -671,7 +671,7 @@ class ReceivingService extends Service {
|
||||
case 'daterange':
|
||||
// 处理日期范围:数组的第一个元素是开始时间,第二个元素是结束时间
|
||||
if (Array.isArray(value) && value.length === 2) {
|
||||
const [ startDate, endDate ] = value;
|
||||
const [startDate, endDate] = value;
|
||||
return [
|
||||
startDate ? service.main.normalizeDate(startDate, false) : null, // 开始时间设为00:00:00
|
||||
endDate ? service.main.normalizeDate(endDate, true) : null, // 结束时间设为23:59:59
|
||||
@ -680,10 +680,10 @@ class ReceivingService extends Service {
|
||||
return value;
|
||||
|
||||
case 'number':
|
||||
{
|
||||
const num = parseFloat(value);
|
||||
return isNaN(num) ? value : num;
|
||||
}
|
||||
{
|
||||
const num = parseFloat(value);
|
||||
return isNaN(num) ? value : num;
|
||||
}
|
||||
case 'text':
|
||||
if (typeof value === 'string') {
|
||||
return value.split(',').map(item => item.trim());
|
||||
@ -705,15 +705,15 @@ class ReceivingService extends Service {
|
||||
const suffixStartIndex = prefix.length + 1;
|
||||
|
||||
const maxReceiving = await app.model.Receiving.findOne({
|
||||
attributes: [ 'receiving_number' ],
|
||||
attributes: ['receiving_number'],
|
||||
where: {
|
||||
receiving_number: {
|
||||
[app.Sequelize.Op.like]: `${prefix}%`,
|
||||
},
|
||||
},
|
||||
order: [
|
||||
[ app.Sequelize.literal(`CAST(SUBSTRING(receiving_number, ${suffixStartIndex}) AS UNSIGNED)`), 'DESC' ],
|
||||
[ 'receiving_number', 'DESC' ],
|
||||
[app.Sequelize.literal(`CAST(SUBSTRING(receiving_number, ${suffixStartIndex}) AS UNSIGNED)`), 'DESC'],
|
||||
['receiving_number', 'DESC'],
|
||||
],
|
||||
});
|
||||
|
||||
@ -943,7 +943,7 @@ class ReceivingService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
if ([ 'receiving', 'completed' ].includes(receiving.status) && Number(receiving.store_id || 0) > 0) {
|
||||
if (['receiving', 'completed'].includes(receiving.status) && Number(receiving.store_id || 0) > 0) {
|
||||
await transaction.rollback();
|
||||
return {
|
||||
code: 400,
|
||||
@ -957,7 +957,7 @@ class ReceivingService extends Service {
|
||||
store_id: storeId,
|
||||
use_status: 1,
|
||||
},
|
||||
attributes: [ 'store_id', 'store_remask' ],
|
||||
attributes: ['store_id', 'store_remask'],
|
||||
transaction,
|
||||
});
|
||||
|
||||
@ -1053,7 +1053,7 @@ class ReceivingService extends Service {
|
||||
include: [{
|
||||
model: ctx.model.StoreWarehouse,
|
||||
as: 'store',
|
||||
attributes: [ 'store_remask' ],
|
||||
attributes: ['store_remask'],
|
||||
where: {
|
||||
use_status: 1,
|
||||
warehouse_id: warehouseId,
|
||||
@ -1062,7 +1062,7 @@ class ReceivingService extends Service {
|
||||
}, {
|
||||
model: ctx.model.AccountStoreEmployee,
|
||||
as: 'creator',
|
||||
attributes: [ 'real_name' ],
|
||||
attributes: ['real_name'],
|
||||
required: false,
|
||||
}],
|
||||
// 不需要order,因为根据id查询已经是唯一的
|
||||
@ -1080,10 +1080,10 @@ class ReceivingService extends Service {
|
||||
{
|
||||
model: ctx.model.LocationSpace,
|
||||
as: 'receiving_space',
|
||||
attributes: [ 'space_code', 'custom_barcode', 'custom_name' ],
|
||||
attributes: ['space_code', 'custom_barcode', 'custom_name'],
|
||||
},
|
||||
],
|
||||
order: [[ 'id', 'DESC' ]], // 保持倒序,最新在前
|
||||
order: [['id', 'DESC']], // 保持倒序,最新在前
|
||||
});
|
||||
|
||||
// 3. 获取明细ID数组
|
||||
@ -1102,7 +1102,7 @@ class ReceivingService extends Service {
|
||||
include: [{
|
||||
model: ctx.model.File,
|
||||
as: 'file',
|
||||
attributes: [ 'file_url' ],
|
||||
attributes: ['file_url'],
|
||||
required: true,
|
||||
}],
|
||||
});
|
||||
@ -1136,7 +1136,7 @@ class ReceivingService extends Service {
|
||||
include: [{
|
||||
model: ctx.model.File,
|
||||
as: 'file',
|
||||
attributes: [ 'file_url' ],
|
||||
attributes: ['file_url'],
|
||||
required: true,
|
||||
}],
|
||||
});
|
||||
@ -1216,7 +1216,7 @@ class ReceivingService extends Service {
|
||||
// 获取更新后的明细列表
|
||||
const allDetails = await ctx.model.ReceivingDetail.findAll({
|
||||
where: { receiving_id },
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
order: [['id', 'DESC']],
|
||||
});
|
||||
|
||||
// 格式化返回数据
|
||||
@ -1322,7 +1322,7 @@ class ReceivingService extends Service {
|
||||
{
|
||||
model: app.model.Receiving,
|
||||
as: 'receiving',
|
||||
attributes: [ 'id', 'warehouse_id', 'store_id', 'store_name', 'status' ],
|
||||
attributes: ['id', 'warehouse_id', 'store_id', 'store_name', 'status'],
|
||||
where: {
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
@ -1347,12 +1347,12 @@ class ReceivingService extends Service {
|
||||
app.model.StoreWarehouse.buildStoreStockInclude({
|
||||
warehouseId,
|
||||
required: false,
|
||||
attributes: [ 'store_id', 'store_remask' ],
|
||||
attributes: ['store_id', 'store_remask'],
|
||||
}),
|
||||
{
|
||||
model: app.model.StockBarcode,
|
||||
as: 'barcodes',
|
||||
attributes: [ 'barcode' ],
|
||||
attributes: ['barcode'],
|
||||
required: false,
|
||||
},
|
||||
],
|
||||
@ -1511,7 +1511,7 @@ class ReceivingService extends Service {
|
||||
{
|
||||
model: ctx.model.Receiving,
|
||||
as: 'receiving',
|
||||
attributes: [ 'id', 'status' ],
|
||||
attributes: ['id', 'status'],
|
||||
},
|
||||
],
|
||||
});
|
||||
@ -1604,7 +1604,7 @@ class ReceivingService extends Service {
|
||||
}
|
||||
|
||||
// 更新明细
|
||||
const [ affectedRows ] = await ctx.model.ReceivingDetail.update(updateData, {
|
||||
const [affectedRows] = await ctx.model.ReceivingDetail.update(updateData, {
|
||||
where: { id },
|
||||
});
|
||||
|
||||
@ -1627,7 +1627,7 @@ class ReceivingService extends Service {
|
||||
{
|
||||
model: ctx.model.StockWarehouse,
|
||||
as: 'system_product',
|
||||
attributes: [ 'id', 'name', 'barcode', 'spec', 'unit', 'images' ],
|
||||
attributes: ['id', 'name', 'barcode', 'spec', 'unit', 'images'],
|
||||
},
|
||||
],
|
||||
});
|
||||
@ -1676,7 +1676,7 @@ class ReceivingService extends Service {
|
||||
ctx.model.StoreWarehouse.buildStoreStockInclude({
|
||||
warehouseId: ctx.user.store_id,
|
||||
required: false,
|
||||
attributes: [ 'store_id', 'store_remask' ],
|
||||
attributes: ['store_id', 'store_remask'],
|
||||
}),
|
||||
],
|
||||
});
|
||||
@ -1759,8 +1759,8 @@ class ReceivingService extends Service {
|
||||
const stats = await ctx.model.ReceivingDetail.findAll({
|
||||
where: { receiving_id: receivingId },
|
||||
attributes: [
|
||||
[ ctx.model.fn('COUNT', ctx.model.col('id')), 'total_items' ],
|
||||
[ ctx.model.fn('SUM', ctx.model.col('actual_quantity')), 'total_quantity' ],
|
||||
[ctx.model.fn('COUNT', ctx.model.col('id')), 'total_items'],
|
||||
[ctx.model.fn('SUM', ctx.model.col('actual_quantity')), 'total_quantity'],
|
||||
],
|
||||
raw: true,
|
||||
transaction,
|
||||
@ -1843,7 +1843,7 @@ class ReceivingService extends Service {
|
||||
{
|
||||
model: ctx.model.Receiving,
|
||||
as: 'receiving',
|
||||
attributes: [ 'id', 'status' ],
|
||||
attributes: ['id', 'status'],
|
||||
where: {
|
||||
warehouse_id,
|
||||
},
|
||||
@ -1894,7 +1894,7 @@ class ReceivingService extends Service {
|
||||
// 获取删除后的所有明细
|
||||
const remainingDetails = await ctx.model.ReceivingDetail.findAll({
|
||||
where: { receiving_id },
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
order: [['id', 'DESC']],
|
||||
});
|
||||
|
||||
// 格式化返回数据
|
||||
@ -2013,7 +2013,7 @@ class ReceivingService extends Service {
|
||||
{
|
||||
model: app.model.Receiving,
|
||||
as: 'receiving',
|
||||
attributes: [ 'id', 'warehouse_id', 'store_id', 'store_name' ],
|
||||
attributes: ['id', 'warehouse_id', 'store_id', 'store_name'],
|
||||
where: {
|
||||
warehouse_id: warehouseId,
|
||||
id: receiving_id,
|
||||
@ -2031,7 +2031,7 @@ class ReceivingService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
if (expiry_date !== undefined && isExpiryDateBeforeToday(expiry_date)) {
|
||||
if (expiry_date && expiry_date !== undefined && isExpiryDateBeforeToday(expiry_date)) {
|
||||
return {
|
||||
code: 400,
|
||||
message: '到期日期已过期,不能录入收货',
|
||||
@ -2090,12 +2090,12 @@ class ReceivingService extends Service {
|
||||
app.model.StoreWarehouse.buildStoreStockInclude({
|
||||
warehouseId,
|
||||
required: false,
|
||||
attributes: [ 'store_id', 'store_remask' ],
|
||||
attributes: ['store_id', 'store_remask'],
|
||||
}),
|
||||
{
|
||||
model: app.model.StockBarcode,
|
||||
as: 'barcodes',
|
||||
attributes: [ 'barcode' ],
|
||||
attributes: ['barcode'],
|
||||
required: false,
|
||||
},
|
||||
],
|
||||
@ -2390,11 +2390,11 @@ class ReceivingService extends Service {
|
||||
const deliveryMethod = String((receiving && receiving.delivery_method) || '').trim();
|
||||
|
||||
if (deliveryMethod === 'truck') {
|
||||
return [[ '车牌号', receiving && receiving.license_plate ]];
|
||||
return [['车牌号', receiving && receiving.license_plate]];
|
||||
}
|
||||
|
||||
if (deliveryMethod === 'express') {
|
||||
return [[ '物流单号', receiving && receiving.tracking_number ]];
|
||||
return [['物流单号', receiving && receiving.tracking_number]];
|
||||
}
|
||||
|
||||
return [];
|
||||
@ -2448,7 +2448,7 @@ class ReceivingService extends Service {
|
||||
);
|
||||
|
||||
const buildLinkCell = urls => {
|
||||
const normalizedUrls = (Array.isArray(urls) ? urls : [ urls ])
|
||||
const normalizedUrls = (Array.isArray(urls) ? urls : [urls])
|
||||
.map(item => String(item || '').trim())
|
||||
.filter(Boolean);
|
||||
|
||||
@ -2484,22 +2484,22 @@ class ReceivingService extends Service {
|
||||
pushReportRow([]);
|
||||
|
||||
[
|
||||
[ '收货单ID', receiving && receiving.id ],
|
||||
[ '收货单号', receiving && receiving.receiving_number ],
|
||||
[ '货主', receiving && receiving.store_name ],
|
||||
[ '来货方式', this.formatDeliveryMethod(receiving && receiving.delivery_method) ],
|
||||
['收货单ID', receiving && receiving.id],
|
||||
['收货单号', receiving && receiving.receiving_number],
|
||||
['货主', receiving && receiving.store_name],
|
||||
['来货方式', this.formatDeliveryMethod(receiving && receiving.delivery_method)],
|
||||
...this.getCompletionContactFields(receiving),
|
||||
[ '总明细数', stats.total_details || details.length ],
|
||||
[ '已匹配明细数', stats.matched_details || 0 ],
|
||||
[ '未匹配明细数', stats.unmatched_details || 0 ],
|
||||
[ '总数量', stats.total_quantity || 0 ],
|
||||
[ '总箱数', receiving && receiving.total_boxes ],
|
||||
[ '总托盘数', receiving && receiving.total_pallets ],
|
||||
[ '完成人', operator.employees_name || operator.real_name || operator.name || '' ],
|
||||
[ '完成时间', this.formatReportDate(receiving && receiving.receiving_end_time) ],
|
||||
[ '备注', receiving && receiving.remark ],
|
||||
].forEach(([ field, value ]) => {
|
||||
pushReportRow([ field, value ], {
|
||||
['总明细数', stats.total_details || details.length],
|
||||
['已匹配明细数', stats.matched_details || 0],
|
||||
['未匹配明细数', stats.unmatched_details || 0],
|
||||
['总数量', stats.total_quantity || 0],
|
||||
['总箱数', receiving && receiving.total_boxes],
|
||||
['总托盘数', receiving && receiving.total_pallets],
|
||||
['完成人', operator.employees_name || operator.real_name || operator.name || ''],
|
||||
['完成时间', this.formatReportDate(receiving && receiving.receiving_end_time)],
|
||||
['备注', receiving && receiving.remark],
|
||||
].forEach(([field, value]) => {
|
||||
pushReportRow([field, value], {
|
||||
toCol: 2,
|
||||
style: {
|
||||
alignment: { vertical: 'top', wrapText: true },
|
||||
@ -2508,7 +2508,7 @@ class ReceivingService extends Service {
|
||||
});
|
||||
|
||||
if (mainImageUrls.length === 0) {
|
||||
pushReportRow([ '收货图片', '无' ], {
|
||||
pushReportRow(['收货图片', '无'], {
|
||||
toCol: 2,
|
||||
style: {
|
||||
alignment: { vertical: 'top', wrapText: true },
|
||||
@ -2517,7 +2517,7 @@ class ReceivingService extends Service {
|
||||
} else {
|
||||
const summaryLinkCell = buildLinkCell(mainImageUrls);
|
||||
const imagePlaceholders = Array(Math.max(mainImageUrls.length, 1)).fill('');
|
||||
const firstImageRowIndex = pushReportRow([ '收货图片', summaryLinkCell, ...imagePlaceholders ], {
|
||||
const firstImageRowIndex = pushReportRow(['收货图片', summaryLinkCell, ...imagePlaceholders], {
|
||||
toCol: 2 + imagePlaceholders.length,
|
||||
height: 88,
|
||||
style: {
|
||||
@ -2554,7 +2554,7 @@ class ReceivingService extends Service {
|
||||
});
|
||||
|
||||
if (details.length === 0) {
|
||||
pushReportRow([ '', '', '无明细' ], {
|
||||
pushReportRow(['', '', '无明细'], {
|
||||
toCol: detailColumns.length,
|
||||
style: {
|
||||
alignment: { vertical: 'top', wrapText: true },
|
||||
@ -2703,7 +2703,7 @@ class ReceivingService extends Service {
|
||||
(completionReport && (completionReport.filename || completionReport.fileKey || completionReport.key)) || `收货完成_${receivingNumber}.xlsx`
|
||||
).trim();
|
||||
const title = `收货单${receivingNumber}已完成`;
|
||||
const contactLines = this.getCompletionContactFields(receiving).map(([ field, value ]) => `${field}:${value || '无'}`);
|
||||
const contactLines = this.getCompletionContactFields(receiving).map(([field, value]) => `${field}:${value || '无'}`);
|
||||
const content = [
|
||||
`收货单号:${receivingNumber} 已完成`,
|
||||
`货主:${receiving.store_name || '未知'}`,
|
||||
@ -2952,11 +2952,12 @@ class ReceivingService extends Service {
|
||||
business_id: {
|
||||
[Op.in]: detailsIds,
|
||||
},
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
include: [{
|
||||
model: ctx.model.File,
|
||||
as: 'file',
|
||||
attributes: [ 'file_url' ],
|
||||
attributes: ['file_url'],
|
||||
required: false,
|
||||
}],
|
||||
transaction,
|
||||
@ -2979,11 +2980,12 @@ class ReceivingService extends Service {
|
||||
where: {
|
||||
business_type: 'receiving',
|
||||
business_id: id,
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
include: [{
|
||||
model: ctx.model.File,
|
||||
as: 'file',
|
||||
attributes: [ 'file_url' ],
|
||||
attributes: ['file_url'],
|
||||
required: false,
|
||||
}],
|
||||
transaction,
|
||||
@ -3136,6 +3138,15 @@ class ReceivingService extends Service {
|
||||
completion_report: completionReport && completionReport.url,
|
||||
});
|
||||
|
||||
// 异步补全商品图片与毛重,不阻塞主进程
|
||||
this._syncProductDataFromReceiving({
|
||||
receivingId: id,
|
||||
warehouseId,
|
||||
details: receiving.details,
|
||||
}).catch(err => {
|
||||
ctx.logger.warn('[receiving._syncProductDataFromReceiving] 异步补全失败,不影响业务', err.message);
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
code: 200,
|
||||
@ -3180,6 +3191,121 @@ class ReceivingService extends Service {
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 收货完成后异步补全商品资料:绑定图片、补填毛重。
|
||||
*
|
||||
* 遍历当前收货单所有已绑定系统商品的明细:
|
||||
* 1. 若商品 is_images === 'N' 且该明细有收货图片,则将收货图片复制为商品图片(FileReference),
|
||||
* 并将商品的 is_images 更新为 'Y'。
|
||||
* 2. 若商品 gross_weight 为 0 或 null,且明细的 weight > 0,则将商品毛重更新为该明细的 weight。
|
||||
*
|
||||
* 本方法通过 setImmediate 调用,运行在事务提交后,任何异常只记录日志,不影响主进程。
|
||||
*
|
||||
* @param {Object} options 参数对象
|
||||
* @param {number} options.receivingId 收货单 ID
|
||||
* @param {number} options.warehouseId 仓库 ID
|
||||
* @param {Array} options.details 收货明细数组(来自 completeReceiving 中已加载的 details)
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async _syncProductDataFromReceiving({ receivingId, warehouseId, details }) {
|
||||
console.log("_syncProductDataFromReceiving异步执行中..."); // 调试日志
|
||||
const { ctx, app } = this;
|
||||
|
||||
// 只处理已绑定系统商品的明细
|
||||
const boundDetails = (Array.isArray(details) ? details : []).filter(
|
||||
d => d && Number(d.system_product_id) > 0
|
||||
);
|
||||
|
||||
if (boundDetails.length === 0) return;
|
||||
|
||||
for (const detail of boundDetails) {
|
||||
const systemProductId = Number(detail.system_product_id);
|
||||
try {
|
||||
// -------- 查询当前商品资料 --------
|
||||
const stock = await app.model.StockWarehouse.findOne({
|
||||
where: {
|
||||
id: systemProductId,
|
||||
warehouse_id: warehouseId,
|
||||
deleted_at: null,
|
||||
},
|
||||
attributes: ['id', 'is_images', 'gross_weight'],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (!stock) continue;
|
||||
|
||||
// 查询该明细是否有收货图片
|
||||
const detailImageRefs = await app.model.FileReference.findAll({
|
||||
where: {
|
||||
business_type: 'receivingItem',
|
||||
business_id: String(detail.id),
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
attributes: ['file_id'],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (detailImageRefs.length > 0) {
|
||||
// 查询商品已有的图片 file_id(避免重复)
|
||||
const existingStockImageFileIds = await app.model.FileReference.findAll({
|
||||
where: {
|
||||
business_type: 'stock',
|
||||
business_id: String(systemProductId),
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
attributes: ['file_id'],
|
||||
raw: true,
|
||||
}).then(rows => rows.map(r => r.file_id));
|
||||
|
||||
const toCreate = detailImageRefs
|
||||
.filter(ref => !existingStockImageFileIds.includes(ref.file_id))
|
||||
.map(ref => ({
|
||||
file_id: ref.file_id,
|
||||
business_type: 'stock',
|
||||
business_id: String(systemProductId),
|
||||
warehouse_id: warehouseId,
|
||||
display_order: 0,
|
||||
created_by: 'system',
|
||||
created_at: new Date(),
|
||||
}));
|
||||
|
||||
if (toCreate.length > 0) {
|
||||
await app.model.FileReference.bulkCreate(toCreate, { ignoreDuplicates: true });
|
||||
}
|
||||
|
||||
// 更新商品 is_images 标记
|
||||
await app.model.StockWarehouse.update(
|
||||
{ is_images: 'Y' },
|
||||
{ where: { id: systemProductId } }
|
||||
);
|
||||
|
||||
ctx.logger.info(
|
||||
`[_syncProductDataFromReceiving] 商品 ${systemProductId} 已补全图片,共复制 ${toCreate.length} 张(收货单 ${receivingId} 明细 ${detail.id})`
|
||||
);
|
||||
}
|
||||
|
||||
// -------- 2. 毛重补全 --------
|
||||
const currentWeight = parseFloat(stock.gross_weight) || 0;
|
||||
const detailWeight = parseFloat(detail.weight) || 0;
|
||||
if (currentWeight <= 0 && detailWeight > 0) {
|
||||
await app.model.StockWarehouse.update(
|
||||
{ gross_weight: detailWeight },
|
||||
{ where: { id: systemProductId } }
|
||||
);
|
||||
|
||||
ctx.logger.info(
|
||||
`[_syncProductDataFromReceiving] 商品 ${systemProductId} 已补全毛重 ${detailWeight}(收货单 ${receivingId} 明细 ${detail.id})`
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
// 单条明细失败不中断后续处理
|
||||
console.log(
|
||||
`[_syncProductDataFromReceiving] 处理明细 ${detail.id} (商品 ${systemProductId}) 失败: ${err.message}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ReceivingService;
|
||||
|
||||
@ -1236,6 +1236,7 @@ class SettingStoreWarehouseService extends Service {
|
||||
auth_end: item.auth_end || null,
|
||||
actual_end: item.actual_end || null,
|
||||
print_quantity: Number(item.print_quantity || 0),
|
||||
print_quantity_locked: Number(item.print_quantity_locked || 0),
|
||||
applied_by: item.applied_by ? Number(item.applied_by) : null,
|
||||
reviewed_by: item.reviewed_by ? Number(item.reviewed_by) : null,
|
||||
ended_by: item.ended_by ? Number(item.ended_by) : null,
|
||||
@ -1782,6 +1783,8 @@ class SettingStoreWarehouseService extends Service {
|
||||
|
||||
await transaction.commit();
|
||||
|
||||
await this.invalidateContractConfigCache(relation.warehouse_id, relation.store_id).catch(() => null);
|
||||
|
||||
// 记录操作日志
|
||||
try {
|
||||
await ctx.service.systems.operationLog.createOperationLog({
|
||||
@ -2218,6 +2221,98 @@ class SettingStoreWarehouseService extends Service {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成货主合约配置缓存键。
|
||||
*
|
||||
* @param {number|string} warehouseId 仓库 ID。
|
||||
* @param {number|string} storeId 货主 ID。
|
||||
* @return {string} 缓存键。
|
||||
*/
|
||||
getContractConfigCacheKey(warehouseId, storeId) {
|
||||
return `store_warehouse:contract_config:${Number(warehouseId || 0)}:${Number(storeId || 0)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 使货主合约配置缓存失效。
|
||||
*
|
||||
* @param {number|string} warehouseId 仓库 ID。
|
||||
* @param {number|string} storeId 货主 ID。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async invalidateContractConfigCache(warehouseId, storeId) {
|
||||
const key = this.getContractConfigCacheKey(warehouseId, storeId);
|
||||
try {
|
||||
const cacheRedis = this.app.redis && this.app.redis.get && this.app.redis.get('cache');
|
||||
if (cacheRedis && typeof cacheRedis.del === 'function') {
|
||||
await cacheRedis.del(key);
|
||||
return;
|
||||
}
|
||||
await this.app.setCacheAsync(key, null, 1);
|
||||
} catch (error) {
|
||||
this.ctx.logger.warn('[storeWarehouse.invalidateContractConfigCache] 缓存失效失败: %s', error.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 按仓库 ID 和货主 ID 读取合约配置,优先读缓存。
|
||||
*
|
||||
* 缓存在 savePolicyConfig 或合约状态变更后立即失效。
|
||||
*
|
||||
* @param {number|string} warehouseId 仓库 ID。
|
||||
* @param {number|string} storeId 货主 ID。
|
||||
* @return {Promise<Object|null>} 合约配置对象,不存在时返回 null。
|
||||
*/
|
||||
async getContractConfig(warehouseId, storeId) {
|
||||
const normalizedWarehouseId = Number(warehouseId || 0);
|
||||
const normalizedStoreId = Number(storeId || 0);
|
||||
if (normalizedWarehouseId <= 0 || normalizedStoreId <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const cacheKey = this.getContractConfigCacheKey(normalizedWarehouseId, normalizedStoreId);
|
||||
|
||||
try {
|
||||
const cached = await this.app.getCacheAsync(cacheKey);
|
||||
if (cached !== null && cached !== undefined) {
|
||||
return cached;
|
||||
}
|
||||
} catch (error) {
|
||||
this.ctx.logger.warn('[storeWarehouse.getContractConfig] 读取缓存失败: %s', error.message);
|
||||
}
|
||||
|
||||
const row = await this.ctx.model.StoreWarehouse.findOne({
|
||||
where: {
|
||||
warehouse_id: normalizedWarehouseId,
|
||||
store_id: normalizedStoreId,
|
||||
},
|
||||
attributes: ['id', 'store_id', 'warehouse_id', 'auth_status', 'policy_config'],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (!row) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const config = {
|
||||
id: row.id,
|
||||
store_id: row.store_id,
|
||||
warehouse_id: row.warehouse_id,
|
||||
auth_status: row.auth_status,
|
||||
policy_config: this.normalizePolicyConfig(row.policy_config, 'policy_config', {
|
||||
allowEmpty: true,
|
||||
sanitizeOnly: true,
|
||||
}),
|
||||
};
|
||||
|
||||
try {
|
||||
await this.app.setCacheAsync(cacheKey, config, 600);
|
||||
} catch (error) {
|
||||
this.ctx.logger.warn('[storeWarehouse.getContractConfig] 写入缓存失败: %s', error.message);
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = SettingStoreWarehouseService;
|
||||
|
||||
@ -428,6 +428,16 @@ class UploadService extends Service {
|
||||
// 生成完整的访问URL
|
||||
const fileUrl = `${cosConfig.cdnurl || cosConfig.uploadurl}/${resolvedFileKey}`;
|
||||
|
||||
// 对外通知时对路径段做 URL 编码(保留 / 分隔符),兼容含中文文件名的历史记录
|
||||
const encodeFileUrl = rawUrl => {
|
||||
const slashIdx = rawUrl.indexOf('/', rawUrl.indexOf('//') + 2);
|
||||
if (slashIdx === -1) return rawUrl;
|
||||
const base = rawUrl.slice(0, slashIdx);
|
||||
const keyPart = rawUrl.slice(slashIdx + 1);
|
||||
return `${base}/${keyPart.split('/').map(seg => encodeURIComponent(seg)).join('/')}`;
|
||||
};
|
||||
const fileUrlEncoded = encodeFileUrl(fileUrl);
|
||||
|
||||
// 计算哈希值(如果前端没有提供)
|
||||
let md5Hash = data.md5Hash || data.md5 || '';
|
||||
let sha1Hash = data.sha1Hash || data.sha1 || '';
|
||||
@ -518,7 +528,7 @@ class UploadService extends Service {
|
||||
this.ctx.logger.info(`文件已存在,返回已有记录: ${existingFile.file_url}`);
|
||||
return {
|
||||
fileId: existingFile.id,
|
||||
fileUrl: existingFile.file_url,
|
||||
fileUrl: encodeFileUrl(existingFile.file_url),
|
||||
fileKey: existingFile.file_key,
|
||||
fileName: existingFile.file_name,
|
||||
expireTime: resolvedExpireTime || existingFile.expire_time || null,
|
||||
@ -546,7 +556,7 @@ class UploadService extends Service {
|
||||
message: '文件上传成功',
|
||||
data: {
|
||||
fileId: savedFile.id,
|
||||
fileUrl,
|
||||
fileUrl: fileUrlEncoded,
|
||||
fileKey: resolvedFileKey,
|
||||
fileName: resolvedFileName,
|
||||
fileSize: resolvedFileSize,
|
||||
|
||||
@ -72,6 +72,7 @@ module.exports = appInfo => {
|
||||
config.fileWriter = {
|
||||
baseDir: path.join(appInfo.baseDir, 'runtime', 'file-writer'),
|
||||
maxFileSize: 100 * 1024 * 1024,
|
||||
maxFileLines: 2000,
|
||||
maxConsumeRecordsPerWindow: 1000,
|
||||
maxConsumeRecordsPerRun: 1000,
|
||||
writeWindowSeconds: 1,
|
||||
|
||||
@ -0,0 +1,63 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
const { DATE } = Sequelize;
|
||||
|
||||
const [ tables ] = await queryInterface.sequelize.query(
|
||||
"SHOW TABLES LIKE 'wms_express_setting'"
|
||||
);
|
||||
|
||||
if (tables.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [ columns ] = await queryInterface.sequelize.query(
|
||||
"SHOW COLUMNS FROM `wms_express_setting` LIKE 'deleted_at'"
|
||||
);
|
||||
|
||||
if (columns.length === 0) {
|
||||
await queryInterface.addColumn('wms_express_setting', 'deleted_at', {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '删除时间',
|
||||
});
|
||||
}
|
||||
|
||||
const [ indexes ] = await queryInterface.sequelize.query(
|
||||
"SHOW INDEX FROM `wms_express_setting` WHERE Key_name = 'idx_warehouse_deleted_at'"
|
||||
);
|
||||
|
||||
if (indexes.length === 0) {
|
||||
await queryInterface.addIndex('wms_express_setting', [ 'warehouse_id', 'deleted_at' ], {
|
||||
name: 'idx_warehouse_deleted_at',
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
const [ tables ] = await queryInterface.sequelize.query(
|
||||
"SHOW TABLES LIKE 'wms_express_setting'"
|
||||
);
|
||||
|
||||
if (tables.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [ indexes ] = await queryInterface.sequelize.query(
|
||||
"SHOW INDEX FROM `wms_express_setting` WHERE Key_name = 'idx_warehouse_deleted_at'"
|
||||
);
|
||||
|
||||
if (indexes.length > 0) {
|
||||
await queryInterface.removeIndex('wms_express_setting', 'idx_warehouse_deleted_at');
|
||||
}
|
||||
|
||||
const [ columns ] = await queryInterface.sequelize.query(
|
||||
"SHOW COLUMNS FROM `wms_express_setting` LIKE 'deleted_at'"
|
||||
);
|
||||
|
||||
if (columns.length > 0) {
|
||||
await queryInterface.removeColumn('wms_express_setting', 'deleted_at');
|
||||
}
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,108 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_NAME = 'wms_order_delivery';
|
||||
const TABLE_LIKE_PATTERN = 'wms_order_delivery\\_%';
|
||||
const COLUMN_NAME = 'weight_type';
|
||||
const COLUMN_DDL = 'int(11) NOT NULL DEFAULT 0';
|
||||
const COLUMN_COMMENT = '重量类型:0常规、1轻货、2重货、3冷链';
|
||||
const PREFERRED_AFTER = 'delivery_type';
|
||||
|
||||
/**
|
||||
* 获取发货单主表及所有分表名称。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。
|
||||
* @return {Promise<Array<Object>>} 表名查询结果。
|
||||
*/
|
||||
async function getOrderDeliveryTables(queryInterface) {
|
||||
const [ tables ] = await queryInterface.sequelize.query(`
|
||||
SELECT TABLE_NAME
|
||||
FROM INFORMATION_SCHEMA.TABLES
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND (TABLE_NAME = '${TABLE_NAME}' OR TABLE_NAME LIKE '${TABLE_LIKE_PATTERN}')
|
||||
`);
|
||||
|
||||
return tables;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断表中是否存在指定字段。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。
|
||||
* @param {string} tableName 表名。
|
||||
* @param {string} columnName 字段名。
|
||||
* @return {Promise<boolean>} 是否存在字段。
|
||||
*/
|
||||
async function hasColumn(queryInterface, tableName, columnName) {
|
||||
const [ columns ] = await queryInterface.sequelize.query(
|
||||
`
|
||||
SELECT COLUMN_NAME
|
||||
FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = :tableName
|
||||
AND COLUMN_NAME = :columnName
|
||||
`,
|
||||
{ replacements: { tableName, columnName } }
|
||||
);
|
||||
|
||||
return columns.length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 ADD COLUMN 的 AFTER 子句。
|
||||
* 当目标表存在 `delivery_type` 时,优先追加到其后;否则返回空串,直接追加到表尾。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。
|
||||
* @param {string} tableName 表名。
|
||||
* @return {Promise<string>} AFTER 子句或空字符串。
|
||||
*/
|
||||
async function resolveAfterClause(queryInterface, tableName) {
|
||||
if (await hasColumn(queryInterface, tableName, PREFERRED_AFTER)) {
|
||||
return ` AFTER \`${PREFERRED_AFTER}\``;
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 为发货单主表及分表补齐 `weight_type` 字段。
|
||||
* 仅在字段缺失时执行 ADD COLUMN,并尽量放在 `delivery_type` 后面。
|
||||
*
|
||||
* @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async up(queryInterface) {
|
||||
const tables = await getOrderDeliveryTables(queryInterface);
|
||||
|
||||
for (const row of tables) {
|
||||
const tableName = row.TABLE_NAME;
|
||||
|
||||
if (await hasColumn(queryInterface, tableName, COLUMN_NAME)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const afterClause = await resolveAfterClause(queryInterface, tableName);
|
||||
await queryInterface.sequelize.query(
|
||||
`ALTER TABLE \`${tableName}\` ADD COLUMN \`${COLUMN_NAME}\` ${COLUMN_DDL} COMMENT '${COLUMN_COMMENT}'${afterClause}`
|
||||
);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚删除发货单主表及分表的 `weight_type` 字段。
|
||||
* 仅在字段存在时执行 DROP COLUMN,保证回滚幂等。
|
||||
*
|
||||
* @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async down(queryInterface) {
|
||||
const tables = await getOrderDeliveryTables(queryInterface);
|
||||
|
||||
for (const row of tables) {
|
||||
const tableName = row.TABLE_NAME;
|
||||
|
||||
if (await hasColumn(queryInterface, tableName, COLUMN_NAME)) {
|
||||
await queryInterface.sequelize.query(
|
||||
`ALTER TABLE \`${tableName}\` DROP COLUMN \`${COLUMN_NAME}\``
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,93 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_NAME = 'wms_order_delivery';
|
||||
const TABLE_LIKE_PATTERN = 'wms_order_delivery\\_%';
|
||||
const COLUMN_NAME = 'order_flag';
|
||||
const UP_COLUMN_DDL = "LONGTEXT NULL COMMENT '订单标记'";
|
||||
const DOWN_COLUMN_DDL = "VARCHAR(200) NULL COMMENT '订单标记'";
|
||||
|
||||
/**
|
||||
* 获取发货单主表及所有分表名称。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。
|
||||
* @return {Promise<Array<Object>>} 表名查询结果。
|
||||
*/
|
||||
async function getOrderDeliveryTables(queryInterface) {
|
||||
const [ tables ] = await queryInterface.sequelize.query(`
|
||||
SELECT TABLE_NAME
|
||||
FROM INFORMATION_SCHEMA.TABLES
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND (TABLE_NAME = '${TABLE_NAME}' OR TABLE_NAME LIKE '${TABLE_LIKE_PATTERN}')
|
||||
`);
|
||||
|
||||
return tables;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断表中是否存在指定字段。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。
|
||||
* @param {string} tableName 表名。
|
||||
* @param {string} columnName 字段名。
|
||||
* @return {Promise<boolean>} 是否存在字段。
|
||||
*/
|
||||
async function hasColumn(queryInterface, tableName, columnName) {
|
||||
const [ columns ] = await queryInterface.sequelize.query(
|
||||
`
|
||||
SELECT COLUMN_NAME
|
||||
FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = :tableName
|
||||
AND COLUMN_NAME = :columnName
|
||||
`,
|
||||
{ replacements: { tableName, columnName } }
|
||||
);
|
||||
|
||||
return columns.length > 0;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 将发货单主表及分表的 `order_flag` 调整为 LONGTEXT。
|
||||
* 仅在目标表存在且字段存在时执行 MODIFY COLUMN,保证幂等。
|
||||
*
|
||||
* @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async up(queryInterface) {
|
||||
const tables = await getOrderDeliveryTables(queryInterface);
|
||||
|
||||
for (const row of tables) {
|
||||
const tableName = row.TABLE_NAME;
|
||||
|
||||
if (!(await hasColumn(queryInterface, tableName, COLUMN_NAME))) {
|
||||
continue;
|
||||
}
|
||||
|
||||
await queryInterface.sequelize.query(
|
||||
`ALTER TABLE \`${tableName}\` MODIFY COLUMN \`${COLUMN_NAME}\` ${UP_COLUMN_DDL}`
|
||||
);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 将发货单主表及分表的 `order_flag` 回滚为 VARCHAR(200)。
|
||||
* 仅在目标表存在且字段存在时执行 MODIFY COLUMN,保证幂等。
|
||||
*
|
||||
* @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async down(queryInterface) {
|
||||
const tables = await getOrderDeliveryTables(queryInterface);
|
||||
|
||||
for (const row of tables) {
|
||||
const tableName = row.TABLE_NAME;
|
||||
|
||||
if (!(await hasColumn(queryInterface, tableName, COLUMN_NAME))) {
|
||||
continue;
|
||||
}
|
||||
|
||||
await queryInterface.sequelize.query(
|
||||
`ALTER TABLE \`${tableName}\` MODIFY COLUMN \`${COLUMN_NAME}\` ${DOWN_COLUMN_DDL}`
|
||||
);
|
||||
}
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,107 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_NAME = 'wms_order_delivery';
|
||||
const TABLE_LIKE_PATTERN = 'wms_order_delivery\\_%';
|
||||
const COLUMN_NAME = 'source_order_codes';
|
||||
const COLUMN_DDL = "TEXT NULL COMMENT '来源订单号集合'";
|
||||
const PREFERRED_AFTER = 'source_platform_name';
|
||||
|
||||
/**
|
||||
* 获取发货单主表及所有分表名称。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。
|
||||
* @return {Promise<Array<Object>>} 表名查询结果。
|
||||
*/
|
||||
async function getOrderDeliveryTables(queryInterface) {
|
||||
const [ tables ] = await queryInterface.sequelize.query(`
|
||||
SELECT TABLE_NAME
|
||||
FROM INFORMATION_SCHEMA.TABLES
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND (TABLE_NAME = '${TABLE_NAME}' OR TABLE_NAME LIKE '${TABLE_LIKE_PATTERN}')
|
||||
`);
|
||||
|
||||
return tables;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断表中是否存在指定字段。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。
|
||||
* @param {string} tableName 表名。
|
||||
* @param {string} columnName 字段名。
|
||||
* @return {Promise<boolean>} 是否存在字段。
|
||||
*/
|
||||
async function hasColumn(queryInterface, tableName, columnName) {
|
||||
const [ columns ] = await queryInterface.sequelize.query(
|
||||
`
|
||||
SELECT COLUMN_NAME
|
||||
FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = :tableName
|
||||
AND COLUMN_NAME = :columnName
|
||||
`,
|
||||
{ replacements: { tableName, columnName } }
|
||||
);
|
||||
|
||||
return columns.length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 ADD COLUMN 的 AFTER 子句。
|
||||
* 当目标表存在 `source_platform_name` 时,优先追加到其后;否则返回空串,直接追加到表尾。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。
|
||||
* @param {string} tableName 表名。
|
||||
* @return {Promise<string>} AFTER 子句或空字符串。
|
||||
*/
|
||||
async function resolveAfterClause(queryInterface, tableName) {
|
||||
if (await hasColumn(queryInterface, tableName, PREFERRED_AFTER)) {
|
||||
return ` AFTER \`${PREFERRED_AFTER}\``;
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 为发货单主表及分表补齐 `source_order_codes` 字段。
|
||||
* 仅在字段缺失时执行 ADD COLUMN,并尽量放在 `source_platform_name` 后面。
|
||||
*
|
||||
* @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async up(queryInterface) {
|
||||
const tables = await getOrderDeliveryTables(queryInterface);
|
||||
|
||||
for (const row of tables) {
|
||||
const tableName = row.TABLE_NAME;
|
||||
|
||||
if (await hasColumn(queryInterface, tableName, COLUMN_NAME)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const afterClause = await resolveAfterClause(queryInterface, tableName);
|
||||
await queryInterface.sequelize.query(
|
||||
`ALTER TABLE \`${tableName}\` ADD COLUMN \`${COLUMN_NAME}\` ${COLUMN_DDL}${afterClause}`
|
||||
);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚删除发货单主表及分表的 `source_order_codes` 字段。
|
||||
* 仅在字段存在时执行 DROP COLUMN,保证回滚幂等。
|
||||
*
|
||||
* @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async down(queryInterface) {
|
||||
const tables = await getOrderDeliveryTables(queryInterface);
|
||||
|
||||
for (const row of tables) {
|
||||
const tableName = row.TABLE_NAME;
|
||||
|
||||
if (await hasColumn(queryInterface, tableName, COLUMN_NAME)) {
|
||||
await queryInterface.sequelize.query(
|
||||
`ALTER TABLE \`${tableName}\` DROP COLUMN \`${COLUMN_NAME}\``
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
@ -6,6 +6,7 @@
|
||||
- 串行写入:同一进程内通过内部队列 `enqueue` 串行化写入,保证单进程内顺序性。
|
||||
- 强制落盘:每次写入使用文件句柄写入并调用 `handle.sync()` 进行 fsync,尽量保证数据落盘。
|
||||
- 自动轮转:当当前文件大小 + 待写入字节数 超过 `maxFileSize` 时,会自增序号并切换到新文件(sequence)。
|
||||
- 自动按行轮转:当单个数据文件累计达到 `maxFileLines` 行后,下一条写入会自动切换到下一个 sequence 文件,默认阈值为 `2000` 行。
|
||||
- 目录结构:默认 baseDir 下按业务与日期分区:
|
||||
- baseDir/<businessSegment>/<YYYY>/<MM>/<DD>/
|
||||
- 文件命名:文件前缀包含业务段与进程标识(`<business>-<machine>-<worker>-p<pid>-<seq>`),尾部带序号与扩展名(`fileExtension`,默认 `.log`)。
|
||||
@ -21,6 +22,7 @@
|
||||
**配置项说明(config.fileWriter)**
|
||||
- `baseDir`:基础目录,默认 `path.join(app.baseDir, 'runtime', 'file-writer')`。
|
||||
- `maxFileSize`:单文件最大字节数,超过后轮转。支持数字(字节)或带单位字符串(如 `100M`、`1G`)。默认 `100 * 1024 * 1024`(100MB)。
|
||||
- `maxFileLines`:单文件最大行数,达到后下一条写入会自动轮转到新的 sequence 文件。默认 `2000`。
|
||||
- `retentionDays`:保留天数,超过则删除。设为 `0` 或负值可禁用清理。默认 `7`。
|
||||
- `cleanupIntervalMs`:触发清理的最小间隔(毫秒),写入时会基于此决定是否执行清理,设置为 `0` 或负值可禁用定期清理。默认 `3600000`(1 小时)。
|
||||
- `sequenceWidth`:文件序号宽度(零填充),默认 `4`(例如 `0001`)。
|
||||
@ -38,6 +40,7 @@ const path = require('path');
|
||||
exports.fileWriter = {
|
||||
baseDir: path.join(__dirname, '..', 'runtime', 'file-writer'),
|
||||
maxFileSize: '200M',
|
||||
maxFileLines: 2000,
|
||||
retentionDays: 14,
|
||||
cleanupIntervalMs: 60 * 60 * 1000,
|
||||
sequenceWidth: 4,
|
||||
|
||||
63
methods/changes/openapi.json
Normal file
63
methods/changes/openapi.json
Normal file
@ -0,0 +1,63 @@
|
||||
[
|
||||
{
|
||||
"version": "2026.04.26-openapi-01",
|
||||
"date": "2026-04-26",
|
||||
"summary": "新增 openapi 入口文档骨架(/openapi),包含请求体解析、app_key 与签名校验规则",
|
||||
"methods": [
|
||||
"openapi.index"
|
||||
],
|
||||
"notes": [
|
||||
"新增 methods/openapi.json:记录 /openapi 入口的文档骨架与校验约定(JSON body 解析、统一错误格式、app_key 校验、签名规则)。",
|
||||
"核心校验规则:1) body 使用 JSON 解析,优先 rawBody;2) 错误对外格式使用 toFailure(flag/code/message/data/timestamp);3) app_key 仅当数据库记录的 interface_type_id=2 且 is_enabled=1 时视为有效;4) 签名按 query 字段字母序排序(排除 sign/signature)+ selfAppSecret + bodySign(md5(stableSerialize(body))),对拼接字符串取 md5。"
|
||||
],
|
||||
"type": "added"
|
||||
}
|
||||
,
|
||||
{
|
||||
"version": "2026.04.26-openapi-02",
|
||||
"date": "2026-04-26",
|
||||
"summary": "说明:/openapi 入口不校验请求头,补充签名别名与 app_key 有效性说明",
|
||||
"methods": [
|
||||
"openapi.index"
|
||||
],
|
||||
"notes": [
|
||||
"修正:明确 /openapi 入口不对请求头进行强制校验(与 qimen 一致),headers 字段仅作为参考。",
|
||||
"确认:body JSON 解析(rawBody 优先)与错误消息保持为 'json数据为空' / 'json数据解析错误';app_key 校验仅当 wms_api_app.interface_type_id=2 且 is_enabled=1 时有效。",
|
||||
"补充:签名字段别名说明(sign/signature)与 app_key 别名(app_key/appkey/self_app_key);签名算法与实现参见 app/lib/api_sign.js。"
|
||||
],
|
||||
"type": "modified"
|
||||
},
|
||||
{
|
||||
"version": "2026.04.26-openapi-03",
|
||||
"date": "2026-04-26",
|
||||
"summary": "新增 openapi 方法 index.ping(基础模块,心跳接口)",
|
||||
"methods": [
|
||||
"index.ping"
|
||||
],
|
||||
"notes": [
|
||||
"新增 openapi 可用性检测接口 index.ping,返回与系统成功结构一致(包含 code/message/data)。"
|
||||
],
|
||||
"type": "added"
|
||||
}
|
||||
,
|
||||
{
|
||||
"version": "2026.04.26-openapi-04",
|
||||
"date": "2026-04-26",
|
||||
"summary": "规范化 /openapi 文档:独立链路、移除请求头校验、返回风格改为 code/message/data、明确签名与 app_key 校验、指向 openapiMethods 分发。",
|
||||
"methods": [
|
||||
"openapi.index",
|
||||
"index.ping"
|
||||
],
|
||||
"notes": [
|
||||
"本次变更:",
|
||||
"1) 明确 /openapi 为独立链路,不复用 system/qimen 的请求头校验;",
|
||||
"2) 移除 platform/project 等请求头的强校验说明;",
|
||||
"3) 返回结构与 system 风格对齐(使用 code/message/data,移除额外 flag 字段);",
|
||||
"4) 保持 body 为 JSON(rawBody 优先),并明确错误文案为 'json数据为空' / 'json数据解析错误';",
|
||||
"5) 明确 app_key 仅当 wms_api_app.interface_type_id=2 且 is_enabled=1 时视为有效;",
|
||||
"6) 明确签名算法:query 按字母序排序 + self_app_secret + bodySign(md5(stableSerialize(body))),支持别名 sign/signature 与 app_key/appkey/self_app_key;",
|
||||
"7) 说明 method 分发走 openapiMethods 专用目录,示例方法 index.ping(基础模块)。"
|
||||
],
|
||||
"type": "modified"
|
||||
}
|
||||
]
|
||||
File diff suppressed because it is too large
Load Diff
160
methods/openapi.json
Normal file
160
methods/openapi.json
Normal file
@ -0,0 +1,160 @@
|
||||
{
|
||||
"module": "openapi",
|
||||
"description": "开放 API 统一入口,独立链路,HTTP POST /openapi,记录入口校验/鉴权规则与返回格式。",
|
||||
"version": "2026.04.26-openapi-04",
|
||||
"updatedAt": "2026-04-26",
|
||||
"http": {
|
||||
"path": "/openapi",
|
||||
"method": "POST"
|
||||
},
|
||||
"headers": [],
|
||||
"endpoints": [
|
||||
{
|
||||
"method": "openapi.index",
|
||||
"description": "开放 API 统一入口,接收 POST /openapi;完成 JSON body 解析、app_key 校验与签名校验,返回统一响应(与系统 style 的 code/message/data 保持一致)。",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": false,
|
||||
"headers": [],
|
||||
"params": [
|
||||
{
|
||||
"name": "method",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"source": "query",
|
||||
"description": "目标系统方法名,必填(例如 order.list)"
|
||||
},
|
||||
{
|
||||
"name": "v",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"source": "query",
|
||||
"description": "API 版本号"
|
||||
},
|
||||
{
|
||||
"name": "timestamp",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"source": "query",
|
||||
"description": "时间戳(数字)"
|
||||
},
|
||||
{
|
||||
"name": "app_key",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"source": "query",
|
||||
"description": "开放平台分配的 app_key;兼容别名 appkey 与 self_app_key(任一存在即可)"
|
||||
},
|
||||
{
|
||||
"name": "sign",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"source": "query",
|
||||
"description": "签名字段,兼容别名 signature(MD5 小写 hex)"
|
||||
}
|
||||
],
|
||||
"requestBody": [
|
||||
{
|
||||
"name": "body",
|
||||
"type": "object",
|
||||
"required": true,
|
||||
"source": "body",
|
||||
"description": "请求体必须为 JSON;入口优先读取 rawBody,空体或非 JSON 返回 400,错误文案为 'json数据为空' 或 'json数据解析错误'。"
|
||||
}
|
||||
],
|
||||
"response": [
|
||||
{
|
||||
"name": "code",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "业务码:成功通常为 1"
|
||||
},
|
||||
{
|
||||
"name": "message",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "提示消息"
|
||||
},
|
||||
{
|
||||
"name": "data",
|
||||
"type": "object",
|
||||
"required": false,
|
||||
"description": "接口返回数据"
|
||||
},
|
||||
{
|
||||
"name": "timestamp",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "响应时间戳"
|
||||
}
|
||||
],
|
||||
"errors": [
|
||||
{
|
||||
"code": 400,
|
||||
"message": "参数缺失或错误: method/v/timestamp 或 app_key"
|
||||
},
|
||||
{
|
||||
"code": 400,
|
||||
"message": "json数据为空"
|
||||
},
|
||||
{
|
||||
"code": 400,
|
||||
"message": "json数据解析错误"
|
||||
},
|
||||
{
|
||||
"code": 401,
|
||||
"message": "app_key 无效或不可用"
|
||||
},
|
||||
{
|
||||
"code": 401,
|
||||
"message": "签名校验失败"
|
||||
},
|
||||
{
|
||||
"code": 500,
|
||||
"message": "接口错误: <message>"
|
||||
}
|
||||
],
|
||||
"notes": [
|
||||
"独立链路:/openapi 为独立入口,不依附于 system/qimen,不复用系统的请求头强校验或鉴权链。",
|
||||
"不校验 platform/project 等请求头:openapi 不对 platform/project 请求头做强制校验或拒绝,headers 字段为空。",
|
||||
"body 使用 JSON 解析:content-type 应包含 application/json;优先读取 ctx.request.rawBody,若未提供则回退到 ctx.request.body 或原始请求流;空体或解析失败返回 400(错误消息为 'json数据为空' 或 'json数据解析错误')。",
|
||||
"app_key 校验:通过数据库表 wms_api_app(或对应模型)按 self_app_key/app_key 查询,要求 is_enabled=1 且 interface_type_id=2(OPEN_API 类型)才视为有效,否则返回 401(消息 'app_key 无效或不可用')。",
|
||||
"签名规则:构建 canonicalQuery(取 query 参数,支持别名 app_key/appkey/self_app_key,签名字段支持 sign/signature;排除签名字段本身),按 key 的字母序排序并用 & 连接 key=value;计算 bodySign 为 md5(稳定序列化(body));将 canonicalQuery + self_app_secret + bodySign 连接成字符串并对该字符串计算 md5(小写 hex),结果与请求中 sign/signature 比对,匹配即通过。",
|
||||
"method 分发:openapi 的 method 分发走 openapiMethods 专用目录(代码内实现独立路由/分发);已存在方法示例:index.ping(模块=基础模块)。",
|
||||
"返回风格:成功与失败返回使用与系统一致的 code/message/data 格式(无需额外 flag 字段),以保证与系统端点兼容。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"method": "index.ping",
|
||||
"description": "基础模块 心跳接口,返回服务可用性(部署在 openapiMethods 中)",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": false,
|
||||
"headers": [],
|
||||
"params": [],
|
||||
"response": [
|
||||
{
|
||||
"name": "code",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "业务状态码,成功通常为 200 或 1"
|
||||
},
|
||||
{
|
||||
"name": "message",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "提示信息"
|
||||
},
|
||||
{
|
||||
"name": "data",
|
||||
"type": "object",
|
||||
"required": false,
|
||||
"description": "返回数据,ping 一般为空或包含版本/uptime 等信息"
|
||||
}
|
||||
],
|
||||
"errors": [],
|
||||
"notes": [
|
||||
"模块:基础模块",
|
||||
"方法部署位置:openapiMethods/index.ping"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
1884
methods/system.json
1884
methods/system.json
File diff suppressed because it is too large
Load Diff
@ -1 +1 @@
|
||||
{"startedAt":1776007031826,"recordCount":1}
|
||||
{"startedAt":1777218488523,"recordCount":1}
|
||||
|
||||
@ -1,2 +0,0 @@
|
||||
{"log_id":"QL-1775804691322-cfe013","from_key":"24869601","to_key":23535631,"method":"deliveryorder.create","sign":"05687722A46473E4018E0EBAAAB84E96","costomer_id":"jky2025102001","v":"2.0","url":"http://127.0.0.1:6060/qimen?app_key=24869601&method=deliveryorder.create&v=2.0&format=xml&sign_method=md5&customerId=jky2025102001&sign=05687722A46473E4018E0EBAAAB84E96×tamp=2026-01-13+23%3A26%3A07","created_at":"2026-04-10T07:04:51.322Z","body":"<?xml version=\"1.0\" encoding=\"utf-8\"?><request><deliveryOrder><deliveryOrderCode>SIM20260410070451</deliveryOrderCode><preDeliveryOrderCode /><preDeliveryOrderId /><orderType>JYCK</orderType><warehouseCode>100000</warehouseCode><orderFlag /><sourcePlatformCode>PDD</sourcePlatformCode><sourcePlatformName>拼多多</sourcePlatformName><buyerMessage /><sellerMessage /><createTime>2026-01-13 23:26:07</createTime><placeOrderTime>2026-01-13 23:22:03</placeOrderTime><payTime>2026-01-13 23:22:03</payTime><payNo /><shopNick>火火家de小店</shopNick><shopCode>0675</shopCode><sellerNick>1</sellerNick><buyerNick>刘付明仁18022440198</buyerNick><operatorName>1</operatorName><totalAmount>10</totalAmount><arAmount>0</arAmount><itemAmount>10</itemAmount><discountAmount>0</discountAmount><freight>0</freight><logisticsCode>SFKY</logisticsCode><logisticsName>顺丰空运</logisticsName><expressCode /><operateTime>2026-01-13 23:26:07</operateTime><isUrgency>N</isUrgency><invoiceFlag>N</invoiceFlag><senderInfo><company>火火家de小店</company><name>1</name><zipCode /><tel>1</tel><mobile>1</mobile><countryCode>CN</countryCode><province>广东省</province><city>广州市</city><area>从化区</area><town>太平镇</town><detailAddress>天豹云仓</detailAddress></senderInfo><receiverInfo><name>刘付明仁</name><zipCode /><tel /><mobile>18022440198</mobile><email /><countryCode>CN</countryCode><province>广东省</province><city>广州市</city><area>白云区</area><town>太和镇</town><detailAddress>广东省 广州市 白云区 太和镇 二路32号</detailAddress><idType>1</idType><idNumber /><oaid /></receiverInfo><remark /><logisticsAreaCode /><insuranceFlag>N</insuranceFlag><gotAmount>0</gotAmount><oaidOrderSourceCode /></deliveryOrder><orderLines><orderLine><orderLineNo>1</orderLineNo><ownerCode>jky2025102001</ownerCode><itemCode>011000000228</itemCode><itemId>1000649</itemId><itemName>测试</itemName><planQty>10</planQty><sourceOrderCode /><subSourceOrderCode /><actualPrice>1</actualPrice><extCode /><batchCode /><retailPrice>1</retailPrice><discountAmount>0</discountAmount><produceCode /><inventoryType>ZP</inventoryType><payNo /><extendProps><RealPayMoney>10</RealPayMoney><shareAmount>10</shareAmount></extendProps></orderLine></orderLines><extendProps><taxAmount>0</taxAmount><taxFee>0</taxFee><actualAmount>0</actualAmount><tariffAmount>0</tariffAmount><consumptionDutyAmount>0</consumptionDutyAmount><addedValueTaxAmount>0</addedValueTaxAmount><discountAmount>0</discountAmount><platDiscountAmount>0</platDiscountAmount><declaringValueAmount>0</declaringValueAmount><pdd_plat_discount>0</pdd_plat_discount><ewaybill_order_code /><selfSupport>false</selfSupport><innerProps /></extendProps></request>","result":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<response>\n <flag>failure</flag>\n <code>0</code>\n <message>奇门吉客云ERP客户编码jky2025102001仓库编码warehouseCode未绑定到你的货主或未启用,请联系仓库绑定</message>\n</response>","use_time":98}
|
||||
{"log_id":"QL-1775804829940-8ee9f4","from_key":"23060081","to_key":23535631,"method":"deliveryorder.create","sign":"F4AC9969DF96CBDBCE02CF60982F2984","costomer_id":"4","v":"2.0","url":"http://127.0.0.1:6060/qimen?app_key=23060081&method=deliveryorder.create&v=2.0&format=xml&sign_method=md5&customerId=4&sign=F4AC9969DF96CBDBCE02CF60982F2984×tamp=2026-01-13+23%3A27%3A38","created_at":"2026-04-10T07:07:09.940Z","body":"<request><deliveryOrder><buyerNick>刘付明仁</buyerNick><createTime>2026-01-13 23:27:36</createTime><deliveryOrderCode>SIM20260410070709</deliveryOrderCode><discountAmount>0.00</discountAmount><freight>0</freight><gotAmount>0.00</gotAmount><itemAmount>0</itemAmount><latestDeliveryTime>2026-01-15 22:51:36</latestDeliveryTime><logisticsCode>SFKY</logisticsCode><logisticsName>顺丰速运_空运</logisticsName><operateTime>2026-01-13 23:27:36</operateTime><orderType>JYCK</orderType><payNo>S20260113225136223</payNo><payTime>2026-01-13 22:51:36</payTime><placeOrderTime>2026-01-13 22:49:50</placeOrderTime><receiverInfo><area>白云区</area><city>广州市</city><detailAddress>钟落潭良沙二路32号</detailAddress><mobile>18022440198</mobile><name>刘付明仁</name><province>广东省</province><extendProps></extendProps></receiverInfo><remark>S260113225136208</remark><senderInfo><area>白云区</area><city>广州市</city><detailAddress>1</detailAddress><mobile>18022440198</mobile><name>天豹测试仓15271658</name><province>广东省</province></senderInfo><shopNick>{线下}</shopNick><sourcePlatformCode>OFFLINE</sourcePlatformCode><sourcePlatformName>线下店铺</sourcePlatformName><totalAmount>0.00</totalAmount><warehouseCode>100000</warehouseCode><extendProps><oid>2042359</oid><subOrderType>Offline</subOrderType><isDecrypt>false</isDecrypt><shopId>0</shopId><isJitx>false</isJitx><isJdMobileDecrypt>true</isJdMobileDecrypt><buyer_paidamount>0</buyer_paidamount><sellerIncome_amount>0</sellerIncome_amount></extendProps></deliveryOrder><orderLines><orderLine><actualPrice>0</actualPrice><inventoryType>ZP</inventoryType><itemCode>023802</itemCode><itemId>1000218</itemId><itemName>空包</itemName><orderLineNo>1158149</orderLineNo><ownerCode>4</ownerCode><planQty>5</planQty><sourceOrderCode>S260113225136208</sourceOrderCode><extendProps><isGift>0</isGift></extendProps></orderLine></orderLines><extendProps></extendProps></request>","result":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<response>\n <flag>failure</flag>\n <code>0</code>\n <message>奇门聚水潭ERP客户编码4仓库编码warehouseCode未绑定到你的货主或未启用,请联系仓库绑定</message>\n</response>","use_time":88}
|
||||
@ -1,7 +0,0 @@
|
||||
{
|
||||
"filePath": "D:\\wms\\runtime\\file-writer\\qimen-logs\\2026\\04\\10\\qimen-logs-MINGREN-worker-p4496-0001.log",
|
||||
"offset": 6149,
|
||||
"processedCount": 2,
|
||||
"completedAt": "2026-04-10T14:20:54.561Z",
|
||||
"updatedAt": "2026-04-10T14:20:54.561Z"
|
||||
}
|
||||
@ -1 +0,0 @@
|
||||
{"log_id":"QL-1776005200436-dfa9d6","from_key":"24869601","to_key":23535631,"method":"deliveryorder.create","sign":"74F6AD27E9412E9F1DABEBD72FBB0FD6","costomer_id":"jky2025102001","v":"2.0","url":"http://127.0.0.1:6060/qimen?app_key=24869601&method=deliveryorder.create&v=2.0&format=xml&sign_method=md5×tamp=1776005200&customerId=jky2025102001&sign=74F6AD27E9412E9F1DABEBD72FBB0FD6","created_at":"2026-04-12T14:46:40.436Z","body":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<request>\n <deliveryOrder>\n <deliveryOrderCode>TRACE_OUTBOUND_1776005196546_B37AA0C5</deliveryOrderCode>\n <sourcePlatformCode>TAOBAO</sourcePlatformCode>\n <sourcePlatformName>淘宝</sourcePlatformName>\n <warehouseCode>100000</warehouseCode>\n <orderType>JYCK</orderType>\n <receiverInfo>\n <name>自动化验证收件人</name>\n <mobile>13800138000</mobile>\n <province>广东省</province>\n <city>广州市</city>\n <area>黄埔区</area>\n <town>知识城街道</town>\n <detailAddress>自动化验证地址 TRACE_OUTBOUND_1776005196546_B37AA0C5</detailAddress>\n <zipCode>510000</zipCode>\n </receiverInfo>\n </deliveryOrder>\n <orderLines>\n <orderLine>\n <itemId>101391</itemId>\n <itemCode>023802</itemCode>\n <itemName>空包</itemName>\n <planQty>1</planQty>\n <orderLineNo>1</orderLineNo>\n </orderLine>\n </orderLines>\n</request>","result":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<response>\n <flag>failure</flag>\n <code>0</code>\n <message>奇门吉客云ERP客户编码jky2025102001仓库编码warehouseCode未绑定到你的货主或未启用,请联系仓库绑定</message>\n</response>","use_time":92}
|
||||
@ -1,7 +0,0 @@
|
||||
{
|
||||
"filePath": "D:\\wms\\runtime\\file-writer\\qimen-logs\\2026\\04\\12\\qimen-logs-MINGREN-worker-p38224-0001.log",
|
||||
"offset": 1713,
|
||||
"processedCount": 1,
|
||||
"completedAt": "2026-04-12T14:46:52.525Z",
|
||||
"updatedAt": "2026-04-12T14:46:52.525Z"
|
||||
}
|
||||
@ -1,4 +0,0 @@
|
||||
{"log_id":"QL-1776005884434-818312","from_key":"24869601","to_key":23535631,"method":"deliveryorder.create","sign":"C591375BD641DD47560872675F5CCA0E","costomer_id":"jky2025102001","v":"2.0","url":"http://127.0.0.1:6060/qimen?app_key=24869601&method=deliveryorder.create&v=2.0&format=xml&sign_method=md5×tamp=1776005884&customerId=jky2025102001&sign=C591375BD641DD47560872675F5CCA0E","created_at":"2026-04-12T14:58:04.434Z","body":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<request>\n <deliveryOrder>\n <deliveryOrderCode>TRACE_OUTBOUND_1776005880432_FA93FDAF</deliveryOrderCode>\n <sourcePlatformCode>TAOBAO</sourcePlatformCode>\n <sourcePlatformName>淘宝</sourcePlatformName>\n <warehouseCode>100000</warehouseCode>\n <orderType>JYCK</orderType>\n <receiverInfo>\n <name>自动化验证收件人</name>\n <mobile>13800138000</mobile>\n <province>广东省</province>\n <city>广州市</city>\n <area>黄埔区</area>\n <town>知识城街道</town>\n <detailAddress>自动化验证地址 TRACE_OUTBOUND_1776005880432_FA93FDAF</detailAddress>\n <zipCode>510000</zipCode>\n </receiverInfo>\n </deliveryOrder>\n <orderLines>\n <orderLine>\n <itemId>101391</itemId>\n <itemCode>023802</itemCode>\n <itemName>空包</itemName>\n <planQty>1</planQty>\n <orderLineNo>1</orderLineNo>\n </orderLine>\n </orderLines>\n</request>","result":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<response>\n <flag>failure</flag>\n <code>0</code>\n <message>奇门吉客云ERP客户编码jky2025102001仓库编码warehouseCode未绑定到你的货主或未启用,请联系仓库绑定</message>\n</response>","use_time":91}
|
||||
{"log_id":"QL-1776006129287-77b8d4","from_key":"24869601","to_key":23535631,"method":"deliveryorder.create","sign":"A0B72528AC9B54B0DDA564298B20E7C0","costomer_id":"jky2025102001","v":"2.0","url":"http://127.0.0.1:6060/qimen?app_key=24869601&method=deliveryorder.create&v=2.0&format=xml&sign_method=md5×tamp=1776006129&customerId=jky2025102001&sign=A0B72528AC9B54B0DDA564298B20E7C0","created_at":"2026-04-12T15:02:09.287Z","body":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<request>\n <deliveryOrder>\n <deliveryOrderCode>TRACE_OUTBOUND_1776006125376_39EA41AC</deliveryOrderCode>\n <sourcePlatformCode>TB</sourcePlatformCode>\n <sourcePlatformName>淘宝</sourcePlatformName>\n <warehouseCode>100000</warehouseCode>\n <orderType>JYCK</orderType>\n <receiverInfo>\n <name>自动化验证收件人</name>\n <mobile>13800138000</mobile>\n <province>广东省</province>\n <city>广州市</city>\n <area>黄埔区</area>\n <town>知识城街道</town>\n <detailAddress>自动化验证地址 TRACE_OUTBOUND_1776006125376_39EA41AC</detailAddress>\n <zipCode>510000</zipCode>\n </receiverInfo>\n </deliveryOrder>\n <orderLines>\n <orderLine>\n <itemId>101391</itemId>\n <itemCode>023802</itemCode>\n <itemName>空包</itemName>\n <planQty>1</planQty>\n <orderLineNo>1</orderLineNo>\n </orderLine>\n </orderLines>\n</request>","result":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<response>\n <flag>failure</flag>\n <code>0</code>\n <message>奇门吉客云ERP客户编码jky2025102001仓库编码warehouseCode未绑定到你的货主或未启用,请联系仓库绑定</message>\n</response>","use_time":88}
|
||||
{"log_id":"QL-1776006776809-5dbb53","from_key":"24869601","to_key":23535631,"method":"deliveryorder.create","sign":"65632055E9198D2C8E466A44D0EF0D4C","costomer_id":"jky2025102001","v":"2.0","url":"http://127.0.0.1:6060/qimen?app_key=24869601&method=deliveryorder.create&v=2.0&format=xml&sign_method=md5×tamp=1776006776&customerId=jky2025102001&sign=65632055E9198D2C8E466A44D0EF0D4C","created_at":"2026-04-12T15:12:56.809Z","body":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<request>\n <deliveryOrder>\n <deliveryOrderCode>TRACE_OUTBOUND_1776006772829_A0ADB113</deliveryOrderCode>\n <sourcePlatformCode>TB</sourcePlatformCode>\n <sourcePlatformName>淘宝</sourcePlatformName>\n <warehouseCode>100000</warehouseCode>\n <orderType>JYCK</orderType>\n <receiverInfo>\n <name>自动化验证收件人</name>\n <mobile>13800138000</mobile>\n <province>广东省</province>\n <city>广州市</city>\n <area>黄埔区</area>\n <town>知识城街道</town>\n <detailAddress>自动化验证地址 TRACE_OUTBOUND_1776006772829_A0ADB113</detailAddress>\n <zipCode>510000</zipCode>\n </receiverInfo>\n </deliveryOrder>\n <orderLines>\n <orderLine>\n <itemId>101391</itemId>\n <itemCode>023802</itemCode>\n <itemName>空包</itemName>\n <planQty>1</planQty>\n <orderLineNo>1</orderLineNo>\n </orderLine>\n </orderLines>\n</request>","result":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<response>\n <flag>failure</flag>\n <code>0</code>\n <message>奇门吉客云ERP客户编码jky2025102001仓库编码warehouseCode未绑定到你的货主或未启用,请联系仓库绑定</message>\n</response>","use_time":95}
|
||||
{"log_id":"QL-1776007031740-155ce0","from_key":"24869601","to_key":23535631,"method":"deliveryorder.create","sign":"AE833C70C726B4B6664544B5A7B412EF","costomer_id":"jky2025102001","v":"2.0","url":"http://127.0.0.1:6060/qimen?app_key=24869601&method=deliveryorder.create&v=2.0&format=xml&sign_method=md5×tamp=1776007031&customerId=jky2025102001&sign=AE833C70C726B4B6664544B5A7B412EF","created_at":"2026-04-12T15:17:11.740Z","body":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<request>\n <deliveryOrder>\n <deliveryOrderCode>TRACE_OUTBOUND_1776007027818_0E2C252D</deliveryOrderCode>\n <sourcePlatformCode>TB</sourcePlatformCode>\n <sourcePlatformName>淘宝</sourcePlatformName>\n <warehouseCode>100000</warehouseCode>\n <orderType>JYCK</orderType>\n <receiverInfo>\n <name>自动化验证收件人</name>\n <mobile>13800138000</mobile>\n <province>广东省</province>\n <city>广州市</city>\n <area>黄埔区</area>\n <town>知识城街道</town>\n <detailAddress>自动化验证地址 TRACE_OUTBOUND_1776007027818_0E2C252D</detailAddress>\n <zipCode>510000</zipCode>\n </receiverInfo>\n </deliveryOrder>\n <orderLines>\n <orderLine>\n <itemId>1000218</itemId>\n <itemCode>023802</itemCode>\n <itemName>空包</itemName>\n <planQty>1</planQty>\n <orderLineNo>1</orderLineNo>\n </orderLine>\n </orderLines>\n</request>","result":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<response>\n <flag>failure</flag>\n <code>0</code>\n <message>奇门吉客云ERP客户编码jky2025102001仓库编码warehouseCode未绑定到你的货主或未启用,请联系仓库绑定</message>\n</response>","use_time":86}
|
||||
@ -1 +0,0 @@
|
||||
{"log_id":"QL-1776005653930-b9f1fa","from_key":"24869601","to_key":23535631,"method":"deliveryorder.create","sign":"4AB934D12D74B558BE1060D5525EFF7B","costomer_id":"jky2025102001","v":"2.0","url":"http://127.0.0.1:6060/qimen?app_key=24869601&method=deliveryorder.create&v=2.0&format=xml&sign_method=md5×tamp=1776005653&customerId=jky2025102001&sign=4AB934D12D74B558BE1060D5525EFF7B","created_at":"2026-04-12T14:54:13.931Z","body":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<request>\n <deliveryOrder>\n <deliveryOrderCode>TRACE_OUTBOUND_1776005649940_B0FA5A9A</deliveryOrderCode>\n <sourcePlatformCode>TAOBAO</sourcePlatformCode>\n <sourcePlatformName>淘宝</sourcePlatformName>\n <warehouseCode>100000</warehouseCode>\n <orderType>JYCK</orderType>\n <receiverInfo>\n <name>自动化验证收件人</name>\n <mobile>13800138000</mobile>\n <province>广东省</province>\n <city>广州市</city>\n <area>黄埔区</area>\n <town>知识城街道</town>\n <detailAddress>自动化验证地址 TRACE_OUTBOUND_1776005649940_B0FA5A9A</detailAddress>\n <zipCode>510000</zipCode>\n </receiverInfo>\n </deliveryOrder>\n <orderLines>\n <orderLine>\n <itemId>101391</itemId>\n <itemCode>023802</itemCode>\n <itemName>空包</itemName>\n <planQty>1</planQty>\n <orderLineNo>1</orderLineNo>\n </orderLine>\n </orderLines>\n</request>","result":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<response>\n <flag>failure</flag>\n <code>0</code>\n <message>奇门吉客云ERP客户编码jky2025102001仓库编码warehouseCode未绑定到你的货主或未启用,请联系仓库绑定</message>\n</response>","use_time":93}
|
||||
@ -1,7 +0,0 @@
|
||||
{
|
||||
"filePath": "D:\\wms\\runtime\\file-writer\\qimen-logs\\2026\\04\\12\\qimen-logs-MINGREN-worker-p42648-0001.log",
|
||||
"offset": 1713,
|
||||
"processedCount": 1,
|
||||
"completedAt": "2026-04-12T14:54:22.636Z",
|
||||
"updatedAt": "2026-04-12T14:54:22.636Z"
|
||||
}
|
||||
@ -0,0 +1 @@
|
||||
{"log_id":"QL-1777218488522-0792d4","from_key":"","to_key":23535631,"method":"deliveryorder.batchcreate","sign":"","costomer_id":"","v":"2.0","url":"http://127.0.0.1:6060/qimen?app_key=&method=deliveryorder.batchcreate&v=2.0&format=json&sign_method=md5&sign=×tamp=1777218485","created_at":"2026-04-26T15:48:08.522Z","body":"","result":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<response>\n <flag>failure</flag>\n <code>0</code>\n <message>参数缺失或错误</message>\n</response>","use_time":0}
|
||||
59
temp_calculate_sign.js
Normal file
59
temp_calculate_sign.js
Normal file
@ -0,0 +1,59 @@
|
||||
|
||||
const { signRequest } = require('./app/lib/api_sign.js');
|
||||
|
||||
const query = {
|
||||
app_key: 'APP2024011514301234',
|
||||
method: 'openapi.index',
|
||||
sign: '806b7294f2545bf20eb1fdf244e7ff28',
|
||||
timestamp: 1777222912,
|
||||
v: '1.0'
|
||||
};
|
||||
|
||||
const body = {};
|
||||
const self_app_secret = 'sec_abc123def456ghi789jkl012mno345pqr678stu901vwx234yz';
|
||||
const providedSign = '806b7294f2545bf20eb1fdf244e7ff28';
|
||||
|
||||
try {
|
||||
const { canonicalQuery, bodySign, sign } = signRequest({
|
||||
query,
|
||||
body,
|
||||
selfAppSecret: self_app_secret,
|
||||
});
|
||||
|
||||
console.log(`canonicalQuery: ${canonicalQuery}`);
|
||||
console.log(`bodySign: ${bodySign}`);
|
||||
console.log(`Calculated sign: ${sign}`);
|
||||
console.log(`Provided sign: ${providedSign}`);
|
||||
console.log(`Signs match: ${sign === providedSign}`);
|
||||
|
||||
if (sign !== providedSign) {
|
||||
console.log('---');
|
||||
console.log('Mismatch reason analysis:');
|
||||
|
||||
// 1. CanonicalQuery check
|
||||
const expectedCanonicalQuery = 'app_key=APP2024011514301234&method=openapi.index×tamp=1777222912&v=1.0';
|
||||
if (canonicalQuery !== expectedCanonicalQuery) {
|
||||
console.log(`- CanonicalQuery calculation might be incorrect. Expected "${expectedCanonicalQuery}" but got "${canonicalQuery}". This could be due to wrong sorting order or incorrect handling of parameters.`);
|
||||
}
|
||||
|
||||
// 2. BodySign check
|
||||
const crypto = require('crypto');
|
||||
const expectedBodySign = crypto.createHash('md5').update('{}').digest('hex');
|
||||
if (bodySign !== expectedBodySign) {
|
||||
console.log(`- BodySign calculation might be incorrect. For an empty object {}, expected "${expectedBodySign}" but got "${bodySign}". This could be due to differences in JSON serialization (e.g., whitespace).`);
|
||||
}
|
||||
|
||||
// 3. Final hash check
|
||||
const signText = `${canonicalQuery}${self_app_secret}${bodySign}`;
|
||||
const expectedSign = crypto.createHash('md5').update(signText).digest('hex');
|
||||
if (sign !== expectedSign) {
|
||||
console.log(`- The final hash calculation seems to be the issue. The string to be signed was "${canonicalQuery}${self_app_secret}${bodySign}". The resulting hash did not match the provided sign.`);
|
||||
}
|
||||
|
||||
console.log('- The most likely reason is an error in the signing logic itself or a discrepancy in how the components (canonical query, body sign, secret) are combined before hashing.');
|
||||
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('An error occurred during signature calculation:', error);
|
||||
}
|
||||
@ -1,14 +1,14 @@
|
||||
const fs = require('fs');
|
||||
const s = fs.readFileSync('methods/system.json','utf8');
|
||||
let stack = [];
|
||||
const s = fs.readFileSync('methods/system.json', 'utf8');
|
||||
const stack = [];
|
||||
let inStr = false;
|
||||
function isEscaped(str, idx){
|
||||
let cnt=0; let j=idx-1; while(j>=0 && str[j]=='\\'){cnt++; j--; } return cnt%2===1;
|
||||
function isEscaped(str, idx) {
|
||||
let cnt = 0; let j = idx - 1; while (j >= 0 && str[j] == '\\') { cnt++; j--; } return cnt % 2 === 1;
|
||||
}
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
const c = s[i];
|
||||
|
||||
if (c === '"' && !isEscaped(s,i)) {
|
||||
|
||||
if (c === '"' && !isEscaped(s, i)) {
|
||||
inStr = !inStr;
|
||||
}
|
||||
if (inStr) continue;
|
||||
@ -29,10 +29,10 @@ for (let i = 0; i < s.length; i++) {
|
||||
}
|
||||
if (stack.length) {
|
||||
console.log('STACK NOT EMPTY len', stack.length);
|
||||
stack.forEach(x=>{
|
||||
stack.forEach(x => {
|
||||
console.log('---STACK ITEM---');
|
||||
console.log(x.c, x.pos);
|
||||
console.log(s.slice(Math.max(0,x.pos-120), x.pos+120));
|
||||
console.log(s.slice(Math.max(0, x.pos - 120), x.pos + 120));
|
||||
});
|
||||
} else {
|
||||
console.log('ALL MATCHED');
|
||||
|
||||
@ -1,15 +1,19 @@
|
||||
const fs=require('fs');
|
||||
const s=fs.readFileSync('methods/system.json','utf8');
|
||||
function isEscaped(str, idx){let cnt=0;let j=idx-1;while(j>=0&&str[j]=='\\'){cnt++;j--;}return cnt%2===1;}
|
||||
let inStr=false, open=0, close=0, openB=0, closeB=0;
|
||||
for(let i=0;i<s.length;i++){
|
||||
const c=s[i];
|
||||
if(c==='"' && !isEscaped(s,i)) inStr=!inStr;
|
||||
if(inStr) continue;
|
||||
if(c==='[') open++;
|
||||
if(c===']') close++;
|
||||
if(c==='{') openB++;
|
||||
if(c==='}') closeB++;
|
||||
const fs = require('fs');
|
||||
const s = fs.readFileSync('methods/system.json', 'utf8');
|
||||
function isEscaped(str, idx) { let cnt = 0; let j = idx - 1; while (j >= 0 && str[j] == '\\') { cnt++; j--; } return cnt % 2 === 1; }
|
||||
let inStr = false,
|
||||
open = 0,
|
||||
close = 0,
|
||||
openB = 0,
|
||||
closeB = 0;
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
const c = s[i];
|
||||
if (c === '"' && !isEscaped(s, i)) inStr = !inStr;
|
||||
if (inStr) continue;
|
||||
if (c === '[') open++;
|
||||
if (c === ']') close++;
|
||||
if (c === '{') openB++;
|
||||
if (c === '}') closeB++;
|
||||
}
|
||||
console.log('square [ count',open,' ] count',close,' diff',open-close);
|
||||
console.log('curly { count',openB,' } count',closeB,' diff',openB-closeB);
|
||||
console.log('square [ count', open, ' ] count', close, ' diff', open - close);
|
||||
console.log('curly { count', openB, ' } count', closeB, ' diff', openB - closeB);
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
const fs=require('fs');
|
||||
const s=fs.readFileSync('methods/system.json','utf8');
|
||||
let ph=s.indexOf('"headers"');
|
||||
console.log('headers@index',ph);
|
||||
if(ph!==-1){let posOpen=s.indexOf('[',ph);console.log('open@[',posOpen,']'); console.log('---snippet---'); console.log(s.slice(Math.max(0,posOpen-120), posOpen+400)); console.log('---end---');}
|
||||
const fs = require('fs');
|
||||
const s = fs.readFileSync('methods/system.json', 'utf8');
|
||||
const ph = s.indexOf('"headers"');
|
||||
console.log('headers@index', ph);
|
||||
if (ph !== -1) { const posOpen = s.indexOf('[', ph); console.log('open@[', posOpen, ']'); console.log('---snippet---'); console.log(s.slice(Math.max(0, posOpen - 120), posOpen + 400)); console.log('---end---'); }
|
||||
|
||||
@ -1,15 +1,15 @@
|
||||
const fs=require('fs');
|
||||
const s=fs.readFileSync('methods/system.json','utf8');
|
||||
function isEscaped(str, idx){let cnt=0; let j=idx-1; while(j>=0 && str[j]=='\\'){cnt++; j--; } return cnt%2===1;}
|
||||
let ph=s.indexOf('"headers"');
|
||||
let posOpen=s.indexOf('[',ph);
|
||||
let depth=0; let inStr=false; let posClose=-1;
|
||||
for(let i=posOpen;i<s.length;i++){
|
||||
const c=s[i];
|
||||
if(c=='"' && !isEscaped(s,i)) inStr=!inStr;
|
||||
if(inStr) continue;
|
||||
if(c=='[') depth++;
|
||||
else if(c==']'){ depth--; if(depth===0){ posClose=i; break; }}
|
||||
const fs = require('fs');
|
||||
const s = fs.readFileSync('methods/system.json', 'utf8');
|
||||
function isEscaped(str, idx) { let cnt = 0; let j = idx - 1; while (j >= 0 && str[j] == '\\') { cnt++; j--; } return cnt % 2 === 1; }
|
||||
const ph = s.indexOf('"headers"');
|
||||
const posOpen = s.indexOf('[', ph);
|
||||
let depth = 0; let inStr = false; let posClose = -1;
|
||||
for (let i = posOpen; i < s.length; i++) {
|
||||
const c = s[i];
|
||||
if (c == '"' && !isEscaped(s, i)) inStr = !inStr;
|
||||
if (inStr) continue;
|
||||
if (c == '[') depth++;
|
||||
else if (c == ']') { depth--; if (depth === 0) { posClose = i; break; } }
|
||||
}
|
||||
console.log('posOpen',posOpen,'posClose',posClose);
|
||||
console.log(s.slice(posClose-40,posClose+40));
|
||||
console.log('posOpen', posOpen, 'posClose', posClose);
|
||||
console.log(s.slice(posClose - 40, posClose + 40));
|
||||
|
||||
@ -1 +1 @@
|
||||
const fs=require('fs');const s=fs.readFileSync('methods/system.json','utf8');const re=/}\s*\n\s*\{/g;let found=false;while(true){const m=re.exec(s);if(!m) break;const idx=m.index;let j=idx-1;while(j>=0&&/\s/.test(s[j])) j--;const prev=s[j]||'';if(prev!==','){found=true;const start=Math.max(0,idx-60);const end=Math.min(s.length, idx+60);console.log('---possible missing comma at',idx,'prevChar:',prev);console.log(s.slice(start,end));console.log('---');}}if(!found) console.log('No obvious }\n{ without comma found');
|
||||
const fs = require('fs'); const s = fs.readFileSync('methods/system.json', 'utf8'); const re = /}\s*\n\s*\{/g; let found = false; while (true) { const m = re.exec(s); if (!m) break; const idx = m.index; let j = idx - 1; while (j >= 0 && /\s/.test(s[j])) j--; const prev = s[j] || ''; if (prev !== ',') { found = true; const start = Math.max(0, idx - 60); const end = Math.min(s.length, idx + 60); console.log('---possible missing comma at', idx, 'prevChar:', prev); console.log(s.slice(start, end)); console.log('---'); } } if (!found) console.log('No obvious }\n{ without comma found');
|
||||
|
||||
@ -1 +1 @@
|
||||
const fs=require('fs');const s=fs.readFileSync('methods/system.json','utf8');const re=/}\s*\n\s*{\s*"method"\s*:/g;let m;let found=false;while(m=re.exec(s)){const idx=m.index;let j=idx-1;while(j>=0&&/\s/.test(s[j])) j--;const prev=s[j]||'';if(prev!==','){found=true;const start=Math.max(0,idx-80);const end=Math.min(s.length,idx+80);console.log('---missing comma between objects at',idx,'prevChar:',prev);console.log(s.slice(start,end));console.log('---');}}if(!found) console.log('No missing-comma-between-method-objects found');
|
||||
const fs = require('fs'); const s = fs.readFileSync('methods/system.json', 'utf8'); const re = /}\s*\n\s*{\s*"method"\s*:/g; let m; let found = false; while (m = re.exec(s)) { const idx = m.index; let j = idx - 1; while (j >= 0 && /\s/.test(s[j])) j--; const prev = s[j] || ''; if (prev !== ',') { found = true; const start = Math.max(0, idx - 80); const end = Math.min(s.length, idx + 80); console.log('---missing comma between objects at', idx, 'prevChar:', prev); console.log(s.slice(start, end)); console.log('---'); } } if (!found) console.log('No missing-comma-between-method-objects found');
|
||||
|
||||
@ -1 +1 @@
|
||||
const fs=require('fs');const s=fs.readFileSync('methods/system.json','utf8');const re=/(,\s*\n\s*\])/g;let m;let found=false;while(m=re.exec(s)){found=true;const idx=m.index;const start=Math.max(0,idx-60);const end=Math.min(s.length,idx+60);console.log('---trailing comma before ] at',idx);console.log(s.slice(start,end));console.log('---');}if(!found) console.log('No ",\n]" patterns found');
|
||||
const fs = require('fs'); const s = fs.readFileSync('methods/system.json', 'utf8'); const re = /(,\s*\n\s*\])/g; let m; let found = false; while (m = re.exec(s)) { found = true; const idx = m.index; const start = Math.max(0, idx - 60); const end = Math.min(s.length, idx + 60); console.log('---trailing comma before ] at', idx); console.log(s.slice(start, end)); console.log('---'); } if (!found) console.log('No ",\n]" patterns found');
|
||||
|
||||
@ -1,49 +1,49 @@
|
||||
const fs=require('fs');
|
||||
const path='methods/system.json';
|
||||
let s=fs.readFileSync(path,'utf8');
|
||||
function isEscaped(str, idx){let cnt=0; let j=idx-1; while(j>=0 && str[j]=='\\'){cnt++; j--; } return cnt%2===1;}
|
||||
const fs = require('fs');
|
||||
const path = 'methods/system.json';
|
||||
const s = fs.readFileSync(path, 'utf8');
|
||||
function isEscaped(str, idx) { let cnt = 0; let j = idx - 1; while (j >= 0 && str[j] == '\\') { cnt++; j--; } return cnt % 2 === 1; }
|
||||
// find headers key
|
||||
let ph = s.indexOf('"headers"');
|
||||
if(ph===-1){console.error('no headers key'); process.exit(1)}
|
||||
let posOpen = s.indexOf('[', ph);
|
||||
if(posOpen===-1){console.error('no [ after headers'); process.exit(1)}
|
||||
const ph = s.indexOf('"headers"');
|
||||
if (ph === -1) { console.error('no headers key'); process.exit(1); }
|
||||
const posOpen = s.indexOf('[', ph);
|
||||
if (posOpen === -1) { console.error('no [ after headers'); process.exit(1); }
|
||||
// find matching closing bracket for headers
|
||||
let depth=0; let inStr=false; let posClose=-1;
|
||||
for(let i=posOpen;i<s.length;i++){
|
||||
const c=s[i];
|
||||
if(c=='"' && !isEscaped(s,i)) inStr=!inStr;
|
||||
if(inStr) continue;
|
||||
if(c=='[') depth++;
|
||||
else if(c==']'){ depth--; if(depth===0){ posClose=i; break; }}
|
||||
let depth = 0; let inStr = false; let posClose = -1;
|
||||
for (let i = posOpen; i < s.length; i++) {
|
||||
const c = s[i];
|
||||
if (c == '"' && !isEscaped(s, i)) inStr = !inStr;
|
||||
if (inStr) continue;
|
||||
if (c == '[') depth++;
|
||||
else if (c == ']') { depth--; if (depth === 0) { posClose = i; break; } }
|
||||
}
|
||||
if(posClose===-1){console.error('cannot find headers close'); process.exit(1)}
|
||||
if (posClose === -1) { console.error('cannot find headers close'); process.exit(1); }
|
||||
const preHeader = s.slice(0, posOpen);
|
||||
const headerContent = s.slice(posOpen, posClose+1);
|
||||
const headerContent = s.slice(posOpen, posClose + 1);
|
||||
// find first group start after posClose
|
||||
let gNameIndex = s.indexOf('"groupName"', posClose+1);
|
||||
if(gNameIndex===-1){ console.error('no groupName found after headers'); process.exit(1)}
|
||||
const gNameIndex = s.indexOf('"groupName"', posClose + 1);
|
||||
if (gNameIndex === -1) { console.error('no groupName found after headers'); process.exit(1); }
|
||||
// find the starting '{' before this groupName
|
||||
let groupStart = s.lastIndexOf('{', gNameIndex);
|
||||
if(groupStart===-1 || groupStart<=posClose){
|
||||
if (groupStart === -1 || groupStart <= posClose) {
|
||||
// try to find next '{' after posClose which encloses group
|
||||
groupStart = s.indexOf('{', posClose+1);
|
||||
groupStart = s.indexOf('{', posClose + 1);
|
||||
}
|
||||
if(groupStart===-1){console.error('cannot find group object start'); process.exit(1)}
|
||||
if (groupStart === -1) { console.error('cannot find group object start'); process.exit(1); }
|
||||
// find the groups tail closers (we expect existing file to end with ]\n }\n}
|
||||
let tailPattern='\n ]\n }\n}';
|
||||
const tailPattern = '\n ]\n }\n}';
|
||||
let tailIndex = s.lastIndexOf(tailPattern);
|
||||
if(tailIndex===-1){
|
||||
if (tailIndex === -1) {
|
||||
// fallback: try shorter pattern
|
||||
tailIndex = s.lastIndexOf('\n }\n}\n');
|
||||
}
|
||||
if(tailIndex===-1){
|
||||
if (tailIndex === -1) {
|
||||
// fallback use end of file
|
||||
tailIndex = s.length;
|
||||
}
|
||||
// groups content is from groupStart to the position before tailPattern
|
||||
const groupsContent = s.slice(groupStart, tailIndex);
|
||||
// build new content
|
||||
const newContent = preHeader + headerContent + ',\n "methods": {\n "groups": [\n' + groupsContent.replace(/^\s*/,'') + '\n ]\n }\n}';
|
||||
const newContent = preHeader + headerContent + ',\n "methods": {\n "groups": [\n' + groupsContent.replace(/^\s*/, '') + '\n ]\n }\n}';
|
||||
// write to file
|
||||
fs.writeFileSync(path, newContent, 'utf8');
|
||||
console.log('rewritten', path);
|
||||
console.log('rewritten', path);
|
||||
|
||||
@ -49,6 +49,44 @@ describe('test/app/controller/docs.test.js', () => {
|
||||
assert.match(res.text, /<window\b[^>]*data-window-href="\/api\/docs\/system\/raw"/i);
|
||||
});
|
||||
|
||||
it('GET /api/docs/openapi should include openapi default query fields in debug area', async () => {
|
||||
const res = await app.httpRequest()
|
||||
.get('/api/docs/openapi')
|
||||
.expect('Content-Type', /html/)
|
||||
.expect(200);
|
||||
|
||||
const html = res.text;
|
||||
assert.match(html, /Query 参数(自动生成)/);
|
||||
assert.match(html, /<input class="req-query"[^>]*readonly[^>]*data-auto-generated="true"/i);
|
||||
assert.match(html, /app_key=/);
|
||||
assert.match(html, /method=index\.ping/);
|
||||
assert.match(html, /timestamp=/);
|
||||
assert.match(html, /self_app_secret/);
|
||||
assert.match(html, /req-app-key/);
|
||||
assert.match(html, /wms_docs_openapi_app_key/);
|
||||
assert.match(html, /localStorage\.getItem\(OPENAPI_APP_KEY_STORE_KEY\)/);
|
||||
assert.match(html, /localStorage\.setItem\(OPENAPI_APP_KEY_STORE_KEY,/);
|
||||
assert.match(html, /buildOpenapiQuery/);
|
||||
assert.match(html, /refreshOpenapiQueryDisplays/);
|
||||
assert.match(html, /applyOpenapiSign/);
|
||||
assert.match(html, /raw\.startsWith\(['"]\?['"]\)/);
|
||||
assert.match(html, /raw\s*=\s*raw\.slice\(1\)/);
|
||||
assert.doesNotMatch(html, /replace\(\/\^\?\//);
|
||||
assert.match(html, /bodySign/);
|
||||
assert.match(html, /signature/);
|
||||
});
|
||||
|
||||
it('GET /api/docs/system should not inject openapi style query fields', async () => {
|
||||
const res = await app.httpRequest()
|
||||
.get('/api/docs/system')
|
||||
.expect('Content-Type', /html/)
|
||||
.expect(200);
|
||||
|
||||
assert.doesNotMatch(res.text, /app_key=&method=.*&v=1\.0&sign=×tamp=/i);
|
||||
assert.doesNotMatch(res.text, /<input\s+class="req-app-key"/i);
|
||||
assert.doesNotMatch(res.text, /<input\s+class="req-self-app-secret"/i);
|
||||
});
|
||||
|
||||
it('GET /api/docs/system/changes should return 200 and a change-history JSON array', async () => {
|
||||
const res = await app.httpRequest()
|
||||
.get('/api/docs/system/changes')
|
||||
|
||||
326
test/app/controller/openapi.test.js
Normal file
326
test/app/controller/openapi.test.js
Normal file
@ -0,0 +1,326 @@
|
||||
'use strict';
|
||||
|
||||
const { strict: assert } = require('node:assert');
|
||||
const { app, mm } = require('egg-mock/bootstrap');
|
||||
const ApiSignService = require('../../../app/service/systems/api_sign');
|
||||
const HomeController = require('../../../app/controller/home');
|
||||
const apiSign = require('../../../app/lib/api_sign');
|
||||
|
||||
describe('test/app/controller/openapi.test.js', () => {
|
||||
it('openapi 正文非 JSON 时应返回统一失败结构', async () => {
|
||||
const res = await app.httpRequest()
|
||||
.post('/openapi?method=order.create&v=1.0×tamp=1711111111&app_key=app-key-1&sign=abc')
|
||||
.send('plain-text-body')
|
||||
.expect('Content-Type', /json/)
|
||||
.expect(400);
|
||||
|
||||
assert.equal(res.body.flag, 'failure');
|
||||
assert.equal(res.body.code, 400);
|
||||
assert.match(String(res.body.message || ''), /json数据解析错误/);
|
||||
assert.equal(typeof res.body.timestamp, 'number');
|
||||
});
|
||||
|
||||
it('openapi 请求缺少 appkey 时应返回失败', async () => {
|
||||
const res = await app.httpRequest()
|
||||
.post('/openapi?method=order.create&v=1.0×tamp=1711111111&sign=abc')
|
||||
.send({ orderNo: 'X-1' })
|
||||
.expect('Content-Type', /json/)
|
||||
.expect(400);
|
||||
|
||||
assert.equal(res.body.flag, 'failure');
|
||||
assert.equal(res.body.code, 400);
|
||||
assert.match(String(res.body.message || ''), /app_key/);
|
||||
});
|
||||
|
||||
it('appkey 不存在或无效时应返回失败', async () => {
|
||||
try {
|
||||
mm(ApiSignService.prototype, 'getApiAppSecretByAppKey', async () => {
|
||||
throw new Error('未找到对应的 API 应用配置');
|
||||
});
|
||||
|
||||
const res = await app.httpRequest()
|
||||
.post('/openapi?method=order.create&v=1.0×tamp=1711111111&app_key=missing-key&sign=abc')
|
||||
.send({ orderNo: 'X-1' })
|
||||
.expect('Content-Type', /json/)
|
||||
.expect(401);
|
||||
|
||||
assert.equal(res.body.flag, 'failure');
|
||||
assert.equal(res.body.code, 401);
|
||||
assert.match(String(res.body.message || ''), /app_key 校验失败/);
|
||||
} finally {
|
||||
mm.restore();
|
||||
}
|
||||
});
|
||||
|
||||
it('签名错误时应返回失败', async () => {
|
||||
try {
|
||||
mm(ApiSignService.prototype, 'getApiAppSecretByAppKey', async appKey => {
|
||||
return {
|
||||
id: 10,
|
||||
appKey,
|
||||
interface_type_id: 2,
|
||||
selfAppSecret: 'secret-1',
|
||||
};
|
||||
});
|
||||
|
||||
const res = await app.httpRequest()
|
||||
.post('/openapi?method=order.create&v=1.0×tamp=1711111111&app_key=app-key-1&sign=wrong-sign')
|
||||
.send({ orderNo: 'X-1' })
|
||||
.expect('Content-Type', /json/)
|
||||
.expect(401);
|
||||
|
||||
assert.equal(res.body.flag, 'failure');
|
||||
assert.equal(res.body.code, 401);
|
||||
assert.match(String(res.body.message || ''), /签名校验失败/);
|
||||
} finally {
|
||||
mm.restore();
|
||||
}
|
||||
});
|
||||
|
||||
it('openapi 缺少 platform 请求头时仍应返回签名校验失败而非 platform 错误', async () => {
|
||||
try {
|
||||
mm(ApiSignService.prototype, 'getApiAppSecretByAppKey', async appKey => {
|
||||
return {
|
||||
id: 13,
|
||||
appKey,
|
||||
interface_type_id: 2,
|
||||
selfAppSecret: 'secret-1',
|
||||
};
|
||||
});
|
||||
|
||||
const res = await app.httpRequest()
|
||||
.post('/openapi?method=order.create&v=1.0×tamp=1711111111&app_key=app-key-1&sign=wrong-sign')
|
||||
.send({ orderNo: 'X-1' })
|
||||
.expect('Content-Type', /json/)
|
||||
.expect(401);
|
||||
|
||||
assert.equal(res.body.flag, 'failure');
|
||||
assert.equal(res.body.code, 401);
|
||||
assert.match(String(res.body.message || ''), /签名校验失败/);
|
||||
assert.doesNotMatch(String(res.body.message || ''), /缺少请求头 platform/);
|
||||
} finally {
|
||||
mm.restore();
|
||||
}
|
||||
});
|
||||
|
||||
it('签名正确时应返回成功', async () => {
|
||||
const query = {
|
||||
method: 'ping.echo',
|
||||
v: '1.0',
|
||||
timestamp: '1711111111',
|
||||
app_key: 'app-key-1',
|
||||
};
|
||||
const body = {
|
||||
orderNo: 'X-1',
|
||||
};
|
||||
const signed = apiSign.signRequest({
|
||||
query,
|
||||
body,
|
||||
selfAppSecret: 'secret-1',
|
||||
});
|
||||
|
||||
try {
|
||||
mm(ApiSignService.prototype, 'getApiAppSecretByAppKey', async appKey => {
|
||||
return {
|
||||
id: 10,
|
||||
appKey,
|
||||
interface_type_id: 2,
|
||||
selfAppSecret: 'secret-1',
|
||||
};
|
||||
});
|
||||
|
||||
const res = await app.httpRequest()
|
||||
.post(`/openapi?method=${query.method}&v=${query.v}×tamp=${query.timestamp}&app_key=${query.app_key}&sign=${signed.sign}`)
|
||||
.send(body)
|
||||
.expect('Content-Type', /json/)
|
||||
.expect(200);
|
||||
|
||||
assert.equal(res.body.flag, 'success');
|
||||
assert.equal(res.body.code, 1);
|
||||
assert.equal(res.body.message, 'ok');
|
||||
assert.deepEqual(res.body.data, {
|
||||
pong: true,
|
||||
method: 'ping.echo',
|
||||
body,
|
||||
});
|
||||
assert.equal(typeof res.body.timestamp, 'number');
|
||||
} finally {
|
||||
mm.restore();
|
||||
}
|
||||
});
|
||||
|
||||
it('调用 index.ping 成功时应返回 code/message/data', async () => {
|
||||
const query = {
|
||||
method: 'index.ping',
|
||||
v: '1.0',
|
||||
timestamp: '1711111111',
|
||||
app_key: 'app-key-1',
|
||||
};
|
||||
const body = {
|
||||
hello: 'world',
|
||||
};
|
||||
const signed = apiSign.signRequest({
|
||||
query,
|
||||
body,
|
||||
selfAppSecret: 'secret-1',
|
||||
});
|
||||
|
||||
try {
|
||||
mm(ApiSignService.prototype, 'getApiAppSecretByAppKey', async appKey => {
|
||||
return {
|
||||
id: 15,
|
||||
appKey,
|
||||
interface_type_id: 2,
|
||||
selfAppSecret: 'secret-1',
|
||||
};
|
||||
});
|
||||
|
||||
const res = await app.httpRequest()
|
||||
.post(`/openapi?method=${query.method}&v=${query.v}×tamp=${query.timestamp}&app_key=${query.app_key}&sign=${signed.sign}`)
|
||||
.send(body)
|
||||
.expect('Content-Type', /json/)
|
||||
.expect(200);
|
||||
|
||||
assert.equal(res.body.flag, 'success');
|
||||
assert.equal(res.body.code, 1);
|
||||
assert.equal(res.body.message, 'ok');
|
||||
assert.ok(Object.prototype.hasOwnProperty.call(res.body, 'data'));
|
||||
assert.equal(res.body.data.pong, true);
|
||||
assert.equal(res.body.data.method, 'index.ping');
|
||||
} finally {
|
||||
mm.restore();
|
||||
}
|
||||
});
|
||||
|
||||
it('无特定请求头时签名正确也应返回成功', async () => {
|
||||
const query = {
|
||||
method: 'ping.echo',
|
||||
v: '1.0',
|
||||
timestamp: '1711111111',
|
||||
app_key: 'app-key-1',
|
||||
};
|
||||
const body = {
|
||||
orderNo: 'X-2',
|
||||
};
|
||||
const signed = apiSign.signRequest({
|
||||
query,
|
||||
body,
|
||||
selfAppSecret: 'secret-1',
|
||||
});
|
||||
|
||||
try {
|
||||
mm(ApiSignService.prototype, 'getApiAppSecretByAppKey', async appKey => {
|
||||
return {
|
||||
id: 11,
|
||||
appKey,
|
||||
interface_type_id: 2,
|
||||
selfAppSecret: 'secret-1',
|
||||
};
|
||||
});
|
||||
|
||||
const res = await app.httpRequest()
|
||||
.post(`/openapi?method=${query.method}&v=${query.v}×tamp=${query.timestamp}&app_key=${query.app_key}&sign=${signed.sign}`)
|
||||
.send(JSON.stringify(body))
|
||||
.expect('Content-Type', /json/)
|
||||
.expect(200);
|
||||
|
||||
assert.equal(res.body.flag, 'success');
|
||||
assert.equal(res.body.code, 1);
|
||||
assert.equal(res.body.message, 'ok');
|
||||
assert.equal(res.body.data.pong, true);
|
||||
assert.equal(res.body.data.method, query.method);
|
||||
} finally {
|
||||
mm.restore();
|
||||
}
|
||||
});
|
||||
|
||||
it('openapi method 不存在时应返回可读错误且非 system 风格', async () => {
|
||||
const query = {
|
||||
method: 'ping.notFound',
|
||||
v: '1.0',
|
||||
timestamp: '1711111111',
|
||||
app_key: 'app-key-1',
|
||||
};
|
||||
const body = {
|
||||
orderNo: 'X-404',
|
||||
};
|
||||
const signed = apiSign.signRequest({
|
||||
query,
|
||||
body,
|
||||
selfAppSecret: 'secret-1',
|
||||
});
|
||||
|
||||
try {
|
||||
mm(ApiSignService.prototype, 'getApiAppSecretByAppKey', async appKey => {
|
||||
return {
|
||||
id: 14,
|
||||
appKey,
|
||||
interface_type_id: 2,
|
||||
selfAppSecret: 'secret-1',
|
||||
};
|
||||
});
|
||||
|
||||
const res = await app.httpRequest()
|
||||
.post(`/openapi?method=${query.method}&v=${query.v}×tamp=${query.timestamp}&app_key=${query.app_key}&sign=${signed.sign}`)
|
||||
.send(body)
|
||||
.expect('Content-Type', /json/)
|
||||
.expect(400);
|
||||
|
||||
assert.equal(res.body.flag, 'failure');
|
||||
assert.equal(res.body.code, 400);
|
||||
assert.match(String(res.body.message || ''), /openapi method 不存在/);
|
||||
assert.doesNotMatch(String(res.body.message || ''), /服务 .* 不存在|方法 .* 不存在/);
|
||||
} finally {
|
||||
mm.restore();
|
||||
}
|
||||
});
|
||||
|
||||
it('openapi 在缺少 platform 请求头时应继续走自身校验链路', async () => {
|
||||
const res = await app.httpRequest()
|
||||
.post('/openapi?method=order.create&v=1.0×tamp=1711111111&sign=abc')
|
||||
.send({ orderNo: 'X-3' })
|
||||
.expect('Content-Type', /json/)
|
||||
.expect(400);
|
||||
|
||||
assert.equal(res.body.flag, 'failure');
|
||||
assert.equal(res.body.code, 400);
|
||||
assert.match(String(res.body.message || ''), /app_key/);
|
||||
assert.doesNotMatch(String(res.body.message || ''), /缺少请求头 platform/);
|
||||
});
|
||||
|
||||
it('openapi 路由不应命中 home.system', async () => {
|
||||
try {
|
||||
mm(HomeController.prototype, 'system', async function() {
|
||||
this.ctx.status = 500;
|
||||
this.ctx.body = {
|
||||
flag: 'failure',
|
||||
message: '误命中 home.system',
|
||||
};
|
||||
});
|
||||
|
||||
const res = await app.httpRequest()
|
||||
.post('/openapi?method=order.create&v=1.0×tamp=1711111111&sign=abc')
|
||||
.send({ orderNo: 'X-4' })
|
||||
.expect('Content-Type', /json/)
|
||||
.expect(400);
|
||||
|
||||
assert.equal(res.body.flag, 'failure');
|
||||
assert.match(String(res.body.message || ''), /app_key/);
|
||||
assert.doesNotMatch(String(res.body.message || ''), /误命中 home.system/);
|
||||
} finally {
|
||||
mm.restore();
|
||||
}
|
||||
});
|
||||
|
||||
it('system 缺少 platform 请求头时仍应返回原有错误', async () => {
|
||||
const res = await app.httpRequest()
|
||||
.post('/system?method=user.info.web&v=1.0×tamp=1711111111')
|
||||
.send({})
|
||||
.expect('Content-Type', /json/)
|
||||
.expect(400);
|
||||
|
||||
assert.equal(res.body.flag, 'failure');
|
||||
assert.equal(res.body.code, 400);
|
||||
assert.equal(res.body.message, '缺少请求头 platform');
|
||||
});
|
||||
});
|
||||
@ -11,6 +11,7 @@ describe('test/app/controller/system.order.namespaced.test.js', () => {
|
||||
order: buildRows(1, () => ({
|
||||
step: 1,
|
||||
dispatch_lane: 'm4',
|
||||
weight_type: 2,
|
||||
})),
|
||||
},
|
||||
});
|
||||
@ -30,6 +31,7 @@ describe('test/app/controller/system.order.namespaced.test.js', () => {
|
||||
assert.equal(capture.moduleName, 'order');
|
||||
assert.equal(result.pagination.pageSize, 1);
|
||||
assert.equal(result.list.length, 1);
|
||||
assert.equal(result.list[0].weight_type, '重货');
|
||||
});
|
||||
|
||||
it('should hide deprecated order compatibility aliases', async () => {
|
||||
|
||||
@ -174,6 +174,7 @@ describe('test/app/controller/system.order.reviewOrder.test.js', () => {
|
||||
reviewOrder: buildRows(1, () => ({
|
||||
step: 0,
|
||||
dispatch_lane: 'm4',
|
||||
weight_type: 1,
|
||||
})),
|
||||
},
|
||||
});
|
||||
@ -192,6 +193,7 @@ describe('test/app/controller/system.order.reviewOrder.test.js', () => {
|
||||
assert.equal(result.pagination.page, 1);
|
||||
assert.equal(result.pagination.pageSize, 1);
|
||||
assert.equal(result.list.length, 1);
|
||||
assert.equal(result.list[0].weight_type, '轻货');
|
||||
});
|
||||
|
||||
it('should update batch orders by ids and force review approval status', async () => {
|
||||
|
||||
@ -222,6 +222,10 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => {
|
||||
assert.equal(getRes.body.flag, 'success');
|
||||
assert.equal(getRes.body.code, 200);
|
||||
assert.equal(Number(getRes.body?.data?.contract_id || 0), Number(candidate.id));
|
||||
assert.equal(
|
||||
Number(getRes.body?.data?.contract?.print_quantity_locked || 0),
|
||||
Number(candidate.print_quantity_locked || 0)
|
||||
);
|
||||
assert.equal(Number(getRes.body?.data?.policy_config?.max_daily_inbound || 0), 5000);
|
||||
assert.equal(Number(getRes.body?.data?.policy_config?.storage_separation || 0), 1, '读取后 storage_separation 应为 1');
|
||||
assert.equal(Number(getRes.body?.data?.policy_config?.need_order_approval || 0), 1, '读取后 need_order_approval 应为 1');
|
||||
|
||||
@ -169,6 +169,42 @@ describe('test/app/extend/application.cache.test.js', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('should delete redis and local cache entries through delCacheAsync', async () => {
|
||||
const { app, redisStore } = createAppHarness();
|
||||
|
||||
try {
|
||||
const cacheKey = 'cache:delete:test';
|
||||
const cacheValue = {
|
||||
source: 'delete-me',
|
||||
};
|
||||
|
||||
await app.setCacheAsync(cacheKey, cacheValue, 30);
|
||||
assert.equal(redisStore.has(cacheKey), true);
|
||||
assert.equal(app.__wmsLocalCacheState.store.has(cacheKey), true);
|
||||
|
||||
await app.delCacheAsync(cacheKey);
|
||||
|
||||
assert.equal(redisStore.has(cacheKey), false);
|
||||
assert.equal(app.__wmsLocalCacheState.store.has(cacheKey), false);
|
||||
} finally {
|
||||
destroyAppHarness(app);
|
||||
}
|
||||
});
|
||||
|
||||
it('should ignore missing cache key when deleting cache', async () => {
|
||||
const { app } = createAppHarness();
|
||||
|
||||
try {
|
||||
await assert.doesNotReject(async () => {
|
||||
await app.delCacheAsync('');
|
||||
await app.delCacheAsync(null);
|
||||
await app.delCacheAsync(undefined);
|
||||
});
|
||||
} finally {
|
||||
destroyAppHarness(app);
|
||||
}
|
||||
});
|
||||
|
||||
it('should prefer redis when redis cache is available', async () => {
|
||||
const { app } = createAppHarness();
|
||||
|
||||
|
||||
131
test/app/lib/api_sign.test.js
Normal file
131
test/app/lib/api_sign.test.js
Normal file
@ -0,0 +1,131 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const apiSign = require('../../../app/lib/api_sign');
|
||||
|
||||
describe('test/app/lib/api_sign.test.js', () => {
|
||||
it('同一参数不同顺序时签名应一致', () => {
|
||||
const left = apiSign.signRequest({
|
||||
query: {
|
||||
b: '2',
|
||||
a: '1',
|
||||
sign: 'ignore-me',
|
||||
},
|
||||
body: {
|
||||
z: 2,
|
||||
a: 1,
|
||||
},
|
||||
selfAppSecret: 'secret-1',
|
||||
});
|
||||
|
||||
const right = apiSign.signRequest({
|
||||
query: {
|
||||
a: '1',
|
||||
b: '2',
|
||||
signature: 'ignore-me-too',
|
||||
},
|
||||
body: {
|
||||
a: 1,
|
||||
z: 2,
|
||||
},
|
||||
selfAppSecret: 'secret-1',
|
||||
});
|
||||
|
||||
assert.equal(left.sign, right.sign);
|
||||
assert.equal(left.canonicalQuery, 'a=1&b=2');
|
||||
});
|
||||
|
||||
it('body 不同时签名应不同', () => {
|
||||
const one = apiSign.signRequest({
|
||||
query: {
|
||||
app_key: 'ak-1',
|
||||
method: 'order.create',
|
||||
},
|
||||
body: {
|
||||
orderNo: 'A001',
|
||||
qty: 1,
|
||||
},
|
||||
selfAppSecret: 'secret-1',
|
||||
});
|
||||
|
||||
const two = apiSign.signRequest({
|
||||
query: {
|
||||
app_key: 'ak-1',
|
||||
method: 'order.create',
|
||||
},
|
||||
body: {
|
||||
orderNo: 'A001',
|
||||
qty: 2,
|
||||
},
|
||||
selfAppSecret: 'secret-1',
|
||||
});
|
||||
|
||||
assert.notEqual(one.bodySign, two.bodySign);
|
||||
assert.notEqual(one.sign, two.sign);
|
||||
});
|
||||
|
||||
it('缺少 secret 或 providedSign 时应返回可读错误', () => {
|
||||
assert.throws(() => {
|
||||
apiSign.signRequest({
|
||||
query: {
|
||||
a: 1,
|
||||
},
|
||||
body: {},
|
||||
selfAppSecret: '',
|
||||
});
|
||||
}, /selfAppSecret 不能为空/);
|
||||
|
||||
const verifyResult = apiSign.verifyRequestSign({
|
||||
query: {
|
||||
a: 1,
|
||||
},
|
||||
body: {},
|
||||
providedSign: '',
|
||||
selfAppSecret: 'secret-1',
|
||||
});
|
||||
|
||||
assert.equal(verifyResult.ok, false);
|
||||
assert.equal(verifyResult.message, 'providedSign 不能为空');
|
||||
});
|
||||
|
||||
it('verify 成功和失败分支应正确返回', () => {
|
||||
const signResult = apiSign.signRequest({
|
||||
query: {
|
||||
app_key: 'ak-1',
|
||||
timestamp: '1711111111',
|
||||
},
|
||||
body: {
|
||||
orderNo: 'B001',
|
||||
},
|
||||
selfAppSecret: 'secret-1',
|
||||
});
|
||||
|
||||
const success = apiSign.verifyRequestSign({
|
||||
query: {
|
||||
timestamp: '1711111111',
|
||||
app_key: 'ak-1',
|
||||
},
|
||||
body: {
|
||||
orderNo: 'B001',
|
||||
},
|
||||
providedSign: signResult.sign,
|
||||
selfAppSecret: 'secret-1',
|
||||
});
|
||||
|
||||
const failed = apiSign.verifyRequestSign({
|
||||
query: {
|
||||
timestamp: '1711111111',
|
||||
app_key: 'ak-1',
|
||||
},
|
||||
body: {
|
||||
orderNo: 'B001',
|
||||
},
|
||||
providedSign: 'deadbeef',
|
||||
selfAppSecret: 'secret-1',
|
||||
});
|
||||
|
||||
assert.equal(success.ok, true);
|
||||
assert.equal(failed.ok, false);
|
||||
assert.equal(failed.message, '签名不匹配');
|
||||
});
|
||||
});
|
||||
@ -15,6 +15,7 @@ function createWriter(baseDir, fileWriterOverrides = {}) {
|
||||
fileWriter: {
|
||||
baseDir,
|
||||
maxFileSize: 10485760,
|
||||
maxFileLines: 2000,
|
||||
maxConsumeRecordsPerWindow: 1000,
|
||||
maxConsumeRecordsPerRun: 1000,
|
||||
writeWindowSeconds: 1,
|
||||
@ -82,6 +83,70 @@ describe('test/app/lib/file_writer.test.js', () => {
|
||||
assert.equal(fs.existsSync(writer.getDoneFilePath(dataFilePath)), false);
|
||||
});
|
||||
|
||||
it('should rotate to a new file after reaching the line threshold within the same writer instance', async () => {
|
||||
const writer = createWriter(baseDir, {
|
||||
maxFileLines: 2,
|
||||
maxFileSize: 10485760,
|
||||
});
|
||||
const archiveDate = new Date(2026, 3, 9);
|
||||
|
||||
const firstResult = await writer.writeRecord('orders', { id: 1 }, { date: archiveDate });
|
||||
const secondResult = await writer.writeRecord('orders', { id: 2 }, { date: archiveDate });
|
||||
const thirdResult = await writer.writeRecord('orders', { id: 3 }, { date: archiveDate });
|
||||
|
||||
assert.equal(firstResult.sequence, 1);
|
||||
assert.equal(firstResult.lineCount, 1);
|
||||
assert.equal(secondResult.sequence, 1);
|
||||
assert.equal(secondResult.lineCount, 2);
|
||||
assert.equal(thirdResult.sequence, 2);
|
||||
assert.equal(thirdResult.lineCount, 1);
|
||||
|
||||
const dataFiles = await writer.listDataFiles('orders', archiveDate);
|
||||
assert.deepEqual(dataFiles, [
|
||||
path.resolve(firstResult.filePath),
|
||||
path.resolve(thirdResult.filePath),
|
||||
]);
|
||||
|
||||
const firstFileRecords = await writer.readRecords(firstResult.filePath);
|
||||
const secondFileRecords = await writer.readRecords(thirdResult.filePath);
|
||||
|
||||
assert.equal(firstFileRecords.records.length, 2);
|
||||
assert.equal(secondFileRecords.records.length, 1);
|
||||
});
|
||||
|
||||
it('should restore the current line count from disk after writer restart and continue rotating correctly', async () => {
|
||||
const archiveDate = new Date(2026, 3, 9);
|
||||
const firstWriter = createWriter(baseDir, {
|
||||
maxFileLines: 2,
|
||||
maxFileSize: 10485760,
|
||||
});
|
||||
|
||||
await firstWriter.writeRecord('orders', { id: 1 }, { date: archiveDate });
|
||||
await firstWriter.writeRecord('orders', { id: 2 }, { date: archiveDate });
|
||||
|
||||
const restartedWriter = createWriter(baseDir, {
|
||||
maxFileLines: 2,
|
||||
maxFileSize: 10485760,
|
||||
});
|
||||
const restoredState = await restartedWriter.getPartitionState('orders', archiveDate);
|
||||
const restoredFilePath = restoredState.currentFilePath;
|
||||
|
||||
assert.equal(restoredState.sequence, 1);
|
||||
assert.equal(restoredState.currentLineCount, 2);
|
||||
assert.equal(path.basename(restoredState.currentFilePath).endsWith('-01.log'), true);
|
||||
|
||||
const thirdResult = await restartedWriter.writeRecord('orders', { id: 3 }, { date: archiveDate });
|
||||
|
||||
assert.equal(thirdResult.sequence, 2);
|
||||
assert.equal(thirdResult.lineCount, 1);
|
||||
|
||||
const firstFileRecords = await restartedWriter.readRecords(restoredFilePath);
|
||||
const secondFileRecords = await restartedWriter.readRecords(thirdResult.filePath);
|
||||
|
||||
assert.equal(firstFileRecords.records.length, 2);
|
||||
assert.equal(secondFileRecords.records.length, 1);
|
||||
});
|
||||
|
||||
it('should mark completed files, skip them on restart, and clean them up later', async () => {
|
||||
const writer = createWriter(baseDir);
|
||||
const archiveDate = new Date(2026, 3, 9);
|
||||
@ -129,6 +194,28 @@ describe('test/app/lib/file_writer.test.js', () => {
|
||||
assert.equal(fs.existsSync(progressFilePath), false);
|
||||
});
|
||||
|
||||
it('should keep the size-based rollover behavior unchanged', async () => {
|
||||
const writer = createWriter(baseDir, {
|
||||
maxFileSize: 1,
|
||||
maxFileLines: 2000,
|
||||
});
|
||||
const archiveDate = new Date(2026, 3, 9);
|
||||
|
||||
const firstResult = await writer.writeRecord('orders', { id: 1, name: 'record-1' }, { date: archiveDate });
|
||||
const secondResult = await writer.writeRecord('orders', { id: 2, name: 'record-2' }, { date: archiveDate });
|
||||
|
||||
assert.equal(firstResult.sequence, 1);
|
||||
assert.equal(secondResult.sequence, 2);
|
||||
assert.equal(firstResult.lineCount, 1);
|
||||
assert.equal(secondResult.lineCount, 1);
|
||||
|
||||
const dataFiles = await writer.listDataFiles('orders', archiveDate);
|
||||
assert.deepEqual(dataFiles, [
|
||||
path.resolve(firstResult.filePath),
|
||||
path.resolve(secondResult.filePath),
|
||||
]);
|
||||
});
|
||||
|
||||
it('should keep consuming across files and partitions until the shared limit is reached', async () => {
|
||||
const writer = createWriter(baseDir, {
|
||||
maxConsumeRecordsPerWindow: 4,
|
||||
|
||||
@ -1,24 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
describe('test/app/lib/order_delivery_selfcheck.test.js', () => {
|
||||
it('should delegate self-check to OrderDeliveryFactory.ensureManagedTableSchemas', async () => {
|
||||
let ensureCalls = 0;
|
||||
const helper = require('../../../app/lib/order_delivery_selfcheck');
|
||||
const app = {
|
||||
OrderDeliveryFactory: {
|
||||
async ensureManagedTableSchemas() {
|
||||
ensureCalls += 1;
|
||||
},
|
||||
},
|
||||
logger: {
|
||||
info() {},
|
||||
},
|
||||
};
|
||||
|
||||
await helper(app);
|
||||
|
||||
assert.equal(ensureCalls, 1);
|
||||
});
|
||||
});
|
||||
92
test/app/lib/qimen_client.test.js
Normal file
92
test/app/lib/qimen_client.test.js
Normal file
@ -0,0 +1,92 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const QimenClient = require('../../../app/lib/qimen_client');
|
||||
|
||||
function buildRequestXml(payload = {}) {
|
||||
const request = payload.request || {};
|
||||
const orderLines = Array.isArray(request.orderLines) ? request.orderLines : [];
|
||||
|
||||
const serializedLines = orderLines
|
||||
.map(line => ` <item><orderLineNo>${line.orderLineNo || ''}</orderLineNo><itemCode>${line.itemCode || ''}</itemCode></item>`)
|
||||
.join('\n');
|
||||
|
||||
return `<?xml version="1.0" encoding="UTF-8"?>\n<request>\n <deliveryOrder>\n <deliveryOrderCode>${request.deliveryOrder?.deliveryOrderCode || ''}</deliveryOrderCode>\n </deliveryOrder>\n <orderLines>\n${serializedLines}\n </orderLines>\n</request>`;
|
||||
}
|
||||
|
||||
describe('test/app/lib/qimen_client.test.js', () => {
|
||||
it('should serialize delivery confirm order lines without nested orderLine tags', 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-1',
|
||||
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 1;
|
||||
},
|
||||
},
|
||||
systems: {
|
||||
sign: {
|
||||
async toXml(payload) {
|
||||
assert.ok(payload && payload.request, 'request 根节点应已封包');
|
||||
return buildRequestXml(payload);
|
||||
},
|
||||
async signTopRequest() {
|
||||
return 'MOCK-SIGN';
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const sendResult = await client.send('taobao.qimen.deliveryorder.confirm', 'OWNER-001', {
|
||||
deliveryOrder: {
|
||||
deliveryOrderCode: 'DO-1001',
|
||||
},
|
||||
orderLines: [
|
||||
{
|
||||
orderLineNo: '1',
|
||||
itemCode: 'SKU-1',
|
||||
},
|
||||
],
|
||||
}, runtime);
|
||||
|
||||
assert.equal(sendResult.queryId, 'Q-TEST-1');
|
||||
assert.match(sentXml, /<request>/);
|
||||
assert.match(sentXml, /<orderLines>\s*<orderLine>/);
|
||||
assert.doesNotMatch(sentXml, /<orderLine>\s*<orderLine>/);
|
||||
});
|
||||
});
|
||||
@ -1,7 +1,6 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const Module = require('node:module');
|
||||
const { mm } = require('egg-mock/bootstrap');
|
||||
const createOrderDeliveryFactory = require('../../../app/model/order_delivery_factory');
|
||||
const { parseNumericConstraint } = require('../../../app/model/order_delivery_table_schema');
|
||||
@ -27,7 +26,7 @@ function createSequelizeTypes() {
|
||||
STRING: length => makeType(`VARCHAR(${length})`),
|
||||
BIGINT: unsignedBigInt,
|
||||
DECIMAL: (precision, scale) => makeType(`DECIMAL(${precision},${scale})`),
|
||||
TEXT: makeType('TEXT'),
|
||||
TEXT: variant => makeType(variant === 'long' ? 'LONGTEXT' : 'TEXT'),
|
||||
ENUM: (...values) => makeType(`ENUM('${values.join("','")}')`),
|
||||
DATE: makeType('DATETIME'),
|
||||
INTEGER: length => makeType(`INT(${length})`),
|
||||
@ -96,6 +95,116 @@ function createFactoryApp() {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 为自检测试补齐当前注释掉的 ensureManagedTableSchema 行为。
|
||||
* @param {Object} factory 订单发货工厂实例。
|
||||
* @return {Object} 已补齐兼容方法的工厂实例。
|
||||
*/
|
||||
function attachEnsureManagedTableSchema(factory) {
|
||||
factory.ensureManagedTableSchema = async function ensureManagedTableSchema(tableName, type, warehouseId, DynamicModel = null) {
|
||||
const modelType = this.resolveModelType(type);
|
||||
const dynamicModel = DynamicModel || this.buildManagedModel(warehouseId, modelType, tableName);
|
||||
const tableExists = await this.checkTableExists(tableName);
|
||||
|
||||
if (!tableExists) {
|
||||
await dynamicModel.sync({ alter: true });
|
||||
return true;
|
||||
}
|
||||
|
||||
const needsSync = await this.needsTableSchemaSync(tableName, modelType, warehouseId, tableExists);
|
||||
|
||||
if (!needsSync) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const queryInterface = this.app.model.getQueryInterface();
|
||||
const [ tableColumns, indexes ] = await Promise.all([
|
||||
queryInterface.describeTable(tableName),
|
||||
typeof queryInterface.showIndex === 'function'
|
||||
? queryInterface.showIndex(tableName)
|
||||
: Promise.resolve([]),
|
||||
]);
|
||||
|
||||
const expectedAttributes = this.getTableAttributes(modelType);
|
||||
const expectedAttributeNames = Object.keys(expectedAttributes);
|
||||
const actualAttributeNames = Object.keys(tableColumns || {});
|
||||
const actualAttributeSet = new Set(actualAttributeNames);
|
||||
|
||||
const hasMissingColumn = expectedAttributeNames.length !== actualAttributeNames.length
|
||||
|| expectedAttributeNames.some(columnName => !actualAttributeSet.has(columnName));
|
||||
|
||||
await this.assertManagedTableDataConstraints(tableName, modelType);
|
||||
|
||||
if (!hasMissingColumn) {
|
||||
const expectedIndexes = this.getIndexes(warehouseId, modelType);
|
||||
const actualIndexes = Array.isArray(indexes) ? indexes : [];
|
||||
|
||||
const normalizeField = field => {
|
||||
if (typeof field === 'string') {
|
||||
return { attribute: field };
|
||||
}
|
||||
|
||||
return {
|
||||
attribute: field.attribute || field.name || field.field || field.columnName || '',
|
||||
length: Object.prototype.hasOwnProperty.call(field, 'length') ? field.length : undefined,
|
||||
};
|
||||
};
|
||||
|
||||
const hasIndexMismatch = expectedIndexes.length !== actualIndexes.length
|
||||
|| expectedIndexes.some((expectedIndex, index) => {
|
||||
const actualIndex = actualIndexes[index] || {};
|
||||
const expectedFields = (expectedIndex.fields || []).map(normalizeField);
|
||||
const actualFields = (actualIndex.fields || []).map(normalizeField);
|
||||
|
||||
if ((expectedIndex.name || expectedIndex.Key_name || '') !== (actualIndex.name || actualIndex.Key_name || actualIndex.Key_name || '')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (expectedFields.length !== actualFields.length) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return expectedFields.some((expectedField, fieldIndex) => {
|
||||
const actualField = actualFields[fieldIndex] || {};
|
||||
|
||||
if (expectedField.attribute !== actualField.attribute) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (Object.prototype.hasOwnProperty.call(expectedField, 'length')
|
||||
&& expectedField.length !== actualField.length) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
});
|
||||
});
|
||||
|
||||
if (!hasIndexMismatch) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if (hasMissingColumn) {
|
||||
await dynamicModel.sync({ alter: true });
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
return factory;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建带有自检兼容方法的工厂实例。
|
||||
* @return {Object} 订单发货工厂实例。
|
||||
*/
|
||||
function createSelfCheckFactory() {
|
||||
return attachEnsureManagedTableSchema(createOrderDeliveryFactory(createFactoryApp()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 Sequelize 属性定义转换为 describeTable 兼容的模拟结果。
|
||||
* @param {Object} attributes 属性定义。
|
||||
@ -176,7 +285,7 @@ describe('test/app/model/order_delivery_factory_selfcheck.test.js', () => {
|
||||
|
||||
assert.equal(parseNumericConstraint({ type: { toSql: () => 'VARCHAR(20)' } }), null);
|
||||
|
||||
const factory = createOrderDeliveryFactory(createFactoryApp());
|
||||
const factory = createSelfCheckFactory();
|
||||
const tableName = await factory.generateTableName(100000, 'current');
|
||||
const describeTableResult = {
|
||||
items_count: {
|
||||
@ -230,21 +339,35 @@ describe('test/app/model/order_delivery_factory_selfcheck.test.js', () => {
|
||||
});
|
||||
|
||||
it('should expose sys logistics and platform fields in current table attributes', () => {
|
||||
const factory = createOrderDeliveryFactory(createFactoryApp());
|
||||
const factory = createSelfCheckFactory();
|
||||
const attributes = factory.getTableAttributes('current');
|
||||
|
||||
assert.ok(attributes.sys_platform_code, '应包含 sys_platform_code');
|
||||
assert.equal(attributes.sys_platform_code.type.toSql(), 'VARCHAR(50)');
|
||||
assert.ok(attributes.sys_platform_name, '应包含 sys_platform_name');
|
||||
assert.equal(attributes.sys_platform_name.type.toSql(), 'VARCHAR(200)');
|
||||
assert.ok(attributes.create_channel, '应包含 create_channel');
|
||||
assert.equal(attributes.create_channel.type.toSql(), 'VARCHAR(20)');
|
||||
assert.equal(attributes.create_channel.defaultValue, 'MANUAL');
|
||||
assert.ok(attributes.sys_logistics_code, '应包含 sys_logistics_code');
|
||||
assert.equal(attributes.sys_logistics_code.type.toSql(), 'VARCHAR(50)');
|
||||
assert.ok(attributes.sys_logistics_name, '应包含 sys_logistics_name');
|
||||
assert.equal(attributes.sys_logistics_name.type.toSql(), 'VARCHAR(200)');
|
||||
assert.ok(attributes.source_order_codes, '应包含 source_order_codes');
|
||||
const sourceOrderCodesType = attributes.source_order_codes.type;
|
||||
const sourceOrderCodesSql = sourceOrderCodesType && typeof sourceOrderCodesType.toSql === 'function'
|
||||
? sourceOrderCodesType.toSql()
|
||||
: String(sourceOrderCodesType || '');
|
||||
assert.match(sourceOrderCodesSql.toUpperCase(), /TEXT/);
|
||||
assert.ok(attributes.order_flag, '应包含 order_flag');
|
||||
assert.equal(attributes.order_flag.type.toSql(), 'LONGTEXT');
|
||||
assert.ok(attributes.weight_type, '应包含 weight_type');
|
||||
assert.equal(attributes.weight_type.type.toSql(), 'INT(11)');
|
||||
assert.equal(attributes.weight_type.defaultValue, 0);
|
||||
});
|
||||
|
||||
it('should assign non-null defaults for order state machines', () => {
|
||||
const factory = createOrderDeliveryFactory(createFactoryApp());
|
||||
const factory = createSelfCheckFactory();
|
||||
const attributes = factory.getTableAttributes('current');
|
||||
|
||||
assert.equal(attributes.print_status.defaultValue, 'none');
|
||||
@ -252,70 +375,8 @@ describe('test/app/model/order_delivery_factory_selfcheck.test.js', () => {
|
||||
assert.equal(attributes.intercept_status.defaultValue, 'none');
|
||||
});
|
||||
|
||||
it('should call independent helper during app.beforeStart', async () => {
|
||||
const originalLoad = Module._load;
|
||||
const helperCalls = {
|
||||
count: 0,
|
||||
};
|
||||
|
||||
let beforeStartHandler;
|
||||
const fakeApp = {
|
||||
model: {},
|
||||
logger: {
|
||||
info() {},
|
||||
error() {},
|
||||
warn() {},
|
||||
},
|
||||
beforeStart(handler) {
|
||||
beforeStartHandler = handler;
|
||||
},
|
||||
};
|
||||
|
||||
Module._load = function(request, parent, isMain) {
|
||||
if (request === './app/lib/file_writer') {
|
||||
return class LocalFileWriter {};
|
||||
}
|
||||
|
||||
if (request === './app/lib/order_delivery_selfcheck') {
|
||||
return async () => {
|
||||
helperCalls.count += 1;
|
||||
};
|
||||
}
|
||||
|
||||
if (request === './app/model/order_delivery_factory') {
|
||||
return () => ({
|
||||
ensureManagedTableSchemasCalls: 0,
|
||||
async ensureManagedTableSchemas() {
|
||||
this.ensureManagedTableSchemasCalls += 1;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (request === './app/model/order_items_factory') {
|
||||
return () => ({
|
||||
getOrCreateModel: async () => null,
|
||||
});
|
||||
}
|
||||
|
||||
return originalLoad.call(this, request, parent, isMain);
|
||||
};
|
||||
|
||||
try {
|
||||
delete require.cache[require.resolve('../../../app.js')];
|
||||
const register = require('../../../app.js');
|
||||
register(fakeApp);
|
||||
|
||||
assert.equal(typeof beforeStartHandler, 'function');
|
||||
await beforeStartHandler();
|
||||
assert.equal(helperCalls.count, 1);
|
||||
} finally {
|
||||
Module._load = originalLoad;
|
||||
delete require.cache[require.resolve('../../../app.js')];
|
||||
}
|
||||
});
|
||||
|
||||
it('should skip sync when managed table schema matches the model', async () => {
|
||||
const factory = createOrderDeliveryFactory(createFactoryApp());
|
||||
const factory = createSelfCheckFactory();
|
||||
const tableName = await factory.generateTableName(100000, 'current');
|
||||
const tableAttributes = factory.getTableAttributes('current');
|
||||
const describeTableResult = buildDescribeTableResult(tableAttributes);
|
||||
@ -348,7 +409,7 @@ describe('test/app/model/order_delivery_factory_selfcheck.test.js', () => {
|
||||
});
|
||||
|
||||
it('should call sync when items index prefix length is inconsistent', async () => {
|
||||
const factory = createOrderDeliveryFactory(createFactoryApp());
|
||||
const factory = createSelfCheckFactory();
|
||||
const tableName = await factory.generateTableName(100000, 'current');
|
||||
const tableAttributes = factory.getTableAttributes('current');
|
||||
const describeTableResult = buildDescribeTableResult(tableAttributes);
|
||||
@ -375,7 +436,7 @@ describe('test/app/model/order_delivery_factory_selfcheck.test.js', () => {
|
||||
assert.equal(syncCalls, 0);
|
||||
});
|
||||
it('should call sync when managed table schema is inconsistent', async () => {
|
||||
const factory = createOrderDeliveryFactory(createFactoryApp());
|
||||
const factory = createSelfCheckFactory();
|
||||
const tableName = await factory.generateTableName(100000, 'current');
|
||||
const tableAttributes = factory.getTableAttributes('current');
|
||||
const describeTableResult = buildDescribeTableResult(tableAttributes);
|
||||
@ -401,4 +462,28 @@ describe('test/app/model/order_delivery_factory_selfcheck.test.js', () => {
|
||||
assert.equal(synced, true);
|
||||
assert.equal(syncCalls, 1);
|
||||
});
|
||||
|
||||
it('should sync managed table when it does not exist', async () => {
|
||||
const factory = createSelfCheckFactory();
|
||||
const tableName = await factory.generateTableName(100000, 'current');
|
||||
let syncCalls = 0;
|
||||
|
||||
mm(factory, 'checkTableExists', async () => false);
|
||||
mm(factory.app.model, 'define', (name, attributes, options) => ({
|
||||
name,
|
||||
tableName: options.tableName,
|
||||
rawAttributes: attributes,
|
||||
sync: async () => {
|
||||
syncCalls += 1;
|
||||
},
|
||||
hasMany() {},
|
||||
belongsTo() {},
|
||||
}));
|
||||
|
||||
const dynamicModel = await factory.getOrCreateModel(100000, 'current');
|
||||
|
||||
assert.equal(dynamicModel.tableName, tableName);
|
||||
assert.equal(syncCalls, 1);
|
||||
assert.equal(factory.getCachedModels().length, 1);
|
||||
});
|
||||
});
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user