Compare commits

..

No commits in common. "9b1a6034af214ba28c5936a8a2aab18ae7200648" and "da4208707d0b0f1079c3b577b5c93745e6abe06b" have entirely different histories.

45 changed files with 132 additions and 6316 deletions

View File

@ -535,15 +535,13 @@ function renderMethodCard(item, entryPath, moduleName) {
const description = item.description || ''; const description = item.description || '';
const isQimen = moduleName === 'qimen'; const isQimen = moduleName === 'qimen';
const isOpenapi = moduleName === 'openapi'; const isOpenapi = moduleName === 'openapi';
const isWarehouse = moduleName === 'warehouse';
const isExternalApi = isOpenapi || isWarehouse;
const queryHint = isQimen const queryHint = isQimen
? 'app_key=xxx&method=...&v=2.0&format=json&sign_method=md5&sign=xxx&timestamp=1700000000' ? 'app_key=xxx&method=...&v=2.0&format=json&sign_method=md5&sign=xxx&timestamp=1700000000'
: isExternalApi : isOpenapi
? `app_key=&method=${methodName}&v=1.0&timestamp=1700000000` ? `app_key=&method=${methodName}&v=1.0&timestamp=1700000000`
: `method=${methodName}&v=1.0&timestamp=1700000000`; : `method=${methodName}&v=1.0&timestamp=1700000000`;
const queryLabel = isExternalApi ? 'Query 参数(自动生成)' : 'Query 参数'; const queryLabel = isOpenapi ? 'Query 参数(自动生成)' : 'Query 参数';
const queryReadonlyAttr = isExternalApi ? ' readonly data-auto-generated="true" aria-label="自动生成"' : ''; 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'}"> 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"> <div class="method-header">
@ -616,7 +614,7 @@ function renderMethodCard(item, entryPath, moduleName) {
<label>${queryLabel}</label> <label>${queryLabel}</label>
<input class="req-query" type="text" placeholder="${escapeHtml(queryHint)}"${queryReadonlyAttr} /> <input class="req-query" type="text" placeholder="${escapeHtml(queryHint)}"${queryReadonlyAttr} />
${isExternalApi ? `<label>app_key(仅外部 API 页面本地保存)</label> ${isOpenapi ? `<label>app_key(仅 openapi 页面本地保存)</label>
<input class="req-app-key" type="text" placeholder="请输入 app_key" autocomplete="off" /> <input class="req-app-key" type="text" placeholder="请输入 app_key" autocomplete="off" />
<label>self_app_secret(仅本地签名计算,不会发送)</label> <label>self_app_secret(仅本地签名计算,不会发送)</label>
<input class="req-self-app-secret" type="password" placeholder="请输入 self_app_secret" autocomplete="off" />` : ''} <input class="req-self-app-secret" type="password" placeholder="请输入 self_app_secret" autocomplete="off" />` : ''}
@ -648,14 +646,12 @@ function renderHtmlPage({
entryPath, entryPath,
}) { }) {
const isOpenapi = docData.module === 'openapi'; const isOpenapi = docData.module === 'openapi';
const isWarehouse = docData.module === 'warehouse';
const isExternalApi = isOpenapi || isWarehouse;
const methodsCount = groups.reduce((sum, group) => sum + toArray(group.list).length, 0); const methodsCount = groups.reduce((sum, group) => sum + toArray(group.list).length, 0);
const globalHeaders = toArray(docData.headers); const globalHeaders = toArray(docData.headers);
const globalHeadersControls = renderGlobalHeadersControls(globalHeaders); const globalHeadersControls = renderGlobalHeadersControls(globalHeaders);
const rawUrl = `/api/docs/${encodeURIComponent(docName)}/raw`; const rawUrl = `/api/docs/${encodeURIComponent(docName)}/raw`;
const changesUrl = `/api/docs/${encodeURIComponent(docName)}/changes`; const changesUrl = `/api/docs/${encodeURIComponent(docName)}/changes`;
const navHtml = isExternalApi ? '' : docs.filter(name => name !== 'openapi' && name !== 'warehouse').map(name => { const navHtml = isOpenapi ? '' : docs.filter(name => name !== 'openapi').map(name => {
const activeClass = name === docName ? 'active' : ''; const activeClass = name === docName ? 'active' : '';
return `<a class="tab ${activeClass}" href="/api/docs/${encodeURIComponent(name)}">${escapeHtml(name)}</a>`; return `<a class="tab ${activeClass}" href="/api/docs/${encodeURIComponent(name)}">${escapeHtml(name)}</a>`;
}).join(''); }).join('');
@ -1080,7 +1076,7 @@ function renderHtmlPage({
<a class="tab" href="${escapeHtml(changesUrl)}">查看变更记录</a> <a class="tab" href="${escapeHtml(changesUrl)}">查看变更记录</a>
<a class="tab" href="${escapeHtml(rawUrl)}">查看 JSON</a> <a class="tab" href="${escapeHtml(rawUrl)}">查看 JSON</a>
</div> </div>
${isExternalApi ? '' : `<div class="global-auth"> ${isOpenapi ? '' : `<div class="global-auth">
<h3>全局 Authorization</h3> <h3>全局 Authorization</h3>
<div class="row"> <div class="row">
<input id="globalAuth" type="text" placeholder="Bearer xxxxx" /> <input id="globalAuth" type="text" placeholder="Bearer xxxxx" />
@ -1091,7 +1087,7 @@ function renderHtmlPage({
${globalHeadersControls} ${globalHeadersControls}
<p class="muted">来自 JSON 的 headers 定义;带 * 的字段为必填,支持下拉 list 选择。</p> <p class="muted">来自 JSON 的 headers 定义;带 * 的字段为必填,支持下拉 list 选择。</p>
</div>`} </div>`}
${isExternalApi ? '' : `<div class="doc-tools"> ${isOpenapi ? '' : `<div class="doc-tools">
<h3>文档资源</h3> <h3>文档资源</h3>
<div class="doc-tools-actions"> <div class="doc-tools-actions">
${renderWindowElement('打开变更记录', changesUrl, 'doc-resource-link')} ${renderWindowElement('打开变更记录', changesUrl, 'doc-resource-link')}
@ -1101,9 +1097,9 @@ function renderHtmlPage({
</div> </div>
<pre id="docResourcePreview" class="req-result muted">点击上方按钮后,可直接预览当前文档的变更记录或原文 JSON。</pre> <pre id="docResourcePreview" class="req-result muted">点击上方按钮后,可直接预览当前文档的变更记录或原文 JSON。</pre>
</div>`} </div>`}
${isExternalApi ? `<div class="openapi-guide"> ${isOpenapi ? `<div class="openapi-guide">
<h3>请求方式</h3> <h3>请求方式</h3>
<pre class="guide-code">POST ${isOpenapi ? '/openapi' : '/warehouse'}?method={方法名}&v=1.0&timestamp={时间戳}&app_key={app_key}&sign={签名} <pre class="guide-code">POST /openapi?method={方法名}&v=1.0&timestamp={时间戳}&app_key={app_key}&sign={签名}
Content-Type: application/json Content-Type: application/json
{请求体 JSON}</pre> {请求体 JSON}</pre>
@ -1142,10 +1138,10 @@ Content-Type: application/json
<li>时间戳 <strong>timestamp</strong> 时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),超时返回 400</li> <li>时间戳 <strong>timestamp</strong> 时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),超时返回 400</li>
<li>签名结果为 32 位小写十六进制字符串</li> <li>签名结果为 32 位小写十六进制字符串</li>
</ul> </ul>
${isOpenapi ? `<p style="margin-top:12px;font-size:13px;"> <p style="margin-top:12px;font-size:13px;">
<a href="/docs/api/openapi/callback-test" style="color:#1565c0;">→ 回调测试工具</a> <a href="/docs/api/openapi/callback-test" style="color:#1565c0;">→ 回调测试工具</a>
<span class="muted">(模拟接收回调通知,验证回调链路)</span> <span class="muted">(模拟接收回调通知,验证回调链路)</span>
</p>` : ''} </p>
</div>` : ''} </div>` : ''}
</section> </section>
@ -1171,10 +1167,9 @@ Content-Type: application/json
(function() { (function() {
var DOC_NAME = ${JSON.stringify(docName)}; var DOC_NAME = ${JSON.stringify(docName)};
var IS_OPENAPI_DOC = DOC_NAME === 'openapi'; var IS_OPENAPI_DOC = DOC_NAME === 'openapi';
var IS_EXTERNAL_API_DOC = DOC_NAME === 'openapi' || DOC_NAME === 'warehouse';
var AUTH_KEY = 'wms_docs_global_auth'; var AUTH_KEY = 'wms_docs_global_auth';
var HEADER_STORE_KEY = 'wms_docs_global_headers_' + ${JSON.stringify(docName)}; var HEADER_STORE_KEY = 'wms_docs_global_headers_' + ${JSON.stringify(docName)};
var OPENAPI_APP_KEY_STORE_KEY = 'wms_docs_' + DOC_NAME + '_app_key'; var OPENAPI_APP_KEY_STORE_KEY = 'wms_docs_openapi_app_key';
var authInput = document.getElementById('globalAuth'); var authInput = document.getElementById('globalAuth');
var clearBtn = document.getElementById('clearAuthBtn'); var clearBtn = document.getElementById('clearAuthBtn');
var searchInput = document.getElementById('methodSearch'); var searchInput = document.getElementById('methodSearch');
@ -1552,7 +1547,7 @@ Content-Type: application/json
return 'app_key=&method=' + encodeURIComponent(methodName) return 'app_key=&method=' + encodeURIComponent(methodName)
+ '&v=2.0&format=json&sign_method=md5&sign=&timestamp=' + nowTimestamp(); + '&v=2.0&format=json&sign_method=md5&sign=&timestamp=' + nowTimestamp();
} }
if (moduleName === 'openapi' || moduleName === 'warehouse') { if (moduleName === 'openapi') {
return buildOpenapiQuery(card, ''); return buildOpenapiQuery(card, '');
} }
return 'method=' + encodeURIComponent(methodName) + '&v=1.0&timestamp=' + nowTimestamp(); return 'method=' + encodeURIComponent(methodName) + '&v=1.0&timestamp=' + nowTimestamp();
@ -1578,7 +1573,7 @@ Content-Type: application/json
var bodyInput = card.querySelector('.req-body'); var bodyInput = card.querySelector('.req-body');
var moduleName = card.getAttribute('data-module') || ''; var moduleName = card.getAttribute('data-module') || '';
if (queryInput) { if (queryInput) {
if (moduleName === 'openapi' || moduleName === 'warehouse') { if (moduleName === 'openapi') {
var appKeyInput = card.querySelector('.req-app-key'); var appKeyInput = card.querySelector('.req-app-key');
var openapiAppKey = (appKeyInput && appKeyInput.value.trim()) || ''; var openapiAppKey = (appKeyInput && appKeyInput.value.trim()) || '';
queryInput.value = buildOpenapiQuery(card, openapiAppKey); queryInput.value = buildOpenapiQuery(card, openapiAppKey);
@ -1598,11 +1593,11 @@ Content-Type: application/json
* @return {void} * @return {void}
*/ */
function refreshOpenapiQueryDisplays(appKey) { function refreshOpenapiQueryDisplays(appKey) {
if (!IS_EXTERNAL_API_DOC) { if (!IS_OPENAPI_DOC) {
return; return;
} }
var cards = document.querySelectorAll('.method-card[data-module="openapi"], .method-card[data-module="warehouse"]'); var cards = document.querySelectorAll('.method-card[data-module="openapi"]');
cards.forEach(function(card) { cards.forEach(function(card) {
var queryInput = card.querySelector('.req-query'); var queryInput = card.querySelector('.req-query');
if (!queryInput) { if (!queryInput) {
@ -1618,7 +1613,7 @@ Content-Type: application/json
* @return {void} * @return {void}
*/ */
function initOpenapiAppKeyInputs() { function initOpenapiAppKeyInputs() {
if (!IS_EXTERNAL_API_DOC) { if (!IS_OPENAPI_DOC) {
return; return;
} }
@ -1861,7 +1856,7 @@ Content-Type: application/json
return; return;
} }
if (moduleName === 'openapi' || moduleName === 'warehouse') { if (moduleName === 'openapi') {
var appKeyInput = card.querySelector('.req-app-key'); var appKeyInput = card.querySelector('.req-app-key');
var openapiAppKey = (appKeyInput && appKeyInput.value.trim()) || ''; var openapiAppKey = (appKeyInput && appKeyInput.value.trim()) || '';
query = buildOpenapiQuery(card, openapiAppKey); query = buildOpenapiQuery(card, openapiAppKey);
@ -2045,14 +2040,6 @@ class DocsController extends Controller {
await this.renderDoc('openapi'); await this.renderDoc('openapi');
} }
/**
* 渲染仓库开放 API 文档独立页面。
* @return {Promise<void>} 无返回值。
*/
async warehouse() {
await this.renderDoc('warehouse');
}
async detail() { async detail() {
const { ctx } = this; const { ctx } = this;
const docName = ctx.params.docName; const docName = ctx.params.docName;

View File

@ -1,127 +0,0 @@
'use strict';
const { Controller } = require('egg');
const { toSuccess, toFailure } = require('../lib/api_response');
/**
* 站内信内部管理接口控制器。
* 提供消息列表、详情、对话链、回信、重推、统计等管理功能。
*/
class InboxController extends Controller {
/**
* 获取当前仓库上下文。
* @return {{ warehouseId: number }} 仓库上下文。
*/
getWarehouseContext() {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id);
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
throw new Error('缺少仓库信息');
}
return { warehouseId };
}
/**
* 内部管理统一入口,分发到对应 service 方法。
* @return {Promise<void>} 无返回值,结果写入 ctx.body。
*/
async index() {
const { ctx } = this;
try {
const method = String(ctx.request.body && ctx.request.body.method || '').trim();
if (!method || !method.startsWith('inbox.')) {
ctx.status = 400;
ctx.body = toFailure({ message: 'method 参数无效' });
ctx.type = 'application/json';
return;
}
const action = method.replace('inbox.', '');
const data = (ctx.request.body && ctx.request.body.data) || {};
let result;
switch (action) {
case 'list': {
const { warehouseId } = this.getWarehouseContext();
result = await ctx.service.inbox.index.list({
warehouseId,
...data,
});
break;
}
case 'detail': {
const { warehouseId } = this.getWarehouseContext();
result = await ctx.service.inbox.index.detail({
warehouseId,
id: data.id,
});
break;
}
case 'thread': {
const { warehouseId } = this.getWarehouseContext();
result = await ctx.service.inbox.index.thread({
warehouseId,
id: data.id,
});
break;
}
case 'reply': {
const { warehouseId } = this.getWarehouseContext();
result = await ctx.service.inbox.index.reply({
warehouseId,
parentId: data.parentId,
targetChannel: data.targetChannel,
targetUrl: data.targetUrl,
targetType: data.targetType,
refCode: data.refCode,
extData: data.extData,
flags: data.flags,
});
break;
}
case 'retry': {
const { warehouseId } = this.getWarehouseContext();
result = await ctx.service.inbox.index.retry({
warehouseId,
id: data.id,
});
break;
}
case 'stats': {
const { warehouseId } = this.getWarehouseContext();
result = await ctx.service.inbox.index.stats({
warehouseId,
direction: data.direction,
});
break;
}
default:
ctx.status = 400;
ctx.body = toFailure({ message: `不支持的 inbox 方法: ${action}` });
ctx.type = 'application/json';
return;
}
ctx.status = 200;
ctx.body = toSuccess(result, 'ok');
ctx.type = 'application/json';
} catch (error) {
const message = String(error && error.message || '请求失败');
ctx.status = 500;
ctx.body = toFailure({ message: `站内信错误: ${message}` });
ctx.type = 'application/json';
}
}
}
module.exports = InboxController;

View File

@ -68,7 +68,6 @@ module.exports = {
ORDER_INTERCEPT_CONFIRM: '确认拦截', ORDER_INTERCEPT_CONFIRM: '确认拦截',
ORDER_PLATFORM_FALLBACK: '平台降级', ORDER_PLATFORM_FALLBACK: '平台降级',
ORDER_EXPRESS_FALLBACK: '快递降级', ORDER_EXPRESS_FALLBACK: '快递降级',
ORDER_EXPRESS_POLICY_MATCH: '策略命中',
ORDER_WAVE_UPDATE: '更新波次', ORDER_WAVE_UPDATE: '更新波次',
ORDER_WAVE_ASSIGN: '分配波次', ORDER_WAVE_ASSIGN: '分配波次',
ORDER_WAVE_REMOVE: '移出波次', ORDER_WAVE_REMOVE: '移出波次',

View File

@ -1,190 +0,0 @@
'use strict';
/**
* 站内信消息 Model。
* 统一管理消息推送状态追踪:谁发来的、要推到哪、推送状态。
* inbound(外部→WMS)与 outbound(WMS→外部)共表,direction + parent_id 形成对话链。
* @param {Object} app Egg.js Application 实例。
* @return {Object} Sequelize Model 定义。
*/
module.exports = app => {
const { BIGINT, STRING, TINYINT, DATE, INTEGER, JSON: JSON_TYPE } = app.Sequelize;
const InboxMessage = app.model.define('inbox_message', {
id: {
type: BIGINT.UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键ID',
},
ext_id: {
type: STRING(128),
allowNull: false,
comment: '外部唯一消息主键(IM msgId / API requestId 等),用于幂等去重',
},
warehouse_id: {
type: BIGINT.UNSIGNED,
allowNull: false,
comment: '所属仓库ID',
},
store_id: {
type: BIGINT.UNSIGNED,
allowNull: true,
comment: '关联货主ID',
},
direction: {
type: STRING(10),
allowNull: false,
defaultValue: 'inbound',
validate: {
isIn: {
args: [[ 'inbound', 'outbound' ]],
msg: 'direction 必须是 inbound 或 outbound',
},
},
comment: '消息方向:inbound=外部→WMS收件 / outbound=WMS→外部回信',
},
parent_id: {
type: BIGINT.UNSIGNED,
allowNull: true,
comment: '关联消息ID(回信时指向原消息,形成对话链)',
},
source_type: {
type: STRING(20),
allowNull: false,
validate: {
isIn: {
args: [[ 'im', 'api', 'system' ]],
msg: 'source_type 必须是 im、api 或 system',
},
},
comment: '来源类型:im / api / system',
},
source_extra: {
type: STRING(100),
allowNull: true,
comment: '来源附加信息(IM 平台 / API app_id)',
},
target_type: {
type: STRING(20),
allowNull: false,
validate: {
isIn: {
args: [[ 'im', 'api', 'webhook' ]],
msg: 'target_type 必须是 im、api 或 webhook',
},
},
comment: '目标类型:im / api / webhook',
},
target_channel: {
type: STRING(50),
allowNull: false,
validate: {
notEmpty: {
msg: 'target_channel 不能为空',
},
},
comment: '目标渠道:wecom / dingtalk / feishu / warehouse_api / webhook',
},
target_url: {
type: STRING(500),
allowNull: false,
validate: {
notEmpty: {
msg: 'target_url 不能为空',
},
len: {
args: [ 1, 500 ],
msg: 'target_url 长度应在1-500个字符之间',
},
},
comment: '推送目标URL(IM Bot webhook 地址 / API 回调地址)',
},
ref_code: {
type: STRING(100),
allowNull: true,
comment: '外部引用编码,推送/回执时原样携带',
},
ext_data: {
type: JSON_TYPE,
allowNull: true,
comment: '外部透传数据,外部传入任意JSON,WMS不解析,回信时原样返回',
},
flags: {
type: JSON_TYPE,
allowNull: true,
comment: '处理标记,外部传入控制WMS处理行为',
},
push_status: {
type: TINYINT(4),
allowNull: false,
defaultValue: 0,
validate: {
isIn: {
args: [[ 0, 1, 2, 3 ]],
msg: 'push_status 必须是 0(待推送)、1(推送中)、2(已送达)、3(失败)',
},
},
comment: '推送状态:0=待推送 1=推送中 2=已送达 3=失败',
},
push_started_at: {
type: DATE,
allowNull: true,
comment: '开始推送时间(僵尸检测:超5分钟仍为1则重置为0)',
},
retry_count: {
type: INTEGER(11),
allowNull: false,
defaultValue: 0,
comment: '已重试次数',
},
push_response: {
type: JSON_TYPE,
allowNull: true,
comment: '目标响应(http_status, body, error)',
},
pushed_at: {
type: DATE,
allowNull: true,
comment: '推送完成时间',
},
work_order_id: {
type: BIGINT.UNSIGNED,
allowNull: true,
comment: '关联工单ID(预留)',
},
work_order_no: {
type: STRING(50),
allowNull: true,
comment: '工单号(预留)',
},
created_at: {
type: DATE,
allowNull: false,
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '创建时间',
},
updated_at: {
type: DATE,
allowNull: false,
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '更新时间',
},
deleted_at: {
type: DATE,
allowNull: true,
comment: '软删除时间',
},
}, {
tableName: 'wms_inbox_message',
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
deletedAt: 'deleted_at',
paranoid: true,
comment: '站内信消息推送状态追踪表',
});
return InboxMessage;
};

View File

@ -1,144 +0,0 @@
'use strict';
/**
* 订单自定义店铺-快递绑定策略模型。
*
* 支持在仓库维度下,为用户自定义店铺标签配置快递绑定策略,
* 按优先级匹配,可附加商品、地区、重量等条件。
*
* @param {import('egg').Application} app Egg 应用实例。
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} Sequelize 模型。
*/
module.exports = app => {
const { BIGINT, STRING, INTEGER, TINYINT, DATE, TEXT, JSON: JSON_TYPE } = app.Sequelize;
const StoreExpressBindingPolicy = app.model.define('store_express_binding_policy', {
id: {
type: BIGINT.UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键ID',
},
warehouse_id: {
type: BIGINT.UNSIGNED,
allowNull: false,
comment: '仓库ID,策略所属仓库',
},
custom_name: {
type: STRING(100),
allowNull: false,
comment: '策略名称,便于人工识别',
},
shop_name: {
type: JSON_TYPE,
allowNull: true,
comment: '包含店铺名称,字符串数组,如["旗舰店","奥莱店"],NULL=不限制',
},
store_ids: {
type: JSON_TYPE,
allowNull: true,
comment: '限定货主ID,数字数组,如[1000000,1000001],NULL=不限制',
},
express_code: {
type: STRING(50),
allowNull: false,
comment: '绑定的快递编码(wms_express.code)',
},
priority: {
type: INTEGER(11),
allowNull: false,
defaultValue: 0,
comment: '优先级,数值越大越优先匹配',
},
is_enabled: {
type: TINYINT(1),
allowNull: false,
defaultValue: 1,
validate: {
isIn: {
args: [[ 0, 1 ]],
msg: '启用状态不合法,0=停用,1=启用',
},
},
comment: '是否启用:0=停用,1=启用',
},
regions: {
type: JSON_TYPE,
allowNull: true,
comment: '限定地区,字符串数组,如["广东省","广州市"],NULL=不限制',
},
exclude_regions: {
type: JSON_TYPE,
allowNull: true,
comment: '排除地区,字符串数组,如["新疆维吾尔自治区"],NULL=不排除',
},
min_weight_g: {
type: INTEGER,
allowNull: true,
comment: '最小重量(克),NULL=不限制',
},
max_weight_g: {
type: INTEGER,
allowNull: true,
comment: '最大重量(克),NULL=不限制',
},
weight_type: {
type: TINYINT(1),
allowNull: false,
defaultValue: 0,
validate: { isIn: { args: [[ 0, 1, 2, 3 ]], msg: '重量类型不合法,0=常规/1=轻货/2=重货/3=冷链' } },
comment: '重量段类型:0=常规/1=轻货/2=重货/3=冷链',
},
prohibited_type_id: {
type: JSON_TYPE,
allowNull: true,
comment: '违禁品类型ID数组(关联 wms_prohibited_type.id),如[1,2],NULL=不限制违禁品',
},
remark: {
type: STRING(500),
allowNull: true,
comment: '备注说明',
},
creator_id: {
type: BIGINT.UNSIGNED,
allowNull: true,
comment: '创建人账户ID(accounts.id)',
},
created_at: {
type: DATE,
allowNull: false,
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '创建时间',
},
updated_at: {
type: DATE,
allowNull: false,
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '更新时间',
},
deleted_at: {
type: DATE,
allowNull: true,
comment: '软删除时间',
},
}, {
tableName: 'wms_store_express_binding_policy',
freezeTableName: true,
underscored: true,
timestamps: false,
comment: '订单自定义店铺-快递绑定策略表',
indexes: [
{
name: 'idx_warehouse_enabled',
fields: [ 'warehouse_id', 'is_enabled', 'deleted_at' ],
},
{
name: 'idx_warehouse_express',
fields: [ 'warehouse_id', 'express_code', 'deleted_at' ],
},
],
});
return StoreExpressBindingPolicy;
};

View File

@ -33,9 +33,6 @@ module.exports = app => {
// OpenAPI 文档 — 所有环境均可访问,必须在通配路由之前注册 // OpenAPI 文档 — 所有环境均可访问,必须在通配路由之前注册
router.get('/docs/api/openapi', controller.docs.openapi); router.get('/docs/api/openapi', controller.docs.openapi);
// Warehouse 开放 API 文档 — 所有环境均可访问
router.get('/docs/api/warehouse', controller.docs.warehouse);
// OpenAPI 回调测试 — 所有环境均可访问的独立调试页面 // OpenAPI 回调测试 — 所有环境均可访问的独立调试页面
router.get('/docs/api/openapi/callback-test', controller.openapiCallback.testPage); router.get('/docs/api/openapi/callback-test', controller.openapiCallback.testPage);
@ -67,7 +64,4 @@ module.exports = app => {
router.get('/testSendData', controller.home.testSendData); router.get('/testSendData', controller.home.testSendData);
// IM交互入口 // IM交互入口
router.post('/im', controller.im.index); router.post('/im', controller.im.index);
// 站内信内部管理接口
router.post('/inbox', controller.inbox.index);
}; };

View File

@ -1,118 +0,0 @@
'use strict';
const Service = require('egg').Service;
const apiSignLib = require('../../../lib/api_sign');
const WAREHOUSE_INTERFACE_TYPE_ID = 3;
const DISPATCH_TIMEOUT_MS = 10000; // 10s 超时
/**
* 统一出站基类,所有渠道 dispatch 继承此类。
* 统一处理:查密钥、签名、发 HTTP。
* 子类只需实现 push(record) 方法,关注消息格式转换。
*/
class OutboundBase extends Service {
/**
* 获取仓库 ApiApp 密钥配置(IM 渠道无需签名,返回 null)。
* @param {number} warehouseId 仓库ID。
* @return {Promise<Object|null>} ApiApp 配置对象,含 appKey / selfAppSecret / warehouseId。
*/
async getApiApp(warehouseId) {
const { ctx } = this;
try {
// 通过仓库ID查找该仓库的 warehouse 类型 ApiApp
const apiApp = await ctx.model.ApiApp.findOne({
attributes: [ 'id', 'self_app_key', 'self_app_secret', 'is_enabled', 'interface_type_id', 'warehouse_id' ],
where: {
warehouse_id: warehouseId,
interface_type_id: WAREHOUSE_INTERFACE_TYPE_ID,
is_enabled: 1,
},
raw: true,
});
if (!apiApp || !apiApp.self_app_secret) {
return null;
}
return {
appKey: apiApp.self_app_key,
selfAppSecret: apiApp.self_app_secret,
warehouseId: Number(apiApp.warehouse_id),
};
} catch (error) {
ctx.logger.warn(`[inbox dispatch] 获取仓库 ApiApp 失败: ${error.message}`);
return null;
}
}
/**
* 生成 MD5 签名,返回带签名后的完整 URL。
* @param {string} url 原始目标URL。
* @param {*} body 请求体。
* @param {Object} secret ApiApp 密钥对象,含 appKey / selfAppSecret。
* @return {string} 带签名的完整URL。
*/
signRequest(url, body, secret) {
const timestamp = Math.floor(Date.now() / 1000);
const query = {
app_key: secret.appKey,
timestamp,
};
const { sign } = apiSignLib.signRequest({
query,
body,
selfAppSecret: secret.selfAppSecret,
});
const separator = url.includes('?') ? '&' : '?';
return `${url}${separator}app_key=${encodeURIComponent(query.app_key)}&timestamp=${timestamp}&sign=${encodeURIComponent(sign)}`;
}
/**
* 统一 HTTP POST 发送。
* @param {string} url 目标URL。
* @param {*} body 请求体。
* @param {Object} [options] 额外选项。
* @param {Object} [options.headers] 自定义请求头。
* @return {Promise<{status: number, data: *}>} 响应结果。
*/
async post(url, body, options = {}) {
const { ctx } = this;
const headers = {
'Content-Type': 'application/json',
...(options.headers || {}),
};
try {
const response = await ctx.curl(url, {
method: 'POST',
dataType: 'json',
contentType: 'json',
data: body,
headers,
timeout: DISPATCH_TIMEOUT_MS,
});
return {
status: response.status,
data: response.data,
};
} catch (error) {
throw new Error(`HTTP 推送失败: ${error.message}`);
}
}
/**
* 子类必须实现的推送方法。
* @param {Object} record 消息记录(Sequelize Model 实例),子类按需使用。
* @throws {Error} 子类未实现时抛出。
*/
async push(record) {
const id = record && record.id;
throw new Error(`子类必须实现 push(record) 方法,当前消息ID: ${id || '未知'}`);
}
}
module.exports = OutboundBase;

View File

@ -1,35 +0,0 @@
'use strict';
const OutboundBase = require('./base');
/**
* 钉钉 Bot 渠道出站实现。
* 推送 Markdown 消息到钉钉机器人 webhook。
*/
class DingtalkDispatch extends OutboundBase {
/**
* 通过钉钉 Bot 推送消息。
* @param {Object} record 消息记录(Sequelize Model 实例)。
* @return {Promise<{status: number, data: *}>} 推送响应。
*/
async push(record) {
const { ctx } = this;
const extData = record.ext_data || {};
const title = extData.title || '新消息通知';
const text = extData.content || extData.text || `消息:${record.ref_code || record.ext_id}`;
const body = {
msgtype: 'markdown',
markdown: {
title,
text: typeof text === 'string' ? text : JSON.stringify(text),
},
};
ctx.logger.info(`[inbox dingtalk] 推送消息 ext_id=${record.ext_id} url=${record.target_url}`);
return await this.post(record.target_url, body);
}
}
module.exports = DingtalkDispatch;

View File

@ -1,60 +0,0 @@
'use strict';
const OutboundBase = require('./base');
/**
* 飞书 Bot 渠道出站实现。
* 推送交互式卡片消息到飞书机器人 webhook。
*/
class FeishuDispatch extends OutboundBase {
/**
* 通过飞书 Bot 推送消息。
* @param {Object} record 消息记录(Sequelize Model 实例)。
* @return {Promise<{status: number, data: *}>} 推送响应。
*/
async push(record) {
const { ctx } = this;
const extData = record.ext_data || {};
const title = extData.title || '新消息通知';
const content = extData.content || extData.text || `消息:${record.ref_code || record.ext_id}`;
const body = {
msg_type: 'interactive',
card: {
header: {
title: {
tag: 'plain_text',
content: title,
},
},
elements: [
{
tag: 'div',
text: {
tag: 'lark_md',
content: typeof content === 'string' ? content : JSON.stringify(content),
},
},
{
tag: 'hr',
},
{
tag: 'note',
elements: [
{
tag: 'plain_text',
content: `编号: ${record.ref_code || record.ext_id}`,
},
],
},
],
},
};
ctx.logger.info(`[inbox feishu] 推送消息 ext_id=${record.ext_id} url=${record.target_url}`);
return await this.post(record.target_url, body);
}
}
module.exports = FeishuDispatch;

View File

@ -1,44 +0,0 @@
'use strict';
const OutboundBase = require('./base');
/**
* Webhook 渠道出站实现。
* 直接 HTTP POST 推送 JSON 到目标 webhook URL。
*/
class WebhookDispatch extends OutboundBase {
/**
* 通过 webhook 渠道推送消息。
* @param {Object} record 消息记录(Sequelize Model 实例)。
* @return {Promise<{status: number, data: *}>} 推送响应。
*/
async push(record) {
const { ctx } = this;
const body = {
ref_code: record.ref_code,
ext_data: record.ext_data,
message_id: record.ext_id,
direction: record.direction,
source_type: record.source_type,
created_at: record.created_at,
};
let targetUrl = record.target_url;
// API 类型需要签名
if (record.target_type === 'api') {
const apiApp = await this.getApiApp(record.warehouse_id);
if (apiApp) {
targetUrl = this.signRequest(targetUrl, body, apiApp);
} else {
ctx.logger.warn(`[inbox webhook] 仓库 ${record.warehouse_id} 没有可用 ApiApp,跳过签名`);
}
}
ctx.logger.info(`[inbox webhook] 推送消息 ext_id=${record.ext_id} url=${targetUrl}`);
return await this.post(targetUrl, body);
}
}
module.exports = WebhookDispatch;

View File

@ -1,33 +0,0 @@
'use strict';
const OutboundBase = require('./base');
/**
* 企微 Bot 渠道出站实现。
* 推送 Markdown 消息到企业微信机器人 webhook。
*/
class WecomDispatch extends OutboundBase {
/**
* 通过企微 Bot 推送消息。
* @param {Object} record 消息记录(Sequelize Model 实例)。
* @return {Promise<{status: number, data: *}>} 推送响应。
*/
async push(record) {
const { ctx } = this;
const extData = record.ext_data || {};
const content = extData.content || extData.text || `新消息通知:${record.ref_code || record.ext_id}`;
const body = {
msgtype: 'markdown',
markdown: {
content: typeof content === 'string' ? content : JSON.stringify(content),
},
};
ctx.logger.info(`[inbox wecom] 推送消息 ext_id=${record.ext_id} url=${record.target_url}`);
return await this.post(record.target_url, body);
}
}
module.exports = WecomDispatch;

View File

@ -1,365 +0,0 @@
'use strict';
const Service = require('egg').Service;
const crypto = require('crypto');
/**
* 站内信查询/管理服务。
* 提供消息列表、详情、对话链、回复、重推、统计等管理功能。
*/
class InboxService extends Service {
/**
* 消息列表(按仓库/状态/方向筛选,分页)。
* @param {Object} params 查询参数。
* @param {number} params.warehouseId 仓库ID(必填,服务端上下文注入)。
* @param {string} [params.direction] 消息方向筛选:inbound / outbound。
* @param {number} [params.pushStatus] 推送状态筛选:0/1/2/3。
* @param {string} [params.targetChannel] 目标渠道筛选。
* @param {string} [params.keyword] 关键词搜索(ext_id / ref_code)。
* @param {number} [params.page=1] 页码。
* @param {number} [params.pageSize=20] 每页数量。
* @return {Promise<{list: Array, pagination: Object}>} 分页结果。
*/
async list(params = {}) {
const { ctx } = this;
const { Op } = ctx.app.Sequelize;
const { InboxMessage } = ctx.model;
const warehouseId = Number(params.warehouseId);
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
throw new Error('warehouseId 无效');
}
const page = Math.max(1, Number(params.page) || 1);
const pageSize = Math.min(200, Math.max(1, Number(params.pageSize) || 20));
const where = {
warehouse_id: warehouseId,
deleted_at: null,
};
if (params.direction && [ 'inbound', 'outbound' ].includes(params.direction)) {
where.direction = params.direction;
}
if (params.pushStatus !== undefined && params.pushStatus !== null && params.pushStatus !== '') {
const status = Number(params.pushStatus);
if ([ 0, 1, 2, 3 ].includes(status)) {
where.push_status = status;
}
}
if (params.targetChannel && typeof params.targetChannel === 'string') {
where.target_channel = params.targetChannel.trim();
}
if (params.keyword && typeof params.keyword === 'string') {
const keyword = `%${params.keyword.trim()}%`;
where[Op.or] = [
{ ext_id: { [Op.like]: keyword } },
];
}
const { count: total, rows } = await InboxMessage.findAndCountAll({
attributes: {
exclude: [ 'ext_data', 'push_response' ],
},
where,
order: [[ 'created_at', 'DESC' ]],
offset: (page - 1) * pageSize,
limit: pageSize,
});
return {
list: rows,
pagination: {
page,
pageSize,
total,
totalPages: Math.ceil(total / pageSize),
hasPrevious: page > 1,
hasNext: page * pageSize < total,
},
};
}
/**
* 消息详情(含 push_response)。
* @param {Object} params 查询参数。
* @param {number} params.warehouseId 仓库ID(必填)。
* @param {number} params.id 消息ID。
* @return {Promise<Object>} 消息详情。
*/
async detail(params = {}) {
const { ctx } = this;
const { InboxMessage } = ctx.model;
const warehouseId = Number(params.warehouseId);
const id = Number(params.id);
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
throw new Error('warehouseId 无效');
}
if (!Number.isFinite(id) || id <= 0) {
throw new Error('消息ID无效');
}
const record = await InboxMessage.findOne({
where: { id, warehouse_id: warehouseId, deleted_at: null },
});
if (!record) {
throw new Error('消息不存在或无权访问');
}
return record;
}
/**
* 对话链查询(原消息 + 所有回信),按 parent_id 递归。
* @param {Object} params 查询参数。
* @param {number} params.warehouseId 仓库ID(必填)。
* @param {number} params.id 消息ID。
* @return {Promise<Array>} 对话链列表。
*/
async thread(params = {}) {
const { ctx } = this;
const { InboxMessage } = ctx.model;
const warehouseId = Number(params.warehouseId);
const id = Number(params.id);
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
throw new Error('warehouseId 无效');
}
if (!Number.isFinite(id) || id <= 0) {
throw new Error('消息ID无效');
}
// 查找根消息
const root = await InboxMessage.findOne({
where: { id, warehouse_id: warehouseId },
});
if (!root) {
throw new Error('消息不存在或无权访问');
}
// 收集对话链:从根到叶
const MAX_THREAD_DEPTH = 50;
const thread = [ root ];
const visited = new Set([ root.id ]);
// 查找所有回信(以 root.id 为 parent_id)
const replies = await InboxMessage.findAll({
where: {
warehouse_id: warehouseId,
parent_id: root.id,
deleted_at: null,
},
order: [[ 'created_at', 'ASC' ]],
});
for (const reply of replies) {
if (!visited.has(reply.id) && thread.length < MAX_THREAD_DEPTH) {
visited.add(reply.id);
thread.push(reply);
}
}
// 如果当前消息不是根(有 parent_id),也向上查找原消息
if (root.parent_id) {
const parent = await InboxMessage.findOne({
where: {
id: root.parent_id,
warehouse_id: warehouseId,
deleted_at: null,
},
});
if (parent && !visited.has(parent.id) && thread.length < MAX_THREAD_DEPTH) {
visited.add(parent.id);
thread.unshift(parent);
}
}
return thread;
}
/**
* 系统回信:写入 outbound 记录 + 异步推送。
* @param {Object} data 回信数据。
* @param {number} data.warehouseId 仓库ID(必填,服务端上下文注入)。
* @param {number} data.parentId 原消息ID。
* @param {string} data.targetChannel 目标渠道。
* @param {string} data.targetUrl 推送目标URL。
* @param {string} [data.refCode] 引用编码。
* @param {Object} [data.extData] 透传数据。
* @param {Object} [data.flags] 处理标记。
* @return {Promise<Object>} 回信结果。
*/
async reply(data = {}) {
const { ctx } = this;
const { InboxMessage } = ctx.model;
const warehouseId = Number(data.warehouseId);
const parentId = Number(data.parentId);
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
throw new Error('warehouseId 无效');
}
if (!Number.isFinite(parentId) || parentId <= 0) {
throw new Error('parentId 无效');
}
// 查找原消息
const parent = await InboxMessage.findOne({
where: { id: parentId, warehouse_id: warehouseId, deleted_at: null },
});
if (!parent) {
throw new Error('原消息不存在或无权访问');
}
const extId = `sys:${crypto.randomUUID()}`;
const result = await ctx.service.inbox.receiver.receive({
ext_id: extId,
warehouse_id: warehouseId,
store_id: parent.store_id,
direction: 'outbound',
parent_id: parentId,
source_type: 'system',
source_extra: null,
target_type: data.targetType || parent.target_type,
target_channel: data.targetChannel,
target_url: data.targetUrl,
ref_code: data.refCode || parent.ref_code,
ext_data: data.extData || parent.ext_data,
flags: data.flags || {},
});
return result;
}
/**
* 手动重推。
* @param {Object} params 重推参数。
* @param {number} params.warehouseId 仓库ID(必填)。
* @param {number} params.id 消息ID。
* @return {Promise<Object>} 重推结果。
*/
async retry(params = {}) {
const { ctx } = this;
const { InboxMessage } = ctx.model;
const warehouseId = Number(params.warehouseId);
const id = Number(params.id);
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
throw new Error('warehouseId 无效');
}
if (!Number.isFinite(id) || id <= 0) {
throw new Error('消息ID无效');
}
const record = await InboxMessage.findOne({
where: { id, warehouse_id: warehouseId },
});
if (!record) {
throw new Error('消息不存在或无权访问');
}
if (![ 3 ].includes(record.push_status)) {
throw new Error('仅失败状态的消息可以手动重推');
}
// 重置为待推送状态,由异步推送接管
await record.update({
push_status: 0,
push_started_at: null,
});
// 触发异步推送
setImmediate(() => {
ctx.service.inbox.receiver.asyncPush(record, 0).catch(err => {
ctx.logger.error(`[inbox] 手动重推异常 ext_id=${record.ext_id}: ${err.message}`);
});
});
return {
ok: true,
id: record.id,
ext_id: record.ext_id,
message: '已触发重推',
};
}
/**
* 推送统计(按仓库 + 状态汇总)。
* @param {Object} params 统计参数。
* @param {number} params.warehouseId 仓库ID(必填)。
* @param {string} [params.direction] 消息方向筛选。
* @return {Promise<Object>} 统计结果。
*/
async stats(params = {}) {
const { ctx } = this;
const { InboxMessage } = ctx.model;
const { Op } = ctx.app.Sequelize;
const warehouseId = Number(params.warehouseId);
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
throw new Error('warehouseId 无效');
}
const where = {
warehouse_id: warehouseId,
};
if (params.direction && [ 'inbound', 'outbound' ].includes(params.direction)) {
where.direction = params.direction;
}
// 按方向统计
const directionStats = await InboxMessage.findAll({
attributes: [
'direction',
[ ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'count' ],
],
where,
group: [ 'direction' ],
raw: true,
});
// 按推送状态统计
const statusStats = await InboxMessage.findAll({
attributes: [
'push_status',
[ ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'count' ],
],
where,
group: [ 'push_status' ],
raw: true,
});
// 最近24小时统计
const recentWhere = {
...where,
created_at: {
[Op.gte]: new Date(Date.now() - 24 * 60 * 60 * 1000),
},
};
const recentCount = await InboxMessage.count({ where: recentWhere });
return {
total_by_direction: directionStats,
total_by_status: statusStats,
recent_24h_count: recentCount,
};
}
}
module.exports = InboxService;

View File

@ -1,409 +0,0 @@
'use strict';
const Service = require('egg').Service;
const { URL } = require('url');
const { networkInterfaces } = require('os');
/** 推<>?body 大小上限<E4B88A>?4KB */
const MAX_PUSH_BODY_SIZE = 64 * 1024;
/** 最大重试次<E8AF95>?*/
const MAX_RETRY_COUNT = 3;
/** 僵尸恢复阈值:5分钟 */
const ZOMBIE_RECOVERY_MINUTES = 5;
/**
* 收集本机所有内<EFBFBD>?IPv4 地址<EFBFBD>?
* @return {string[]} 内网IP地址列表<EFBFBD>?
*/
function getLocalInternalIps() {
const ips = new Set();
const nets = networkInterfaces();
for (const interfaces of Object.values(nets)) {
for (const iface of interfaces) {
if (iface.family === 'IPv4' && !iface.internal) {
ips.add(iface.address);
}
}
}
return Array.from(ips);
}
/** 内网 IP 前缀集合 */
const INTERNAL_IP_PREFIXES = [
'127.',
'10.',
'192.168.',
'0.',
];
/**
* 判断给定 IP 是否属于本机内网IP<EFBFBD>?
* @param {string} ip IP地址<EFBFBD>?
* @return {boolean} 是否为内网IP<EFBFBD>?
*/
function isInternalIp(ip) {
if (!ip || ip === 'localhost') return true;
// 检查已知内网前缀
for (const prefix of INTERNAL_IP_PREFIXES) {
if (ip.startsWith(prefix)) return true;
}
// 检<>?172.16.0.0 ~ 172.31.255.255
const parts = ip.split('.').map(Number);
if (parts.length === 4 && parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) {
return true;
}
// 检查本机实际内网IP
const localIps = getLocalInternalIps();
if (localIps.includes(ip)) return true;
return false;
}
/**
* 校验 target_url 安全性:仅允<EFBFBD>?https://,禁止内网IP<49>?
* @param {string} urlStr 目标URL<EFBFBD>?
* @throws {Error} URL 不合法时抛出<EFBFBD>?
*/
// eslint-disable-next-line no-unused-vars
function validateTargetUrl(urlStr) {
if (!urlStr || typeof urlStr !== 'string') {
throw new Error('target_url 不能为空');
}
let parsed;
try {
parsed = new URL(urlStr);
} catch (e) {
throw new Error(`target_url 格式不合<E4B88D>? ${urlStr}`);
}
if (parsed.protocol !== 'https:') {
throw new Error('target_url 仅允<E4BB85>?https:// 协议');
}
const hostname = parsed.hostname || '';
if (isInternalIp(hostname)) {
throw new Error('target_url 不允许指向内网地址');
}
}
/**
* 站内信接收服务<EFBFBD>?
* 统一处理消息入站:幂等去重、写库、异步推送、指数退避重试、僵尸恢复<EFBFBD>?
*/
class InboxReceiverService extends Service {
/**
* 获取支持的目标渠道集合<EFBFBD>?
* @return {Set<string>} 支持的目标渠道<EFBFBD>?
*/
static get SUPPORTED_CHANNELS() {
return new Set([
'webhook',
'wecom',
'dingtalk',
'feishu',
'warehouse_api',
]);
}
/**
* 初始化时执行僵尸恢复<EFBFBD>?
* @param {Object} ctx Egg.js 上下文<EFBFBD>?
*/
constructor(ctx) {
super(ctx);
// 异步执行僵尸恢复,不阻塞服务启动
setImmediate(() => {
this.recoverZombieMessages().catch(err => {
ctx.logger.error(`[inbox] 僵尸恢复失败: ${err.message}`);
});
});
}
/**
* 统一接收入口:幂等去重、写库、异步推送<EFBFBD>?
* @param {Object} data 消息数据<EFBFBD>?
* @param {string} data.ext_id 外部唯一消息主键<EFBFBD>?
* @param {number} data.warehouse_id 所属仓库ID(服务端上下文注入,禁止外部传入)<EFBFBD>?
* @param {number} [data.store_id] 关联货主ID<EFBFBD>?
* @param {string} [data.direction='inbound'] 消息方向<EFBFBD>?
* @param {number} [data.parent_id] 关联消息ID(回信时指向原消息)<EFBFBD>?
* @param {string} data.source_type 来源类型:im / api / system<EFBFBD>?
* @param {string} [data.source_extra] 来源附加信息<EFBFBD>?
* @param {string} data.target_type 目标类型:im / api / webhook<EFBFBD>?
* @param {string} data.target_channel 目标渠道<EFBFBD>?
* @param {string} data.target_url 推送目标URL<EFBFBD>?
* @param {string} [data.ref_code] 引用编码<EFBFBD>?
* @param {Object} [data.ext_data] 透传数据<EFBFBD>?
* @param {Object} [data.flags] 处理标记<EFBFBD>?
* @return {Promise<{ok: boolean, id: number, ext_id: string}>} 接收结果<EFBFBD>?
*/
async receive(data = {}) {
const { ctx } = this;
const { InboxMessage } = ctx.model;
// 安全边界:校<EFBC9A>?ext_id 不能为空
const extId = String(data.ext_id || '').trim();
if (!extId) {
throw new Error('ext_id 不能为空');
}
// 安全边界:warehouse_id 必须由服务端上下文提<E69687>?
const warehouseId = Number(data.warehouse_id);
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
throw new Error('warehouse_id 无效');
}
// 枚举校验:direction
const VALID_DIRECTIONS = [ 'inbound', 'outbound' ];
const direction = VALID_DIRECTIONS.includes(data.direction) ? data.direction : 'inbound';
// 枚举校验:source_type
const VALID_SOURCE_TYPES = [ 'im', 'api', 'system' ];
const sourceType = VALID_SOURCE_TYPES.includes(data.source_type) ? data.source_type : (data.source_type || 'api');
// 枚举校验:target_type
const VALID_TARGET_TYPES = [ 'im', 'api', 'webhook' ];
const targetType = VALID_TARGET_TYPES.includes(data.target_type) ? data.target_type : (data.target_type || 'im');
// parent_id 存在性校验
const parentId = data.parent_id ? Number(data.parent_id) : null;
if (parentId) {
const parentExists = await InboxMessage.findOne({
where: { id: parentId, warehouse_id: warehouseId },
attributes: [ 'id' ],
});
if (!parentExists) {
throw new Error(`parent_id=${parentId} 对应的消息不存在`);
}
}
// 校验 target_channel 是否存在
const targetChannel = String(data.target_channel || '').trim();
if (!targetChannel || !InboxReceiverService.SUPPORTED_CHANNELS.has(targetChannel)) {
throw new Error(`不支持的目标渠道: ${targetChannel},支持的渠道: ${Array.from(InboxReceiverService.SUPPORTED_CHANNELS).join(', ')}`);
}
// 安全边界:校<EFBC9A>?target_url
// 幂等检查:ext_id 已存在则直接返回
const exist = await InboxMessage.findOne({
where: { ext_id: extId },
attributes: [ 'id', 'ext_id', 'push_status' ],
paranoid: false,
});
if (exist) {
ctx.logger.info(`[inbox] 消息已存在,跳过入库 ext_id=${extId} id=${exist.id}`);
return {
ok: true,
id: exist.id,
ext_id: extId,
};
}
// 推<>?body 大小限制(序列化后检查)
const pushBody = {
ext_data: data.ext_data || null,
};
const bodySize = Buffer.byteLength(JSON.stringify(pushBody), 'utf8');
if (bodySize > MAX_PUSH_BODY_SIZE) {
throw new Error(`推<EFBFBD>?body 超过 64KB 限制(当<EFBC88>?${Math.round(bodySize / 1024)}KB)`);
}
// 写库
// store_id 签约校验,若传入 store_id,必须存在有效合约关系
const storeId = data.store_id ? Number(data.store_id) : null;
if (storeId && Number.isFinite(storeId) && storeId > 0) {
const contract = await ctx.model.StoreWarehouse.findOne({
where: {
store_id: storeId,
warehouse_id: warehouseId,
auth_status: 2,
warehouse_use_status: 1,
},
attributes: [ 'id' ],
});
if (!contract) {
throw new Error(`store_id=${storeId} 与仓库 ${warehouseId} 无有效签约关系`);
}
}
const record = await InboxMessage.create({
ext_id: extId,
warehouse_id: warehouseId,
store_id: data.store_id || null,
direction,
parent_id: parentId,
source_type: sourceType,
source_extra: data.source_extra || null,
target_type: targetType,
target_channel: targetChannel,
ext_data: data.ext_data || null,
flags: data.flags || {},
push_status: 0,
});
ctx.logger.info(`[inbox] 消息入库成功 ext_id=${extId} id=${record.id}`);
// 异步后台推送(不阻塞响应)
setImmediate(() => {
this.asyncPush(record).catch(err => {
ctx.logger.error(`[inbox] setImmediate 异步推送异<E98081>?ext_id=${extId}: ${err.message}`);
// 异常已由 asyncPush 内部 try/catch,这里作为兜<E4B8BA>?
try {
InboxMessage.update(
{
push_status: 3,
push_response: { error: `setImmediate 异常: ${err.message}` },
pushed_at: new Date(),
},
{ where: { id: record.id, push_status: { [this.ctx.app.Sequelize.Op.in]: [ 0, 1 ] } } }
);
} catch (updateErr) {
ctx.logger.error(`[inbox] 兜底更新推送状态失<E68081>?ext_id=${extId}: ${updateErr.message}`);
}
});
});
return {
ok: true,
id: record.id,
ext_id: extId,
};
}
/**
* 异步推<EFBFBD>?+ 指数退避重试<EFBFBD>?
* @param {Object} record 消息记录(Sequelize Model 实例)<EFBFBD>?
* @param {number} [attempt=0] 当前重试次数<EFBFBD>?
* @return {Promise<void>} 推送结果<EFBFBD>?
*/
async asyncPush(record, attempt = 0) {
const { ctx } = this;
const { InboxMessage } = ctx.model;
const { Op } = ctx.app.Sequelize;
try {
// 乐观锁:<E99481>?push_status=0 或(重试<E9878D>?push_status=3)时可取<E58FAF>?
const allowedStatuses = attempt === 0 ? [ 0 ] : [ 3 ];
const [ updatedCount ] = await InboxMessage.update(
{
push_status: 1,
push_started_at: new Date(),
},
{
where: {
id: record.id,
push_status: { [Op.in]: allowedStatuses },
},
}
);
if (updatedCount === 0) {
ctx.logger.info(`[inbox] 消息已被其他进程取走,跳过推<E8BF87>?ext_id=${record.ext_id} id=${record.id}`);
return;
}
// 获取 dispatch 服务
const channel = record.target_channel;
if (!InboxReceiverService.SUPPORTED_CHANNELS.has(channel)) {
throw new Error(`不支持的目标渠道: ${channel}`);
}
// 统一渠道映射:warehouse_api <20>?webhook
const dispatchChannel = channel === 'warehouse_api' ? 'webhook' : channel;
const dispatchService = ctx.service.inbox.dispatch[dispatchChannel];
if (!dispatchService || typeof dispatchService.push !== 'function') {
throw new Error(`dispatch 渠道 ${dispatchChannel} 未实现`);
}
// 执行推<E8A18C>?
const response = await dispatchService.push(record);
// 推送成<E98081>?
await InboxMessage.update(
{
push_status: 2,
push_response: {
http_status: response.status,
body: response.data,
},
pushed_at: new Date(),
},
{ where: { id: record.id, push_status: 1 } }
);
ctx.logger.info(`[inbox] 推送成<E98081>?ext_id=${record.ext_id} channel=${channel}`);
} catch (error) {
const next = attempt + 1;
ctx.logger.warn(`[inbox] 推送失<E98081>?ext_id=${record.ext_id} attempt=${next} error=${error.message}`);
// 更新失败状<E8B4A5>?
await InboxMessage.update(
{
push_status: next >= MAX_RETRY_COUNT ? 3 : 3,
retry_count: next,
push_response: { error: error.message },
...(next >= MAX_RETRY_COUNT ? { pushed_at: new Date() } : {}),
},
{ where: { id: record.id, push_status: 1 } }
);
// 指数退避重试:30s <20>?60s <20>?120s
if (next < MAX_RETRY_COUNT) {
const delay = 30000 * Math.pow(2, attempt);
ctx.logger.info(`[inbox] 将在 ${delay / 1000}s 后重<E5908E>?ext_id=${record.ext_id} attempt=${next}`);
setTimeout(() => {
this.asyncPush(record, next).catch(err => {
ctx.logger.error(`[inbox] 重试推送异<E98081>?ext_id=${record.ext_id}: ${err.message}`);
});
}, delay);
} else {
ctx.logger.error(`[inbox] 推送达到最大重试次数,标记为终态失<E68081>?ext_id=${record.ext_id}`);
}
}
}
/**
* 僵尸恢复:重置卡<EFBFBD>?推送中"超过5分钟的消息为"待推<EFBFBD>?<EFBFBD>?
* 在服务启动时及定时任务中调用<EFBFBD>?
* @return {Promise<number>} 恢复的消息数量<EFBFBD>?
*/
async recoverZombieMessages() {
const { ctx } = this;
const { InboxMessage } = ctx.model;
const { Op } = ctx.app.Sequelize;
const threshold = new Date(Date.now() - ZOMBIE_RECOVERY_MINUTES * 60 * 1000);
const [ updatedCount ] = await InboxMessage.update(
{
push_status: 0,
push_started_at: null,
},
{
where: {
push_status: 1,
push_started_at: {
[Op.lt]: threshold,
},
},
}
);
if (updatedCount > 0) {
ctx.logger.info(`[inbox] 僵尸恢复完成,重<EFBC8C>?${updatedCount} 条消息为待推送`);
}
return updatedCount;
}
}
module.exports = InboxReceiverService;

View File

@ -910,102 +910,6 @@ class OrderBaseService extends MainService {
}; };
} }
/**
* 提取买家留言虚拟筛选条件 buyer_message_has。
* 覆盖 buyer_message / seller_message / remark 三个字段,任一有值即为"有留言"。
* 将其从 where 中移除并解析为布尔值,后续在 buildWhere 之后注入 Sequelize 条件。
* @param {Object} whereInput 标准化后的 where 条件。
* @return {{ where: Object, buyerMessageHas: boolean|null }} 清洗后的 where 与买家留言标记。
*/
extractBuyerMessageHasVirtualFilter(whereInput = {}) {
const normalizedWhere = this.isPlainObject(whereInput)
? { ...whereInput }
: {};
const buyerMessageHasCondition = normalizedWhere.buyer_message_has;
delete normalizedWhere.buyer_message_has;
if (!buyerMessageHasCondition) {
return { where: normalizedWhere, buyerMessageHas: null };
}
const rawValue = this.isPlainObject(buyerMessageHasCondition)
&& Object.prototype.hasOwnProperty.call(buyerMessageHasCondition, 'value')
? buyerMessageHasCondition.value
: buyerMessageHasCondition;
// 兼容布尔值、字符串 'true'/'false'、'Y'/'N'、数字 1/0、以及前端 select 组件值 'has'/'empty'/'none'
const normalizedRawValue = typeof rawValue === 'string' ? rawValue.trim().toLowerCase() : rawValue;
if (rawValue === true || normalizedRawValue === 'true' || normalizedRawValue === 'y' || normalizedRawValue === 'has' || rawValue === 1) {
return { where: normalizedWhere, buyerMessageHas: true };
}
if (rawValue === false || normalizedRawValue === 'false' || normalizedRawValue === 'n' || normalizedRawValue === 'empty' || normalizedRawValue === 'none' || rawValue === 0) {
return { where: normalizedWhere, buyerMessageHas: false };
}
return { where: normalizedWhere, buyerMessageHas: null };
}
/**
* 构建 buyer_message_has 虚拟字段的 Sequelize where 条件。
* 覆盖三个留言/备注字段:buyer_message、seller_message、remark。
* @param {boolean} hasMessage true=任一字段有留言,false=三个字段全部为空。
* @return {Object|null} Sequelize where 条件,无效时返回 null。
*/
buildBuyerMessageHasCondition(hasMessage) {
if (typeof hasMessage !== 'boolean') {
return null;
}
const { Op } = this.app.Sequelize;
const hasContent = col => ({
[Op.and]: [
{ [col]: { [Op.not]: null } },
{ [col]: { [Op.ne]: '' } },
],
});
const isEmpty = col => ({
[Op.or]: [
{ [col]: { [Op.is]: null } },
{ [col]: { [Op.eq]: '' } },
],
});
const fields = [ 'buyer_message', 'seller_message', 'remark' ];
if (hasMessage) {
return { [Op.or]: fields.map(col => hasContent(col)) };
}
return { [Op.and]: fields.map(col => isEmpty(col)) };
}
/**
* 将附加条件并入 queryWhere,兼容 flat 对象与 { [Op.and]: [...] } 结构。
* @param {Object} queryWhere 现有 Sequelize where 条件。
* @param {Object} extraCondition 待并入的条件。
* @return {Object} 合并后的 where 条件。
*/
appendConditionToWhere(queryWhere = {}, extraCondition = null) {
if (!extraCondition || !this.isPlainObject(extraCondition)
|| (Object.keys(extraCondition).length === 0 && Object.getOwnPropertySymbols(extraCondition).length === 0)) {
return queryWhere;
}
const { Op } = this.app.Sequelize;
if (!this.isPlainObject(queryWhere)
|| (Object.keys(queryWhere).length === 0 && Object.getOwnPropertySymbols(queryWhere).length === 0)) {
return extraCondition;
}
if (Array.isArray(queryWhere[Op.and])) {
return {
...queryWhere,
[Op.and]: [ ...queryWhere[Op.and], extraCondition ],
};
}
return {
[Op.and]: [ queryWhere, extraCondition ],
};
}
/** /**
* 规范化运单号筛选输入,兼容字符串、数组与 { value } 结构。 * 规范化运单号筛选输入,兼容字符串、数组与 { value } 结构。
* @param {*} condition 运单号筛选条件。 * @param {*} condition 运单号筛选条件。
@ -1246,8 +1150,7 @@ class OrderBaseService extends MainService {
}, },
}); });
const { where: sanitizedWhere, expressNumbers } = this.extractOrderListExpressVirtualFilter(where); const { where: sanitizedWhere, expressNumbers } = this.extractOrderListExpressVirtualFilter(where);
const { where: whereAfterBuyerMessage, buyerMessageHas } = this.extractBuyerMessageHasVirtualFilter(sanitizedWhere); const mergedWhere = this.mergeWhereObjects(this.getDefaultWhere(moduleName), sanitizedWhere);
const mergedWhere = this.mergeWhereObjects(this.getDefaultWhere(moduleName), whereAfterBuyerMessage);
let queryWhere = this.buildWhere(mergedWhere, contextWarehouseId, { let queryWhere = this.buildWhere(mergedWhere, contextWarehouseId, {
specialFieldMap: { specialFieldMap: {
quickWhere: { quickWhere: {
@ -1261,11 +1164,6 @@ class OrderBaseService extends MainService {
queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, orderIds); queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, orderIds);
} }
if (buyerMessageHas !== null) {
const buyerMessageCondition = this.buildBuyerMessageHasCondition(buyerMessageHas);
queryWhere = this.appendConditionToWhere(queryWhere, buyerMessageCondition);
}
const model = await this.getOrderModel(moduleName, contextWarehouseId); const model = await this.getOrderModel(moduleName, contextWarehouseId);
const order = this.buildListOrder(requestData.sort, moduleName); const order = this.buildListOrder(requestData.sort, moduleName);
const offset = (page - 1) * pageSize; const offset = (page - 1) * pageSize;

View File

@ -3999,9 +3999,8 @@ class WaveService extends OrderBaseService {
{ specialFieldMap: { quickWhere: { bucket: 'quick' } } } { specialFieldMap: { quickWhere: { bucket: 'quick' } } }
); );
const { where: sanitizedWhere, expressNumbers } = this.extractOrderListExpressVirtualFilter(ctxWhere); const { where: sanitizedWhere, expressNumbers } = this.extractOrderListExpressVirtualFilter(ctxWhere);
const { where: whereAfterBuyerMessage, buyerMessageHas } = this.extractBuyerMessageHasVirtualFilter(sanitizedWhere);
const defaultWhere = this.getDefaultWhere('waveStrategyFallbackOrder'); const defaultWhere = this.getDefaultWhere('waveStrategyFallbackOrder');
const mergedWhere = this.mergeWhereObjects(defaultWhere, whereAfterBuyerMessage); const mergedWhere = this.mergeWhereObjects(defaultWhere, sanitizedWhere);
let queryWhere = this.buildWhere(mergedWhere, contextWarehouseId, { let queryWhere = this.buildWhere(mergedWhere, contextWarehouseId, {
specialFieldMap: { quickWhere: { bucket: 'quick' } }, specialFieldMap: { quickWhere: { bucket: 'quick' } },
}); });
@ -4012,11 +4011,6 @@ class WaveService extends OrderBaseService {
queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, orderIds); queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, orderIds);
} }
if (buyerMessageHas !== null) {
const buyerMessageCondition = this.buildBuyerMessageHasCondition(buyerMessageHas);
queryWhere = this.appendConditionToWhere(queryWhere, buyerMessageCondition);
}
// 追加 OR 条件:未匹配策略(wave_scan_result=2) 或 已完全打印被排除(print_status='fin') // 追加 OR 条件:未匹配策略(wave_scan_result=2) 或 已完全打印被排除(print_status='fin')
const { Sequelize } = this.app; const { Sequelize } = this.app;
queryWhere = { queryWhere = {
@ -11072,48 +11066,12 @@ class WaveService extends OrderBaseService {
selectedWaveIds, selectedWaveIds,
waveNoMap, waveNoMap,
}); });
// 查询波次索引(wave_index),使 box_no 与 wms_order_wave_index.wave_index 一致
const waveIndexMap = new Map();
if (selectedOrderIds.length > 0 && selectedWaveIds.length > 0) {
try {
const waveIndexRows = await this.ctx.model.query(
`SELECT order_id, wave_index
FROM wms_order_wave_index
WHERE warehouse_id = :warehouseId
AND wave_id IN (:waveIds)
AND order_id IN (:orderIds)`,
{
replacements: {
warehouseId,
waveIds: selectedWaveIds,
orderIds: selectedOrderIds,
},
type: this.ctx.model.QueryTypes.SELECT,
transaction,
}
);
for (const wr of (Array.isArray(waveIndexRows) ? waveIndexRows : [])) {
const wrOrderId = Number(wr && wr.order_id || 0);
if (wrOrderId > 0) {
waveIndexMap.set(wrOrderId, Number(wr.wave_index || 0));
}
}
} catch (e) {
this.ctx.logger.warn('[wave.createTask] 查询波次索引失败,box_no 将退化为任务内序号', {
error: e && e.message,
warehouseId,
waveIds: selectedWaveIds,
});
}
}
const taskOrderRows = this.buildTaskOrderRows({ const taskOrderRows = this.buildTaskOrderRows({
taskId, taskId,
plan: effectivePlan, plan: effectivePlan,
selectedWaveIds, selectedWaveIds,
selectedOrderIds, selectedOrderIds,
cartId: normalizedCartId, cartId: normalizedCartId,
waveIndexMap,
}); });
const taskSkuRows = await this.buildTaskSkuRows({ const taskSkuRows = await this.buildTaskSkuRows({
plan: effectivePlan, plan: effectivePlan,
@ -11307,16 +11265,12 @@ class WaveService extends OrderBaseService {
/** /**
* 构建任务订单明细写入行。 * 构建任务订单明细写入行。
* *
* box_no 与 wms_order_wave_index.wave_index 保持一致(波次内全局顺序)。
* 若 waveIndexMap 中无对应记录,则退化为当前订单在 selectedOrderIds 中的 index + 1。
*
* @param {Object} options 构建参数。 * @param {Object} options 构建参数。
* @param {number} options.taskId 任务ID。 * @param {number} options.taskId 任务ID。
* @param {Object} options.plan 预处理计划。 * @param {Object} options.plan 预处理计划。
* @param {Array<number>} options.selectedWaveIds 已选波次ID。 * @param {Array<number>} options.selectedWaveIds 已选波次ID。
* @param {Array<number>} options.selectedOrderIds 已选订单ID。 * @param {Array<number>} options.selectedOrderIds 已选订单ID。
* @param {number} options.cartId 绑定车ID。 * @param {number} options.cartId 绑定车ID。
* @param {Map<number, number>} [options.waveIndexMap] orderId → wave_index 映射。
* @return {Array<Object>} 任务订单行。 * @return {Array<Object>} 任务订单行。
*/ */
buildTaskOrderRows(options = {}) { buildTaskOrderRows(options = {}) {
@ -11331,25 +11285,18 @@ class WaveService extends OrderBaseService {
? options.selectedOrderIds ? options.selectedOrderIds
: []; : [];
const cartId = Number(options && options.cartId || 0); const cartId = Number(options && options.cartId || 0);
const waveIndexMap = options && options.waveIndexMap instanceof Map
? options.waveIndexMap
: new Map();
if (![ 2, 3, 4 ].includes(pickMode)) { if (![ 2, 3, 4 ].includes(pickMode)) {
return []; return [];
} }
const defaultWaveId = selectedWaveIds.length > 0 ? selectedWaveIds[0] : null; const defaultWaveId = selectedWaveIds.length > 0 ? selectedWaveIds[0] : null;
return selectedOrderIds.map((orderId, index) => { return selectedOrderIds.map((orderId, index) => ({
const waveIndex = waveIndexMap.has(orderId)
? Number(waveIndexMap.get(orderId) || 0)
: 0;
return {
task_id: taskId, task_id: taskId,
wave_id: defaultWaveId, wave_id: defaultWaveId,
order_id: orderId, order_id: orderId,
order_no: null, order_no: null,
box_no: waveIndex > 0 ? waveIndex : (index + 1), box_no: index + 1,
cart_id: cartId > 0 ? cartId : null, cart_id: cartId > 0 ? cartId : null,
cart_code_snapshot: null, cart_code_snapshot: null,
warehouse_id: warehouseId, warehouse_id: warehouseId,
@ -11361,8 +11308,7 @@ class WaveService extends OrderBaseService {
exception_reason: null, exception_reason: null,
picked_time: null, picked_time: null,
review_time: null, review_time: null,
}; }));
});
} }
/** /**

View File

@ -258,52 +258,16 @@ class PickService extends MainService {
); );
if (normalizedOrderIds.length > 0) { if (normalizedOrderIds.length > 0) {
// 查询波次索引(wave_index),使 box_no 与 wms_order_wave_index.wave_index 一致
const waveIndexMap = new Map();
try {
const waveIndexRows = await ctx.model.query(
`SELECT order_id, wave_index
FROM wms_order_wave_index
WHERE warehouse_id = :warehouseId
AND wave_id = :waveId
AND order_id IN (:orderIds)`,
{
replacements: {
warehouseId,
waveId,
orderIds: normalizedOrderIds,
},
type: ctx.model.QueryTypes.SELECT,
transaction,
}
);
for (const wr of (Array.isArray(waveIndexRows) ? waveIndexRows : [])) {
const wrOrderId = Number(wr && wr.order_id || 0);
if (wrOrderId > 0) {
waveIndexMap.set(wrOrderId, Number(wr.wave_index || 0));
}
}
} catch (e) {
ctx.logger.warn('[pick.createWavePickTask] 查询波次索引失败,box_no 将退化为任务内序号', {
error: e && e.message,
warehouseId,
waveId,
});
}
const orderValuesSql = []; const orderValuesSql = [];
const orderReplacements = {}; const orderReplacements = {};
normalizedOrderIds.forEach((orderId, index) => { normalizedOrderIds.forEach((orderId, index) => {
const orderIdKey = `orderId${index}`; const orderIdKey = `orderId${index}`;
const orderNoKey = `orderNo${index}`; const orderNoKey = `orderNo${index}`;
const boxNoKey = `boxNo${index}`;
const waveIndex = waveIndexMap.get(orderId);
orderValuesSql.push(`( orderValuesSql.push(`(
:taskId, :taskId,
:waveId, :waveId,
:${orderIdKey}, :${orderIdKey},
:${orderNoKey}, :${orderNoKey},
:${boxNoKey},
:warehouseId, :warehouseId,
0, 0,
0, 0,
@ -312,7 +276,6 @@ class PickService extends MainService {
)`); )`);
orderReplacements[orderIdKey] = orderId; orderReplacements[orderIdKey] = orderId;
orderReplacements[orderNoKey] = orderNoMap.get(orderId) || ''; orderReplacements[orderNoKey] = orderNoMap.get(orderId) || '';
orderReplacements[boxNoKey] = Number.isFinite(waveIndex) && waveIndex > 0 ? waveIndex : (index + 1);
}); });
await ctx.model.query( await ctx.model.query(
@ -322,7 +285,6 @@ class PickService extends MainService {
wave_id, wave_id,
order_id, order_id,
order_no, order_no,
box_no,
warehouse_id, warehouse_id,
pick_status, pick_status,
review_status, review_status,

View File

@ -971,18 +971,6 @@ class PrintService extends MainService {
printIds: Array.isArray(expressSendResult.printIds) ? expressSendResult.printIds : [], printIds: Array.isArray(expressSendResult.printIds) ? expressSendResult.printIds : [],
}); });
} }
// 异步检查是否需要解绑拣货车(不阻塞返回)
const expressWaveIds = this.extractUniqueWaveIds(data.waveGroups);
for (const wid of expressWaveIds) {
this.tryUnbindCartAfterPrintComplete(wid).catch(err => {
this.ctx.logger.error('[print.send] 异步解绑车标异常', {
waveId: wid,
warehouseId,
error: err && err.message ? err.message : `${err}`,
});
});
}
this.ctx.logger.info('[print.send] 最终返回 success', { this.ctx.logger.info('[print.send] 最终返回 success', {
warehouseId, warehouseId,
type, type,
@ -1206,23 +1194,6 @@ class PrintService extends MainService {
return Array.from(platformCodeSet); return Array.from(platformCodeSet);
} }
/**
* 从 waveGroups 中提取去重后的 wave_id 列表。
* @param {Array<Object>} waveGroups 波次分组数据。
* @return {Array<number>} 去重后的波次ID列表。
*/
extractUniqueWaveIds(waveGroups = []) {
const normalizedWaveGroups = Array.isArray(waveGroups) ? waveGroups : [];
const waveIdSet = new Set();
for (const waveGroup of normalizedWaveGroups) {
const waveId = Number(waveGroup && waveGroup.wave_id || 0);
if (Number.isInteger(waveId) && waveId > 0) {
waveIdSet.add(waveId);
}
}
return Array.from(waveIdSet);
}
/** /**
* 从波次平台数据中提取订单ID列表。 * 从波次平台数据中提取订单ID列表。
* *
@ -2779,68 +2750,6 @@ class PrintService extends MainService {
return this.success('success', { data: null, code: 0 }); return this.success('success', { data: null, code: 0 });
} }
async tryUnbindCartAfterPrintComplete(waveId, warehouseId) {
const { ctx } = this;
const resolvedWarehouseId = Number(warehouseId || ctx.user && ctx.user.store_id || 0);
let taskId = 0;
let waveType = 0;
try {
const waveBatch = await ctx.model.WaveBatch.findOne({ where: { wave_id: waveId }, attributes: [ 'wave_type' ], raw: true });
if (!waveBatch) return;
waveType = Number(waveBatch.wave_type);
if (![ 1, 2 ].includes(waveType)) return;
const taskWaveRows = await ctx.model.query(
'SELECT task_id FROM wms_wave_pick_task_wave WHERE wave_id = :waveId AND warehouse_id = :warehouseId LIMIT 1',
{ replacements: { waveId, warehouseId: resolvedWarehouseId }, type: ctx.model.QueryTypes.SELECT }
);
const taskWave = Array.isArray(taskWaveRows) && taskWaveRows.length > 0 ? taskWaveRows[0] : null;
if (!taskWave || !taskWave.task_id) return;
taskId = Number(taskWave.task_id);
if (!taskId) return;
if (waveType === 1) {
const taskRows = await ctx.model.query(
'SELECT pick_mode FROM wms_wave_pick_task WHERE id = :taskId LIMIT 1',
{ replacements: { taskId }, type: ctx.model.QueryTypes.SELECT }
);
const task = Array.isArray(taskRows) && taskRows.length > 0 ? taskRows[0] : null;
const pickMode = task ? Number(task.pick_mode) : 0;
if (pickMode !== 1) return;
}
// 团购 / 散单统一按订单维度检查:所有订单均已打印时才解绑
const taskOrders = await ctx.model.query(
'SELECT DISTINCT order_id FROM wms_wave_pick_task_order WHERE task_id = :taskId',
{ replacements: { taskId }, type: ctx.model.QueryTypes.SELECT }
);
const orderIds = (Array.isArray(taskOrders) ? taskOrders : []).map(r => Number(r && r.order_id)).filter(id => id > 0);
if (orderIds.length === 0) return;
const orderDeliveryFactory = ctx.model && ctx.model.OrderDeliveryFactory;
if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') {
this.ctx.logger.warn('[print.unbindCart] OrderDeliveryFactory 不可用,跳过检查');
return;
}
const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(resolvedWarehouseId);
const unprintedCount = await orderDeliveryModel.count({
where: { id: { [ctx.model.Sequelize.Op.in]: orderIds }, print_status: 'none' },
});
if (unprintedCount > 0) {
this.ctx.logger.info('[print.unbindCart] 尚有未打印订单,跳过解绑', { waveId, warehouseId, taskId, waveType, waveTypeLabel: waveType === 1 ? '团购' : '散单', totalOrders: orderIds.length, unprintedCount });
return;
}
const operator = this.getPrintOrderOperationOperator();
const unbindUserId = operator.id || null;
await ctx.model.query(
'UPDATE wms_pick_task_cart_binding SET is_active = 0, unbind_user_id = :unbindUserId, unbind_time = NOW(), update_time = NOW() WHERE task_id = :taskId AND is_active = 1',
{ replacements: { taskId, unbindUserId } }
);
this.ctx.logger.info('[print.unbindCart] 车标解绑成功', { waveId, warehouseId: resolvedWarehouseId, taskId, waveType, waveTypeLabel: waveType === 1 ? '团购' : '散单', unbindUserId });
} catch (error) {
this.ctx.logger.error('[print.unbindCart] 解绑车标检查异常', { waveId, warehouseId: resolvedWarehouseId, taskId, waveType, error: error && error.message ? error.message : String(error) });
}
}
} }
module.exports = PrintService; module.exports = PrintService;

View File

@ -119,125 +119,7 @@ class expressInterfaceService extends MainService {
}, },
}); });
const result = await this.callSystemExpressInterface('list', payload, '获取快递接口列表失败'); return await this.callSystemExpressInterface('list', payload, '获取快递接口列表失败');
if (result.flag !== 'success') {
return result;
}
const list = result.data?.list || result.list || [];
if (list.length === 0) {
return result;
}
// 收集唯一 shop_id(去重)
const shopIds = [...new Set(
list
.map(item => item.shop_id)
.filter(id => id !== null && id !== undefined && Number(id) !== 0)
)];
if (shopIds.length === 0) {
const defaultList = list.map(item => ({ ...item, quantity: 0, recycled_quantity: 0, cancel_quantity: 0, allocated_quantity: 0 }));
if (result.data) {
result.data.list = defaultList;
} else {
result.list = defaultList;
}
return result;
}
const { ctx } = this;
// 并行调用 getShopExpressList,构建 Map<shopId, expressList>
const shopExpressMap = new Map();
const shopResults = await Promise.all(
shopIds.map(async (shopId) => {
try {
const shopExpressResult = await ctx.service.systemMethods.index.getShopExpressList({
shop_id: shopId,
});
return { shopId: Number(shopId), result: shopExpressResult };
} catch (err) {
ctx.logger.warn(
`[expressInterface.list] 获取店铺 ${shopId} 快递签约数据异常: ${err.message}`
);
return { shopId: Number(shopId), result: null };
}
})
);
for (const { shopId, result: shopResult } of shopResults) {
ctx.logger.info('[expressInterface.list] shopId=' + shopId + ' flag=' + (shopResult ? shopResult.flag : 'null') + ' msg=' + (shopResult ? shopResult.message : 'null'));
if (shopResult && shopResult.flag === 'success') {
const shopExpressList = shopResult.data?.list || shopResult.list || [];
if (shopExpressList.length > 0) {
shopExpressMap.set(shopId, shopExpressList);
}
}
}
// 为每条记录匹配并汇总 quantity
const enrichedList = list.map(item => {
const shopId = item.shop_id;
if (shopId === null || shopId === undefined) {
return { ...item, quantity: 0, recycled_quantity: 0, cancel_quantity: 0, allocated_quantity: 0 };
}
const shopExpressList = shopExpressMap.get(Number(shopId));
if (!shopExpressList || shopExpressList.length === 0) {
return { ...item, quantity: 0, recycled_quantity: 0, cancel_quantity: 0, allocated_quantity: 0 };
}
const sysExpressCode = (item.sys_express_code || '').trim().toUpperCase();
const expressCode = (item.express_code || '').trim().toUpperCase();
// 按 sys_express_code 或 express_code(wp_code) 匹配
const matchedExpress = shopExpressList.find(expressItem => {
const itemSysCode = (expressItem.sys_express_code || '').trim().toUpperCase();
const itemWpCode = (expressItem.wp_code || '').trim().toUpperCase();
return itemSysCode === sysExpressCode
|| itemWpCode === expressCode
|| itemSysCode === expressCode;
});
if (!matchedExpress) {
return { ...item, quantity: 0, recycled_quantity: 0, cancel_quantity: 0, allocated_quantity: 0 };
}
let accounts = Array.isArray(matchedExpress.accounts) ? matchedExpress.accounts : [];
// 若有 site_code,进一步按 branch_code 筛选匹配的网点账号
const siteCode = (item.site_code || '').trim().toUpperCase();
if (siteCode) {
const branchMatched = accounts.filter(acc =>
(acc.branch_code || '').trim().toUpperCase() === siteCode
);
if (branchMatched.length > 0) {
accounts = branchMatched;
}
}
// 若有 shipperno,进一步按 customer_code_list 筛选匹配的账号
const shipperNo = (item.shipperno || '').trim();
if (shipperNo && accounts.length > 0) {
const shipperMatched = accounts.filter(acc =>
Array.isArray(acc.customer_code_list) && acc.customer_code_list.includes(shipperNo)
);
if (shipperMatched.length > 0) {
accounts = shipperMatched;
}
}
return { ...item, quantity: accounts.reduce((sum, acc) => sum + (Number(acc.quantity) || 0), 0), recycled_quantity: accounts.reduce((sum, acc) => sum + (Number(acc.recycled_quantity) || 0), 0), cancel_quantity: accounts.reduce((sum, acc) => sum + (Number(acc.cancel_quantity) || 0), 0), allocated_quantity: accounts.reduce((sum, acc) => sum + (Number(acc.allocated_quantity) || 0), 0) };
});
if (result.data) {
result.data.list = enrichedList;
} else {
result.list = enrichedList;
}
return result;
} }
/** /**

View File

@ -1,210 +0,0 @@
'use strict';
const MainService = require('../main');
/**
* 店铺-快递绑定策略 methods 出口。
*
* 支持以下 method 调用(通过 /system?method=storeExpressBindingPolicy.xxx):
* - storeExpressBindingPolicy.list 分页查询策略列表
* - storeExpressBindingPolicy.add 新增策略
* - storeExpressBindingPolicy.edit 编辑策略
* - storeExpressBindingPolicy.del 软删除策略
*/
class StoreExpressBindingPolicyMethodService extends MainService {
/**
* 初始化鉴权配置。
* @param {Egg.Context} ctx 上下文对象
*/
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = '';
const _noNeedLog = '*';
const _noNeedAuth = '';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 统一调用业务服务。
* @param {string} methodName 业务方法名
* @param {Object} data 请求参数
* @param {string} fallbackMessage 默认错误文案
* @return {Promise<Object>} methods 标准返回
*/
async callSystem(methodName, data, fallbackMessage) {
const { service } = this;
try {
const result = await service.systems.storeExpressBindingPolicy[methodName](data);
return this.success('ok', { data: result, code: 200 });
} catch (error) {
return this.fail(error.message || fallbackMessage, {
code: Number(error.code) || 500,
});
}
}
/**
* storeExpressBindingPolicy.list:分页查询策略列表。
* @param {Object} [data={}] 请求参数
* @return {Promise<Object>} 查询结果
*/
async list(data = {}) {
const payload = {
...(data && typeof data === 'object' ? data : {}),
};
this.prepareWhereContext(payload, {
specialFieldMap: this.service.systems.storeExpressBindingPolicy.getListWhereSpecialFieldMap(),
});
return await this.callSystem('list', payload, '查询策略列表失败');
}
/**
* storeExpressBindingPolicy.add:新增策略。
* @param {Object} [data={}] 请求参数
* @return {Promise<Object>} 新增结果
*/
async add(data = {}) {
const {
custom_name: customName,
customName: customNameCamel,
express_code: expressCode,
expressCode: expressCodeCamel,
priority,
is_enabled: isEnabled,
isEnabled: isEnabledCamel,
regions,
shop_name: shopName,
store_ids: storeIds,
exclude_regions: excludeRegions,
min_weight_g: minWeightG,
max_weight_g: maxWeightG,
weight_type: weightType,
prohibited_type_id: prohibitedTypeId,
prohibitedTypeId: prohibitedTypeIdCamel,
remark,
creator_id: creatorId,
creatorId: creatorIdCamel,
} = data || {};
return await this.callSystem('add', {
custom_name: customName !== undefined ? customName : customNameCamel,
express_code: expressCode !== undefined ? expressCode : expressCodeCamel,
priority,
is_enabled: isEnabled !== undefined ? isEnabled : isEnabledCamel,
regions,
shop_name: shopName,
store_ids: storeIds,
exclude_regions: excludeRegions,
min_weight_g: minWeightG,
max_weight_g: maxWeightG,
weight_type: weightType,
prohibited_type_id: prohibitedTypeId !== undefined ? prohibitedTypeId : prohibitedTypeIdCamel,
remark,
creator_id: creatorId !== undefined ? creatorId : creatorIdCamel,
}, '新增策略失败');
}
/**
* storeExpressBindingPolicy.edit:编辑策略。
* @param {Object} [data={}] 请求参数
* @return {Promise<Object>} 编辑结果
*/
async edit(data = {}) {
const {
id,
policy_id: policyId,
policyId: policyIdCamel,
custom_name: customName,
customName: customNameCamel,
express_code: expressCode,
expressCode: expressCodeCamel,
priority,
is_enabled: isEnabled,
isEnabled: isEnabledCamel,
regions,
shop_name: shopName,
store_ids: storeIds,
exclude_regions: excludeRegions,
min_weight_g: minWeightG,
max_weight_g: maxWeightG,
weight_type: weightType,
prohibited_type_id: prohibitedTypeId,
prohibitedTypeId: prohibitedTypeIdCamel,
remark,
creator_id: creatorId,
creatorId: creatorIdCamel,
} = data || {};
const payload = {
id: id !== undefined ? id : (policyId !== undefined ? policyId : policyIdCamel),
};
if (customName !== undefined || customNameCamel !== undefined) {
payload.custom_name = customName !== undefined ? customName : customNameCamel;
}
if (expressCode !== undefined || expressCodeCamel !== undefined) {
payload.express_code = expressCode !== undefined ? expressCode : expressCodeCamel;
}
if (priority !== undefined) {
payload.priority = priority;
}
if (isEnabled !== undefined || isEnabledCamel !== undefined) {
payload.is_enabled = isEnabled !== undefined ? isEnabled : isEnabledCamel;
}
if (regions !== undefined) {
payload.regions = regions;
}
if (shopName !== undefined) {
payload.shop_name = shopName;
}
if (storeIds !== undefined) {
payload.store_ids = storeIds;
}
if (excludeRegions !== undefined) {
payload.exclude_regions = excludeRegions;
}
if (minWeightG !== undefined) {
payload.min_weight_g = minWeightG;
}
if (maxWeightG !== undefined) {
payload.max_weight_g = maxWeightG;
}
if (weightType !== undefined) {
payload.weight_type = weightType;
}
if (prohibitedTypeId !== undefined || prohibitedTypeIdCamel !== undefined) {
payload.prohibited_type_id = prohibitedTypeId !== undefined ? prohibitedTypeId : prohibitedTypeIdCamel;
}
if (remark !== undefined) {
payload.remark = remark;
}
if (creatorId !== undefined || creatorIdCamel !== undefined) {
payload.creator_id = creatorId !== undefined ? creatorId : creatorIdCamel;
}
return await this.callSystem('edit', payload, '编辑策略失败');
}
/**
* storeExpressBindingPolicy.del:软删除策略。
* @param {Object} [data={}] 请求参数
* @return {Promise<Object>} 删除结果
*/
async del(data = {}) {
const {
id,
policy_id: policyId,
policyId: policyIdCamel,
} = data || {};
return await this.callSystem('del', {
id: id !== undefined ? id : (policyId !== undefined ? policyId : policyIdCamel),
}, '删除策略失败');
}
}
module.exports = StoreExpressBindingPolicyMethodService;

View File

@ -22,7 +22,6 @@ const ORDER_OPERATION_CODES = Object.freeze({
CREATE: 'ORDER_CREATE', CREATE: 'ORDER_CREATE',
PLATFORM_FALLBACK: 'ORDER_PLATFORM_FALLBACK', PLATFORM_FALLBACK: 'ORDER_PLATFORM_FALLBACK',
EXPRESS_FALLBACK: 'ORDER_EXPRESS_FALLBACK', EXPRESS_FALLBACK: 'ORDER_EXPRESS_FALLBACK',
EXPRESS_POLICY_MATCH: 'ORDER_EXPRESS_POLICY_MATCH',
}); });
const STORE_SUBJECT_CONFIG_CACHE_TTL_SECONDS = 600; const STORE_SUBJECT_CONFIG_CACHE_TTL_SECONDS = 600;
@ -515,12 +514,11 @@ class DeliveryOrderService extends Service {
|| '' || ''
).trim(); ).trim();
const fallbackExpress = this.findCodeOption(expressList, defaultCode) const fallbackExpress = this.findCodeOption(expressList, defaultCode);
|| this.findCodeOption(expressList, DEFAULT_STORE_SUBJECT_CONFIG.default_express_code);
const fallbackLogisticsCode = String( const fallbackLogisticsCode = String(
fallbackExpress && (fallbackExpress.code || fallbackExpress.value || fallbackExpress.express_code || defaultCode || DEFAULT_STORE_SUBJECT_CONFIG.default_express_code) fallbackExpress && (fallbackExpress.code || fallbackExpress.value || fallbackExpress.express_code || defaultCode)
|| defaultCode || defaultCode
|| DEFAULT_STORE_SUBJECT_CONFIG.default_express_code || ''
).trim(); ).trim();
const fallbackLogisticsName = this.getOptionName(fallbackExpress); const fallbackLogisticsName = this.getOptionName(fallbackExpress);
const explicitEnableExternalExpressCode = info && Object.prototype.hasOwnProperty.call(info, 'enableExternalExpressCode') const explicitEnableExternalExpressCode = info && Object.prototype.hasOwnProperty.call(info, 'enableExternalExpressCode')
@ -538,7 +536,6 @@ class DeliveryOrderService extends Service {
logisticsName: fallbackLogisticsName, logisticsName: fallbackLogisticsName,
sysLogisticsCode: fallbackLogisticsCode, sysLogisticsCode: fallbackLogisticsCode,
sysLogisticsName: fallbackLogisticsName, sysLogisticsName: fallbackLogisticsName,
weightType: 0,
}; };
} }
@ -557,7 +554,6 @@ class DeliveryOrderService extends Service {
logisticsName: String(expressSetting.name || '').trim(), logisticsName: String(expressSetting.name || '').trim(),
sysLogisticsCode: matchedSysLogisticsCode, sysLogisticsCode: matchedSysLogisticsCode,
sysLogisticsName: matchedSysLogisticsName, sysLogisticsName: matchedSysLogisticsName,
weightType: 0,
}; };
} }
@ -574,7 +570,6 @@ class DeliveryOrderService extends Service {
logisticsName: matchedLogisticsName, logisticsName: matchedLogisticsName,
sysLogisticsCode: matchedLogisticsCode, sysLogisticsCode: matchedLogisticsCode,
sysLogisticsName: matchedLogisticsName, sysLogisticsName: matchedLogisticsName,
weightType: 0,
}; };
} }
if (fallbackExpress) { if (fallbackExpress) {
@ -597,7 +592,6 @@ class DeliveryOrderService extends Service {
logisticsName: fallbackLogisticsName, logisticsName: fallbackLogisticsName,
sysLogisticsCode: fallbackLogisticsCode, sysLogisticsCode: fallbackLogisticsCode,
sysLogisticsName: fallbackLogisticsName, sysLogisticsName: fallbackLogisticsName,
weightType: 0,
}; };
} }
@ -614,7 +608,6 @@ class DeliveryOrderService extends Service {
logisticsName: fallbackLogisticsName, logisticsName: fallbackLogisticsName,
sysLogisticsCode: fallbackLogisticsCode, sysLogisticsCode: fallbackLogisticsCode,
sysLogisticsName: fallbackLogisticsName, sysLogisticsName: fallbackLogisticsName,
weightType: 0,
}; };
} }
@ -735,110 +728,6 @@ class DeliveryOrderService extends Service {
updated_at: new Date(), updated_at: new Date(),
}; };
// ===== 快递绑定策略漏斗匹配(items 处理后 weight 可用) =====
try {
const receiverInfo = deliveryOrder.receiverInfo;
const shopNick = deliveryOrder.shopNick;
const hasEnoughData = shopNick || (receiverInfo && (receiverInfo.province || receiverInfo.city));
if (hasEnoughData) {
const address = [
receiverInfo?.province || '',
receiverInfo?.city || '',
receiverInfo?.area || '',
receiverInfo?.town || '',
receiverInfo?.detail_address || '',
].join('').trim();
const matchResult = await ctx.service.systems.expressPolicy.matchPolicy(
info.warehouseId,
{
storeId: info.storeId,
customShopName: shopNick || '',
address: address || '',
weight: itemsInfo.total_weight || null,
prohibitedTypeIds: null, // TODO: 后续从商品 StockWarehouse.prohibited_id 聚合
}
);
if (matchResult && matchResult.expressCode) {
const expressList = await ctx.service.systems.express.getExpressList();
const matchedExpress = expressList.find(
item => item && String(item.code || item.value || '').trim() === String(matchResult.expressCode).trim()
);
let logisticsCode;
let logisticsName;
let sysLogisticsCode;
let sysLogisticsName;
if (matchedExpress) {
if (matchedExpress.is_system_setting) {
// 自定义映射:sys 写映射的系统快递,logistics 写自定义编码
sysLogisticsCode = String(matchedExpress.express_code || '').trim();
const sysItem = expressList.find(
item => item && !item.is_system_setting && String(item.code || item.value || '').trim() === sysLogisticsCode
);
sysLogisticsName = sysItem ? String(sysItem.name || sysItem.label || sysLogisticsCode).trim() : sysLogisticsCode;
logisticsCode = String(matchedExpress.code || matchedExpress.value || matchResult.expressCode).trim();
logisticsName = String(matchedExpress.alias || matchedExpress.name || logisticsCode).trim();
} else {
// 系统快递:4 字段一致
logisticsCode = String(matchedExpress.code || matchedExpress.value || matchResult.expressCode).trim();
logisticsName = String(matchedExpress.name || matchedExpress.label || logisticsCode).trim();
sysLogisticsCode = logisticsCode;
sysLogisticsName = logisticsName;
}
} else {
// 未在列表中,fallback
logisticsCode = String(matchResult.expressCode).trim();
logisticsName = logisticsCode;
sysLogisticsCode = logisticsCode;
sysLogisticsName = logisticsCode;
}
stats.logistics_code = logisticsCode;
stats.logistics_name = logisticsName;
stats.sys_logistics_code = sysLogisticsCode;
stats.sys_logistics_name = sysLogisticsName;
stats.weight_type = matchResult.weightType;
stats.updated_at = new Date();
// 写入操作日志:命中了哪条策略
this.appendOrderOperationLog(
operationLogs,
ORDER_OPERATION_CODES.EXPRESS_POLICY_MATCH,
`快递策略命中: ${matchResult.policyName || '未知'}(${matchResult.policyId || '?'}) → ${sysLogisticsName || sysLogisticsCode}`
);
ctx.logger.info('[ExpressPolicyMatch] 策略命中(延迟匹配)', {
orderId,
orderCode: deliveryOrder.deliveryOrderCode,
logisticsCode,
sysLogisticsCode,
weightType: matchResult.weightType,
policyName: matchResult.policyName,
policyId: matchResult.policyId,
totalWeight: itemsInfo.total_weight,
});
} else if (hasEnoughData) {
// 策略未命中:记快递降级日志(取已落库的初始快递值)
const fallbackCode = orderData.sys_logistics_code || orderData.logistics_code;
const fallbackName = orderData.sys_logistics_name || orderData.logistics_name;
this.appendOrderOperationLog(
operationLogs,
ORDER_OPERATION_CODES.EXPRESS_FALLBACK,
`未命中快递策略,使用默认快递: ${fallbackName || fallbackCode}`
);
}
}
} catch (policyErr) {
ctx.logger.warn('[ExpressPolicyMatch] 策略匹配异常,跳过', {
orderId,
error: policyErr.message,
});
}
await DeliveryModel.update( await DeliveryModel.update(
stats, stats,
{ {
@ -1215,7 +1104,6 @@ class DeliveryOrderService extends Service {
sys_logistics_code: expressSnapshot.sysLogisticsCode, sys_logistics_code: expressSnapshot.sysLogisticsCode,
sys_logistics_name: expressSnapshot.sysLogisticsName, sys_logistics_name: expressSnapshot.sysLogisticsName,
express_code: expressCode || '', express_code: expressCode || '',
weight_type: expressSnapshot.weightType ?? 0,
logistics_area_code: logisticsAreaCode || '', logistics_area_code: logisticsAreaCode || '',
is_urgency: isUrgency || 'N', is_urgency: isUrgency || 'N',
invoice_flag: invoiceFlag || 'N', invoice_flag: invoiceFlag || 'N',

View File

@ -1797,8 +1797,6 @@ class ExpressService extends Service {
sys_platform_code: sysPlatformCode, sys_platform_code: sysPlatformCode,
print_platform_code: printPlatformCode, print_platform_code: printPlatformCode,
logistics_code: logisticsCode, logistics_code: logisticsCode,
sys_logistics_code: String(order.sys_logistics_code || '').trim(),
weight_type: order.weight_type !== undefined ? Number(order.weight_type) : 0,
sys_platform_name: order.sys_platform_name || '', sys_platform_name: order.sys_platform_name || '',
logistics_name: order.logistics_name || '', logistics_name: order.logistics_name || '',
store_id: order.store_id || 0, store_id: order.store_id || 0,
@ -1856,16 +1854,10 @@ class ExpressService extends Service {
&& groupedOrder.options && groupedOrder.options
&& groupedOrder.options.logistics_code && groupedOrder.options.logistics_code
); );
const sysLogisticsCode = normalizeCode(
groupedOrder if (!logisticsCode) {
&& groupedOrder.options return null;
&& groupedOrder.options.sys_logistics_code }
);
const orderWeightType = Number(
groupedOrder
&& groupedOrder.options
&& groupedOrder.options.weight_type
) || 0;
const platformCode = normalizeCode( const platformCode = normalizeCode(
groupedOrder groupedOrder
@ -1879,46 +1871,29 @@ class ExpressService extends Service {
&& matchedPlatform.print_platform_code && matchedPlatform.print_platform_code
); );
const enabledList = (Array.isArray(interfaceList) ? interfaceList : []) for (const item of Array.isArray(interfaceList) ? interfaceList : []) {
.filter(item => item && typeof item === 'object' && Number(item.is_enabled) === 1); if (!item || typeof item !== 'object') {
continue;
// 通用匹配函数
const matchByCode = (item, targetCode, useSysCode = true) => {
if (!targetCode) return false;
const candidateCodes = [ normalizeCode(item.express_code) ];
if (useSysCode) {
candidateCodes.push(normalizeCode(item.sys_express_code));
} }
// 停用的快递接口不允许分配运单号
if (Number(item.is_enabled) !== 1) {
continue;
}
const candidateCodes = [
normalizeCode(item.sys_express_code),
normalizeCode(item.express_code),
];
const expressMap = item.express && typeof item.express === 'object' ? item.express : null; const expressMap = item.express && typeof item.express === 'object' ? item.express : null;
if (expressMap && platformCode) { if (expressMap && platformCode) {
candidateCodes.push(normalizeCode(expressMap[platformCode])); candidateCodes.push(normalizeCode(expressMap[platformCode]));
} }
if (!candidateCodes.some(code => code && code === targetCode)) return false;
const itemWeightType = item.weight_type !== null && item.weight_type !== undefined if (candidateCodes.some(code => code && code === logisticsCode)) {
? Number(item.weight_type) : null;
if (itemWeightType !== null && itemWeightType !== orderWeightType) return false;
return true;
};
// 第一步:logistics_code 仅匹配 express_code + 平台码(不用 sys_express_code)
if (logisticsCode) {
for (const item of enabledList) {
if (matchByCode(item, logisticsCode, false)) {
return item; return item;
} }
} }
}
// 第二步:sys_logistics_code 匹配 sys_express_code + express_code(全放开)
if (sysLogisticsCode) {
for (const item of enabledList) {
if (matchByCode(item, sysLogisticsCode, true)) {
return item;
}
}
}
return null; return null;
} }
@ -2660,8 +2635,6 @@ class ExpressService extends Service {
printPlatformCode: groupedOrder.options.print_platform_code, printPlatformCode: groupedOrder.options.print_platform_code,
expressInterfacePlatformCode, expressInterfacePlatformCode,
logisticsCode: groupedOrder.options.logistics_code, logisticsCode: groupedOrder.options.logistics_code,
sysLogisticsCode: groupedOrder.options.sys_logistics_code,
weightType: groupedOrder.options.weight_type,
matchedPlatformCode: matchedPlatformWithRequestCode && matchedPlatformWithRequestCode.code, matchedPlatformCode: matchedPlatformWithRequestCode && matchedPlatformWithRequestCode.code,
requestPlatformCode: matchedPlatformWithRequestCode && matchedPlatformWithRequestCode.request_platform_code, requestPlatformCode: matchedPlatformWithRequestCode && matchedPlatformWithRequestCode.request_platform_code,
hasExpressInterface: Boolean(expressInterface), hasExpressInterface: Boolean(expressInterface),

View File

@ -1,275 +0,0 @@
'use strict';
const Service = require('egg').Service;
/**
* 快递策略内部服务。
*
* 为快递匹配链路提供策略查询能力,内置缓存加速。
* 不对外暴露 method 路由,仅供其他 service 内部调用。
*/
class ExpressPolicyService extends Service {
// -------------------- 缓存键 --------------------
/**
* 仓库维度策略列表缓存键。
* @param {number} warehouseId 仓库 ID
* @return {string} 缓存键
*/
getWarehousePolicyCacheKey(warehouseId) {
return `express_policy:warehouse:${warehouseId}`;
}
/**
* 仓库维度策略缓存过期秒数(默认 300s)。
* @return {number} 过期秒数
*/
getWarehousePolicyCacheTTL() {
return 300;
}
// -------------------- 缓存清理 --------------------
/**
* 清理指定仓库的策略缓存。
* @param {number} warehouseId 仓库 ID
* @return {Promise<void>}
*/
async clearWarehousePolicyCache(warehouseId) {
const cacheKey = this.getWarehousePolicyCacheKey(warehouseId);
if (this.app && typeof this.app.delCacheAsync === 'function') {
await this.app.delCacheAsync(cacheKey);
}
}
// -------------------- 数据查询 --------------------
/**
* 从数据库查询仓库下所有启用的策略,按优先级降序排列。
* @param {number} warehouseId 仓库 ID
* @return {Promise<Array<Object>>} 策略列表(plain object)
*/
async fetchWarehousePoliciesFromDB(warehouseId) {
const { ctx } = this;
try {
const rows = await ctx.model.StoreExpressBindingPolicy.findAll({
where: {
warehouse_id: warehouseId,
is_enabled: 1,
deleted_at: null,
},
order: [[ 'priority', 'DESC' ], [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]],
raw: true,
});
return rows;
} catch (error) {
if (ctx.logger && typeof ctx.logger.warn === 'function') {
ctx.logger.warn('[ExpressPolicyDBError]', error.message, { warehouseId });
}
return [];
}
}
// -------------------- 对外方法 --------------------
/**
* 获取仓库策略目录(缓存优先)。
*
* 查询链路:缓存命中 → 直接返回;缓存未命中 → 查库 → 写缓存 → 返回。
*
* @param {number} warehouseId 仓库 ID
* @param {Object} [options] 选项
* @param {boolean} [options.forceRefresh=false] 是否强制刷新缓存
* @return {Promise<Array<Object>>} 策略列表(按 priority DESC 排序)
*/
async getWarehousePolicies(warehouseId, options = {}) {
const { app } = this;
const { forceRefresh = false } = options;
if (!Number.isFinite(Number(warehouseId)) || Number(warehouseId) <= 0) {
return [];
}
const cacheKey = this.getWarehousePolicyCacheKey(warehouseId);
const ttl = this.getWarehousePolicyCacheTTL();
// 1) 读缓存(非强制刷新时)
if (!forceRefresh && app && typeof app.getCacheAsync === 'function') {
try {
const cached = await app.getCacheAsync(cacheKey);
if (cached && Array.isArray(cached) && cached.length > 0) {
return cached;
}
} catch (error) {
if (app.logger && typeof app.logger.warn === 'function') {
app.logger.warn('[ExpressPolicyCacheReadError]', error.message, { warehouseId });
}
}
}
// 2) 查库
const policies = await this.fetchWarehousePoliciesFromDB(warehouseId);
// 3) 写缓存
if (app && typeof app.setCacheAsync === 'function') {
try {
await app.setCacheAsync(cacheKey, policies, ttl);
} catch (error) {
if (app.logger && typeof app.logger.warn === 'function') {
app.logger.warn('[ExpressPolicyCacheWriteError]', error.message, { warehouseId });
}
}
}
return policies;
}
// -------------------- 策略匹配 --------------------
/**
* 检查 policy 中数组字段的任意值是否命中目标字符串(子串包含匹配)。
* @param {Array<string>|null} policyArray 策略中的数组字段
* @param {string} target 目标字符串(如地址、店铺名称)
* @return {boolean} 是否命中
*/
_matchAnyToken(policyArray, target) {
if (!Array.isArray(policyArray) || policyArray.length === 0) {
return true; // 未限定 = 不限制
}
const normalizedTarget = String(target || '').trim();
if (!normalizedTarget) {
return false;
}
return policyArray.some(token => {
const t = String(token || '').trim();
return t && normalizedTarget.includes(t);
});
}
/**
* 检查两个数组是否有交集。
* @param {Array<*>|null} policyArray 策略中的数组字段
* @param {Array<*>|null} inputArray 传入的数组
* @return {boolean} 是否有交集
*/
_matchAnyIntersect(policyArray, inputArray) {
if (!Array.isArray(policyArray) || policyArray.length === 0) {
return true; // 未限定 = 不限制
}
if (!Array.isArray(inputArray) || inputArray.length === 0) {
return false;
}
const policySet = new Set(policyArray.map(v => Number(v)));
return inputArray.some(v => policySet.has(Number(v)));
}
/**
* 检查传入值是否在策略数组范围内。
* @param {Array<*>|null} policyArray 策略中的数组字段
* @param {number} value 传入值
* @return {boolean} 是否命中
*/
_matchValueInArray(policyArray, value) {
if (!Array.isArray(policyArray) || policyArray.length === 0) {
return true; // 未限定 = 不限制
}
return policyArray.some(v => Number(v) === Number(value));
}
/**
* 按策略优先级漏斗筛选,返回命中策略的快递编码与重量段类型。
*
* 筛选顺序(按 priority DESC,同 priority 按 updated_at DESC):
* 1. store_ids —— 传入货主ID是否在策略限定范围内(NULL=不限)
* 2. shop_name —— 自定义店铺名称子串匹配(任意一个命中即通过)
* 3. prohibited_type_id —— 违禁品类型ID数组交集(有交集即命中)
* 4. regions —— 地址包含任意限定地区即命中
* 5. exclude_regions —— 地址包含任意排除地区则跳过该策略
* 6. min_weight_g / max_weight_g —— 重量区间
*
* @param {number} warehouseId 仓库 ID
* @param {Object} params 匹配参数
* @param {number} [params.storeId] 货主 ID
* @param {string} [params.customShopName] 自定义店铺名称
* @param {Array<number>} [params.prohibitedTypeIds] 商品违禁品类型 ID 数组
* @param {string} [params.address] 省市区详细地址(单个字符串)
* @param {number} [params.weight] 重量(克)
* @return {Promise<{expressCode: string|null, weightType: number|null}>}
*/
async matchPolicy(warehouseId, params = {}) {
const {
storeId,
customShopName,
prohibitedTypeIds,
address,
weight,
} = params;
const policies = await this.getWarehousePolicies(warehouseId);
if (!Array.isArray(policies) || policies.length === 0) {
return { expressCode: null, weightType: null };
}
for (const policy of policies) {
// 1) store_ids — 未限定(NULL)视为不限;否则传入 storeId 必须在范围内
if (!this._matchValueInArray(policy.store_ids, storeId)) {
continue;
}
// 2) shop_name — 子串包含匹配
if (!this._matchAnyToken(policy.shop_name, customShopName)) {
continue;
}
// 3) prohibited_type_id — 数组交集
if (!this._matchAnyIntersect(policy.prohibited_type_id, prohibitedTypeIds)) {
continue;
}
// 4) regions — 地址包含任意限定地区
if (!this._matchAnyToken(policy.regions, address)) {
continue;
}
// 5) exclude_regions — 地址包含任意排除地区则跳过
if (Array.isArray(policy.exclude_regions) && policy.exclude_regions.length > 0) {
const excluded = policy.exclude_regions.some(token => {
const t = String(token || '').trim();
return t && String(address || '').includes(t);
});
if (excluded) {
continue;
}
}
// 6) 重量区间
const weightNum = Number(weight);
if (Number.isFinite(weightNum)) {
if (policy.min_weight_g !== null && policy.min_weight_g !== undefined) {
if (weightNum < Number(policy.min_weight_g)) {
continue;
}
}
if (policy.max_weight_g !== null && policy.max_weight_g !== undefined) {
if (weightNum > Number(policy.max_weight_g)) {
continue;
}
}
}
// 全部通过 → 命中
return {
expressCode: policy.express_code || null,
weightType: policy.weight_type !== undefined ? policy.weight_type : 0,
policyName: policy.custom_name || null,
policyId: policy.id || null,
};
}
// 无命中
return { expressCode: null, weightType: null };
}
}
module.exports = ExpressPolicyService;

View File

@ -615,10 +615,9 @@ class OrderExportService extends OrderBaseService {
}, },
}); });
const { where: sanitizedWhere, expressNumbers } = this.extractOrderListExpressVirtualFilter(where); const { where: sanitizedWhere, expressNumbers } = this.extractOrderListExpressVirtualFilter(where);
const { where: whereAfterBuyerMessage, buyerMessageHas } = this.extractBuyerMessageHasVirtualFilter(sanitizedWhere);
const mergedWhere = this.mergeWhereObjects( const mergedWhere = this.mergeWhereObjects(
target.defaultWhereModuleName ? this.getDefaultWhere(target.defaultWhereModuleName) : {}, target.defaultWhereModuleName ? this.getDefaultWhere(target.defaultWhereModuleName) : {},
whereAfterBuyerMessage sanitizedWhere
); );
let queryWhere = this.buildWhere(mergedWhere, warehouseId, { let queryWhere = this.buildWhere(mergedWhere, warehouseId, {
specialFieldMap: { specialFieldMap: {
@ -633,11 +632,6 @@ class OrderExportService extends OrderBaseService {
queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, orderIds); queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, orderIds);
} }
if (buyerMessageHas !== null) {
const buyerMessageCondition = this.buildBuyerMessageHasCondition(buyerMessageHas);
queryWhere = this.appendConditionToWhere(queryWhere, buyerMessageCondition);
}
const orderModel = await this.getOrderModelByTableType(target.tableType, warehouseId); const orderModel = await this.getOrderModelByTableType(target.tableType, warehouseId);
const pageSize = this.getExportPageSize(); const pageSize = this.getExportPageSize();
const order = this.buildListOrder(requestData.sort, target.sortModuleName); const order = this.buildListOrder(requestData.sort, target.sortModuleName);

View File

@ -1,696 +0,0 @@
'use strict';
const Service = require('egg').Service;
/**
* 订单自定义店铺-快递绑定策略业务服务。
*/
class StoreExpressBindingPolicyService extends Service {
/**
* 获取当前仓库 ID。
* @return {number} 仓库 ID
*/
getCurrentWarehouseId() {
const warehouseId = Number(this.ctx.user && this.ctx.user.store_id);
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
throw this.createError('未识别到当前仓库', 400);
}
return warehouseId;
}
/**
* 创建业务错误。
* @param {string} message 错误信息
* @param {number} [code=500] 错误码
* @return {Error} 业务错误对象
*/
createError(message, code = 500) {
const error = new Error(message);
error.code = code;
return error;
}
/**
* 规范化字符串参数。
* @param {*} value 原始值
* @param {string} fieldName 字段名
* @param {Object} [options={}] 选项
* @return {string|null} 规范化结果
*/
normalizeText(value, fieldName, options = {}) {
const { required = false, maxLength = 255 } = options;
if (value === undefined || value === null) {
if (required) throw this.createError(`${fieldName} 不能为空`, 400);
return null;
}
const normalized = String(value).trim();
if (!normalized) {
if (required) throw this.createError(`${fieldName} 不能为空`, 400);
return null;
}
if (normalized.length > maxLength) {
throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400);
}
return normalized;
}
/**
* 规范化整数参数。
* @param {*} value 原始值
* @param {string} fieldName 字段名
* @param {Object} [options={}] 选项
* @return {number|null} 规范化结果
*/
normalizeInteger(value, fieldName, options = {}) {
const { required = false, min = null } = options;
if (value === undefined || value === null || value === '') {
if (required) throw this.createError(`${fieldName} 不能为空`, 400);
return null;
}
const normalized = Number(value);
if (!Number.isInteger(normalized)) {
throw this.createError(`${fieldName} 参数不合法`, 400);
}
if (min !== null && normalized < min) {
throw this.createError(`${fieldName} 参数不合法`, 400);
}
return normalized;
}
/**
* 规范化重量段类型。
* @param {*} value 原始值
* @return {number|null} NULL 或 0/1/2/3
*/
normalizeWeightType(value) {
if (value === undefined || value === null || value === '') return 0;
const v = Number(value);
if (![ 0, 1, 2, 3 ].includes(v)) throw this.createError('weight_type 不合法,仅支持 0/1/2/3(常规/轻货/重货/冷链)', 400);
return v;
}
/**
* 校验快递编码是否存在。
* @param {string} expressCode 快递编码
* @return {Promise<string>} 标准化快递编码
*/
normalizeJsonArray(value, fieldName) {
if (value === undefined || value === null || value === '') return null;
if (Array.isArray(value)) return value.length > 0 ? value : null;
if (typeof value === 'string') {
try { const parsed = JSON.parse(value); if (Array.isArray(parsed)) return parsed.length > 0 ? parsed : null; } catch (e) {}
}
throw this.createError(fieldName + ' 必须是字符串数组', 400);
}
async ensureExpressExists(expressCode) {
const { ctx } = this;
const normalizedCode = this.normalizeText(expressCode, 'express_code', {
required: true,
maxLength: 50,
});
// 使用合并后的快递列表(含系统快递 + 仓库自定义映射)
const expressList = await ctx.service.systems.express.getExpressList();
const found = Array.isArray(expressList)
? expressList.find(item => item && String(item.code || item.value || '').trim() === normalizedCode)
: null;
if (!found) {
throw this.createError(`快递编码 "${normalizedCode}" 不存在`, 400);
}
return normalizedCode;
}
/**
* 获取列表字段过滤映射。
* @return {Object} specialFieldMap
*/
getListWhereSpecialFieldMap() {
return {
id: { field: 'id' },
custom_name: { field: 'custom_name' },
shop_name: { field: 'shop_name' },
store_ids: { field: 'store_ids' },
express_code: { field: 'express_code' },
priority: { field: 'priority' },
is_enabled: { field: 'is_enabled' },
prohibited_type_id: { field: 'prohibited_type_id' },
regions: { field: 'regions' },
exclude_regions: { field: 'exclude_regions' },
min_weight_g: { field: 'min_weight_g' },
max_weight_g: { field: 'max_weight_g' },
weight_type: { field: 'weight_type' },
creator_id: { field: 'creator_id' },
quickWhere: { bucket: 'quick' },
};
}
/**
* 构建列表查询条件。
* @param {Object} [data={}] 请求参数
* @return {Object} where 条件
*/
buildListWhere(data = {}) {
const { app, ctx } = this;
const { Op } = app.Sequelize;
const parsedResult = ctx.whereParsed || {
dynamicConditions: [],
rawConditionsByField: {},
};
const whereAndConditions = [
{ warehouse_id: this.getCurrentWarehouseId() },
{ deleted_at: null },
];
const dynamicConditions = Array.isArray(parsedResult.dynamicConditions)
? parsedResult.dynamicConditions
: [];
if (dynamicConditions.length > 0) {
whereAndConditions.push({ [Op.and]: dynamicConditions });
}
// 快速搜索:按 custom_name 模糊匹配
const quickWhereCondition = parsedResult.rawConditionsByField
? parsedResult.rawConditionsByField.quickWhere
: null;
const quickWhereValue = quickWhereCondition && typeof quickWhereCondition === 'object'
? quickWhereCondition.value
: null;
const keyword = String(quickWhereValue || '').trim();
if (keyword) {
whereAndConditions.push({
[Op.or]: [
{ custom_name: { [Op.like]: `%${keyword}%` } },
{ express_code: { [Op.like]: `%${keyword}%` } },
],
});
}
return { [Op.and]: whereAndConditions };
}
/**
* 规范化分页参数。
* @param {Object} [data={}] 请求参数
* @return {{ page: number, pageSize: number, offset: number }}
*/
normalizePagination(data = {}) {
const pagination = data && typeof data.pagination === 'object' ? data.pagination : {};
const pageSource = pagination.page !== undefined
? pagination.page
: (data.page !== undefined ? data.page : data.currentPage);
const pageSizeSource = pagination.pageSize !== undefined
? pagination.pageSize
: (pagination.page_size !== undefined ? pagination.page_size : (data.pageSize !== undefined ? data.pageSize : data.page_size));
const page = Math.max(Number.parseInt(pageSource, 10) || 1, 1);
const pageSize = Math.min(Math.max(Number.parseInt(pageSizeSource, 10) || 20, 1), 200);
return { page, pageSize, offset: (page - 1) * pageSize };
}
/**
* 规范化策略记录输出。
* @param {Object} row 策略记录
* @return {Object} 输出结构
*/
formatPolicyRow(row) {
return {
id: row.id,
warehouse_id: row.warehouse_id,
custom_name: row.custom_name,
shop_name: row.shop_name,
store_ids: row.store_ids,
store_names: row._store_names || null,
express_code: row.express_code,
express_name: row._express_name || row.express_code || null,
priority: row.priority,
is_enabled: row.is_enabled,
prohibited_type_id: row.prohibited_type_id,
prohibited_type_names: row._prohibited_type_names || null,
regions: row.regions,
exclude_regions: row.exclude_regions,
min_weight_g: row.min_weight_g,
max_weight_g: row.max_weight_g,
weight_type: row.weight_type,
remark: row.remark,
creator_id: row.creator_id,
created_at: row.created_at,
updated_at: row.updated_at,
};
}
/**
* 查询策略分页列表。
* @param {Object} [data={}] 请求参数
* @return {Promise<Object>} 列表结果
*/
async list(data = {}) {
const { ctx } = this;
const { page, pageSize, offset } = this.normalizePagination(data);
const where = this.buildListWhere(data);
const result = await ctx.model.StoreExpressBindingPolicy.findAndCountAll({
where,
order: [[ 'priority', 'DESC' ], [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]],
offset,
limit: pageSize,
});
const rows = Array.isArray(result && result.rows) ? result.rows : [];
const plainRows = rows.map(row => (row && typeof row.get === 'function' ? row.get({ plain: true }) : row));
// 批量解析货主名称 & 违禁品名称
const allStoreIds = new Set();
const allProhibitedIds = new Set();
for (const row of plainRows) {
if (Array.isArray(row.store_ids)) {
row.store_ids.forEach(id => allStoreIds.add(id));
}
if (Array.isArray(row.prohibited_type_id)) {
row.prohibited_type_id.forEach(id => allProhibitedIds.add(id));
}
}
const storeNameMap = new Map();
if (allStoreIds.size > 0) {
const stores = await ctx.model.Store.findAll({
where: { id: [ ...allStoreIds ] },
attributes: [ 'id', 'company_name' ],
});
for (const s of stores) {
storeNameMap.set(s.id, s.company_name);
}
}
const prohibitedNameMap = new Map();
if (allProhibitedIds.size > 0) {
const types = await ctx.model.ProhibitedType.findAll({
where: { id: [ ...allProhibitedIds ] },
attributes: [ 'id', 'type_name' ],
});
for (const t of types) {
prohibitedNameMap.set(t.id, t.type_name);
}
}
// 批量解析快递名称(含系统快递 + 自定义映射)
const allExpressCodes = new Set();
for (const row of plainRows) {
if (row.express_code) allExpressCodes.add(row.express_code);
}
const expressNameMap = new Map();
if (allExpressCodes.size > 0) {
try {
const expressList = await ctx.service.systems.express.getExpressList();
for (const item of (Array.isArray(expressList) ? expressList : [])) {
const code = String(item && (item.code || item.value) || '').trim();
if (code && allExpressCodes.has(code)) {
expressNameMap.set(code, String(item.name || item.label || code).trim());
}
}
} catch (_) { /* 快递列表查询失败不影响列表 */ }
}
// 将名称数组挂到临时属性上
for (const row of plainRows) {
if (Array.isArray(row.store_ids)) {
row._store_names = row.store_ids.map(id => storeNameMap.get(id) || String(id));
}
if (Array.isArray(row.prohibited_type_id)) {
row._prohibited_type_names = row.prohibited_type_id.map(id => prohibitedNameMap.get(id) || String(id));
}
if (row.express_code) {
row._express_name = expressNameMap.get(row.express_code) || row.express_code;
}
}
const list = plainRows.map(row => this.formatPolicyRow(row));
const total = Number(result && result.count ? result.count : 0);
return {
list,
pagination: {
page,
pageSize,
total,
totalPages: pageSize > 0 ? Math.ceil(total / pageSize) : 0,
hasNext: page * pageSize < total,
hasPrevious: page > 1,
},
};
}
/**
* 校验自定义名称在同仓库下唯一(排除自身)。
* @param {Object} payload 入参
* @return {Promise<void>}
*/
async ensureCustomNameUnique(payload) {
const { ctx } = this;
const { Op } = this.app.Sequelize;
const { warehouseId, customName, excludeId = null } = payload;
const where = {
warehouse_id: warehouseId,
custom_name: customName,
deleted_at: null,
};
if (excludeId !== null) {
where.id = { [Op.ne]: excludeId };
}
const existed = await ctx.model.StoreExpressBindingPolicy.findOne({
where,
attributes: [ 'id' ],
});
if (existed) {
throw this.createError('同仓库下策略名称已存在', 409);
}
}
/**
* 新增策略。
* @param {Object} [data={}] 请求参数
* @return {Promise<Object>} 新增结果
*/
async add(data = {}) {
const { ctx } = this;
const warehouseId = this.getCurrentWarehouseId();
const customName = this.normalizeText(
data.custom_name !== undefined ? data.custom_name : data.customName,
'custom_name',
{ required: true, maxLength: 100 }
);
const expressCode = await this.ensureExpressExists(
data.express_code !== undefined ? data.express_code : data.expressCode
);
const priority = this.normalizeInteger(
data.priority !== undefined ? data.priority : 0,
'priority',
{ required: false }
);
const isEnabled = data.is_enabled !== undefined
? Number(data.is_enabled)
: (data.isEnabled !== undefined ? Number(data.isEnabled) : 1);
if (![ 0, 1 ].includes(isEnabled)) {
throw this.createError('is_enabled 参数不合法,仅支持 0 或 1', 400);
}
const regions = this.normalizeJsonArray(
data.regions !== undefined ? data.regions : null,
'regions'
);
const shopName = this.normalizeJsonArray(
data.shop_name !== undefined ? data.shop_name : data.shopName,
'shop_name'
);
const storeIds = this.normalizeJsonArray(
data.store_ids !== undefined ? data.store_ids : data.storeIds,
'store_ids'
);
const excludeRegions = this.normalizeJsonArray(
data.exclude_regions !== undefined ? data.exclude_regions : data.excludeRegions,
'exclude_regions'
);
const minWeightG = this.normalizeInteger(
data.min_weight_g !== undefined ? data.min_weight_g : data.minWeightG,
'min_weight_g'
);
const maxWeightG = this.normalizeInteger(
data.max_weight_g !== undefined ? data.max_weight_g : data.maxWeightG,
'max_weight_g'
);
const weightType = this.normalizeWeightType(
data.weight_type !== undefined ? data.weight_type : data.weightType
);
const prohibitedTypeIds = this.normalizeJsonArray(
data.prohibited_type_id !== undefined ? data.prohibited_type_id : data.prohibitedTypeId,
'prohibited_type_id'
);
const remark = this.normalizeText(
data.remark !== undefined ? data.remark : null,
'remark',
{ maxLength: 500 }
);
const creatorId = this.normalizeInteger(
data.creator_id !== undefined ? data.creator_id : data.creatorId,
'creator_id'
);
// 校验名称唯一性
await this.ensureCustomNameUnique({ warehouseId, customName });
const created = await ctx.model.StoreExpressBindingPolicy.create({
warehouse_id: warehouseId,
custom_name: customName,
express_code: expressCode,
priority: priority ?? 0,
is_enabled: isEnabled,
regions,
shop_name: shopName,
store_ids: storeIds,
exclude_regions: excludeRegions,
min_weight_g: minWeightG,
max_weight_g: maxWeightG,
weight_type: weightType,
prohibited_type_id: prohibitedTypeIds,
remark,
creator_id: creatorId,
});
// 清理当前仓库策略缓存
try {
await ctx.service.systems.expressPolicy.clearWarehousePolicyCache(warehouseId);
} catch (_) {
// 缓存清理失败不影响主流程
}
const plainRow = created && typeof created.get === 'function'
? created.get({ plain: true })
: created;
return { id: plainRow.id };
}
/**
* 读取策略并校验仓库归属。
* @param {*} policyId 策略 ID
* @return {Promise<Object>} 策略模型实例
*/
async findPolicyById(policyId) {
const { ctx } = this;
const id = this.normalizeInteger(policyId, 'id', { required: true, min: 1 });
const policy = await ctx.model.StoreExpressBindingPolicy.findOne({
where: {
id,
warehouse_id: this.getCurrentWarehouseId(),
deleted_at: null,
},
});
if (!policy) {
throw this.createError('策略不存在', 404);
}
return policy;
}
/**
* 编辑策略。
* @param {Object} [data={}] 请求参数
* @return {Promise<Object>} 编辑结果
*/
async edit(data = {}) {
const id = data.id !== undefined ? data.id : data.policy_id;
const policy = await this.findPolicyById(id);
const warehouseId = this.getCurrentWarehouseId();
const updateFields = {};
// custom_name
const customName = data.custom_name !== undefined
? data.custom_name
: (data.customName !== undefined ? data.customName : undefined);
if (customName !== undefined) {
const normalized = this.normalizeText(customName, 'custom_name', { maxLength: 100 });
if (normalized && normalized !== policy.custom_name) {
await this.ensureCustomNameUnique({
warehouseId,
customName: normalized,
excludeId: Number(policy.id),
});
}
updateFields.custom_name = normalized;
}
// express_code
const expressCode = data.express_code !== undefined
? data.express_code
: (data.expressCode !== undefined ? data.expressCode : undefined);
if (expressCode !== undefined) {
updateFields.express_code = await this.ensureExpressExists(expressCode);
}
// priority
const priority = data.priority !== undefined ? data.priority : undefined;
if (priority !== undefined) {
updateFields.priority = this.normalizeInteger(priority, 'priority');
}
// is_enabled
const isEnabled = data.is_enabled !== undefined
? data.is_enabled
: (data.isEnabled !== undefined ? data.isEnabled : undefined);
if (isEnabled !== undefined) {
const val = Number(isEnabled);
if (![ 0, 1 ].includes(val)) {
throw this.createError('is_enabled 参数不合法,仅支持 0 或 1', 400);
}
updateFields.is_enabled = val;
}
// regions
const regions = data.regions !== undefined ? data.regions : undefined;
if (regions !== undefined) {
updateFields.regions = this.normalizeJsonArray(regions, 'regions');
}
// shop_name
const shopName = data.shop_name !== undefined
? data.shop_name
: (data.shopName !== undefined ? data.shopName : undefined);
if (shopName !== undefined) {
updateFields.shop_name = this.normalizeJsonArray(shopName, 'shop_name');
}
// store_ids
const storeIds = data.store_ids !== undefined
? data.store_ids
: (data.storeIds !== undefined ? data.storeIds : undefined);
if (storeIds !== undefined) {
updateFields.store_ids = this.normalizeJsonArray(storeIds, 'store_ids');
}
// exclude_regions
const excludeRegions = data.exclude_regions !== undefined
? data.exclude_regions
: (data.excludeRegions !== undefined ? data.excludeRegions : undefined);
if (excludeRegions !== undefined) {
updateFields.exclude_regions = this.normalizeJsonArray(excludeRegions, 'exclude_regions');
}
// min_weight_g
const minWeightG = data.min_weight_g !== undefined
? data.min_weight_g
: (data.minWeightG !== undefined ? data.minWeightG : undefined);
if (minWeightG !== undefined) {
updateFields.min_weight_g = this.normalizeInteger(minWeightG, 'min_weight_g');
}
// max_weight_g
const maxWeightG = data.max_weight_g !== undefined
? data.max_weight_g
: (data.maxWeightG !== undefined ? data.maxWeightG : undefined);
if (maxWeightG !== undefined) {
updateFields.max_weight_g = this.normalizeInteger(maxWeightG, 'max_weight_g');
}
// weight_type
const weightType = data.weight_type !== undefined
? data.weight_type
: (data.weightType !== undefined ? data.weightType : undefined);
if (weightType !== undefined) {
updateFields.weight_type = this.normalizeWeightType(weightType);
}
// prohibited_type_id
const prohibitedTypeIds = data.prohibited_type_id !== undefined
? data.prohibited_type_id
: (data.prohibitedTypeId !== undefined ? data.prohibitedTypeId : undefined);
if (prohibitedTypeIds !== undefined) {
updateFields.prohibited_type_id = this.normalizeJsonArray(prohibitedTypeIds, 'prohibited_type_id');
}
// remark
const remark = data.remark !== undefined ? data.remark : undefined;
if (remark !== undefined) {
updateFields.remark = this.normalizeText(remark, 'remark', { maxLength: 500 });
}
// creator_id
const creatorId = data.creator_id !== undefined
? data.creator_id
: (data.creatorId !== undefined ? data.creatorId : undefined);
if (creatorId !== undefined) {
updateFields.creator_id = this.normalizeInteger(creatorId, 'creator_id');
}
if (Object.keys(updateFields).length === 0) {
throw this.createError('没有需要更新的字段', 400);
}
await policy.update(updateFields);
// 清理当前仓库策略缓存
try {
await this.ctx.service.systems.expressPolicy.clearWarehousePolicyCache(warehouseId);
} catch (_) {
// 缓存清理失败不影响主流程
}
const updated = policy && typeof policy.get === 'function'
? policy.get({ plain: true })
: policy;
return { id: updated.id };
}
/**
* 软删除策略。
* @param {Object} [data={}] 请求参数
* @return {Promise<Object>} 删除结果
*/
async del(data = {}) {
const id = data.id !== undefined ? data.id : data.policy_id;
const policy = await this.findPolicyById(id);
const now = new Date();
await policy.update({ deleted_at: now, is_enabled: 0 });
// 清理当前仓库策略缓存
try {
const warehouseId = Number(policy.warehouse_id);
if (warehouseId > 0) {
await this.ctx.service.systems.expressPolicy.clearWarehousePolicyCache(warehouseId);
}
} catch (_) {
// 缓存清理失败不影响主流程
}
return { id: Number(policy.id) };
}
}
module.exports = StoreExpressBindingPolicyService;

View File

@ -1,58 +0,0 @@
'use strict';
const MainService = require('../main');
/**
* 仓库开放 API — 站内信模块处理器。
* 接收仓库级外部适配器推送的 inbox.push 请求,
* 统一委托 app/service/inbox/receiver.receive 处理写库与异步推送。
*/
class WarehouseInboxService extends MainService {
/**
* 仓库 API 消息入站入口。
* warehouse_id 从验签后上下文注入,禁止外部传入。
* @param {Object} options 请求参数。
* @param {Object} options.body 请求体。
* @return {Promise<Object>} 入站结果。
*/
async push({ body = {} } = {}) {
const { ctx } = this;
const { warehouseId, appKey } = this.getInfo();
// 安全边界:warehouse_id 一律从验签后上下文获取
if (!warehouseId) {
throw new Error('缺少仓库信息');
}
// 安全边界:校验必填参数
if (!body.requestId || !String(body.requestId).trim()) {
throw new Error('requestId 不能为空');
}
if (!body.targetChannel || !String(body.targetChannel).trim()) {
throw new Error('targetChannel 不能为空');
}
// 构造 ext_id
const extId = `api:${String(appKey || 'unknown')}:${String(body.requestId).trim()}`;
// 构造入站数据并委托给 inbox receiver
const result = await ctx.service.inbox.receiver.receive({
ext_id: extId,
warehouse_id: warehouseId,
store_id: body.storeId || null,
direction: 'inbound',
parent_id: body.parentId || null,
source_type: body.sourceType || 'api',
source_extra: String(appKey || ''),
target_type: body.targetType || 'im',
target_channel: body.targetChannel,
ext_data: body.extData || null,
flags: body.flags || {},
});
return result;
}
}
module.exports = WarehouseInboxService;

View File

@ -1,441 +0,0 @@
# 站内信(Inbox)模块设计方案
> **状态**: 📋 设计中
> **设计日期**: 2026-08-03
> **设计人**: wms-test-agent
> **模块**: `app/service/inbox/`,独立文件模块
> **表**: 1 张 — `wms_inbox_message`
---
## 一、概念
消息推送状态追踪表。不重复存储消息内容(消息体由 IM 回调 / API 请求各自管理),只记录**谁发来的、要推到哪、推送状态**。收件(inbound)和回信(outbound)共表,`direction` + `parent_id` 形成对话链。
```
inbound(外部 → WMS) outbound(WMS → 外部)
┌──────────────────────┐ ┌──────────────────────┐
│ IM 回调 / API push │ │ 系统回信 / 工单通知 │
└──────────┬───────────┘ └──────────┬───────────┘
│ │
▼ ▼
┌─────────────────────────────────────────┐
│ wms_inbox_message(同一张表) │
│ │
│ direction: inbound │ outbound │
│ parent_id: NULL │ parent_id: 原消息ID │
│ │
│ "IM msg_001 → API app_10 → success" │
│ "WMS 回复 → 企微 Bot → success" │
└─────────────────────────────────────────┘
│
▼ setImmediate async push
dispatch → HTTP POST / Bot API
```
---
## 二、数据库表
### `wms_inbox_message`
| 字段 | 类型 | 必填 | 默认值 | 说明 |
|------|------|------|--------|------|
| `id` | `BIGINT UNSIGNED` | ✅ | AUTO | 主键 |
| `ext_id` | `VARCHAR(128)` | ✅ | — | **外部唯一消息主键**(IM msgId / API requestId 等),唯一索引,幂等去重 |
| `warehouse_id` | `BIGINT UNSIGNED` | ✅ | — | 所属仓库 |
| `store_id` | `BIGINT UNSIGNED` | — | NULL | 关联货主 |
| `direction` | `VARCHAR(10)` | ✅ | `inbound` | `inbound`=外部→WMS 收件 / `outbound`=WMS→外部 回信 |
| `parent_id` | `BIGINT UNSIGNED` | — | NULL | 关联消息 ID(回信时指向原消息,形成对话链) |
#### 来源 / 目标
| 字段 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `source_type` | `VARCHAR(20)` | ✅ | `im` / `api` |
| `source_extra` | `VARCHAR(100)` | — | 附加信息(IM 平台 / API app_id) |
| `target_type` | `VARCHAR(20)` | ✅ | `im` / `api` |
| `target_channel` | `VARCHAR(50)` | ✅ | 目标渠道:`wecom` / `dingtalk` / `feishu` / `warehouse_api` / `webhook` |
| `target_url` | `VARCHAR(500)` | ✅ | 推送目标 URL(IM Bot webhook 地址 / API 回调地址) |
> **安全设计**:
> - `target_url` 不含 secret。IM Bot URL 中 token 已内嵌,API 推送时 secret 从 `ApiApp.self_app_secret` 查。
> - **出站签名**:推送到仓库开放 API 时,使用与该仓库 ApiApp 相同的 MD5 签名算法(`canonicalQuery + self_app_secret + bodySign`),接收方用同一 `app_key` 验证。IM 通道则使用各自 Bot 的原生鉴权。
> **inbound vs outbound 的 source/target 语义**:
> ```
> inbound(外部→WMS):source=外部来源 target=WMS 内部要转发到的渠道
> outbound(WMS→外部):source=WMS 内部 target=要推送到的外部渠道
> ```
| `ref_code` | `VARCHAR(100)` | — | 外部引用编码,推送/回执时原样携带 |
| `ext_data` | `JSON` | — | **外部透传数据**,外部传入任意 JSON,WMS 不解析,回信时原样返回 |
| `flags` | `JSON` | — | **处理标记**,外部传入控制 WMS 处理行为,见下表 |
> **`flags` 支持的标记**:
> ```json
> {
> "skip_ai_parse": true, // 跳过智能解析(内部员工发信时设为 true)
> "skip_auto_reply": true, // 跳过自动回复
> "skip_forward": true // 仅存档,不转发
> }
> ```
> 外部不传 → 默认全部开启(智能解析 + 自动回复 + 转发)。内部系统调用 `inbox.push` 时按需关闭特定行为。
#### 推送状态
| 字段 | 类型 | 必填 | 默认值 | 说明 |
|------|------|------|--------|------|
| `push_status` | `TINYINT(4)` | ✅ | 0 | 0=待推送 1=推送中 2=已送达 3=失败 |
| `push_started_at` | `DATETIME` | — | NULL | 开始推送时间(僵尸检测:超 5 分钟仍为 1 → 重置为 0) |
| `retry_count` | `INT(11)` | ✅ | 0 | 已重试次数 |
| `push_response` | `JSON` | — | NULL | 目标响应(http_status, body, error) |
| `pushed_at` | `DATETIME` | — | NULL | 推送完成时间 |
> **防重机制**:`push_status` 字段本身即状态流转,不需要额外流转表。使用乐观锁 `UPDATE SET push_status=1 WHERE push_status=0` 保证单条消息不会被重复取走。`push_started_at` 用于进程崩溃后的僵尸恢复。
#### 关联(后续)
| 字段 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `work_order_id` | `BIGINT UNSIGNED` | — | 🔮 关联工单 |
| `work_order_no` | `VARCHAR(50)` | — | 🔮 工单号 |
#### 时间
| 字段 | 类型 | 必填 | 默认值 | 说明 |
|------|------|------|--------|------|
| `created_at` | `DATETIME` | ✅ | CURRENT_TIMESTAMP | |
| `updated_at` | `DATETIME` | ✅ | CURRENT_TIMESTAMP ON UPDATE | |
| `deleted_at` | `DATETIME` | — | NULL | 软删除 |
### 索引
| 索引名 | 字段 | 用途 |
|--------|------|------|
| `PRIMARY` | `id` | — |
| `uk_ext_id` | `ext_id` UNIQUE | 外部幂等去重 |
| `idx_warehouse_status` | `warehouse_id, push_status` | 按仓库+状态查询 |
| `idx_warehouse_direction` | `warehouse_id, direction, created_at` | 收件/回信列表 |
| `idx_parent` | `parent_id` | 对话链查询 |
| `idx_created_at` | `created_at` | 时间范围 |
> **`ext_id` 唯一键防碰撞**:不同来源的消息 ID 可能重复(IM msgId 与 API requestId 撞车)。入库时按来源加前缀:
> ```
> IM 消息: ext_id = `im:wecom:${msg.msgId}`
> API 消息: ext_id = `api:${apiAppId}:${body.requestId}`
> 系统回信: ext_id = `sys:${uuid}`
> ```
> 前缀保证不同来源的消息不会因 ID 相同而误判为重复。
> **容量规划**:`BIGINT UNSIGNED` 主键容量无限。单表 InnoDB 建议 ≤ 5000 万行。以 100 仓 × 日均 5000 条 = 日 50 万条计,达到上限需 ~100 天。届时加 `PARTITION BY HASH(warehouse_id) PARTITIONS 16` 即可水平扩展,无需分库分表,代码零改动。
### 安全边界(强制)
| 边界 | 规则 |
|------|------|
| **warehouse_id 归属** | 禁止外部传入。IM 路径从回调解析获取,API 路径从验签后 `ctx.warehouseId` 获取 |
| **ext_id 前缀** | `im:{platform}:{msgId}` / `api:{appId}:{requestId}` / `sys:{uuid}`,receiver 入站时统一格式 |
| **target_url SSRF** | 仅允许 `https://`,禁止内网 IP(127.0.0.1/10.x/172.16-31.x/192.168.x) |
| **dispatch 超时** | HTTP 请求超时 10s,超时视为失败进入重试 |
| **setImmediate 异常** | `try/catch` 包裹,异常写入 `push_response.error`,`push_status=3` |
| **target_channel 校验** | `dispatch[channel]` 不存在时返回明确错误,不静默丢弃 |
| **僵尸恢复** | 启动时 + 每 5 分钟定时执行 `UPDATE push_status=0 WHERE push_status=1 AND push_started_at < NOW()-5MIN` |
| **推送 body 大小** | 限制 64KB,超限拒绝写入 |
---
## 三、推送流程
```
receiver.receive()
│
├─ 1. 幂等检查(ext_id 已存在 → 直接返回)
├─ 2. INSERT(push_status=0)
└─ 3. setImmediate(() => asyncPush(record))
│
├─ UPDATE push_status=1(推送中)
├─ dispatch(target_channel, target_url)
│ ├─ 成功 → UPDATE push_status=2, pushed_at=NOW()
│ └─ 失败 → retry_count++
│ ├─ < 3 次 → setTimeout(delay, asyncPush) 指数退避重试
│ └─ ≥ 3 次 → UPDATE push_status=3(终态)
└─ 返回
```
**指数退避**:30s → 60s → 120s,最多重试 3 次。
**关键**:不依赖定时任务轮询,利用 Node.js 事件循环的 `setImmediate` + `setTimeout` 在同一个进程内异步完成推送与重试。
---
## 四、两个接收入口
### IM 消息入站
```
企微/钉钉/飞书 Bot 回调 → receiver.receive({
// warehouse_id 由 IM 回调解析 / 签名验证后从上下文获取,不外部传入
source_type: 'im',
ext_id: `im:wecom:${msg.msgId}`,
source_extra: 'wecom',
target_type: 'api',
target_channel: 'warehouse_api',
target_url: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx',
ref_code: msg.userId,
ext_data: { conversation_id: msg.conversationId },
flags: {},
warehouse_id: ctx.warehouseId, // ← 来自鉴权上下文,非外部传入
})
```
### 仓库 API 消息入站
```
POST /warehouse?method=inbox.push → receiver.receive({
// warehouse_id 由仓库 API 验签后从 ApiApp 解析,不外部传入
source_type: 'api',
ext_id: `api:${ctx.apiAppId}:${body.requestId}`,
source_extra: String(ctx.apiAppId),
target_type: 'im',
target_channel: body.targetChannel || 'wecom',
target_url: body.targetUrl,
ref_code: body.refCode,
ext_data: body.extData,
flags: body.flags || {},
warehouse_id: ctx.warehouseId, // ← 来自鉴权上下文,非外部传入
})
```
### 系统回信(outbound)
```
WMS 内部(工单通知/状态更新)→ receiver.reply({
parent_id: 1, // 原消息 ID
target_type: 'im',
target_channel: 'wecom',
target_url: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx',
ref_code: 'TICKET-001',
ext_data: { ... }, // 继承原消息 ext_data
warehouse_id: ctx.warehouseId, // ← WMS 内部上下文
})
// 自动写入 direction=outbound, parent_id=1
// 推送成功后,可通过 inbox.thread 查完整对话链
```
---
## 五、API
### 5.1 内部管理 (`inbox.*`)
| method | 说明 |
|--------|------|
| `inbox.list` | 消息列表(`direction` 区分收件/回信) |
| `inbox.detail` | 消息详情(含 push_response) |
| `inbox.thread` | 对话链(原消息 + 所有回信) |
| `inbox.reply` | 系统回信(写入 outbound 记录 + 异步推送) |
| `inbox.retry` | 手动重推 |
| `inbox.stats` | 推送统计 |
### 5.2 仓库 API (`inbox.push`)
`POST /warehouse?method=inbox.push`
| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `body.sourceType` | `string` | ✅ | 来源类型:`im` / `api` |
| `body.sourceChannel` | `string` | — | 来源渠道(IM 平台 / API 标识) |
| `body.requestId` | `string` | ✅ | 来源请求 ID(组成 ext_id) |
| `body.targetChannel` | `string` | ✅ | 目标渠道 |
| `body.targetUrl` | `string` | ✅ | 推送目标 URL |
| `body.refCode` | `string` | — | 引用编码 |
| `body.extData` | `object` | — | 透传数据 |
| `body.flags` | `object` | — | 处理标记 `{ skip_ai_parse, skip_auto_reply, skip_forward }` |
| `body.storeId` | `number` | — | 关联货主 |
---
## 六、异步推送实现
不启动独立 consumer,利用 Egg.js / Node.js 原生异步能力:
```javascript
// receiver.js
async receive(data) {
// 1. 幂等检查
const exist = await this.ctx.model.InboxMessage.findOne({
where: { ext_id: data.ext_id },
});
if (exist) return { ok: true, id: exist.id, ext_id: data.ext_id };
// 2. 写入记录
const record = await this.ctx.model.InboxMessage.create({
ext_id: data.ext_id,
warehouse_id: data.warehouse_id,
source_type: data.source_type,
source_extra: data.source_extra,
target_type: data.target_type,
target_channel: data.target_channel,
target_url: data.target_url,
ref_code: data.ref_code,
ext_data: data.ext_data,
flags: data.flags || {},
push_status: 0,
});
// 3. 异步后台推送(不阻塞响应)
setImmediate(() => this.asyncPush(record));
return { ok: true, id: record.id, ext_id: data.ext_id };
}
async asyncPush(record, attempt = 0) {
// 乐观锁:仅 push_status=0 时可取走,防重
const [ updated ] = await InboxMessage.update(
{ push_status: 1, push_started_at: new Date() },
{ where: { id: record.id, push_status: attempt === 0 ? 0 : 3 } }
);
if (!updated) return; // 已被其他进程取走
try {
// API 渠道:用仓库 ApiApp 生成 MD5 签名,接收方同密钥验证
const payload = { ref_code: record.ref_code, ext_data: record.ext_data };
const signedUrl = record.target_type === 'api'
? await this.signRequest(record, payload)
: record.target_url;
const res = await this.ctx.service.inbox.dispatch[record.target_channel].push(
signedUrl, payload
);
await record.update({
push_status: 2,
push_response: { http_status: res.status, body: res.data },
pushed_at: new Date(),
});
} catch (err) {
const next = attempt + 1;
await record.update({ push_status: 3, retry_count: next, push_response: { error: err.message } });
if (next < 3) {
const delay = 30000 * Math.pow(2, attempt); // 30s → 60s → 120s
setTimeout(() => this.asyncPush(record, next), delay);
}
}
}
```
**不需要**:定时任务、消息队列、独立 worker 进程。
> **僵尸恢复**:进程崩溃导致 `push_status=1` 的记录卡死时,启动时执行 `UPDATE SET push_status=0 WHERE push_status=1 AND push_started_at < NOW() - INTERVAL 5 MINUTE` 即可复活。
> **出站签名**:推送到 `target_type=api` 时,使用仓库 ApiApp 的 `self_app_secret` 生成 MD5 签名附加到 URL query:
> ```
> signedUrl = target_url
> + '?app_key=' + apiApp.self_app_key
> + '&timestamp=' + now
> + '&sign=' + md5(queryString + self_app_secret + md5(body))
> ```
> 接收方(仓库开放侧)可用同一 `app_key` 调用 `apiSignLib.verifyRequestSign()` 验证。IM 通道(wecom/dingtalk/feishu)使用各自 Bot 原生鉴权,不走此签名。
---
## 七、模块结构
**分层原则**:API 入口只做校验与签名,统一委托 `app/service/inbox/` 处理写库与推送逻辑。`methods/` 仅放接口定义,不放业务代码。
```
入口层(校验 + 签名) 统一处理层(写库 + 推送) 数据层
────────────────────────── ────────────────────────── ──────
app/controller/ app/service/inbox/ app/model/
im.js ─────────────┐ ┌─ receiver.js inbox_message.js
warehouse.js ──────┤ │ 统一接收(幂等去重) ↑
├──调用──→ │ 写库(INSERT) │
app/service/im.js ─┘ │ 异步推送(setImmediate) │
│ │ 重试(setTimeout 指数退避) │
│ │ │
│ ├─ index.js │
│ │ 列表/详情/重推/统计 │
│ │ │
│ └─ dispatch/ │
│ base.js ← 统一出站:查 ApiApp、取密钥、签名、发 HTTP │
│ webhook.js ← 继承 base,HTTP POST │
│ wecom.js ← 继承 base,企微 Bot │
│ dingtalk.js ← 继承 base,钉钉 Bot │
│ feishu.js ← 继承 base,飞书 Bot │
│ │
methods/ (仅接口定义,不放逻辑) │
warehouse.json ← inbox.push 参数声明 │
system.json ← inbox.* 参数声明 │
```
> **关键**:`app/service/inbox/` 是独立的统一处理目录,所有写库、推送、重试逻辑集中在此。后续新增渠道只需在 `dispatch/` 下加一个文件,不影响其他层。
### 统一出站基类 `dispatch/base.js`
所有渠道 dispatch 继承此基类,统一处理查密钥、签名、发 HTTP:
```javascript
// dispatch/base.js
class OutboundBase {
constructor(ctx) { this.ctx = ctx; }
// 获取仓库 ApiApp 密钥(IM 渠道无需签名,返回 null)
async getApiApp(warehouseId) {
return await this.ctx.service.systems.apiSign.getApiAppConfigByAppKey(
/* appKey from warehouse */, WAREHOUSE_INTERFACE_TYPE_ID
);
}
// 生成 MD5 签名(复用 apiSignLib)
signRequest(url, body, secret) {
const query = { app_key: secret.appKey, timestamp: Math.floor(Date.now() / 1000) };
const { sign } = apiSignLib.signRequest({ query, body, selfAppSecret: secret.selfAppSecret });
return `${url}?app_key=${query.app_key}&timestamp=${query.timestamp}&sign=${sign}`;
}
// 统一发送(子类可覆盖签名逻辑)
async post(url, body) { /* axios/post */ }
// 子类必须实现
async push(record) { throw new Error('子类实现'); }
}
```
> **调用链**:`receiver.asyncPush()` → `dispatch[channel].push(record)` → 基类 `signRequest()` + `post()` → 外部。各渠道只关注消息格式转换,签名和 HTTP 由基类统一处理。
### 与现有系统集成
```
app/controller/im.js(已有)
→ IM 回调签名校验后 → ctx.service.inbox.receiver.receive({ source_type: 'im', ... })
app/controller/warehouse.js(已有)
→ method=inbox.push → ctx.service.inbox.receiver.receive({ source_type: 'api', ... })
methods/warehouse.json(修改)
→ 新增 inbox.push 方法定义,注册到 warehouse 开放接口方法列表
```
---
## 八、文件变更清单
| 文件 | 操作 |
|------|------|
| `database/migrations/{ts}-create-inbox-message.js` | 新增 DDL |
| `app/model/inbox_message.js` | 新增 |
| `app/service/inbox/index.js` | 新增 |
| `app/service/inbox/receiver.js` | 新增(统一接收 + 写库 + 异步推送入口) |
| `app/service/inbox/dispatch/base.js` | 新增(统一出站:查密钥 + 签名 + HTTP) |
| `app/service/inbox/dispatch/webhook.js` | 新增(HTTP POST 推送) |
| `app/service/inbox/dispatch/wecom.js` | 新增(企微 Bot) |
| `app/service/inbox/dispatch/dingtalk.js` | 新增(钉钉 Bot) |
| `app/service/inbox/dispatch/feishu.js` | 新增(飞书 Bot) |
| `app/controller/inbox.js` | 新增 |
| `methods/warehouse.json` | 新增 `inbox.push` |
| `methods/system.json` | 新增 `inbox.*` |

View File

@ -1,138 +0,0 @@
# 订单自定义店铺-快递绑定策略 设计方案
> **状态**: 📋 设计中
> **设计日期**: 2026-08-03
> **模块**: 订单快递分配策略
> **表**: 1 张 — `wms_store_express_binding_policy`
---
## 一、背景与目的
在 WMS 系统中,订单的快递分配目前依赖以下路径:
1. `store_warehouse.policy_config.auto_allocate_express` 控制是否自动分配
2. `express_interface` 表提供「仓库 + 店铺 + 平台 + 快递」的接口配置映射
3. 货主 `subject_config.default_express_code` 提供默认快递
**痛点**:无法根据业务场景灵活配置"某个仓库下,某店铺(或某货主)强制使用/优先使用某快递"的策略。例如:
- 仓库 A 的拼多多店铺「旗舰店」必须走中通(ZTO),而「奥莱店」走圆通(YTO)
- 同一店铺在不同条件下(如收件省份、商品类型)使用不同快递
- 多人同时管理时需要记录创建人、创建时间,方便追溯
**解决方案**:新增 `wms_store_express_binding_policy` 表,支持自定义店铺-快递绑定策略,按优先级匹配。
---
## 二、数据库表
### `wms_store_express_binding_policy`
| 字段 | 类型 | 必填 | 默认值 | 说明 |
|------|------|------|--------|------|
| `id` | `BIGINT UNSIGNED` | ✅ | AUTO | 主键 |
| `warehouse_id` | `BIGINT UNSIGNED` | ✅ | — | 仓库ID,策略所属仓库 |
| `custom_name` | `VARCHAR(100)` | ✅ | — | 自定义店铺标签名称(自由文本,与系统店铺无关) |
| `express_code` | `VARCHAR(50)` | ✅ | — | 绑定的快递编码(关联 wms_express.code) |
| `priority` | `INT(11)` | ✅ | 0 | 优先级,数值越大越优先匹配 |
| `is_enabled` | `TINYINT(1)` | ✅ | 1 | 是否启用:0=停用,1=启用 |
| `match_condition` | `JSON` | — | NULL | 附加匹配条件(见下方说明) |
| `remark` | `VARCHAR(500)` | — | NULL | 备注说明 |
| `creator_id` | `BIGINT UNSIGNED` | — | NULL | 创建人账户ID(关联 accounts 表) |
| `created_at` | `DATETIME` | ✅ | CURRENT_TIMESTAMP | 创建时间 |
| `updated_at` | `DATETIME` | ✅ | CURRENT_TIMESTAMP ON UPDATE | 更新时间 |
| `deleted_at` | `DATETIME` | — | NULL | 软删除时间 |
### 索引设计
| 索引名 | 字段 | 说明 |
|--------|------|------|
| `PRIMARY` | `id` | 主键 |
| `idx_warehouse_enabled` | `warehouse_id`, `is_enabled`, `deleted_at` | 按仓库查询启用策略 |
| `idx_warehouse_express` | `warehouse_id`, `express_code`, `deleted_at` | 按仓库+快递反查绑定 |
### `match_condition` 字段说明(JSON,可选)
用于扩展匹配条件,可进一步按以下维度过滤:
```jsonc
{
"platform_codes": ["PDD", "TB"], // 限定平台编码
"provinces": ["广东省", "浙江省"], // 限定收件省份
"cities": ["广州市", "杭州市"], // 限定收件城市
"item_codes": ["SKU001", "SKU002"], // 限定商品编码
"min_weight_g": 0, // 最小重量(g),NULL=不限制
"max_weight_g": 5000, // 最大重量(g),NULL=不限制
"min_amount": 0, // 最小金额(元),NULL=不限制
"max_amount": 1000 // 最大金额(元),NULL=不限制
}
```
## 三、匹配逻辑(伪代码)
```
1. 查询 wms_store_express_binding_policy
WHERE warehouse_id = :warehouseId
AND is_enabled = 1
AND deleted_at IS NULL
ORDER BY priority DESC, id ASC
2. 遍历结果集,对每条策略:
a. 若 match_condition 为空 → 命中,返回 express_code
b. 若 match_condition 不为空 → 逐条件判断:
- platform_codes:订单平台编码是否在列表中
- provinces / cities:收件地址省/市是否在列表中
- item_codes:订单商品编码是否命中
- min/max_weight_g:订单总重量是否在范围内
- min/max_amount:订单总金额是否在范围内
c. 所有条件 AND 全部满足 → 命中,返回 express_code
3. 若未命中任何策略 → 回退到原有默认逻辑
(express_interface 匹配 → subject_config.default_express_code)
```
## 四、与现有表的关系
```
wms_store_express_binding_policy
├─ warehouse_id → stores.id(逻辑关联,不做物理外键)
├─ express_code → wms_express.code(逻辑关联)
└─ creator_id → accounts.id(逻辑关联)
```
## 五、典型使用场景
### 场景1:按自定义店铺标签绑定快递
```sql
INSERT INTO wms_store_express_binding_policy
(warehouse_id, custom_name, express_code, priority, creator_id)
VALUES
(1000000, '旗舰店-中通', 'ZTO', 10, 10001);
```
### 场景2:按自定义店铺标签+省份绑定快递(偏远地区走邮政)
```sql
INSERT INTO wms_store_express_binding_policy
(warehouse_id, custom_name, express_code, priority, match_condition, creator_id)
VALUES
(1000000, '偏远地区邮政', 'EMS', 20,
'{"provinces":["新疆维吾尔自治区","西藏自治区","青海省"]}', 10001);
```
### 场景3:全局默认快递
```sql
INSERT INTO wms_store_express_binding_policy
(warehouse_id, custom_name, express_code, priority, creator_id)
VALUES
(1000000, '全局顺丰', 'SF', 5, 10001);
```
## 六、后续扩展
- 策略命中日志:记录每次快递分配命中了哪条策略,便于分析调整
- 策略生效时间段:增加 `start_time` / `end_time` 支持定时策略(如大促期间切换快递)
- 策略复制:支持跨仓库复制策略配置

View File

@ -1,182 +0,0 @@
'use strict';
const TABLE_NAME = 'wms_inbox_message';
module.exports = {
/**
* 创建站内信消息表。
* @param {Object} queryInterface Sequelize QueryInterface 实例。
* @param {Object} Sequelize Sequelize 类。
* @return {Promise<void>} 迁移执行结果。
*/
up: async (queryInterface, Sequelize) => {
const tables = await queryInterface.showAllTables();
const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME);
if (exists) return;
await queryInterface.createTable(TABLE_NAME, {
id: {
type: Sequelize.BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键ID',
},
ext_id: {
type: Sequelize.STRING(128),
allowNull: false,
comment: '外部唯一消息主键(IM msgId / API requestId 等),用于幂等去重',
},
warehouse_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: false,
comment: '所属仓库ID',
},
store_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
comment: '关联货主ID',
},
direction: {
type: Sequelize.STRING(10),
allowNull: false,
defaultValue: 'inbound',
comment: '消息方向:inbound=外部→WMS收件 / outbound=WMS→外部回信',
},
parent_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
comment: '关联消息ID(回信时指向原消息,形成对话链)',
},
source_type: {
type: Sequelize.STRING(20),
allowNull: false,
comment: '来源类型:im / api',
},
source_extra: {
type: Sequelize.STRING(100),
allowNull: true,
comment: '来源附加信息(IM 平台 / API app_id)',
},
target_type: {
type: Sequelize.STRING(20),
allowNull: false,
comment: '目标类型:im / api',
},
target_channel: {
type: Sequelize.STRING(50),
allowNull: false,
comment: '目标渠道:wecom / dingtalk / feishu / warehouse_api / webhook',
},
target_url: {
type: Sequelize.STRING(500),
allowNull: false,
comment: '推送目标URL(IM Bot webhook 地址 / API 回调地址)',
},
ref_code: {
type: Sequelize.STRING(100),
allowNull: true,
comment: '外部引用编码,推送/回执时原样携带',
},
ext_data: {
type: Sequelize.JSON,
allowNull: true,
comment: '外部透传数据,外部传入任意JSON,WMS不解析,回信时原样返回',
},
flags: {
type: Sequelize.JSON,
allowNull: true,
comment: '处理标记,外部传入控制WMS处理行为',
},
push_status: {
type: Sequelize.TINYINT(4),
allowNull: false,
defaultValue: 0,
comment: '推送状态:0=待推送 1=推送中 2=已送达 3=失败',
},
push_started_at: {
type: Sequelize.DATE,
allowNull: true,
comment: '开始推送时间(僵尸检测:超5分钟仍为1则重置为0)',
},
retry_count: {
type: Sequelize.INTEGER(11),
allowNull: false,
defaultValue: 0,
comment: '已重试次数',
},
push_response: {
type: Sequelize.JSON,
allowNull: true,
comment: '目标响应(http_status, body, error)',
},
pushed_at: {
type: Sequelize.DATE,
allowNull: true,
comment: '推送完成时间',
},
work_order_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
comment: '关联工单ID(预留)',
},
work_order_no: {
type: Sequelize.STRING(50),
allowNull: true,
comment: '工单号(预留)',
},
created_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '创建时间',
},
updated_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
comment: '更新时间',
},
deleted_at: {
type: Sequelize.DATE,
allowNull: true,
comment: '软删除时间',
},
});
// 唯一索引 — 外部幂等去重
await queryInterface.addIndex(TABLE_NAME, [ 'ext_id' ], {
unique: true,
name: 'uk_ext_id',
});
// 仓库+状态查询
await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'push_status' ], {
name: 'idx_warehouse_status',
});
// 仓库+方向+时间
await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'direction', 'created_at' ], {
name: 'idx_warehouse_direction',
});
// 对话链查询
await queryInterface.addIndex(TABLE_NAME, [ 'parent_id' ], {
name: 'idx_parent',
});
// 时间范围查询
await queryInterface.addIndex(TABLE_NAME, [ 'created_at' ], {
name: 'idx_created_at',
});
},
/**
* 回滚站内信消息表。
* @param {Object} queryInterface Sequelize QueryInterface 实例。
* @return {Promise<void>} 迁移回滚结果。
*/
down: async queryInterface => {
await queryInterface.dropTable(TABLE_NAME);
},
};

