feat(waybill): 运单物流轨迹表与 waybill.getTrace 批量更新
- 新增 wms_order_express_trace(1 运单 : N 轨迹):express_id 关联主表,
冗余 waybill_code / order_id,warehouse_id 隔离,raw_data 存原始报文;
uk_express_op_scan(express_id, op_time, scan_type) 幂等;字符集与主表一致
- 新增出站回调 waybill.getTrace(注册到 callback_functions,管理端可勾选):
入参与 waybill.getreceive 一致({ request: { waybill_codes: [...] } },单批 10 单,
signMode=simple);响应 [{ waybillNo, trace: {...} }],兼容 trace 数组与 {code,data} 包装
- 新增 waybill.warehouse.updateTrace / updateTraceTaskProgress:
复用导出任务的异步任务ID与进度模式(前缀 waybill_trace_),
支持 waybillCodes 或与 waybill.warehouse.list 一致的 where 条件圈选(上限 5000);
轨迹按 (express_id, op_time, scan_type) upsert,未匹配运单计入 not_found
- 文档:methods/system.json(0.3.325)、变更记录、设计文档 2.2.1/3.9、出站回调说明 3.7
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
parent
e3eff20aaa
commit
89e4cd22c0
@ -21,6 +21,13 @@ const CALLBACK_FUNCTIONS = [
|
||||
description: '按运单号批量查询是否已揽收:请求 { waybill_codes: [...] },'
|
||||
+ '外部返回 [{ waybill_code, is_galaxy_receive: 1|0 }],回写 wms_order_express.is_galaxy_receive',
|
||||
},
|
||||
{
|
||||
method: 'waybill.getTrace',
|
||||
name: '运单物流轨迹查询',
|
||||
description: '按运单号批量查询物流轨迹:请求 { waybill_codes: [...] },'
|
||||
+ '外部返回 [{ waybillNo, trace: { opTime, outBizCode, memo, opOrgCityName, weight, scanType } }],'
|
||||
+ '落库 wms_order_express_trace(按 express_id + op_time + scan_type 幂等)',
|
||||
},
|
||||
];
|
||||
|
||||
/** method 合法值集合(供管理端 create/update 校验) */
|
||||
|
||||
95
app/model/order_express_trace.js
Normal file
95
app/model/order_express_trace.js
Normal file
@ -0,0 +1,95 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 运单物流轨迹模型。
|
||||
* 一个运单(express_id)对应多条轨迹,由外部快递/轨迹接口回传。
|
||||
* @param {import('egg').Application} app Egg 应用实例。
|
||||
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} Sequelize 模型。
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, INTEGER, DATE, JSON: JSON_TYPE } = app.Sequelize;
|
||||
|
||||
const OrderExpressTrace = app.model.define('order_express_trace', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键ID',
|
||||
},
|
||||
express_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '运单ID(wms_order_express.id)',
|
||||
},
|
||||
waybill_code: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: '运单号(冗余,便于按运单号直查)',
|
||||
},
|
||||
order_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '订单ID(冗余,便于按订单查轨迹)',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '仓库ID(数据隔离维度)',
|
||||
},
|
||||
op_time: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '操作时间(opTime)',
|
||||
},
|
||||
out_biz_code: {
|
||||
type: STRING(191),
|
||||
allowNull: true,
|
||||
comment: '外部业务码(outBizCode)',
|
||||
},
|
||||
memo: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '轨迹描述(memo)',
|
||||
},
|
||||
op_org_city_name: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '操作机构所在城市(opOrgCityName)',
|
||||
},
|
||||
weight: {
|
||||
type: INTEGER(11),
|
||||
allowNull: true,
|
||||
defaultValue: 0,
|
||||
comment: '重量(weight,来源原值)',
|
||||
},
|
||||
scan_type: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '扫描类型(scanType),如 发件/到件/派件/签收',
|
||||
},
|
||||
raw_data: {
|
||||
type: JSON_TYPE,
|
||||
allowNull: true,
|
||||
comment: '原始轨迹报文(未落库字段的兜底存储)',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_order_express_trace',
|
||||
freezeTableName: true,
|
||||
underscored: true,
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
deletedAt: 'deleted_at',
|
||||
paranoid: true,
|
||||
comment: '运单物流轨迹表(1 运单 : N 轨迹)',
|
||||
indexes: [
|
||||
{ name: 'uk_express_op_scan', unique: true, fields: [ 'express_id', 'op_time', 'scan_type' ] },
|
||||
{ name: 'idx_waybill_code', fields: [ 'waybill_code', 'op_time' ] },
|
||||
{ name: 'idx_order_id', fields: [ 'order_id' ] },
|
||||
{ name: 'idx_warehouse_op_time', fields: [ 'warehouse_id', 'op_time' ] },
|
||||
],
|
||||
});
|
||||
|
||||
return OrderExpressTrace;
|
||||
};
|
||||
@ -4,6 +4,12 @@ const MainService = require('../../main');
|
||||
|
||||
const WAYBILL_EXPORT_TASK_CACHE_KEY_PREFIX = 'waybill_export_task_';
|
||||
const WAYBILL_RECEIVE_TASK_CACHE_KEY_PREFIX = 'waybill_receive_task_';
|
||||
const WAYBILL_TRACE_TASK_CACHE_KEY_PREFIX = 'waybill_trace_task_';
|
||||
/** 物流轨迹查询所依赖的出站回调 method */
|
||||
const WAYBILL_TRACE_EVENT = 'waybill.getTrace';
|
||||
/** 仓库未配置轨迹查询外部接口时的失败提示(直接失败,不进入任务流程) */
|
||||
const WAYBILL_TRACE_NOT_CONFIGURED_MESSAGE =
|
||||
'如需更新运单物流轨迹信息,到【设置】->【基础设置】->【API开放接口】配置相应的外部访问接口';
|
||||
/** 揽收状态查询所依赖的出站回调 method */
|
||||
const WAYBILL_RECEIVE_EVENT = 'waybill.getreceive';
|
||||
/** 仓库未配置外部接口时的失败提示(直接失败,不进入任务流程) */
|
||||
@ -23,9 +29,9 @@ class WaybillWarehouseService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'list,detail,export,exportTaskProgress,updateReceive,updateReceiveTaskProgress';
|
||||
const _noNeedRight = 'list,detail,export,exportTaskProgress,updateReceive,updateReceiveTaskProgress,updateTrace,updateTraceTaskProgress';
|
||||
const _noNeedLog = '';
|
||||
const _noNeedAuth = 'list,detail,export,exportTaskProgress,updateReceive,updateReceiveTaskProgress';
|
||||
const _noNeedAuth = 'list,detail,export,exportTaskProgress,updateReceive,updateReceiveTaskProgress,updateTrace,updateTraceTaskProgress';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
@ -592,6 +598,253 @@ class WaybillWarehouseService extends MainService {
|
||||
async getReceiveTaskProgress(taskId = '') {
|
||||
return await this.getTaskProgress(taskId, WAYBILL_RECEIVE_TASK_CACHE_KEY_PREFIX);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量更新运单物流轨迹(仓库侧)。
|
||||
*
|
||||
* 链路走 OpenAPI 出站回调 `waybill.getTrace`(单批最多 10 单,自动切批),
|
||||
* 请求与 `waybill.getreceive` 一致(`{ request: { waybill_codes: [...] } }`),
|
||||
* 查询结果按 (express_id, op_time, scan_type) 幂等落库到 `wms_order_express_trace`。
|
||||
* 异步任务模式:提交后通过 `updateTraceTaskProgress` 查询进度。
|
||||
* 仓库未配置承接该 method 的 API 应用时直接失败(不创建任务)。
|
||||
*
|
||||
* 入参二选一:
|
||||
* - `waybillCodes`:显式运单号列表(优先);
|
||||
* - `where`:与 `waybill.warehouse.list` 完全一致的筛选条件(不含分页/排序)。
|
||||
*
|
||||
* @param {Object} data 请求参数。
|
||||
* @param {string[]} [data.waybillCodes] 运单号列表(兼容 waybill_codes)。
|
||||
* @param {Object} [data.where] 筛选条件(同 waybill.warehouse.list 的 where)。
|
||||
* @return {Promise<Object>} 任务提交结果,含 task_id。
|
||||
*/
|
||||
async updateTrace(data = {}) {
|
||||
try {
|
||||
const safeData = this.isPlainObject(data) ? data : {};
|
||||
let waybillCodes = this.normalizeReceiveWaybillCodes(safeData.waybillCodes || safeData.waybill_codes);
|
||||
const rawWhere = this.isPlainObject(safeData.where) ? safeData.where : null;
|
||||
|
||||
if (waybillCodes.length === 0 && !rawWhere) {
|
||||
return this.fail('运单号不能为空,或传入 where 筛选条件');
|
||||
}
|
||||
|
||||
const warehouseId = Number(this.ctx?.user?.store_id || 0);
|
||||
if (!warehouseId) {
|
||||
return this.fail('无法获取当前仓库ID');
|
||||
}
|
||||
|
||||
// 未配置外部访问接口:直接失败,不进入任务流程
|
||||
const appKey = await this.resolveTraceAppKey(warehouseId);
|
||||
if (!appKey) {
|
||||
return this.fail(WAYBILL_TRACE_NOT_CONFIGURED_MESSAGE);
|
||||
}
|
||||
|
||||
if (waybillCodes.length === 0) {
|
||||
const resolved = await this.service.systems.waybill.resolveWaybillCodesByWhere({
|
||||
where: rawWhere,
|
||||
warehouseId,
|
||||
limit: WAYBILL_RECEIVE_MAX_CODES,
|
||||
});
|
||||
if (resolved.exceeded) {
|
||||
return this.fail(
|
||||
`符合条件的运单超过 ${WAYBILL_RECEIVE_MAX_CODES} 条,请缩小筛选范围或直接传 waybillCodes`
|
||||
);
|
||||
}
|
||||
waybillCodes = this.normalizeReceiveWaybillCodes(resolved.codes);
|
||||
if (waybillCodes.length === 0) {
|
||||
return this.fail('未匹配到符合条件的运单');
|
||||
}
|
||||
}
|
||||
|
||||
const taskId = this.generateTraceTaskId();
|
||||
const taskPayload = {
|
||||
task_id: taskId,
|
||||
status: 'submitted',
|
||||
progress: 0,
|
||||
current_count: 0,
|
||||
total_count: waybillCodes.length,
|
||||
message: '更新物流轨迹任务已提交',
|
||||
result: null,
|
||||
error: '',
|
||||
};
|
||||
await this.setTraceTaskProgress(taskId, taskPayload);
|
||||
|
||||
setImmediate(async () => {
|
||||
try {
|
||||
await this.setTraceTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'running',
|
||||
progress: 0,
|
||||
current_count: 0,
|
||||
total_count: waybillCodes.length,
|
||||
message: '正在查询运单物流轨迹',
|
||||
result: null,
|
||||
error: '',
|
||||
});
|
||||
|
||||
const result = await this.service.systems.waybill.queryTraces({
|
||||
warehouseId,
|
||||
waybillCodes,
|
||||
appKey,
|
||||
onProgress: async progress => {
|
||||
const safeProgress = this.isPlainObject(progress) ? progress : {};
|
||||
await this.setTraceTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'running',
|
||||
progress: safeProgress.progress || 0,
|
||||
current_count: safeProgress.currentCount || 0,
|
||||
total_count: safeProgress.totalCount || waybillCodes.length,
|
||||
message: safeProgress.message || '正在查询运单物流轨迹',
|
||||
result: null,
|
||||
error: '',
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
if (!result || result.success !== true) {
|
||||
await this.setTraceTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'failed',
|
||||
progress: 100,
|
||||
current_count: 0,
|
||||
total_count: waybillCodes.length,
|
||||
message: '更新物流轨迹失败',
|
||||
result: null,
|
||||
error: String(result && result.reason || '运单物流轨迹查询失败'),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const failedList = Array.isArray(result.failed) ? result.failed : [];
|
||||
await this.setTraceTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'success',
|
||||
progress: 100,
|
||||
current_count: waybillCodes.length,
|
||||
total_count: waybillCodes.length,
|
||||
message: `更新完成:新增 ${result.inserted} 条轨迹,更新 ${result.updated} 条,失败 ${failedList.length} 单`,
|
||||
result: {
|
||||
total: result.total,
|
||||
matched: result.matched,
|
||||
inserted: result.inserted,
|
||||
updated: result.updated,
|
||||
not_found: Array.isArray(result.not_found) ? result.not_found : [],
|
||||
failed: failedList,
|
||||
},
|
||||
error: '',
|
||||
});
|
||||
} catch (error) {
|
||||
const errorMessage = error && error.message ? error.message : `${error}`;
|
||||
await this.setTraceTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'failed',
|
||||
progress: 100,
|
||||
message: '更新物流轨迹失败',
|
||||
result: null,
|
||||
error: errorMessage,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return this.success('ok', {
|
||||
...taskPayload,
|
||||
update_time: Date.now(),
|
||||
});
|
||||
} catch (e) {
|
||||
return this.fail(e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询运单物流轨迹更新任务进度。
|
||||
*
|
||||
* @param {Object} data 请求参数。
|
||||
* @param {string} [data.task_id] 任务ID(下划线写法)。
|
||||
* @param {string} [data.taskId] 任务ID(驼峰写法)。
|
||||
* @return {Promise<Object>} 任务进度信息。
|
||||
*/
|
||||
async updateTraceTaskProgress(data = {}) {
|
||||
try {
|
||||
const safeData = this.isPlainObject(data) ? data : {};
|
||||
const taskId = String(safeData.task_id || safeData.taskId || '').trim();
|
||||
const notFoundPayload = {
|
||||
task_id: taskId,
|
||||
status: 'not_found',
|
||||
progress: 0,
|
||||
current_count: 0,
|
||||
total_count: 0,
|
||||
message: '任务不存在',
|
||||
result: null,
|
||||
error: '',
|
||||
update_time: Date.now(),
|
||||
};
|
||||
|
||||
if (!taskId) {
|
||||
return this.success('ok', notFoundPayload);
|
||||
}
|
||||
|
||||
const cachedTask = await this.getTraceTaskProgress(taskId);
|
||||
if (!cachedTask) {
|
||||
return this.success('ok', notFoundPayload);
|
||||
}
|
||||
|
||||
return this.success('ok', {
|
||||
task_id: taskId,
|
||||
...cachedTask,
|
||||
update_time: Date.now(),
|
||||
});
|
||||
} catch (e) {
|
||||
return this.fail(e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成运单物流轨迹更新任务ID。
|
||||
* @return {string} 任务ID。
|
||||
*/
|
||||
generateTraceTaskId() {
|
||||
const warehouseId = this.ctx?.user?.store_id || 'unknown';
|
||||
const timestamp = Date.now();
|
||||
const randomToken = Math.random().toString(36).slice(2, 10);
|
||||
return `waybill_trace_${warehouseId}_${timestamp}_${randomToken}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析仓库承接 waybill.getTrace 的 API 应用 AppKey(按 id 升序取首个)。
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @return {Promise<string>} 目标应用 AppKey,未配置时返回空字符串。
|
||||
*/
|
||||
async resolveTraceAppKey(warehouseId) {
|
||||
const warehouseNotify = this.service.systems && this.service.systems.warehouseNotify;
|
||||
if (!warehouseNotify || typeof warehouseNotify.listCallbackConfigs !== 'function') {
|
||||
return '';
|
||||
}
|
||||
|
||||
const candidates = await warehouseNotify.listCallbackConfigs(
|
||||
Number(warehouseId) || 0,
|
||||
WAYBILL_TRACE_EVENT
|
||||
);
|
||||
const first = Array.isArray(candidates) ? candidates[0] : null;
|
||||
return String(first && first.appKey || '').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入运单物流轨迹任务进度缓存。
|
||||
* @param {string} taskId 任务ID。
|
||||
* @param {Object} payload 任务状态。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async setTraceTaskProgress(taskId = '', payload = {}) {
|
||||
await this.setTaskProgress(taskId, payload, WAYBILL_TRACE_TASK_CACHE_KEY_PREFIX);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取运单物流轨迹任务进度缓存。
|
||||
* @param {string} taskId 任务ID。
|
||||
* @return {Promise<Object|null>} 任务状态对象或 null。
|
||||
*/
|
||||
async getTraceTaskProgress(taskId = '') {
|
||||
return await this.getTaskProgress(taskId, WAYBILL_TRACE_TASK_CACHE_KEY_PREFIX);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WaybillWarehouseService;
|
||||
|
||||
@ -22,6 +22,15 @@ const WAYBILL_RECEIVE_FLAGS = [ 'Y', 'N' ];
|
||||
*/
|
||||
const WAYBILL_RECEIVE_SIGN_MODE = 'simple';
|
||||
|
||||
/** 出站回调 method:批量查询运单物流轨迹 */
|
||||
const WAYBILL_TRACE_EVENT = 'waybill.getTrace';
|
||||
|
||||
/** 单次轨迹回调最多携带的运单号数量(与揽收查询一致,按 10 单切批) */
|
||||
const WAYBILL_TRACE_MAX_BATCH = 10;
|
||||
|
||||
/** 轨迹查询回调签名模式:与揽收查询一致(仓库通知协议) */
|
||||
const WAYBILL_TRACE_SIGN_MODE = WAYBILL_RECEIVE_SIGN_MODE;
|
||||
|
||||
/**
|
||||
* 业务逻辑层:waybill(运单号快速查询)。
|
||||
*/
|
||||
@ -1530,6 +1539,335 @@ class WaybillService extends MainService {
|
||||
if ([ '0', 'N', 'NO', 'FALSE' ].includes(text)) return 'N';
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量查询运单物流轨迹(出站回调 waybill.getTrace)并落库 wms_order_express_trace。
|
||||
*
|
||||
* 请求与 `waybill.getreceive` 一致:`{ request: { waybill_codes: [...] } }`,单批最多 10 单。
|
||||
* 外部返回:
|
||||
* ```
|
||||
* [{ "waybillNo": "770358128188071",
|
||||
* "trace": { "opTime": "2026-11-10 06:15:53", "outBizCode": "...",
|
||||
* "memo": "【广州市】快件已发往 山东济南转运中心",
|
||||
* "opOrgCityName": "广州市", "weight": 0, "scanType": "发件" } }]
|
||||
* ```
|
||||
* 兼容 `trace` 为数组、`traces` 数组、以及 `{ code, data: [...] }` 包装。
|
||||
* 落库按 (express_id, op_time, scan_type) 幂等:已存在则更新轨迹文案等字段,不产生重复行。
|
||||
*
|
||||
* @param {Object} options 查询参数。
|
||||
* @param {number} options.warehouseId 仓库 ID(回写隔离)。
|
||||
* @param {Array<string>} options.waybillCodes 运单号列表。
|
||||
* @param {string} [options.appKey] 指定目标应用 AppKey,不传则按仓库订阅关系解析。
|
||||
* @param {Function} [options.onProgress] 进度回调(每批完成后触发)。
|
||||
* @return {Promise<Object>} 结果 { success, event, app_key, total, matched, inserted, updated, not_found, failed, reason }。
|
||||
*/
|
||||
async queryTraces({ warehouseId, waybillCodes, appKey = '', onProgress = null } = {}) {
|
||||
const { ctx } = this;
|
||||
const normalizedWarehouseId = Number(warehouseId) || 0;
|
||||
const codes = this.normalizeWaybillCodes(waybillCodes);
|
||||
const base = {
|
||||
success: false,
|
||||
event: WAYBILL_TRACE_EVENT,
|
||||
app_key: String(appKey || '').trim(),
|
||||
total: codes.length,
|
||||
matched: 0,
|
||||
inserted: 0,
|
||||
updated: 0,
|
||||
not_found: [],
|
||||
failed: [],
|
||||
};
|
||||
|
||||
if (codes.length === 0) {
|
||||
return { ...base, reason: '运单号不能为空' };
|
||||
}
|
||||
if (!normalizedWarehouseId) {
|
||||
return { ...base, reason: '缺少仓库ID' };
|
||||
}
|
||||
|
||||
const targetAppKey = base.app_key
|
||||
|| await this.resolveTraceQueryAppKey(normalizedWarehouseId);
|
||||
if (!targetAppKey) {
|
||||
return {
|
||||
...base,
|
||||
skipped: true,
|
||||
reason: '无应用承接该回调 method(callback_functions 未勾选或应用未启用)',
|
||||
};
|
||||
}
|
||||
|
||||
const callbackService = ctx.service.openapi && ctx.service.openapi.callback;
|
||||
if (!callbackService || typeof callbackService.sendByAppKey !== 'function') {
|
||||
return { ...base, app_key: targetAppKey, reason: 'OpenAPI 回调服务不可用' };
|
||||
}
|
||||
|
||||
const traceGroups = [];
|
||||
const failed = [];
|
||||
let processedCount = 0;
|
||||
|
||||
for (let offset = 0; offset < codes.length; offset += WAYBILL_TRACE_MAX_BATCH) {
|
||||
const batch = codes.slice(offset, offset + WAYBILL_TRACE_MAX_BATCH);
|
||||
const result = await callbackService.sendByAppKey({
|
||||
appKey: targetAppKey,
|
||||
event: WAYBILL_TRACE_EVENT,
|
||||
request: { waybill_codes: batch },
|
||||
signMode: WAYBILL_TRACE_SIGN_MODE,
|
||||
});
|
||||
|
||||
if (!result || result.success !== true) {
|
||||
const error = String(result && result.error || '未知错误');
|
||||
ctx.logger.warn('[WaybillService.queryTraces] 轨迹查询回调失败', {
|
||||
warehouseId: normalizedWarehouseId,
|
||||
appKey: targetAppKey,
|
||||
batchSize: batch.length,
|
||||
error,
|
||||
});
|
||||
for (const code of batch) {
|
||||
failed.push({ waybill_code: code, reason: `回调失败: ${error}` });
|
||||
}
|
||||
} else {
|
||||
const businessError = this.extractReceiveError(result.response);
|
||||
if (businessError) {
|
||||
ctx.logger.warn('[WaybillService.queryTraces] 外部接口返回业务失败', {
|
||||
warehouseId: normalizedWarehouseId,
|
||||
appKey: targetAppKey,
|
||||
batchSize: batch.length,
|
||||
error: businessError,
|
||||
});
|
||||
for (const code of batch) {
|
||||
failed.push({ waybill_code: code, reason: `外部接口返回失败: ${businessError}` });
|
||||
}
|
||||
} else {
|
||||
const rows = this.extractTraceRows(result.response);
|
||||
for (const row of rows) {
|
||||
const waybillNo = String(row.waybillNo || row.waybill_no || row.waybillCode || '').trim();
|
||||
if (!waybillNo) continue;
|
||||
const traceList = this.normalizeTraceList(row);
|
||||
if (traceList.length === 0) {
|
||||
failed.push({ waybill_code: waybillNo, reason: '轨迹内容为空' });
|
||||
continue;
|
||||
}
|
||||
traceGroups.push({ waybillNo, traces: traceList });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
processedCount += batch.length;
|
||||
await this.reportReceiveProgress(onProgress, {
|
||||
processedCount,
|
||||
totalCount: codes.length,
|
||||
failedCount: failed.length,
|
||||
});
|
||||
}
|
||||
|
||||
if (traceGroups.length === 0) {
|
||||
return { ...base, app_key: targetAppKey, failed };
|
||||
}
|
||||
|
||||
const saveResult = await this.saveTraces({
|
||||
warehouseId: normalizedWarehouseId,
|
||||
traceGroups,
|
||||
});
|
||||
|
||||
const notFound = [ ...saveResult.notFound, ...failed.map(item => item.waybill_code) ]
|
||||
.filter((code, index, arr) => arr.indexOf(code) === index);
|
||||
|
||||
ctx.logger.info('[WaybillService.queryTraces] 轨迹同步完成', {
|
||||
warehouseId: normalizedWarehouseId,
|
||||
appKey: targetAppKey,
|
||||
total: codes.length,
|
||||
matched: saveResult.matched,
|
||||
inserted: saveResult.inserted,
|
||||
updated: saveResult.updated,
|
||||
notFound: saveResult.notFound.length,
|
||||
failed: failed.length,
|
||||
});
|
||||
|
||||
return {
|
||||
...base,
|
||||
success: !failed.length || saveResult.inserted + saveResult.updated > 0,
|
||||
app_key: targetAppKey,
|
||||
matched: saveResult.matched,
|
||||
inserted: saveResult.inserted,
|
||||
updated: saveResult.updated,
|
||||
not_found: notFound,
|
||||
failed,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析轨迹查询的目标应用:取仓库下勾选了 waybill.getTrace 的首个应用(按 id 升序)。
|
||||
* @param {number} warehouseId 仓库 ID。
|
||||
* @return {Promise<string>} 目标应用 AppKey,无承接应用时返回空字符串。
|
||||
*/
|
||||
async resolveTraceQueryAppKey(warehouseId) {
|
||||
const warehouseNotify = this.service.systems && this.service.systems.warehouseNotify;
|
||||
if (!warehouseNotify || typeof warehouseNotify.listCallbackConfigs !== 'function') {
|
||||
return '';
|
||||
}
|
||||
|
||||
const candidates = await warehouseNotify.listCallbackConfigs(
|
||||
Number(warehouseId) || 0,
|
||||
WAYBILL_TRACE_EVENT
|
||||
);
|
||||
const first = Array.isArray(candidates) ? candidates[0] : null;
|
||||
return String(first && first.appKey || '').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 从回调响应中提取轨迹行,兼容裸数组与 { code, data: [...] } 包装。
|
||||
* @param {*} response 回调响应体。
|
||||
* @return {Array<Object>} 轨迹行列表(每行含 waybillNo + trace)。
|
||||
*/
|
||||
extractTraceRows(response) {
|
||||
if (Array.isArray(response)) return response;
|
||||
if (!response || typeof response !== 'object') return [];
|
||||
if (Array.isArray(response.data)) return response.data;
|
||||
if (Array.isArray(response.traces)) return response.traces;
|
||||
if (response.data && Array.isArray(response.data.traces)) return response.data.traces;
|
||||
if (response.data && Array.isArray(response.data.results)) return response.data.results;
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一单个运单的轨迹列表:trace 支持对象或数组,另兼容 traces / traceList。
|
||||
* @param {Object} row 外部返回的单行。
|
||||
* @return {Array<Object>} 轨迹对象数组。
|
||||
*/
|
||||
normalizeTraceList(row) {
|
||||
if (!row || typeof row !== 'object') return [];
|
||||
const candidates = [ row.trace, row.traces, row.traceList, row.trace_list ];
|
||||
const list = [];
|
||||
for (const item of candidates) {
|
||||
if (Array.isArray(item)) {
|
||||
list.push(...item.filter(one => one && typeof one === 'object'));
|
||||
} else if (item && typeof item === 'object') {
|
||||
list.push(item);
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析轨迹操作时间:支持 'YYYY-MM-DD HH:mm:ss' 与 ISO 字符串,非法值返回 null。
|
||||
* @param {*} value 外部返回值。
|
||||
* @return {Date|null} 解析后的时间。
|
||||
*/
|
||||
parseTraceTime(value) {
|
||||
const text = String(value === undefined || value === null ? '' : value).trim();
|
||||
if (!text) return null;
|
||||
const normalized = text.includes('T') ? text : text.replace(' ', 'T');
|
||||
const date = new Date(normalized);
|
||||
return Number.isNaN(date.getTime()) ? null : date;
|
||||
}
|
||||
|
||||
/**
|
||||
* 轨迹落库:按 (express_id, op_time, scan_type) 幂等 upsert 到 wms_order_express_trace。
|
||||
* 仅处理当前仓库下能匹配到运单的轨迹,其余计入 notFound。
|
||||
*
|
||||
* @param {Object} options 落库参数。
|
||||
* @param {number} options.warehouseId 仓库 ID。
|
||||
* @param {Array<{waybillNo: string, traces: Array<Object>}>} options.traceGroups 轨迹分组。
|
||||
* @return {Promise<{matched: number, inserted: number, updated: number, notFound: Array<string>}>} 落库统计。
|
||||
*/
|
||||
async saveTraces({ warehouseId, traceGroups = [] } = {}) {
|
||||
const { ctx } = this;
|
||||
const { Op } = this.app.Sequelize;
|
||||
const waybillCodes = [ ...new Set(traceGroups.map(item => item.waybillNo).filter(Boolean)) ];
|
||||
if (waybillCodes.length === 0) {
|
||||
return { matched: 0, inserted: 0, updated: 0, notFound: [] };
|
||||
}
|
||||
|
||||
const expressRows = await ctx.model.OrderExpress.findAll({
|
||||
attributes: [ 'id', 'waybill_code', 'order_id' ],
|
||||
where: {
|
||||
waybill_code: { [Op.in]: waybillCodes },
|
||||
warehouse_id: Number(warehouseId) || 0,
|
||||
},
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const expressMap = new Map();
|
||||
for (const row of expressRows) {
|
||||
const code = String(row.waybill_code || '').trim();
|
||||
// 同一运单号可能有多条子单记录,取 id 最小的一条作为轨迹归属
|
||||
if (!code) continue;
|
||||
const current = expressMap.get(code);
|
||||
if (!current || Number(row.id) < Number(current.id)) {
|
||||
expressMap.set(code, row);
|
||||
}
|
||||
}
|
||||
|
||||
const notFound = waybillCodes.filter(code => !expressMap.has(code));
|
||||
const rows = [];
|
||||
for (const group of traceGroups) {
|
||||
const express = expressMap.get(group.waybillNo);
|
||||
if (!express) continue;
|
||||
for (const trace of group.traces) {
|
||||
rows.push({
|
||||
express_id: Number(express.id),
|
||||
waybill_code: group.waybillNo,
|
||||
order_id: express.order_id ? Number(express.order_id) : null,
|
||||
warehouse_id: Number(warehouseId) || 0,
|
||||
op_time: this.parseTraceTime(trace.opTime || trace.op_time),
|
||||
out_biz_code: String(trace.outBizCode || trace.out_biz_code || '').trim() || null,
|
||||
memo: String(trace.memo || '').trim().slice(0, 500) || null,
|
||||
op_org_city_name: String(trace.opOrgCityName || trace.op_org_city_name || '').trim() || null,
|
||||
weight: Number(trace.weight) || 0,
|
||||
scan_type: String(trace.scanType || trace.scan_type || '').trim() || null,
|
||||
raw_data: trace,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (rows.length === 0) {
|
||||
return { matched: waybillCodes.length - notFound.length, inserted: 0, updated: 0, notFound };
|
||||
}
|
||||
|
||||
// 预判已存在的轨迹(用于区分新增/更新统计)
|
||||
const expressIds = [ ...new Set(rows.map(row => row.express_id)) ];
|
||||
const existed = await ctx.model.OrderExpressTrace.findAll({
|
||||
attributes: [ 'express_id', 'op_time', 'scan_type' ],
|
||||
where: { express_id: { [Op.in]: expressIds } },
|
||||
raw: true,
|
||||
});
|
||||
const existedKeys = new Set(existed.map(row => this.buildTraceKey(
|
||||
row.express_id,
|
||||
row.op_time,
|
||||
row.scan_type
|
||||
)));
|
||||
|
||||
let inserted = 0;
|
||||
let updated = 0;
|
||||
for (const row of rows) {
|
||||
if (existedKeys.has(this.buildTraceKey(row.express_id, row.op_time, row.scan_type))) {
|
||||
updated++;
|
||||
} else {
|
||||
inserted++;
|
||||
}
|
||||
}
|
||||
|
||||
const TraceModel = ctx.model.OrderExpressTrace;
|
||||
if (TraceModel && typeof TraceModel.bulkCreate === 'function') {
|
||||
await TraceModel.bulkCreate(rows, {
|
||||
updateOnDuplicate: [ 'out_biz_code', 'memo', 'op_org_city_name', 'weight', 'raw_data', 'updated_at' ],
|
||||
});
|
||||
}
|
||||
|
||||
return { matched: waybillCodes.length - notFound.length, inserted, updated, notFound };
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造轨迹去重键(与表唯一索引 uk_express_op_scan 口径一致)。
|
||||
* @param {*} expressId 运单ID。
|
||||
* @param {*} opTime 操作时间。
|
||||
* @param {*} scanType 扫描类型。
|
||||
* @return {string} 去重键。
|
||||
*/
|
||||
buildTraceKey(expressId, opTime, scanType) {
|
||||
const time = opTime instanceof Date
|
||||
? opTime.toISOString()
|
||||
: String(opTime || '');
|
||||
return `${Number(expressId) || 0}|${time}|${String(scanType || '')}`;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WaybillService;
|
||||
|
||||
@ -75,6 +75,29 @@
|
||||
| `express_print_record` | `express_no` ↔ `waybill_code` | 打印记录(打印时间、打印机、模板) |
|
||||
| `pack_task` | `waybill_code` | 打包任务(打包状态、打包人、打包时间) |
|
||||
| `package_material` | `package_material_id` ↔ `id` | 包材详情 |
|
||||
| `wms_order_express_trace` | `express_id` ↔ `id`(另冗余 `waybill_code` / `order_id`) | 运单物流轨迹(1 运单 : N 轨迹,外部快递接口回传) |
|
||||
|
||||
### 2.2.1 `wms_order_express_trace`(运单物流轨迹,2026-11-11 新增)
|
||||
|
||||
一个运单对应多条轨迹,外部返回的轨迹行字段同名转下划线落库,未建模字段存 `raw_data` 兜底。
|
||||
|
||||
| 列 | 类型 | 对应外部字段 | 说明 |
|
||||
|---|---|---|---|
|
||||
| `express_id` | BIGINT UNSIGNED NOT NULL | — | 关联 `wms_order_express.id`(弱引用,不建物理外键) |
|
||||
| `waybill_code` | VARCHAR(50) NOT NULL | — | 运单号(冗余,便于直查) |
|
||||
| `order_id` | BIGINT UNSIGNED NULL | — | 订单ID(冗余,便于按订单查) |
|
||||
| `warehouse_id` | BIGINT UNSIGNED NOT NULL | — | 仓库隔离维度 |
|
||||
| `op_time` | DATETIME NULL | `opTime` | 操作时间 |
|
||||
| `out_biz_code` | VARCHAR(191) NULL | `outBizCode` | 外部业务码 |
|
||||
| `memo` | VARCHAR(500) NULL | `memo` | 轨迹描述 |
|
||||
| `op_org_city_name` | VARCHAR(100) NULL | `opOrgCityName` | 操作机构城市 |
|
||||
| `weight` | INT NULL DEFAULT 0 | `weight` | 重量(来源原值) |
|
||||
| `scan_type` | VARCHAR(50) NULL | `scanType` | 扫描类型(发件/到件/派件/签收) |
|
||||
| `raw_data` | JSON NULL | — | 原始轨迹报文兜底 |
|
||||
|
||||
索引:`uk_express_op_scan (express_id, op_time, scan_type)` 幂等去重、`idx_waybill_code (waybill_code, op_time)`、`idx_order_id`、`idx_warehouse_op_time (warehouse_id, op_time)`。
|
||||
|
||||
模型:`app/model/order_express_trace.js`(`paranoid`,`deleted_at` 软删除)。表字符集与主表一致(`utf8mb4_general_ci`)。
|
||||
|
||||
### 2.3 索引评估
|
||||
|
||||
@ -212,14 +235,16 @@ POST /system { method: "waybill.warehouse.list", ... }
|
||||
| 4 | `waybill.warehouse.exportTaskProgress` | 运单导出任务进度查询 | ✓ | ✗ |
|
||||
| 5 | `waybill.warehouse.updateReceive` | 批量更新运单是否揽收(走出站回调 `waybill.getreceive`,异步任务) | ✓ | ✗ |
|
||||
| 6 | `waybill.warehouse.updateReceiveTaskProgress` | 揽收状态更新任务进度查询 | ✓ | ✗ |
|
||||
| 7 | `waybill.warehouse.updateTrace` | 批量更新运单物流轨迹(走出站回调 `waybill.getTrace`,异步任务) | ✓ | ✗ |
|
||||
| 8 | `waybill.warehouse.updateTraceTaskProgress` | 物流轨迹更新任务进度查询 | ✓ | ✗ |
|
||||
|
||||
> **预留接口(本期不实现)**:
|
||||
>
|
||||
> | # | method | 描述 |
|
||||
> |---|--------|------|
|
||||
> | 7 | `waybill.store.list` | 运单列表-货主侧(按 store_id 隔离) |
|
||||
> | 8 | `waybill.store.detail` | 运单详情-货主侧 |
|
||||
> | 9 | `waybill.store.export` | 运单导出-货主侧 |
|
||||
> | 9 | `waybill.store.list` | 运单列表-货主侧(按 store_id 隔离) |
|
||||
> | 10 | `waybill.store.detail` | 运单详情-货主侧 |
|
||||
> | 11 | `waybill.store.export` | 运单导出-货主侧 |
|
||||
|
||||
---
|
||||
|
||||
@ -582,6 +607,64 @@ waybill.warehouse.updateReceive(入口层:参数校验 + 接口配置预检
|
||||
|
||||
---
|
||||
|
||||
### 3.9 `waybill.warehouse.updateTrace` / `waybill.warehouse.updateTraceTaskProgress` — 批量更新物流轨迹(仓库侧)
|
||||
|
||||
**功能说明**:按运单号(或 `where` 条件圈选)调用外部访问接口查询物流轨迹,落库到 `wms_order_express_trace`。入参与 `waybill.warehouse.updateReceive` **完全一致**。
|
||||
|
||||
#### 调用链路
|
||||
|
||||
```
|
||||
waybill.warehouse.updateTrace(入口层:参数校验 + 接口配置预检 + 建任务)
|
||||
→ systems/waybill.js#queryTraces(每批 ≤10 单)
|
||||
→ openapi/callback.js#sendByAppKey(event = waybill.getTrace,signMode=simple)
|
||||
→ systems/waybill.js#saveTraces(按 express_id + op_time + scan_type 幂等 upsert)
|
||||
```
|
||||
|
||||
#### 请求参数
|
||||
|
||||
```json
|
||||
{ "method": "waybill.warehouse.updateTrace", "waybillCodes": ["770358128188071"] }
|
||||
```
|
||||
```json
|
||||
{ "method": "waybill.warehouse.updateTrace", "where": { "isGalaxyReceive": "Y", "logisticsCode": "YTO" } }
|
||||
```
|
||||
|
||||
参数、优先级、5000 条上限与 `updateReceive` 相同(`waybillCodes` > `where`)。
|
||||
|
||||
#### 外部接口约定(`waybill.getTrace`)
|
||||
|
||||
- 请求体:`{ "request": { "waybill_codes": [...] } }`,单批最多 10 单;签名同 `waybill.getreceive`(`MD5(appSecret + timestamp + bodyJson)`)
|
||||
- 响应:
|
||||
|
||||
```json
|
||||
[{
|
||||
"waybillNo": "770358128188071",
|
||||
"trace": {
|
||||
"opTime": "2026-11-10 06:15:53",
|
||||
"outBizCode": "770358128188071_510180_1794262553000_210",
|
||||
"memo": "【广州市】快件已发往 山东济南转运中心",
|
||||
"opOrgCityName": "广州市",
|
||||
"weight": 0,
|
||||
"scanType": "发件"
|
||||
}
|
||||
}]
|
||||
```
|
||||
|
||||
- 兼容:`trace` 可为数组(一个运单多条轨迹)、`traces`/`traceList` 数组、`{ code, data: [...] }` 包装
|
||||
- 落库映射:`opTime→op_time`、`outBizCode→out_biz_code`、`memo→memo`、`opOrgCityName→op_org_city_name`、`weight→weight`、`scanType→scan_type`,原始报文存 `raw_data`
|
||||
- 幂等:唯一键 `(express_id, op_time, scan_type)`,重复回传只更新 `memo` / `op_org_city_name` / `weight` / `raw_data`
|
||||
- 匹配不到运单的轨迹不落库,运单号写入任务 `result.not_found`
|
||||
|
||||
#### 任务进度
|
||||
|
||||
`task_id` 前缀 `waybill_trace_`,缓存键前缀 `waybill_trace_task_`(与 `waybill_export_`、`waybill_receive_` 隔离),`result` 返回 `{ total, matched, inserted, updated, not_found, failed }`。
|
||||
|
||||
```json
|
||||
{ "method": "waybill.warehouse.updateTraceTaskProgress", "task_id": "waybill_trace_1000028_1731190000000_ab12cd34" }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 四、`methods/system.json` 变更
|
||||
|
||||
在 `methods.groups[]` 中新增 `waybill.warehouse` group:
|
||||
|
||||
@ -0,0 +1,137 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 创建运单物流轨迹表 wms_order_express_trace。
|
||||
*
|
||||
* 与 wms_order_express 关联:一个运单(express_id)对应多条轨迹(1:N),
|
||||
* 轨迹由外部快递/轨迹接口回传(如奇门 taobao.qimen.trace.query 的 traces 节点)。
|
||||
*
|
||||
* 字段口径(与外部返回的轨迹行同名转下划线):
|
||||
* op_time opTime 操作时间
|
||||
* out_biz_code outBizCode 外部业务码(可能是拼接串,如 770358128188071_510180_1794262553000_210)
|
||||
* memo memo 轨迹描述,如【广州市】快件已发往 山东济南转运中心
|
||||
* op_org_city_name opOrgCityName 操作机构所在城市
|
||||
* weight weight 重量(来源原值,单位以对接方为准)
|
||||
* scan_type scanType 扫描类型,如 发件 / 到件 / 派件 / 签收
|
||||
* raw_data 原始报文 JSON,便于后续新增字段时不改表结构
|
||||
*
|
||||
* 关联与隔离:
|
||||
* express_id / waybill_code / order_id 冗余落库,便于「按运单」「按订单」直接查询;
|
||||
* warehouse_id 做仓库隔离,避免跨仓串读。
|
||||
*
|
||||
* 幂等去重:uk_express_op_scan(express_id + op_time + scan_type)保证重复回传不落重复行。
|
||||
*
|
||||
* 索引:
|
||||
* uk_express_op_scan(express_id, op_time, scan_type 唯一)
|
||||
* idx_waybill_code(waybill_code, op_time)
|
||||
* idx_order_id(order_id)
|
||||
* idx_warehouse_op_time(warehouse_id, op_time)
|
||||
*/
|
||||
|
||||
const TABLE_NAME = 'wms_order_express_trace';
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
const { BIGINT, STRING, INTEGER, DATE, JSON: JSON_TYPE } = Sequelize;
|
||||
|
||||
await queryInterface.createTable(TABLE_NAME, {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键ID',
|
||||
},
|
||||
express_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '运单ID(wms_order_express.id)',
|
||||
},
|
||||
waybill_code: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: '运单号(冗余,便于按运单号直查)',
|
||||
},
|
||||
order_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '订单ID(冗余,便于按订单查轨迹)',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '仓库ID(数据隔离维度)',
|
||||
},
|
||||
op_time: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '操作时间(opTime)',
|
||||
},
|
||||
out_biz_code: {
|
||||
type: STRING(191),
|
||||
allowNull: true,
|
||||
comment: '外部业务码(outBizCode)',
|
||||
},
|
||||
memo: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '轨迹描述(memo),如【广州市】快件已发往 山东济南转运中心',
|
||||
},
|
||||
op_org_city_name: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '操作机构所在城市(opOrgCityName)',
|
||||
},
|
||||
weight: {
|
||||
type: INTEGER(11),
|
||||
allowNull: true,
|
||||
defaultValue: 0,
|
||||
comment: '重量(weight,来源原值)',
|
||||
},
|
||||
scan_type: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '扫描类型(scanType),如 发件/到件/派件/签收',
|
||||
},
|
||||
raw_data: {
|
||||
type: JSON_TYPE,
|
||||
allowNull: true,
|
||||
comment: '原始轨迹报文(未落库字段的兜底存储)',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '更新时间',
|
||||
},
|
||||
deleted_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '软删除时间',
|
||||
},
|
||||
}, {
|
||||
// 与主表 wms_order_express 保持一致(utf8mb4_general_ci),避免轨迹描述含 4 字节字符时写入失败
|
||||
charset: 'utf8mb4',
|
||||
collate: 'utf8mb4_general_ci',
|
||||
comment: '运单物流轨迹表(1 运单 : N 轨迹)',
|
||||
});
|
||||
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'express_id', 'op_time', 'scan_type' ], {
|
||||
unique: true,
|
||||
name: 'uk_express_op_scan',
|
||||
});
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'waybill_code', 'op_time' ], { name: 'idx_waybill_code' });
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'order_id' ], { name: 'idx_order_id' });
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'op_time' ], { name: 'idx_warehouse_op_time' });
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.dropTable(TABLE_NAME);
|
||||
},
|
||||
};
|
||||
@ -372,6 +372,33 @@ app_key=APP2024011514301234&method=entryorder.confirm×tamp=1758047400&v=1.0
|
||||
- `is_galaxy_receive` 兼容取值:`1`/`0`、`'Y'`/`'N'`(大小写不敏感)、布尔值;非法取值计入 `failed`,不写库
|
||||
- 回写口径:按 `waybill_code` + `warehouse_id` 更新 `wms_order_express.is_galaxy_receive`(`1→Y`、`0→N`),跨仓不串写
|
||||
|
||||
### 3.7 waybill.getTrace(查询型回调:物流轨迹)
|
||||
|
||||
- label:运单物流轨迹查询
|
||||
- description:按运单号批量查询物流轨迹;消费外部响应并落库 `wms_order_express_trace`
|
||||
- 注册位置:`app/lib/callback_functions.js#CALLBACK_FUNCTIONS`
|
||||
- 实现:`app/service/systems/waybill.js#queryTraces` + `#saveTraces`;业务入口 `waybill.warehouse.updateTrace`(进度走 `waybill.warehouse.updateTraceTaskProgress`)
|
||||
- 入参:与 `waybill.getreceive` 一致(`{ request: { waybill_codes: [...] } }`,单批最多 10 单);签名同样为 `MD5(appSecret + timestamp + bodyJson)`
|
||||
- 响应:
|
||||
|
||||
```json
|
||||
[{
|
||||
"waybillNo": "770358128188071",
|
||||
"trace": {
|
||||
"opTime": "2026-11-10 06:15:53",
|
||||
"outBizCode": "770358128188071_510180_1794262553000_210",
|
||||
"memo": "【广州市】快件已发往 山东济南转运中心",
|
||||
"opOrgCityName": "广州市",
|
||||
"weight": 0,
|
||||
"scanType": "发件"
|
||||
}
|
||||
}]
|
||||
```
|
||||
|
||||
- 兼容:`trace` 可为数组(一个运单多条轨迹)、`traces` / `traceList` 数组、`{ code, data: [...] }` 包装
|
||||
- 落库:`wms_order_express_trace`,唯一键 `(express_id, op_time, scan_type)` 幂等,命中时更新 `memo` / `op_org_city_name` / `weight` / `raw_data`
|
||||
- 失败识别:与 3.6 相同(HTTP 200 但 `code` 非 `0/1/200` 整批判失败)
|
||||
|
||||
## 4. timestamp 规范(2026-09-12 已统一为秒)
|
||||
|
||||
`timestamp` 已统一为**秒级(10 位字符串)**规范值:`String(Math.floor(Date.now() / 1000))`。
|
||||
|
||||
@ -1,4 +1,24 @@
|
||||
[
|
||||
{
|
||||
"version": "0.3.325",
|
||||
"date": "2026-11-11",
|
||||
"type": "added",
|
||||
"summary": "新增运单物流轨迹批量更新:waybill.warehouse.updateTrace 与 waybill.warehouse.updateTraceTaskProgress,链路走 OpenAPI 出站回调 waybill.getTrace(入参同 waybill.getreceive,单批 10 单),结果按 (express_id, op_time, scan_type) 幂等落库 wms_order_express_trace",
|
||||
"methods": [
|
||||
"waybill.warehouse.updateTrace",
|
||||
"waybill.warehouse.updateTraceTaskProgress"
|
||||
],
|
||||
"notes": [
|
||||
"回调方法注册:app/lib/callback_functions.js#CALLBACK_FUNCTIONS 新增 waybill.getTrace(名称「运单物流轨迹查询」),管理端 apiApp.listCallbackFunctions 可拉取并勾选。",
|
||||
"入参:与 waybill.warehouse.updateReceive 完全一致,支持 waybillCodes(优先)或 where(与 waybill.warehouse.list 同口径,不含分页/排序,上限 5000 条)。",
|
||||
"请求体:{ request: { waybill_codes: [...] } },单批最多 10 个运单号;签名口径与 waybill.getreceive 一致(MD5(appSecret + timestamp + bodyJson))。",
|
||||
"响应解析:[{ waybillNo, trace: {...} }],兼容 trace 为数组、traces 数组、traceList 与 { code, data: [...] } 包装。",
|
||||
"落库:wms_order_express_trace,字段映射 opTime→op_time、outBizCode→out_biz_code、memo→memo、opOrgCityName→op_org_city_name、weight→weight、scanType→scan_type,原始报文存 raw_data;唯一键 (express_id, op_time, scan_type) 保证重复回传不产生重复行,命中时更新轨迹文案等字段。",
|
||||
"任务:task_id 前缀 waybill_trace_,Redis 缓存键前缀 waybill_trace_task_;状态流转 submitted → running → success/failed,result 返回 { total, matched, inserted, updated, not_found, failed }。",
|
||||
"前置校验:仓库下无应用承接 waybill.getTrace 时直接失败并提示「如需更新运单物流轨迹信息,到【设置】->【基础设置】->【API开放接口】配置相应的外部访问接口」,不创建任务。",
|
||||
"代码依据:app/service/systemMethods/waybill/warehouse.js#updateTrace/#updateTraceTaskProgress,app/service/systems/waybill.js#queryTraces/#saveTraces。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.324",
|
||||
"date": "2026-11-11",
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
{
|
||||
"module": "system",
|
||||
"description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内",
|
||||
"version": "0.3.324",
|
||||
"version": "0.3.325",
|
||||
"updatedAt": "2026-11-11",
|
||||
"headers": [
|
||||
{
|
||||
@ -43237,6 +43237,303 @@
|
||||
"message": "服务器内部错误:揽收状态更新进度查询失败"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"method": "waybill.warehouse.updateTrace",
|
||||
"description": "批量更新运单物流轨迹-仓库侧:按运单号(或按 where 筛选条件圈选的运单号)调用外部访问接口 waybill.getTrace 查询轨迹(单批最多 10 单,超出自动切批),结果按 (express_id, op_time, scan_type) 幂等落库到 wms_order_express_trace(仓库隔离)。异步任务模式,提交后通过 updateTraceTaskProgress 查询进度。仓库未配置承接该回调方法的 API 应用时直接失败,不创建任务。",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
"headers": [
|
||||
{
|
||||
"name": "Authorization",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "****** warehouseId(仓库上下文,ctx.user.store_id)"
|
||||
}
|
||||
],
|
||||
"params": [
|
||||
{
|
||||
"name": "waybillCodes",
|
||||
"type": "array",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "运单号列表(字符串数组),提交后按 10 单一批调用外部接口;与 where 二选一,两者都传时以 waybillCodes 为准"
|
||||
},
|
||||
{
|
||||
"name": "waybill_codes",
|
||||
"type": "array",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "waybillCodes 的下划线别名,二者取其一"
|
||||
},
|
||||
{
|
||||
"name": "where",
|
||||
"type": "object",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "筛选条件,与 waybill.warehouse.list 完全一致(不含 pagination/sort),支持 waybillCode / mainWaybillCode / orderId / logisticsCode / status / isBack / isIntercept / isGalaxyReceive / keyword / createdAt 等;服务端先按条件解析运单号再走同一任务链路,匹配数超过 5000 条时失败并要求缩小范围"
|
||||
}
|
||||
],
|
||||
"response": [
|
||||
{
|
||||
"name": "code",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "业务状态码,200 表示成功"
|
||||
},
|
||||
{
|
||||
"name": "message",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "业务提示信息"
|
||||
},
|
||||
{
|
||||
"name": "data",
|
||||
"type": "object",
|
||||
"required": true,
|
||||
"description": "成功时返回的任务受理信息(异步任务模式)",
|
||||
"children": [
|
||||
{
|
||||
"name": "task_id",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "异步任务ID,前缀 waybill_trace_,用于通过 updateTraceTaskProgress 查询进度"
|
||||
},
|
||||
{
|
||||
"name": "status",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "任务状态:submitted(已提交)/ running(执行中)/ success(成功)/ failed(失败)"
|
||||
},
|
||||
{
|
||||
"name": "progress",
|
||||
"type": "number",
|
||||
"required": false,
|
||||
"description": "任务进度百分比(0-100)"
|
||||
},
|
||||
{
|
||||
"name": "current_count",
|
||||
"type": "number",
|
||||
"required": false,
|
||||
"description": "已查询的运单数"
|
||||
},
|
||||
{
|
||||
"name": "total_count",
|
||||
"type": "number",
|
||||
"required": false,
|
||||
"description": "本次提交的运单总数"
|
||||
},
|
||||
{
|
||||
"name": "message",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"description": "任务状态说明"
|
||||
},
|
||||
{
|
||||
"name": "update_time",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"description": "任务最近更新时间"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"errors": [
|
||||
{
|
||||
"code": "401",
|
||||
"message": "未登录,请先登录"
|
||||
},
|
||||
{
|
||||
"code": "403",
|
||||
"message": "如需更新运单物流轨迹信息,到【设置】->【基础设置】->【API开放接口】配置相应的外部访问接口"
|
||||
},
|
||||
{
|
||||
"code": "405",
|
||||
"message": "参数校验失败:运单号不能为空,或传入 where 筛选条件"
|
||||
},
|
||||
{
|
||||
"code": "405",
|
||||
"message": "参数校验失败:符合条件的运单超过 5000 条,请缩小筛选范围或直接传 waybillCodes"
|
||||
},
|
||||
{
|
||||
"code": "405",
|
||||
"message": "参数校验失败:未匹配到符合条件的运单"
|
||||
},
|
||||
{
|
||||
"code": "500",
|
||||
"message": "服务器内部错误:更新物流轨迹任务创建失败"
|
||||
}
|
||||
],
|
||||
"notes": [
|
||||
"链路:systemMethods/waybill/warehouse.js#updateTrace → systems/waybill.js#queryTraces → openapi/callback.js#sendByAppKey(event=waybill.getTrace)",
|
||||
"请求与 waybill.getreceive 一致:{ request: { waybill_codes: [...] } },单批最多 10 个运单号,超出自动切批并在每批完成后更新任务进度",
|
||||
"外部返回格式:[{ waybillNo, trace: { opTime, outBizCode, memo, opOrgCityName, weight, scanType } }];兼容 trace 为数组、traces 数组、{ code, data: [...] } 包装",
|
||||
"落库:写 wms_order_express_trace,express_id 由 waybill_code + warehouse_id 匹配 wms_order_express 得到;按 (express_id, op_time, scan_type) 幂等,已存在则更新 memo/op_org_city_name/weight/raw_data",
|
||||
"匹配不到运单的轨迹不计入落库,运单号写入任务 result.not_found",
|
||||
"签名口径:与 waybill.getreceive 一致(signMode=simple,MD5(appSecret + timestamp + bodyJson))",
|
||||
"签名字段映射:opTime→op_time、outBizCode→out_biz_code、memo→memo、opOrgCityName→op_org_city_name、weight→weight、scanType→scan_type,原始报文存 raw_data",
|
||||
"where 圈选上限 5000 条(与 updateReceive 一致);运单号来源优先级 waybillCodes > where",
|
||||
"任务进度:task_id 前缀 waybill_trace_,Redis 缓存键前缀 waybill_trace_task_,与导出(waybill_export_)、揽收(waybill_receive_)互相隔离",
|
||||
"目标应用:仓库下 callback_functions 勾选了 waybill.getTrace 的首个启用应用(按 id 升序)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"method": "waybill.warehouse.updateTraceTaskProgress",
|
||||
"description": "运单物流轨迹更新进度查询-仓库侧:按 task_id 或 taskId 查询异步任务执行进度。任务进度通过 Redis 缓存存储,任务 ID 前缀 waybill_trace_。",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
"headers": [
|
||||
{
|
||||
"name": "Authorization",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "****** warehouseId(仓库上下文,ctx.user.store_id)"
|
||||
}
|
||||
],
|
||||
"params": [
|
||||
{
|
||||
"name": "task_id",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "异步任务ID(前缀 waybill_trace_)。与 taskId 二选一"
|
||||
},
|
||||
{
|
||||
"name": "taskId",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "异步任务ID(别名,优先使用)"
|
||||
}
|
||||
],
|
||||
"response": [
|
||||
{
|
||||
"name": "code",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "业务状态码,200 表示成功"
|
||||
},
|
||||
{
|
||||
"name": "message",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "业务提示信息"
|
||||
},
|
||||
{
|
||||
"name": "data",
|
||||
"type": "object",
|
||||
"required": true,
|
||||
"description": "成功时返回的任务进度信息",
|
||||
"children": [
|
||||
{
|
||||
"name": "task_id",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "任务ID"
|
||||
},
|
||||
{
|
||||
"name": "status",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "任务状态:submitted / running / success / failed / not_found"
|
||||
},
|
||||
{
|
||||
"name": "progress",
|
||||
"type": "number",
|
||||
"required": false,
|
||||
"description": "任务进度百分比(0-100)"
|
||||
},
|
||||
{
|
||||
"name": "current_count",
|
||||
"type": "number",
|
||||
"required": false,
|
||||
"description": "当前已处理的运单数"
|
||||
},
|
||||
{
|
||||
"name": "total_count",
|
||||
"type": "number",
|
||||
"required": false,
|
||||
"description": "本次提交的运单总数"
|
||||
},
|
||||
{
|
||||
"name": "message",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"description": "任务状态说明"
|
||||
},
|
||||
{
|
||||
"name": "result",
|
||||
"type": "object",
|
||||
"required": false,
|
||||
"description": "任务执行结果(status=success 时返回)",
|
||||
"children": [
|
||||
{
|
||||
"name": "total",
|
||||
"type": "number",
|
||||
"required": false,
|
||||
"description": "本次提交的运单总数"
|
||||
},
|
||||
{
|
||||
"name": "matched",
|
||||
"type": "number",
|
||||
"required": false,
|
||||
"description": "匹配到运单记录的运单数"
|
||||
},
|
||||
{
|
||||
"name": "inserted",
|
||||
"type": "number",
|
||||
"required": false,
|
||||
"description": "新增的轨迹条数"
|
||||
},
|
||||
{
|
||||
"name": "updated",
|
||||
"type": "number",
|
||||
"required": false,
|
||||
"description": "已存在并更新的轨迹条数"
|
||||
},
|
||||
{
|
||||
"name": "not_found",
|
||||
"type": "array",
|
||||
"required": false,
|
||||
"description": "当前仓库下未匹配到运单或轨迹为空的运单号列表"
|
||||
},
|
||||
{
|
||||
"name": "failed",
|
||||
"type": "array",
|
||||
"required": false,
|
||||
"description": "失败明细 [{ waybill_code, reason }]:回调失败、业务码失败或返回值非法"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "error",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"description": "错误信息(status=failed 时返回)"
|
||||
},
|
||||
{
|
||||
"name": "update_time",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"description": "任务最近更新时间"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"errors": [
|
||||
{
|
||||
"code": "401",
|
||||
"message": "未登录,请先登录"
|
||||
},
|
||||
{
|
||||
"code": "404",
|
||||
"message": "任务不存在或已过期"
|
||||
},
|
||||
{
|
||||
"code": "500",
|
||||
"message": "服务器内部错误:物流轨迹更新进度查询失败"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user