View File

@ -1,129 +0,0 @@
'use strict';
const TABLE_NAME = 'wms_store_express_binding_policy';
module.exports = {
/**
* 创建订单自定义店铺-快递绑定策略表。
* @param {Object} queryInterface Sequelize QueryInterface 实例。
* @param {Object} Sequelize Sequelize 类。
* @return {Promise<void>} 迁移执行结果。
*/
up: async (queryInterface, Sequelize) => {
const tables = await queryInterface.showAllTables();
const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME);
if (exists) return;
await queryInterface.createTable(TABLE_NAME, {
id: {
type: Sequelize.BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键ID',
},
warehouse_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: false,
comment: '仓库ID,策略所属仓库',
},
custom_name: {
type: Sequelize.STRING(100),
allowNull: false,
comment: '自定义策略名称,便于人工识别',
},
store_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
comment: '货主ID(stores.id),NULL=适用所有货主',
},
shop_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
comment: '店铺ID(shops.id),NULL=适用所有店铺',
},
express_code: {
type: Sequelize.STRING(50),
allowNull: false,
comment: '绑定的快递编码(wms_express.code)',
},
priority: {
type: Sequelize.INTEGER(11),
allowNull: false,
defaultValue: 0,
comment: '优先级,数值越大越优先匹配',
},
is_enabled: {
type: Sequelize.TINYINT(1),
allowNull: false,
defaultValue: 1,
comment: '是否启用:0=停用,1=启用',
},
match_condition: {
type: Sequelize.JSON,
allowNull: true,
comment: '附加匹配条件(JSON):platform_codes/provinces/cities/item_codes/min_weight_g/max_weight_g/min_amount/max_amount',
},
remark: {
type: Sequelize.STRING(500),
allowNull: true,
comment: '备注说明',
},
creator_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
comment: '创建人账户ID(accounts.id)',
},
created_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '创建时间',
},
updated_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
comment: '更新时间',
},
deleted_at: {
type: Sequelize.DATE,
allowNull: true,
comment: '软删除时间',
},
}, {
comment: '订单自定义店铺-快递绑定策略表',
engine: 'InnoDB',
charset: 'utf8mb4',
collate: 'utf8mb4_general_ci',
});
// 索引:按仓库查询启用策略
await queryInterface.addIndex(TABLE_NAME, {
name: 'idx_warehouse_enabled',
fields: [ 'warehouse_id', 'is_enabled', 'deleted_at' ],
});
// 索引:按仓库+货主+店铺精确匹配
await queryInterface.addIndex(TABLE_NAME, {
name: 'idx_warehouse_store_shop',
fields: [ 'warehouse_id', 'store_id', 'shop_id', 'deleted_at' ],
});
// 索引:按仓库+快递反查绑定店铺
await queryInterface.addIndex(TABLE_NAME, {
name: 'idx_warehouse_express',
fields: [ 'warehouse_id', 'express_code', 'deleted_at' ],
});
},
/**
* 回滚:删除表。
* @param {Object} queryInterface Sequelize QueryInterface 实例。
* @param {Object} Sequelize Sequelize 类。
* @return {Promise<void>} 迁移执行结果。
*/
down: async (queryInterface, Sequelize) => {
await queryInterface.dropTable(TABLE_NAME);
},
};

View File

@ -1,40 +0,0 @@
'use strict';
const TABLE_NAME = 'wms_store_express_binding_policy';
module.exports = {
/**
* 移除冗余字段 store_id / shop_id 及其索引。
* @param {Object} queryInterface Sequelize QueryInterface 实例。
* @param {Object} Sequelize Sequelize 类。
* @return {Promise<void>} 迁移执行结果。
*/
up: async (queryInterface, Sequelize) => {
await queryInterface.removeIndex(TABLE_NAME, 'idx_warehouse_store_shop');
await queryInterface.removeColumn(TABLE_NAME, 'store_id');
await queryInterface.removeColumn(TABLE_NAME, 'shop_id');
},
/**
* 回滚:恢复 store_id / shop_id 列及索引。
* @param {Object} queryInterface Sequelize QueryInterface 实例。
* @param {Object} Sequelize Sequelize 类。
* @return {Promise<void>} 迁移执行结果。
*/
down: async (queryInterface, Sequelize) => {
await queryInterface.addColumn(TABLE_NAME, 'store_id', {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
comment: '货主ID(stores.id),NULL=适用所有货主',
});
await queryInterface.addColumn(TABLE_NAME, 'shop_id', {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
comment: '店铺ID(shops.id),NULL=适用所有店铺',
});
await queryInterface.addIndex(TABLE_NAME, {
name: 'idx_warehouse_store_shop',
fields: [ 'warehouse_id', 'store_id', 'shop_id', 'deleted_at' ],
});
},
};

View File

@ -1,18 +0,0 @@
'use strict';
const TABLE_NAME = 'wms_store_express_binding_policy';
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.addColumn(TABLE_NAME, 'prohibited_type_id', {
type: Sequelize.INTEGER.UNSIGNED,
allowNull: true,
comment: '违禁品类型ID(关联 wms_prohibited_type.id),NULL=不限制违禁品',
after: 'match_condition',
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.removeColumn(TABLE_NAME, 'prohibited_type_id');
},
};

View File

@ -1,31 +0,0 @@
'use strict';
const TABLE_NAME = 'wms_store_express_binding_policy';
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.removeColumn(TABLE_NAME, 'match_condition');
await queryInterface.addColumn(TABLE_NAME, 'provinces', {
type: Sequelize.TEXT,
allowNull: true,
comment: '限定省份,逗号分隔,如"广东省,浙江省",NULL=不限制',
after: 'is_enabled',
});
await queryInterface.addColumn(TABLE_NAME, 'cities', {
type: Sequelize.TEXT,
allowNull: true,
comment: '限定城市,逗号分隔,如"广州市,杭州市",NULL=不限制',
after: 'provinces',
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.removeColumn(TABLE_NAME, 'cities');
await queryInterface.removeColumn(TABLE_NAME, 'provinces');
await queryInterface.addColumn(TABLE_NAME, 'match_condition', {
type: Sequelize.JSON,
allowNull: true,
comment: '附加匹配条件(JSON)',
});
},
};

View File

@ -1,25 +0,0 @@
'use strict';
const TABLE_NAME = 'wms_store_express_binding_policy';
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.addColumn(TABLE_NAME, 'min_weight_g', {
type: Sequelize.INTEGER,
allowNull: true,
comment: '最小重量(克),NULL=不限制',
after: 'cities',
});
await queryInterface.addColumn(TABLE_NAME, 'max_weight_g', {
type: Sequelize.INTEGER,
allowNull: true,
comment: '最大重量(克),NULL=不限制',
after: 'min_weight_g',
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.removeColumn(TABLE_NAME, 'max_weight_g');
await queryInterface.removeColumn(TABLE_NAME, 'min_weight_g');
},
};

View File

@ -1,18 +0,0 @@
'use strict';
const TABLE_NAME = 'wms_store_express_binding_policy';
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.addColumn(TABLE_NAME, 'weight_type', {
type: Sequelize.TINYINT(1),
allowNull: true,
comment: '重量段类型:NULL=不限制/0=常规/1=轻货/2=重货/3=冷链',
after: 'max_weight_g',
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.removeColumn(TABLE_NAME, 'weight_type');
},
};

View File

@ -1,23 +0,0 @@
'use strict';
const TABLE_NAME = 'wms_store_express_binding_policy';
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.changeColumn(TABLE_NAME, 'weight_type', {
type: Sequelize.TINYINT(1),
allowNull: false,
defaultValue: 0,
comment: '重量段类型:0=常规/1=轻货/2=重货/3=冷链',
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.changeColumn(TABLE_NAME, 'weight_type', {
type: Sequelize.TINYINT(1),
allowNull: true,
defaultValue: null,
comment: '重量段类型:NULL=不限制/0=常规/1=轻货/2=重货/3=冷链',
});
},
};

View File

@ -1,30 +0,0 @@
'use strict';
const TABLE_NAME = 'wms_store_express_binding_policy';
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.removeColumn(TABLE_NAME, 'cities');
await queryInterface.removeColumn(TABLE_NAME, 'provinces');
await queryInterface.addColumn(TABLE_NAME, 'regions', {
type: Sequelize.TEXT,
allowNull: true,
comment: '限定地区,逗号分隔,如"广东省,广州市,深圳市",NULL=不限制',
after: 'is_enabled',
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.removeColumn(TABLE_NAME, 'regions');
await queryInterface.addColumn(TABLE_NAME, 'provinces', {
type: Sequelize.TEXT,
allowNull: true,
comment: '限定省份',
});
await queryInterface.addColumn(TABLE_NAME, 'cities', {
type: Sequelize.TEXT,
allowNull: true,
comment: '限定城市',
});
},
};

View File

@ -1,18 +0,0 @@
'use strict';
const TABLE_NAME = 'wms_store_express_binding_policy';
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.addColumn(TABLE_NAME, 'exclude_regions', {
type: Sequelize.TEXT,
allowNull: true,
comment: '排除地区,逗号分隔,如"新疆维吾尔自治区,西藏自治区",NULL=不排除',
after: 'regions',
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.removeColumn(TABLE_NAME, 'exclude_regions');
},
};

View File

@ -1,18 +0,0 @@
'use strict';
const TABLE_NAME = 'wms_store_express_binding_policy';
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.addColumn(TABLE_NAME, 'shop_name', {
type: Sequelize.TEXT,
allowNull: true,
comment: '包含店铺名称,逗号分隔,NULL=不限制',
after: 'custom_name',
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.removeColumn(TABLE_NAME, 'shop_name');
},
};

View File

@ -1,18 +0,0 @@
'use strict';
const TABLE_NAME = 'wms_store_express_binding_policy';
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.addColumn(TABLE_NAME, 'store_ids', {
type: Sequelize.TEXT,
allowNull: true,
comment: '限定货主ID,逗号分隔,NULL=不限制',
after: 'shop_name',
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.removeColumn(TABLE_NAME, 'store_ids');
},
};

View File

@ -1,19 +0,0 @@
'use strict';
const TABLE_NAME = 'wms_store_express_binding_policy';
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.changeColumn(TABLE_NAME, 'regions', { type: Sequelize.JSON, allowNull: true, comment: '限定地区,字符串数组' });
await queryInterface.changeColumn(TABLE_NAME, 'exclude_regions', { type: Sequelize.JSON, allowNull: true, comment: '排除地区,字符串数组' });
await queryInterface.changeColumn(TABLE_NAME, 'shop_name', { type: Sequelize.JSON, allowNull: true, comment: '包含店铺名称,字符串数组' });
await queryInterface.changeColumn(TABLE_NAME, 'store_ids', { type: Sequelize.JSON, allowNull: true, comment: '限定货主ID,数字数组' });
},
down: async (queryInterface, Sequelize) => {
await queryInterface.changeColumn(TABLE_NAME, 'regions', { type: Sequelize.TEXT, allowNull: true, comment: '限定地区,逗号分隔' });
await queryInterface.changeColumn(TABLE_NAME, 'exclude_regions', { type: Sequelize.TEXT, allowNull: true, comment: '排除地区,逗号分隔' });
await queryInterface.changeColumn(TABLE_NAME, 'shop_name', { type: Sequelize.TEXT, allowNull: true, comment: '包含店铺名称,逗号分隔' });
await queryInterface.changeColumn(TABLE_NAME, 'store_ids', { type: Sequelize.TEXT, allowNull: true, comment: '限定货主ID,逗号分隔' });
},
};

View File

@ -1,21 +0,0 @@
'use strict';
const TABLE_NAME = 'wms_store_express_binding_policy';
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.changeColumn(TABLE_NAME, 'prohibited_type_id', {
type: Sequelize.JSON,
allowNull: true,
comment: '违禁品类型ID数组(关联 wms_prohibited_type.id),如[1,2],NULL=不限制违禁品',
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.changeColumn(TABLE_NAME, 'prohibited_type_id', {
type: Sequelize.INTEGER.UNSIGNED,
allowNull: true,
comment: '违禁品类型ID(关联 wms_prohibited_type.id),NULL=不限制违禁品',
});
},
};

View File

@ -5107,197 +5107,5 @@
"waybill.warehouse.exportTaskProgress:无变更,保持不变。" "waybill.warehouse.exportTaskProgress:无变更,保持不变。"
], ],
"module": "waybill.warehouse" "module": "waybill.warehouse"
},
{
"version": "2026.08.03-system-01",
"date": "2026-08-03",
"type": "added",
"summary": "新增站内信(Inbox)管理模块,支持消息列表、详情、对话链、回信、重推、统计等管理功能,仓库维度隔离,warehouseId 由服务端上下文注入",
"methods": [
"inbox.list",
"inbox.detail",
"inbox.thread",
"inbox.reply",
"inbox.retry",
"inbox.stats"
],
"notes": [
"入口:POST /system,body.method=inbox.{action},路由到 app/controller/inbox.index",
"inbox.list:分页查询消息列表,支持 direction/pushStatus/targetChannel/keyword 筛选,列表不含 ext_data 和 push_response 大字段",
"inbox.detail:查单条消息详情,含完整 push_response 推送响应信息",
"inbox.thread:对话链查询,从指定消息向上查找根消息,向下收集所有回信,按时间升序返回",
"inbox.reply:系统回信,自动继承原消息 ext_data/ref_code,写入 direction=outbound + parent_id 形成对话链,异步推送到目标渠道",
"inbox.retry:手动重推失败消息(仅 push_status=3 可重推),重置为 push_status=0 并触发 setImmediate 异步推送",
"inbox.stats:按方向/推送状态汇总统计 + 最近24小时新增数量",
"安全边界:warehouse_id 由 ctx.user.store_id 注入(内部管理端),外部不可传入,保证仓库隔离",
"底层服务:app/service/inbox/index.js(查询管理)+ app/service/inbox/receiver.js(接收推送)"
],
"module": "inbox"
},
{
"version": "2026.08.03-system-02",
"date": "2026-08-03",
"summary": "setting.expressInterface.list 返回新增 quantity/recycled_quantity/cancel_quantity/allocated_quantity 扁平字段,数据源为 index.getShopExpressList",
"methods": [
"setting.expressInterface.list"
],
"notes": [
"每条记录新增四个扁平字段:quantity(可用面单数)、recycled_quantity(已回收)、cancel_quantity(已取消)、allocated_quantity(已分配)",
"数据通过 Promise.all 并行调用 index.getShopExpressList 获取各店铺快递签约数据",
"匹配逻辑分三层:sys_express_code 匹配快递 → site_code/branch_code 匹配网点 → shipperno/customer_code_list 匹配账号",
"无店铺或无数据时四个字段均为 0"
]
},
{
"version": "2026.08.03-system-03",
"date": "2026-08-03",
"summary": "补全 setting.expressInterface.list response 所有返回字段文档,包含 express 子对象、quantity 四字段等",
"methods": [
"setting.expressInterface.list"
],
"notes": [
"补全所有 response list children 字段:从原有的 4 个扩展为 42 个完整字段",
"新增 express 子对象文档(code/name/polyapi_code/polyapi_extra_info/pdd_code/ks_code/dyxd_code)",
"保留 quantity/recycled_quantity/cancel_quantity/allocated_quantity 四个扁平面单数量字段"
]
},
{
"version": "2026.08.03-system-04",
"date": "2026-08-03",
"type": "added",
"summary": "新增店铺-快递绑定策略模块 storeExpressBindingPolicy,支持仓库维度的货主/店铺->快递绑定策略 CRUD,按优先级匹配,可附加商品/地区/重量/金额等条件",
"methods": [
"storeExpressBindingPolicy.list",
"storeExpressBindingPolicy.add",
"storeExpressBindingPolicy.edit",
"storeExpressBindingPolicy.del"
],
"notes": [
"storeExpressBindingPolicy.list:分页查询策略列表,支持 where 条件筛选(id/custom_name/store_id/shop_id/express_code/priority/is_enabled/creator_id/quickWhere),按 priority DESC、updated_at DESC 排序。",
"storeExpressBindingPolicy.add:新增策略,必填 custom_name 和 express_code。express_code 须存在于 wms_express。同仓库下 custom_name 唯一。可选 store_id/shop_id/priority/is_enabled/match_condition/remark/creator_id。",
"storeExpressBindingPolicy.edit:编辑策略,必填 id。仅更新传入的非 undefined 字段。修改 custom_name 时校验同仓库唯一性。",
"storeExpressBindingPolicy.del:软删除策略(deleted_at + is_enabled=0),不物理删除。",
"仓库隔离:所有操作按 ctx.user.store_id → warehouse_id 自动过滤。",
"匹配条件 match_condition(JSON):支持 platform_codes/provinces/cities/item_codes/min_weight_g/max_weight_g/min_amount/max_amount。"
],
"module": "storeExpressBindingPolicy"
},
{
"version": "2026.08.03-system-05",
"date": "2026-08-03",
"type": "changed",
"summary": "精简 storeExpressBindingPolicy:移除 store_id/shop_id 冗余字段,custom_name 明确为纯自由文本标签(与系统 shops 无关)",
"methods": [
"storeExpressBindingPolicy.list",
"storeExpressBindingPolicy.add",
"storeExpressBindingPolicy.edit",
"storeExpressBindingPolicy.del"
],
"notes": [
"移除 add/edit 入参中的 store_id/shop_id(含 camelCase 兼容)",
"list 响应不再返回 store_id/shop_id",
"custom_name 为纯自由文本标签,与系统 shops 表无关"
],
"module": "storeExpressBindingPolicy"
},
{
"version": "2026.08.04-system-01",
"date": "2026-08-04",
"type": "changed",
"summary": "storeExpressBindingPolicy 字段重构: match_condition JSON 拆分为独立字段 provinces/cities/min_weight_g/max_weight_g/weight_type,新增 prohibited_type_id",
"methods": [
"storeExpressBindingPolicy.list",
"storeExpressBindingPolicy.add",
"storeExpressBindingPolicy.edit",
"storeExpressBindingPolicy.del"
],
"notes": [
"移除 match_condition JSON,拆分 provinces TEXT逗号分隔 + cities TEXT逗号分隔 + min_weight_g INT + max_weight_g INT + weight_type TINYINT 默认0",
"weight_type 枚举 0=常规 1=轻货 2=重货 3=冷链 必填默认0",
"新增 prohibited_type_id 关联 wms_prohibited_type.id"
],
"module": "storeExpressBindingPolicy"
},
{
"version": "2026.08.04-system-02",
"date": "2026-08-04",
"type": "changed",
"summary": "合并 provinces/cities 为单一 regions 字段 TEXT逗号分隔",
"methods": [
"storeExpressBindingPolicy.list",
"storeExpressBindingPolicy.add",
"storeExpressBindingPolicy.edit",
"storeExpressBindingPolicy.del"
],
"notes": [
"移除 provinces/cities 两个字段,合并为 regions TEXT 逗号分隔"
],
"module": "storeExpressBindingPolicy"
},
{
"version": "2026.08.04-system-03",
"date": "2026-08-04",
"type": "added",
"summary": "新增 exclude_regions 排除地区字段",
"methods": [
"storeExpressBindingPolicy.list",
"storeExpressBindingPolicy.add",
"storeExpressBindingPolicy.edit",
"storeExpressBindingPolicy.del"
],
"notes": [
"新增 exclude_regions 排除地区字段 TEXT逗号分隔"
],
"module": "storeExpressBindingPolicy"
},
{
"version": "2026.08.04-system-04",
"date": "2026-08-04",
"type": "changed",
"summary": "修正 API 文档风格,对齐项目 shops.list 等模块规范",
"methods": [
"storeExpressBindingPolicy.list",
"storeExpressBindingPolicy.add",
"storeExpressBindingPolicy.edit",
"storeExpressBindingPolicy.del"
],
"notes": [
"list page/pageSize 描述对齐 shops.list 风格",
"add/edit 参数描述补充兼容性说明和详细格式"
],
"module": "storeExpressBindingPolicy"
},
{
"version": "2026.08.04-system-05",
"date": "2026-08-04",
"type": "added",
"summary": "新增 shop_name 字段,用于包含店铺名称匹配",
"methods": [
"storeExpressBindingPolicy.list",
"storeExpressBindingPolicy.add",
"storeExpressBindingPolicy.edit",
"storeExpressBindingPolicy.del"
],
"notes": [
"新增 shop_name TEXT逗号分隔,与 custom_name区分:custom_name=策略名称,shop_name=包含店铺名称"
],
"module": "storeExpressBindingPolicy"
},
{
"version": "2026.08.04-system-06",
"date": "2026-08-04",
"type": "added",
"summary": "新增shop_name和store_ids字段",
"methods": [
"storeExpressBindingPolicy.list",
"storeExpressBindingPolicy.add",
"storeExpressBindingPolicy.edit",
"storeExpressBindingPolicy.del"
],
"notes": [
"新增shop_name包含店铺名称",
"新增store_ids限定货主ID"
],
"module": "storeExpressBindingPolicy"
} }
] ]

View File

@ -18,24 +18,5 @@
"api_sign.js 改造:getApiAppConfigByAppKey 新增 interfaceTypeId 参数(默认 2 保持向后兼容),warehouse 入口传 3,查询增加 interface_type_id 条件并返回 warehouse_id。" "api_sign.js 改造:getApiAppConfigByAppKey 新增 interfaceTypeId 参数(默认 2 保持向后兼容),warehouse 入口传 3,查询增加 interface_type_id 条件并返回 warehouse_id。"
], ],
"module": "warehouse" "module": "warehouse"
},
{
"version": "2026.08.03-warehouse-01",
"date": "2026-08-03",
"type": "added",
"summary": "新增仓库开放 API 站内信模块 inbox.push,支持外部系统将消息推入仓库站内信,WMS 异步转发到目标渠道(IM/API/webhook)",
"methods": [
"inbox.push"
],
"notes": [
"POST /warehouse?method=inbox.push,interface_type_id=3(仓库侧),使用 MD5 签名鉴权",
"warehouse_id 由验签后上下文注入,禁止外部传入(安全边界)",
"ext_id 格式:api:{appKey}:{requestId},用于幂等去重",
"target_url 仅允许 https://,禁止内网 IP(SSRF 防护)",
"推送 body 大小限制 64KB",
"异步推送使用 setImmediate,不阻塞响应;失败指数退避重试(30s→60s→120s,最多3次)",
"路由到 app/service/warehouseMethods/inbox.push → app/service/inbox/receiver.receive"
],
"module": "inbox"
} }
] ]

File diff suppressed because it is too large Load Diff

View File

@ -1,8 +1,8 @@
{ {
"module": "warehouse", "module": "warehouse",
"description": "仓库开放 API 统一入口,供仓库级外部适配器(企微/钉钉/飞书/IM 等)调用,HTTP POST /warehouse,使用 MD5 签名鉴权(interface_type_id=3)", "description": "仓库开放 API 统一入口,供仓库级外部适配器(企微/钉钉/飞书/IM 等)调用,HTTP POST /warehouse,使用 HMAC-SHA256 签名鉴权(interface_type_id=3)",
"version": "1.0.0", "version": "1.0.0",
"updatedAt": "2026-08-03", "updatedAt": "2026-08-01",
"http": { "http": {
"path": "/warehouse", "path": "/warehouse",
"method": "POST" "method": "POST"
@ -197,134 +197,6 @@
] ]
} }
] ]
},
{
"groupName": "站内信模块",
"module": "inbox",
"list": [
{
"method": "inbox.push",
"description": "外部系统将消息推入仓库站内信,WMS 异步转发到目标渠道。warehouse_id 由验签后上下文注入,禁止外部传入。",
"isNeedAuth": false,
"isNeedLogin": false,
"headers": [],
"params": [
{
"name": "sourceType",
"type": "string",
"required": false,
"source": "body",
"description": "来源类型:im / api,默认 api"
},
{
"name": "sourceChannel",
"type": "string",
"required": false,
"source": "body",
"description": "来源渠道标识(IM 平台名称 / API 标识),将写入 source_extra"
},
{
"name": "requestId",
"type": "string",
"required": true,
"source": "body",
"description": "来源请求唯一 ID,与 appKey 组合为 ext_id(api:{appKey}:{requestId}),用于幂等去重"
},
{
"name": "targetType",
"type": "string",
"required": false,
"source": "body",
"description": "目标类型:im / api / webhook,默认 im"
},
{
"name": "targetChannel",
"type": "string",
"required": true,
"source": "body",
"description": "目标渠道:wecom / dingtalk / feishu / warehouse_api / webhook"
},
{
"name": "extData",
"type": "object",
"required": false,
"source": "body",
"description": "外部透传数据,任意 JSON,WMS 不解析,回信时原样返回"
},
{
"name": "flags",
"type": "object",
"required": false,
"source": "body",
"description": "处理标记,可选:skip_ai_parse(跳过智能解析)、skip_auto_reply(跳过自动回复)、skip_forward(仅存档不转发)"
},
{
"name": "storeId",
"type": "number",
"required": false,
"source": "body",
"description": "关联货主 ID"
},
{
"name": "parentId",
"type": "number",
"required": false,
"source": "body",
"description": "关联消息 ID(回信时指向原消息,形成对话链)"
}
],
"response": [
{
"name": "ok",
"type": "boolean",
"required": true,
"description": "操作是否成功"
},
{
"name": "id",
"type": "number",
"required": true,
"description": "站内信记录 ID"
},
{
"name": "ext_id",
"type": "string",
"required": true,
"description": "外部唯一消息主键"
}
],
"errors": [
{
"code": "400",
"message": "requestId 不能为空"
},
{
"code": "400",
"message": "targetChannel 不能为空"
},
{
"code": "400",
"message": "targetUrl 不能为空"
},
{
"code": "400",
"message": "缺少仓库信息"
},
{
"code": "400",
"message": "target_url 仅允许 https:// 协议"
},
{
"code": "400",
"message": "target_url 不允许指向内网地址"
},
{
"code": "500",
"message": "站内信入站失败"
}
]
}
]
} }
] ]
} }