feat(waybill): 批量更新运单揽收状态(waybill.getreceive)与 Y/N 标记列治理
- 新增出站回调 waybill.getreceive(注册到 callback_functions,管理端可勾选):
请求 { request: { waybill_codes: [...] } },响应裸数组/包装体均兼容,
1/0 与 Y/N 归一后回写 wms_order_express.is_galaxy_receive(按 warehouse_id 隔离)
- 回调签名新增 signMode=simple(MD5(appSecret+timestamp+bodyJson)),
waybill.getreceive 使用该口径,与仓库通知协议一致;其它事件默认口径不变
- 新增 waybill.warehouse.updateReceive / updateReceiveTaskProgress:
复用导出的异步任务ID与进度模式(前缀 waybill_receive_),单批 10 单自动切批;
支持 waybillCodes 或与 waybill.warehouse.list 一致的 where 条件圈选(上限 5000);
仓库未配置外部接口时直接失败,不创建任务
- 抽出 buildListQueryWhere / resolveWaybillCodesByWhere,列表与批量更新共用筛选口径
- order_express:is_back / is_intercept / is_galaxy_receive 补默认值 N
- 迁移:存量 NULL 回填为 N(Y 不动);三列分别建立单列索引(INPLACE + LOCK=NONE)
- 文档:methods/system.json(0.3.324)、变更记录、设计文档与出站回调说明同步
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
parent
25dac21b4b
commit
e3eff20aaa
@ -15,6 +15,12 @@ const CALLBACK_FUNCTIONS = [
|
||||
name: '站内信通知回执',
|
||||
description: '站内信/系统通知/回执出站推送(warehouseNotify 与 inbox 回执共用)',
|
||||
},
|
||||
{
|
||||
method: 'waybill.getreceive',
|
||||
name: '运单揽收状态查询',
|
||||
description: '按运单号批量查询是否已揽收:请求 { waybill_codes: [...] },'
|
||||
+ '外部返回 [{ waybill_code, is_galaxy_receive: 1|0 }],回写 wms_order_express.is_galaxy_receive',
|
||||
},
|
||||
];
|
||||
|
||||
/** method 合法值集合(供管理端 create/update 校验) */
|
||||
|
||||
@ -39,16 +39,19 @@ module.exports = app => {
|
||||
is_galaxy_receive: {
|
||||
type: ENUM('Y', 'N'),
|
||||
allowNull: true,
|
||||
defaultValue: 'N',
|
||||
comment: '是否揽收',
|
||||
},
|
||||
is_back: {
|
||||
type: ENUM('Y', 'N'),
|
||||
allowNull: true,
|
||||
defaultValue: 'N',
|
||||
comment: '是否退回',
|
||||
},
|
||||
is_intercept: {
|
||||
type: ENUM('Y', 'N'),
|
||||
allowNull: true,
|
||||
defaultValue: 'N',
|
||||
comment: '是否拦截',
|
||||
},
|
||||
logistics_code: {
|
||||
|
||||
@ -1,11 +1,18 @@
|
||||
'use strict';
|
||||
|
||||
const crypto = require('crypto');
|
||||
const Service = require('egg').Service;
|
||||
const { signRequest } = require('../../lib/api_sign');
|
||||
|
||||
/** @type {number} 最大重试次数 */
|
||||
const MAX_RETRY = 3;
|
||||
|
||||
/** 签名模式:md5(canonicalQuery + secret + md5(body)),与 /openapi 入站验签一致 */
|
||||
const SIGN_MODE_OPENAPI = 'openapi';
|
||||
|
||||
/** 签名模式:md5(secret + timestamp + bodyJson),与 methods/warehouse_notify.json 协议一致 */
|
||||
const SIGN_MODE_SIMPLE = 'simple';
|
||||
|
||||
/** @type {number[]} 递增重试延迟(毫秒) */
|
||||
const RETRY_DELAY_MS = [ 2000, 5000, 15000 ];
|
||||
|
||||
@ -17,17 +24,31 @@ const RETRY_DELAY_MS = [ 2000, 5000, 15000 ];
|
||||
class OpenapiCallbackService extends Service {
|
||||
|
||||
/**
|
||||
* 计算回调签名(与 OpenAPI 入口签名算法完全一致)。
|
||||
* 算法:md5(canonicalQuery + selfAppSecret + md5(stableStringify(body)))。
|
||||
* 计算回调签名。
|
||||
* 默认算法(signMode=openapi):md5(canonicalQuery + selfAppSecret + md5(stableStringify(body))),
|
||||
* 与 OpenAPI 入口签名算法完全一致。
|
||||
* signMode=simple 时改用 md5(selfAppSecret + timestamp + bodyJson),与
|
||||
* `methods/warehouse_notify.json` 描述的仓库通知协议一致(部分外部系统按该口径验签)。
|
||||
* @param {Object} options 签名参数。
|
||||
* @param {string} options.event 回调 method(模块.动作,如 deliveryorder.confirm),仅用于 query 的 method。
|
||||
* @param {string} options.appKey 应用 app_key。
|
||||
* @param {string} options.selfAppSecret 应用密钥。
|
||||
* @param {Object} options.body 完整回调报文体(奇门同层级 { request: {...} })。
|
||||
* @param {string} options.timestamp 秒级时间戳(10 位字符串,与 /openapi 入站时效校验一致)。
|
||||
* @param {string} [options.signMode='openapi'] 签名模式:openapi / simple。
|
||||
* @return {{ canonicalQuery: string, bodySign: string, sign: string }} 签名计算结果。
|
||||
*/
|
||||
signCallback({ event, appKey, selfAppSecret, body, timestamp }) {
|
||||
signCallback({ event, appKey, selfAppSecret, body, timestamp, signMode = SIGN_MODE_OPENAPI }) {
|
||||
if (signMode === SIGN_MODE_SIMPLE) {
|
||||
const bodyJson = JSON.stringify(body || {});
|
||||
const secret = String(selfAppSecret || '');
|
||||
return {
|
||||
canonicalQuery: '',
|
||||
bodySign: '',
|
||||
sign: crypto.createHash('md5').update(secret + timestamp + bodyJson).digest('hex'),
|
||||
};
|
||||
}
|
||||
|
||||
const query = {
|
||||
method: event,
|
||||
v: '1.0',
|
||||
@ -49,15 +70,16 @@ class OpenapiCallbackService extends Service {
|
||||
* @param {string} options.selfAppSecret 应用密钥。
|
||||
* @param {string} options.event 回调 method(模块.动作,如 deliveryorder.confirm),仅用于 query 的 method。
|
||||
* @param {Object} options.request 奇门同层级业务报文内容(不含外层 request 包装,由发送端包装)。
|
||||
* @param {string} [options.signMode='openapi'] 签名模式:openapi(默认)/ simple(仓库通知协议)。
|
||||
* @return {Promise<Object>} 回调结果 { success, retryCount, response, error }。
|
||||
*/
|
||||
async sendWithRetry({ callbackUrl, appKey, selfAppSecret, event, request }) {
|
||||
async sendWithRetry({ callbackUrl, appKey, selfAppSecret, event, request, signMode = SIGN_MODE_OPENAPI }) {
|
||||
const { ctx } = this;
|
||||
// 秒级时间戳(10 位):与 /openapi 入站时效校验(±600 秒窗口)及回调调试页保持一致
|
||||
const timestamp = String(Math.floor(Date.now() / 1000));
|
||||
// 报文体固定为奇门同层级 { request }:event 只出现在 query 的 method 中
|
||||
const body = { request: request || {} };
|
||||
const { sign } = this.signCallback({ event, appKey, selfAppSecret, body, timestamp });
|
||||
const { sign } = this.signCallback({ event, appKey, selfAppSecret, body, timestamp, signMode });
|
||||
|
||||
const queryString = [
|
||||
`method=${encodeURIComponent(event)}`,
|
||||
@ -158,9 +180,10 @@ class OpenapiCallbackService extends Service {
|
||||
* @param {string} options.appKey 应用 app_key。
|
||||
* @param {string} options.event 回调 method(模块.动作,如 deliveryorder.confirm),仅用于 query 的 method。
|
||||
* @param {Object} options.request 奇门同层级业务报文内容(不含外层 request 包装,由发送端包装)。
|
||||
* @param {string} [options.signMode='openapi'] 签名模式:openapi(默认)/ simple(仓库通知协议)。
|
||||
* @return {Promise<Object>} 回调结果 { success, retryCount, response, error }。
|
||||
*/
|
||||
async sendByAppKey({ appKey, event, request }) {
|
||||
async sendByAppKey({ appKey, event, request, signMode = SIGN_MODE_OPENAPI }) {
|
||||
const { ctx } = this;
|
||||
const normalizedAppKey = String(appKey || '').trim();
|
||||
|
||||
@ -201,6 +224,7 @@ class OpenapiCallbackService extends Service {
|
||||
selfAppSecret: appConfig.self_app_secret || '',
|
||||
event,
|
||||
request,
|
||||
signMode,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@ -3,6 +3,15 @@
|
||||
const MainService = require('../../main');
|
||||
|
||||
const WAYBILL_EXPORT_TASK_CACHE_KEY_PREFIX = 'waybill_export_task_';
|
||||
const WAYBILL_RECEIVE_TASK_CACHE_KEY_PREFIX = 'waybill_receive_task_';
|
||||
/** 揽收状态查询所依赖的出站回调 method */
|
||||
const WAYBILL_RECEIVE_EVENT = 'waybill.getreceive';
|
||||
/** 仓库未配置外部接口时的失败提示(直接失败,不进入任务流程) */
|
||||
const WAYBILL_RECEIVE_NOT_CONFIGURED_MESSAGE =
|
||||
'如需更新运单是否揽收信息,到【设置】->【基础设置】->【API开放接口】配置相应的外部访问接口';
|
||||
|
||||
/** 按 where 筛选解析运单号时允许的最大条数(超出要求缩小范围) */
|
||||
const WAYBILL_RECEIVE_MAX_CODES = 5000;
|
||||
|
||||
/**
|
||||
* 运单号仓库侧入口层。
|
||||
@ -14,9 +23,9 @@ class WaybillWarehouseService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'list,detail,export,exportTaskProgress';
|
||||
const _noNeedRight = 'list,detail,export,exportTaskProgress,updateReceive,updateReceiveTaskProgress';
|
||||
const _noNeedLog = '';
|
||||
const _noNeedAuth = 'list,detail,export,exportTaskProgress';
|
||||
const _noNeedAuth = 'list,detail,export,exportTaskProgress,updateReceive,updateReceiveTaskProgress';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
@ -221,7 +230,206 @@ class WaybillWarehouseService extends MainService {
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 导出任务辅助方法 ====================
|
||||
/**
|
||||
* 批量更新运单是否揽收(仓库侧)。
|
||||
*
|
||||
* 链路走 OpenAPI 出站回调 `waybill.getreceive`(单批最多 10 单,自动切批),
|
||||
* 不读取本地库的揽收标记;返回结果按 waybill_code + warehouse_id 回写
|
||||
* `wms_order_express.is_galaxy_receive`。
|
||||
* 异步任务模式:提交后通过 `updateReceiveTaskProgress` 查询进度。
|
||||
* 仓库未配置承接该 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 updateReceive(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.resolveReceiveAppKey(warehouseId);
|
||||
if (!appKey) {
|
||||
return this.fail(WAYBILL_RECEIVE_NOT_CONFIGURED_MESSAGE);
|
||||
}
|
||||
|
||||
// 仅传 where 时:按与列表一致的筛选口径解析运单号(带数量上限,避免一次任务过大)
|
||||
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.generateReceiveTaskId();
|
||||
const taskPayload = {
|
||||
task_id: taskId,
|
||||
status: 'submitted',
|
||||
progress: 0,
|
||||
current_count: 0,
|
||||
total_count: waybillCodes.length,
|
||||
message: '更新揽收状态任务已提交',
|
||||
result: null,
|
||||
error: '',
|
||||
};
|
||||
await this.setReceiveTaskProgress(taskId, taskPayload);
|
||||
|
||||
setImmediate(async () => {
|
||||
try {
|
||||
await this.setReceiveTaskProgress(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.queryReceiveStatus({
|
||||
warehouseId,
|
||||
waybillCodes,
|
||||
appKey,
|
||||
onProgress: async progress => {
|
||||
const safeProgress = this.isPlainObject(progress) ? progress : {};
|
||||
await this.setReceiveTaskProgress(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.setReceiveTaskProgress(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.setReceiveTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'success',
|
||||
progress: 100,
|
||||
current_count: waybillCodes.length,
|
||||
total_count: waybillCodes.length,
|
||||
message: `更新完成:更新 ${result.updated} 单,未变化 ${result.unchanged} 单,失败 ${failedList.length} 单`,
|
||||
result: {
|
||||
total: result.total,
|
||||
updated: result.updated,
|
||||
unchanged: result.unchanged,
|
||||
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.setReceiveTaskProgress(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 updateReceiveTaskProgress(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.getReceiveTaskProgress(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。
|
||||
@ -234,6 +442,47 @@ class WaybillWarehouseService extends MainService {
|
||||
return `waybill_export_${warehouseId}_${timestamp}_${randomToken}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成运单揽收状态更新任务ID。
|
||||
* @return {string} 任务ID。
|
||||
*/
|
||||
generateReceiveTaskId() {
|
||||
const warehouseId = this.ctx?.user?.store_id || 'unknown';
|
||||
const timestamp = Date.now();
|
||||
const randomToken = Math.random().toString(36).slice(2, 10);
|
||||
return `waybill_receive_${warehouseId}_${timestamp}_${randomToken}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化运单号:转字符串、去空格、去空、去重。
|
||||
* @param {Array<string>} waybillCodes 原始运单号列表。
|
||||
* @return {Array<string>} 规范化后的运单号列表。
|
||||
*/
|
||||
normalizeReceiveWaybillCodes(waybillCodes) {
|
||||
if (!Array.isArray(waybillCodes)) return [];
|
||||
return [ ...new Set(waybillCodes.map(code => String(code || '').trim()).filter(Boolean)) ];
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析仓库承接 waybill.getreceive 的 API 应用 AppKey(按 id 升序取首个)。
|
||||
* 返回空字符串表示仓库未配置该外部访问接口。
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @return {Promise<string>} 目标应用 AppKey。
|
||||
*/
|
||||
async resolveReceiveAppKey(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_RECEIVE_EVENT
|
||||
);
|
||||
const first = Array.isArray(candidates) ? candidates[0] : null;
|
||||
return String(first && first.appKey || '').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范导出任务ID。
|
||||
* @param {Object} data 请求体。
|
||||
@ -245,26 +494,28 @@ class WaybillWarehouseService extends MainService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取运单导出任务缓存键。
|
||||
* 获取运单任务缓存键。
|
||||
* @param {string} taskId 任务ID。
|
||||
* @param {string} [prefix] 缓存键前缀,区分导出/揽收状态更新等任务类型。
|
||||
* @return {string} 缓存键。
|
||||
*/
|
||||
getExportTaskCacheKey(taskId = '') {
|
||||
getTaskCacheKey(taskId = '', prefix = WAYBILL_EXPORT_TASK_CACHE_KEY_PREFIX) {
|
||||
const normalizedTaskId = String(taskId || '').trim();
|
||||
if (!normalizedTaskId) {
|
||||
return '';
|
||||
}
|
||||
return `${WAYBILL_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`;
|
||||
return `${prefix}${normalizedTaskId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入运单导出任务进度缓存。
|
||||
* 写入运单任务进度缓存。
|
||||
* @param {string} taskId 任务ID。
|
||||
* @param {Object} payload 任务状态。
|
||||
* @param {string} [prefix] 缓存键前缀。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async setExportTaskProgress(taskId = '', payload = {}) {
|
||||
const cacheKey = this.getExportTaskCacheKey(taskId);
|
||||
async setTaskProgress(taskId = '', payload = {}, prefix = WAYBILL_EXPORT_TASK_CACHE_KEY_PREFIX) {
|
||||
const cacheKey = this.getTaskCacheKey(taskId, prefix);
|
||||
if (!cacheKey || typeof this.app.setCacheAsync !== 'function') {
|
||||
return;
|
||||
}
|
||||
@ -291,17 +542,56 @@ class WaybillWarehouseService extends MainService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取运单导出任务进度缓存。
|
||||
* 读取运单任务进度缓存。
|
||||
* @param {string} taskId 任务ID。
|
||||
* @param {string} [prefix] 缓存键前缀。
|
||||
* @return {Promise<Object|null>} 任务状态对象或 null。
|
||||
*/
|
||||
async getExportTaskProgress(taskId = '') {
|
||||
const cacheKey = this.getExportTaskCacheKey(taskId);
|
||||
async getTaskProgress(taskId = '', prefix = WAYBILL_EXPORT_TASK_CACHE_KEY_PREFIX) {
|
||||
const cacheKey = this.getTaskCacheKey(taskId, prefix);
|
||||
if (!cacheKey || typeof this.app.getCacheAsync !== 'function') {
|
||||
return null;
|
||||
}
|
||||
return await this.app.getCacheAsync(cacheKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入运单导出任务进度缓存。
|
||||
* @param {string} taskId 任务ID。
|
||||
* @param {Object} payload 任务状态。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async setExportTaskProgress(taskId = '', payload = {}) {
|
||||
await this.setTaskProgress(taskId, payload, WAYBILL_EXPORT_TASK_CACHE_KEY_PREFIX);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取运单导出任务进度缓存。
|
||||
* @param {string} taskId 任务ID。
|
||||
* @return {Promise<Object|null>} 任务状态对象或 null。
|
||||
*/
|
||||
async getExportTaskProgress(taskId = '') {
|
||||
return await this.getTaskProgress(taskId, WAYBILL_EXPORT_TASK_CACHE_KEY_PREFIX);
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入运单揽收状态更新任务进度缓存。
|
||||
* @param {string} taskId 任务ID。
|
||||
* @param {Object} payload 任务状态。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async setReceiveTaskProgress(taskId = '', payload = {}) {
|
||||
await this.setTaskProgress(taskId, payload, WAYBILL_RECEIVE_TASK_CACHE_KEY_PREFIX);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取运单揽收状态更新任务进度缓存。
|
||||
* @param {string} taskId 任务ID。
|
||||
* @return {Promise<Object|null>} 任务状态对象或 null。
|
||||
*/
|
||||
async getReceiveTaskProgress(taskId = '') {
|
||||
return await this.getTaskProgress(taskId, WAYBILL_RECEIVE_TASK_CACHE_KEY_PREFIX);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WaybillWarehouseService;
|
||||
|
||||
@ -7,6 +7,21 @@ const fsp = require('fs').promises;
|
||||
const path = require('path');
|
||||
const os = require('os');
|
||||
|
||||
/** 出站回调 method:批量查询运单揽收状态 */
|
||||
const WAYBILL_RECEIVE_EVENT = 'waybill.getreceive';
|
||||
|
||||
/** 单次回调最多携带的运单号数量(waybill.getreceive 外部接口上限 10 单) */
|
||||
const WAYBILL_RECEIVE_MAX_BATCH = 10;
|
||||
|
||||
/** 揽收状态合法取值(与 wms_order_express.is_galaxy_receive 枚举一致) */
|
||||
const WAYBILL_RECEIVE_FLAGS = [ 'Y', 'N' ];
|
||||
|
||||
/**
|
||||
* 揽收查询回调的签名模式:外部接口按 methods/warehouse_notify.json 协议验签
|
||||
* (md5(appSecret + timestamp + bodyJson)),与 /openapi 入站的 canonicalQuery 口径不同。
|
||||
*/
|
||||
const WAYBILL_RECEIVE_SIGN_MODE = 'simple';
|
||||
|
||||
/**
|
||||
* 业务逻辑层:waybill(运单号快速查询)。
|
||||
*/
|
||||
@ -196,19 +211,15 @@ class WaybillService extends MainService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 运单列表查询(仓库侧)。
|
||||
* 按仓库维度查询运单号列表,支持分页、多条件筛选、排序。
|
||||
* 核心查询仅使用 wms_order_express 单表(利用快照字段),
|
||||
* 主单号通过 SELF JOIN 同 order_id 下 business_key=1 的记录获取。
|
||||
* 构建运单查询条件(与 waybill.warehouse.list 完全一致的筛选口径,不含分页与排序)。
|
||||
* 供列表查询与「按条件批量更新揽收状态」共用,避免两处筛选逻辑漂移。
|
||||
*
|
||||
* @param {Object} [options={}] 查询参数。
|
||||
* @param {Object} [options.where] 筛选条件,支持 waybillCode(字符串模糊匹配 / 字符串数组精确匹配)/ mainWaybillCode(字符串 / 字符串数组精确匹配,数组时返回多个主单对应订单下的运单)/ orderId / orderNo / logisticsCode / logisticsInterfaceId / platformCode / status / isBack / isIntercept / isGalaxyReceive / packageMaterialId / hasWeighingWeight / keyword / createdAt({operator:'between', value:[start,end]},兼容 createAt 别名)/ createdAtStart / createdAtEnd(旧写法兼容)。
|
||||
* @param {Object} [options.pagination] 分页参数 { page, pageSize },默认 page=1, pageSize=20。
|
||||
* @param {Object} [options.sort] 排序参数 { field, order },默认 create_at desc。
|
||||
* @return {Promise<Object>} 运单列表与分页信息 { list, pagination }。
|
||||
* @param {Object} [rawWhere={}] 原始筛选条件(支持 operator/value 格式)。
|
||||
* @param {number} warehouseId 仓库ID(强制隔离,非空)。
|
||||
* @return {Promise<{ empty: boolean, queryWhere: Object }>} empty=true 表示条件已确定无匹配(如主单号均不存在)。
|
||||
*/
|
||||
async list({ where: rawWhere = {}, pagination = {}, sort = {} } = {}) {
|
||||
const { ctx, app } = this;
|
||||
async buildListQueryWhere(rawWhere = {}, warehouseId) {
|
||||
const { app } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
|
||||
// 标准化 where 条件:将前端 operator/value 格式(如 {operator:"contains", value:"YT..."})统一转为标准条件对象
|
||||
@ -228,32 +239,14 @@ class WaybillService extends MainService {
|
||||
return c;
|
||||
};
|
||||
|
||||
// 仓库隔离
|
||||
const warehouseId = Number(ctx.user && ctx.user.store_id);
|
||||
if (!warehouseId) {
|
||||
this.throwError('用户未绑定仓库,无法查询运单');
|
||||
}
|
||||
|
||||
// 分页参数
|
||||
const page = Math.max(Number(pagination.page) || 1, 1);
|
||||
const pageSize = Math.min(Math.max(Number(pagination.pageSize) || 20, 1), 500);
|
||||
|
||||
// 排序参数
|
||||
const allowedSortFields = [ 'create_at', 'weighing_weight', 'id' ];
|
||||
const sortField = allowedSortFields.includes(sort.field) ? sort.field : 'create_at';
|
||||
const sortOrder = sort.order === 'asc' ? 'ASC' : 'DESC';
|
||||
|
||||
// 构建查询条件
|
||||
const queryWhere = { warehouse_id: warehouseId };
|
||||
|
||||
// 主单号查询:先通过主单号(支持单值/数组)定位 order_id,再查这些订单下所有运单(主+子)
|
||||
const mainResolved = await this.resolveMainWaybillOrderIds(val(where.mainWaybillCode), warehouseId);
|
||||
if (mainResolved.empty) {
|
||||
// 主单号均不存在,直接返回空结果
|
||||
return {
|
||||
list: [],
|
||||
pagination: { page, pageSize, total: 0, totalPages: 0 },
|
||||
};
|
||||
// 主单号均不存在,条件已确定无匹配
|
||||
return { empty: true, queryWhere };
|
||||
}
|
||||
if (mainResolved.orderIds.length > 0) {
|
||||
// 单主单保持标量 order_id(向后兼容),多主单使用 Op.in
|
||||
@ -396,9 +389,80 @@ class WaybillService extends MainService {
|
||||
}
|
||||
}
|
||||
|
||||
// 核心查询:仅查 wms_order_express 单表
|
||||
// TODO: warehouse_name_snapshot / store_id_snapshot / store_name_snapshot / delivery_order_code
|
||||
// 快照列未落库,暂时只查已有字段;快照列就绪后替换为快照直读
|
||||
return { empty: false, queryWhere };
|
||||
}
|
||||
|
||||
/**
|
||||
* 按筛选条件解析运单号列表(用于按条件批量更新揽收状态)。
|
||||
* 复用 buildListQueryWhere,条件口径与 waybill.warehouse.list 完全一致;不含分页/排序。
|
||||
*
|
||||
* @param {Object} options 查询参数。
|
||||
* @param {Object} [options.where={}] 筛选条件(同 list)。
|
||||
* @param {number} options.warehouseId 仓库ID。
|
||||
* @param {number} options.limit 最大返回数量(超出即判定超限,不做截断)。
|
||||
* @return {Promise<{ codes: Array<string>, exceeded: boolean }>} 运单号列表与是否超限。
|
||||
*/
|
||||
async resolveWaybillCodesByWhere({ where: rawWhere = {}, warehouseId, limit }) {
|
||||
const maxCount = Math.max(Number(limit) || 0, 1);
|
||||
const { empty, queryWhere } = await this.buildListQueryWhere(rawWhere, warehouseId);
|
||||
if (empty) {
|
||||
return { codes: [], exceeded: false };
|
||||
}
|
||||
|
||||
const rows = await this.ctx.model.OrderExpress.findAll({
|
||||
attributes: [ 'waybill_code' ],
|
||||
where: queryWhere,
|
||||
limit: maxCount + 1,
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (rows.length > maxCount) {
|
||||
return { codes: [], exceeded: true };
|
||||
}
|
||||
|
||||
const codes = [ ...new Set(rows.map(row => String(row.waybill_code || '').trim()).filter(Boolean)) ];
|
||||
return { codes, exceeded: false };
|
||||
}
|
||||
|
||||
/**
|
||||
* 运单列表查询(仓库侧)。
|
||||
* 按仓库维度查询运单号列表,支持分页、多条件筛选、排序。
|
||||
* 核心查询仅使用 wms_order_express 单表(利用快照字段),
|
||||
* 主单号通过 SELF JOIN 同 order_id 下 business_key=1 的记录获取。
|
||||
*
|
||||
* @param {Object} [options={}] 查询参数。
|
||||
* @param {Object} [options.where] 筛选条件,支持 waybillCode(字符串模糊匹配 / 字符串数组精确匹配)/ mainWaybillCode(字符串 / 字符串数组精确匹配,数组时返回多个主单对应订单下的运单)/ orderId / orderNo / logisticsCode / logisticsInterfaceId / platformCode / status / isBack / isIntercept / isGalaxyReceive / packageMaterialId / hasWeighingWeight / keyword / createdAt({operator:'between', value:[start,end]},兼容 createAt 别名)/ createdAtStart / createdAtEnd(旧写法兼容)。
|
||||
* @param {Object} [options.pagination] 分页参数 { page, pageSize },默认 page=1, pageSize=20。
|
||||
* @param {Object} [options.sort] 排序参数 { field, order },默认 create_at desc。
|
||||
* @return {Promise<Object>} 运单列表与分页信息 { list, pagination }。
|
||||
*/
|
||||
async list({ where: rawWhere = {}, pagination = {}, sort = {} } = {}) {
|
||||
const { ctx, app } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
|
||||
// 仓库隔离
|
||||
const warehouseId = Number(ctx.user && ctx.user.store_id);
|
||||
if (!warehouseId) {
|
||||
this.throwError('用户未绑定仓库,无法查询运单');
|
||||
}
|
||||
|
||||
// 分页参数
|
||||
const page = Math.max(Number(pagination.page) || 1, 1);
|
||||
const pageSize = Math.min(Math.max(Number(pagination.pageSize) || 20, 1), 500);
|
||||
|
||||
// 排序参数
|
||||
const allowedSortFields = [ 'create_at', 'weighing_weight', 'id' ];
|
||||
const sortField = allowedSortFields.includes(sort.field) ? sort.field : 'create_at';
|
||||
const sortOrder = sort.order === 'asc' ? 'ASC' : 'DESC';
|
||||
|
||||
// 查询条件:与「按条件批量更新揽收状态」共用同一套筛选口径
|
||||
const { empty, queryWhere } = await this.buildListQueryWhere(rawWhere, warehouseId);
|
||||
if (empty) {
|
||||
return {
|
||||
list: [],
|
||||
pagination: { page, pageSize, total: 0, totalPages: 0 },
|
||||
};
|
||||
}
|
||||
const { count, rows } = await ctx.model.OrderExpress.findAndCountAll({
|
||||
where: queryWhere,
|
||||
attributes: [
|
||||
@ -1182,6 +1246,290 @@ class WaybillService extends MainService {
|
||||
filename,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量查询运单揽收状态(出站回调 waybill.getreceive)。
|
||||
*
|
||||
* 业务报文:`{ waybill_codes: [...] }`,经 `openapi.callback.sendByAppKey` 统一
|
||||
* 包装为 `{ request: { waybill_codes: [...] } }` 发送(与其它出站回调一致)。
|
||||
* 外部返回 `[{ waybill_code, is_galaxy_receive: 1|0 }]`,兼容 `{ code, data: [...] }` 包装
|
||||
* 与 `'Y'/'N'` 字符串取值;命中结果按 waybill_code + warehouse_id 回写
|
||||
* `wms_order_express.is_galaxy_receive`。
|
||||
*
|
||||
* 目标应用:未显式传 appKey 时,取该仓库下 callback_functions 勾选了
|
||||
* waybill.getreceive 的首个应用(按 id 升序),口径与 notify.reply 的路由一致。
|
||||
*
|
||||
* @param {Object} options 查询参数。
|
||||
* @param {number} options.warehouseId 仓库 ID,用于回写隔离。
|
||||
* @param {Array<string>} options.waybillCodes 运单号列表。
|
||||
* @param {string} [options.appKey] 指定目标应用 AppKey,不传则按仓库订阅关系解析。
|
||||
* @param {Function} [options.onProgress] 进度回调,每批完成后触发
|
||||
* ({ status, progress, currentCount, totalCount, message, updated, unchanged, failed })。
|
||||
* @return {Promise<Object>} 结果 { success, event, app_key, total, updated, unchanged, not_found, failed, reason }。
|
||||
*/
|
||||
async queryReceiveStatus({ warehouseId, waybillCodes, appKey = '', onProgress = null } = {}) {
|
||||
const { ctx } = this;
|
||||
const normalizedWarehouseId = Number(warehouseId) || 0;
|
||||
const codes = this.normalizeWaybillCodes(waybillCodes);
|
||||
const base = {
|
||||
success: false,
|
||||
event: WAYBILL_RECEIVE_EVENT,
|
||||
app_key: String(appKey || '').trim(),
|
||||
total: codes.length,
|
||||
updated: 0,
|
||||
unchanged: 0,
|
||||
not_found: [],
|
||||
failed: [],
|
||||
};
|
||||
|
||||
if (codes.length === 0) {
|
||||
return { ...base, reason: '运单号不能为空' };
|
||||
}
|
||||
if (!normalizedWarehouseId) {
|
||||
return { ...base, reason: '缺少仓库ID' };
|
||||
}
|
||||
|
||||
const targetAppKey = base.app_key
|
||||
|| await this.resolveReceiveQueryAppKey(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 statusMap = new Map();
|
||||
const failed = [];
|
||||
let processedCount = 0;
|
||||
for (let offset = 0; offset < codes.length; offset += WAYBILL_RECEIVE_MAX_BATCH) {
|
||||
const batch = codes.slice(offset, offset + WAYBILL_RECEIVE_MAX_BATCH);
|
||||
const result = await callbackService.sendByAppKey({
|
||||
appKey: targetAppKey,
|
||||
event: WAYBILL_RECEIVE_EVENT,
|
||||
request: { waybill_codes: batch },
|
||||
signMode: WAYBILL_RECEIVE_SIGN_MODE,
|
||||
});
|
||||
|
||||
if (!result || result.success !== true) {
|
||||
const error = String(result && result.error || '未知错误');
|
||||
ctx.logger.warn('[WaybillService.queryReceiveStatus] 揽收查询回调失败', {
|
||||
warehouseId: normalizedWarehouseId,
|
||||
appKey: targetAppKey,
|
||||
batchSize: batch.length,
|
||||
error,
|
||||
});
|
||||
for (const code of batch) {
|
||||
failed.push({ waybill_code: code, reason: `回调失败: ${error}` });
|
||||
}
|
||||
} else if (this.extractReceiveError(result.response)) {
|
||||
// HTTP 200 但业务码非成功(如验签失败 code=401):整批计失败,避免静默当作「无数据」
|
||||
const error = this.extractReceiveError(result.response);
|
||||
ctx.logger.warn('[WaybillService.queryReceiveStatus] 外部接口返回业务失败', {
|
||||
warehouseId: normalizedWarehouseId,
|
||||
appKey: targetAppKey,
|
||||
batchSize: batch.length,
|
||||
error,
|
||||
});
|
||||
for (const code of batch) {
|
||||
failed.push({ waybill_code: code, reason: `外部接口返回失败: ${error}` });
|
||||
}
|
||||
} else {
|
||||
for (const row of this.extractReceiveRows(result.response)) {
|
||||
const code = String(row && (row.waybill_code || row.waybillCode) || '').trim();
|
||||
if (!code) continue;
|
||||
const flag = this.normalizeReceiveFlag(row.is_galaxy_receive);
|
||||
if (!flag) {
|
||||
failed.push({ waybill_code: code, reason: 'is_galaxy_receive 取值非法' });
|
||||
continue;
|
||||
}
|
||||
statusMap.set(code, flag);
|
||||
}
|
||||
}
|
||||
|
||||
processedCount += batch.length;
|
||||
await this.reportReceiveProgress(onProgress, {
|
||||
processedCount,
|
||||
totalCount: codes.length,
|
||||
failedCount: failed.length,
|
||||
});
|
||||
}
|
||||
|
||||
const queriedCodes = [ ...statusMap.keys() ];
|
||||
if (queriedCodes.length === 0) {
|
||||
return { ...base, app_key: targetAppKey, failed };
|
||||
}
|
||||
|
||||
const { Op } = this.app.Sequelize;
|
||||
const rows = await ctx.model.OrderExpress.findAll({
|
||||
attributes: [ 'waybill_code', 'is_galaxy_receive' ],
|
||||
where: {
|
||||
waybill_code: { [Op.in]: queriedCodes },
|
||||
warehouse_id: normalizedWarehouseId,
|
||||
},
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const existingMap = new Map(rows.map(row => [ String(row.waybill_code || ''), String(row.is_galaxy_receive || 'N') ]));
|
||||
const notFound = queriedCodes.filter(code => !existingMap.has(code));
|
||||
|
||||
let updated = 0;
|
||||
let unchanged = 0;
|
||||
for (const flag of WAYBILL_RECEIVE_FLAGS) {
|
||||
const targets = [];
|
||||
for (const [ code, current ] of existingMap.entries()) {
|
||||
if (statusMap.get(code) !== flag) continue;
|
||||
if (current === flag) {
|
||||
unchanged++;
|
||||
continue;
|
||||
}
|
||||
targets.push(code);
|
||||
}
|
||||
if (targets.length === 0) continue;
|
||||
|
||||
const [ affected ] = await ctx.model.OrderExpress.update(
|
||||
{ is_galaxy_receive: flag },
|
||||
{
|
||||
where: {
|
||||
waybill_code: { [Op.in]: targets },
|
||||
warehouse_id: normalizedWarehouseId,
|
||||
},
|
||||
}
|
||||
);
|
||||
updated += Number(affected) || targets.length;
|
||||
}
|
||||
|
||||
ctx.logger.info('[WaybillService.queryReceiveStatus] 揽收状态同步完成', {
|
||||
warehouseId: normalizedWarehouseId,
|
||||
appKey: targetAppKey,
|
||||
total: codes.length,
|
||||
queried: queriedCodes.length,
|
||||
updated,
|
||||
unchanged,
|
||||
notFound: notFound.length,
|
||||
failed: failed.length,
|
||||
});
|
||||
|
||||
return {
|
||||
...base,
|
||||
success: true,
|
||||
app_key: targetAppKey,
|
||||
updated,
|
||||
unchanged,
|
||||
not_found: notFound,
|
||||
failed,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 触发揽收查询进度回调(未传 onProgress 时静默跳过)。
|
||||
* 进度按已处理条数计算并封顶 99%,剩余 1% 由调用方在任务完成时置 100%。
|
||||
* @param {Function|null} onProgress 调用方进度回调。
|
||||
* @param {Object} options 进度数据。
|
||||
* @param {number} options.processedCount 已处理运单号数量。
|
||||
* @param {number} options.totalCount 运单号总数。
|
||||
* @param {number} options.failedCount 已失败数量。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async reportReceiveProgress(onProgress, { processedCount, totalCount, failedCount } = {}) {
|
||||
if (typeof onProgress !== 'function') return;
|
||||
|
||||
const total = Number(totalCount) || 0;
|
||||
const processed = Math.min(Number(processedCount) || 0, total);
|
||||
const progress = total > 0
|
||||
? Math.min(99, Math.round((processed / total) * 100))
|
||||
: 0;
|
||||
|
||||
await onProgress({
|
||||
status: 'running',
|
||||
progress,
|
||||
currentCount: processed,
|
||||
totalCount: total,
|
||||
message: `已查询 ${processed}/${total} 单${failedCount > 0 ? `(失败 ${failedCount})` : ''}`,
|
||||
failedCount: Number(failedCount) || 0,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化运单号:转字符串、去空格、去空、去重。
|
||||
* @param {Array<string>} waybillCodes 原始运单号列表。
|
||||
* @return {Array<string>} 规范化后的运单号列表。
|
||||
*/
|
||||
normalizeWaybillCodes(waybillCodes) {
|
||||
if (!Array.isArray(waybillCodes)) return [];
|
||||
return [ ...new Set(waybillCodes.map(code => String(code || '').trim()).filter(Boolean)) ];
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析揽收查询的目标应用:取仓库下勾选了 waybill.getreceive 的首个应用(按 id 升序)。
|
||||
* @param {number} warehouseId 仓库 ID。
|
||||
* @return {Promise<string>} 目标应用 AppKey,无承接应用时返回空字符串。
|
||||
*/
|
||||
async resolveReceiveQueryAppKey(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_RECEIVE_EVENT
|
||||
);
|
||||
const first = Array.isArray(candidates) ? candidates[0] : null;
|
||||
return String(first && first.appKey || '').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 从回调响应中提取运单行,兼容裸露数组与 { code, data: [...] } 包装。
|
||||
* @param {*} response 回调响应体。
|
||||
* @return {Array<Object>} 运单行列表。
|
||||
*/
|
||||
extractReceiveRows(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.waybills)) return response.waybills;
|
||||
if (response.data && Array.isArray(response.data.waybills)) return response.data.waybills;
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取外部接口的业务失败信息(HTTP 200 但 code 非成功)。
|
||||
* 成功码口径:0 / 1 / 200;无法识别 code 的结构(含裸数组)返回空串。
|
||||
* @param {*} response 回调响应体。
|
||||
* @return {string} 失败原因,非失败时返回空串。
|
||||
*/
|
||||
extractReceiveError(response) {
|
||||
if (!response || typeof response !== 'object' || Array.isArray(response)) return '';
|
||||
|
||||
const rawCode = response.code;
|
||||
if (rawCode === undefined || rawCode === null || rawCode === '') return '';
|
||||
|
||||
const code = Number(rawCode);
|
||||
if (!Number.isFinite(code) || [ 0, 1, 200 ].includes(code)) return '';
|
||||
|
||||
return String(response.msg || response.message || `外部接口返回 code=${code}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一揽收状态:支持 1/0、'Y'/'N'、布尔值与常见同义词,无法识别时返回 null。
|
||||
* @param {*} value 外部返回值。
|
||||
* @return {'Y'|'N'|null} 归一后的状态。
|
||||
*/
|
||||
normalizeReceiveFlag(value) {
|
||||
if (value === true) return 'Y';
|
||||
if (value === false) return 'N';
|
||||
|
||||
const text = String(value === undefined || value === null ? '' : value).trim().toUpperCase();
|
||||
if ([ '1', 'Y', 'YES', 'TRUE' ].includes(text)) return 'Y';
|
||||
if ([ '0', 'N', 'NO', 'FALSE' ].includes(text)) return 'N';
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WaybillService;
|
||||
|
||||
@ -90,6 +90,10 @@
|
||||
|
||||
> **索引迁移**:以下索引已通过迁移文件 `20260729140000-add-waybill-list-indexes.js` 正式创建,见 §五 文件变更清单。
|
||||
|
||||
**Y/N 标记列单列索引(2026-11-11 新增)**:`is_back` / `is_intercept` / `is_galaxy_receive` 三列此前无索引,而它们是列表常用筛选条件(且用于「批量更新揽收状态」的条件圈选)。迁移 `20261111041500-add-yn-flag-indexes-to-order-express.js` 为三列分别建立单列索引(`idx_is_back` / `idx_is_intercept` / `idx_is_galaxy_receive`,`ALGORITHM=INPLACE, LOCK=NONE` 在线创建)。不同筛选方向各自独立命中,故不建联合索引。
|
||||
|
||||
**默认值**:三列默认值均为 `'N'`(模型 `defaultValue` + 数据库 `DEFAULT 'N'`),存量 NULL 已由迁移 `20261111033000-init-is-back-intercept-receive-to-n.js` 回填为 `'N'`(`Y` 不动)。
|
||||
|
||||
### 2.4 主单号/子单号关联关系
|
||||
|
||||
**规则**(沿用系统已有约定):
|
||||
@ -205,14 +209,17 @@ POST /system { method: "waybill.warehouse.list", ... }
|
||||
| 1 | `waybill.warehouse.list` | 运单列表-仓库侧(分页+筛选) | ✓ | ✗ |
|
||||
| 2 | `waybill.warehouse.detail` | 运单详情-仓库侧(含订单/打印/打包/称重信息) | ✓ | ✗ |
|
||||
| 3 | `waybill.warehouse.export` | 运单导出-仓库侧(按筛选条件) | ✓ | ✗ |
|
||||
| 4 | `waybill.warehouse.exportTaskProgress` | 运单导出任务进度查询 | ✓ | ✗ |
|
||||
| 5 | `waybill.warehouse.updateReceive` | 批量更新运单是否揽收(走出站回调 `waybill.getreceive`,异步任务) | ✓ | ✗ |
|
||||
| 6 | `waybill.warehouse.updateReceiveTaskProgress` | 揽收状态更新任务进度查询 | ✓ | ✗ |
|
||||
|
||||
> **预留接口(本期不实现)**:
|
||||
>
|
||||
> | # | method | 描述 |
|
||||
> |---|--------|------|
|
||||
> | 4 | `waybill.store.list` | 运单列表-货主侧(按 store_id 隔离) |
|
||||
> | 5 | `waybill.store.detail` | 运单详情-货主侧 |
|
||||
> | 6 | `waybill.store.export` | 运单导出-货主侧 |
|
||||
> | 7 | `waybill.store.list` | 运单列表-货主侧(按 store_id 隔离) |
|
||||
> | 8 | `waybill.store.detail` | 运单详情-货主侧 |
|
||||
> | 9 | `waybill.store.export` | 运单导出-货主侧 |
|
||||
|
||||
---
|
||||
|
||||
@ -504,6 +511,77 @@ POST /system { method: "waybill.warehouse.list", ... }
|
||||
|
||||
---
|
||||
|
||||
### 3.8 `waybill.warehouse.updateReceive` / `waybill.warehouse.updateReceiveTaskProgress` — 批量更新是否揽收(仓库侧)
|
||||
|
||||
**功能说明**:`wms_order_express.is_galaxy_receive` 此前只有创建默认值 `N`,没有任何写入来源。本接口按运单号调用**外部访问接口**查询揽收状态并回写,链路不读取本地库的揽收标记。
|
||||
|
||||
#### 调用链路
|
||||
|
||||
```
|
||||
waybill.warehouse.updateReceive(入口层:参数校验 + 接口配置预检 + 建任务)
|
||||
→ systems/waybill.js#queryReceiveStatus(每批 ≤10 单,逐批回写 + 回调进度)
|
||||
→ openapi/callback.js#sendByAppKey(event = waybill.getreceive)
|
||||
→ 回写 wms_order_express.is_galaxy_receive(waybill_code + warehouse_id 隔离)
|
||||
```
|
||||
|
||||
#### 请求参数
|
||||
|
||||
两种用法二选一(`waybillCodes` 优先):
|
||||
|
||||
```json
|
||||
{ "method": "waybill.warehouse.updateReceive", "waybillCodes": ["YT1234567890", "SF1234567890"] }
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"method": "waybill.warehouse.updateReceive",
|
||||
"where": { "isGalaxyReceive": "N", "logisticsCode": "YTO", "createdAt": ["2026-11-01", "2026-11-11"] }
|
||||
}
|
||||
```
|
||||
|
||||
| 参数 | 类型 | 必填 | 说明 |
|
||||
|------|------|------|------|
|
||||
| `waybillCodes` | `string[]` | ✗ | 运单号列表,内部按 10 单一批调用外部接口 |
|
||||
| `waybill_codes` | `string[]` | ✗ | `waybillCodes` 的下划线别名 |
|
||||
| `where` | `object` | ✗ | **与 `waybill.warehouse.list` 完全一致的筛选条件**(不含 `pagination` / `sort`);仅传 `where` 时由 `buildListQueryWhere` 解析运单号后再走同一任务链路 |
|
||||
|
||||
`where` 支持的字段与列表一致:`waybillCode` / `mainWaybillCode` / `orderId` / `orderNo` / `logisticsCode` / `logisticsInterfaceId` / `platformCode` / `status` / `isBack` / `isIntercept` / `isGalaxyReceive` / `waybillType` / `storeId` / `packageMaterialId` / `hasWeighingWeight` / `keyword` / `createdAt`(含 `createAt` 别名、`createdAtStart`/`createdAtEnd` 旧写法)。
|
||||
|
||||
约束:
|
||||
- 两者都不传 → 失败「运单号不能为空,或传入 where 筛选条件」
|
||||
- `where` 匹配数 **> 5000** → 失败「符合条件的运单超过 5000 条,请缩小筛选范围或直接传 waybillCodes」(不截断,避免误更新)
|
||||
- `where` 匹配 0 条 → 失败「未匹配到符合条件的运单」
|
||||
|
||||
#### 外部接口约定(`waybill.getreceive`)
|
||||
|
||||
- 请求体:`{ "request": { "waybill_codes": [...] } }`(由 `sendByAppKey` 统一包装,单批最多 10 单)
|
||||
- 签名:`sign = MD5(appSecret + timestamp + bodyJson)`(仓库通知协议,`signMode=simple`);**不使用** `/openapi` 入站的 `canonicalQuery` 口径。外部接收端(如 `new_wms_notify`)按该协议验签,用旧口径会返回 `{"code":401,"msg":"签名验证失败"}`
|
||||
- 响应:裸数组 `[{ "waybill_code": "YT...", "is_galaxy_receive": 1 }]`,兼容 `{ code, data: [...] }` 与 `{ data: { waybills: [...] } }`
|
||||
- 取值:`1`/`0`、`'Y'`/`'N'`(大小写不敏感)、布尔;非法值计入 `failed`,不写库
|
||||
- 业务失败:HTTP 200 但 `code` 非 `0/1/200` 时整批计入 `failed`
|
||||
- 目标应用:该仓库 `callback_functions` 勾选 `waybill.getreceive` 的首个启用应用(按 `id` 升序)
|
||||
|
||||
#### 失败前置校验(不进入任务流程)
|
||||
|
||||
仓库下无任何应用承接 `waybill.getreceive` 时,`updateReceive` 直接返回失败(不创建任务、不写进度缓存):
|
||||
|
||||
```
|
||||
如需更新运单是否揽收信息,到【设置】->【基础设置】->【API开放接口】配置相应的外部访问接口
|
||||
```
|
||||
|
||||
#### 任务进度
|
||||
|
||||
`task_id` 前缀 `waybill_receive_`,Redis 缓存键前缀 `waybill_receive_task_`(与导出的 `waybill_export_` 互相隔离)。状态流转 `submitted → running → success/failed`,`result` 返回 `{ total, updated, unchanged, not_found, failed }`。
|
||||
|
||||
```json
|
||||
{
|
||||
"method": "waybill.warehouse.updateReceiveTaskProgress",
|
||||
"task_id": "waybill_receive_1000028_1731190000000_ab12cd34"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 四、`methods/system.json` 变更
|
||||
|
||||
在 `methods.groups[]` 中新增 `waybill.warehouse` group:
|
||||
|
||||
@ -0,0 +1,142 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* wms_order_express 三个 Y/N 标记列补默认值与存量回填:
|
||||
*
|
||||
* - `is_back`(是否退回)、`is_intercept`(是否拦截)、`is_galaxy_receive`(是否揽收)
|
||||
* 建表时均为 `ENUM('Y','N') NULL` 且无默认值,业务创建运单时多数不显式赋值 →
|
||||
* 存量约 100% 为 NULL,导致运单列表按「是否退回 / 是否拦截 / 是否揽收 = N」筛选时
|
||||
* 直接返回空(NULL 不参与 ='N' 比较)。
|
||||
*
|
||||
* 本迁移做两件事:
|
||||
* 1) 三列补 `DEFAULT 'N'`(保留 NULL 允许,避免历史裸 SQL 显式写 NULL 时报错);
|
||||
* 2) 存量 NULL 回填为 'N',已为 'Y' 的一律不动。
|
||||
*
|
||||
* 回填按主键区间分批(每批 ≤ 20000 个 id),走 PK 范围扫描,
|
||||
* 避免单条大 UPDATE 长时间持锁(生产约 159 万行 × 3 列)。
|
||||
*
|
||||
* 幂等:列默认值已是 'N' 时跳过 MODIFY;无 NULL 时跳过该批 UPDATE,可重复执行。
|
||||
*/
|
||||
|
||||
const TABLE_NAME = 'wms_order_express';
|
||||
const COLUMNS = [ 'is_back', 'is_intercept', 'is_galaxy_receive' ];
|
||||
const FILL_VALUE = 'N';
|
||||
|
||||
/** 单批主键区间宽度(控制单条 UPDATE 的锁持有时间) */
|
||||
const ID_WINDOW = 20000;
|
||||
|
||||
/**
|
||||
* 读取列定义(类型 / 可空 / 默认值 / 注释),用于构造 MODIFY COLUMN。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {string} tableName 表名。
|
||||
* @param {string} columnName 列名。
|
||||
* @return {Promise<Object|null>} 列定义,列不存在时返回 null。
|
||||
*/
|
||||
async function describeColumn(queryInterface, tableName, columnName) {
|
||||
const [ rows ] = await queryInterface.sequelize.query(
|
||||
'SELECT COLUMN_TYPE AS columnType, IS_NULLABLE AS isNullable, '
|
||||
+ 'COLUMN_DEFAULT AS columnDefault, COLUMN_COMMENT AS columnComment '
|
||||
+ 'FROM INFORMATION_SCHEMA.COLUMNS '
|
||||
+ 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?',
|
||||
{ replacements: [ tableName, columnName ] }
|
||||
);
|
||||
return (rows || [])[0] || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将列默认值设置为 'N'。
|
||||
*
|
||||
* 使用 `ALTER COLUMN ... SET DEFAULT`(MySQL 5.7 元数据变更,不重建表、不锁写),
|
||||
* 而不是 `MODIFY COLUMN`(5.7 下会触发表重建,生产 wms_order_express 约 159 万行)。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {string} columnName 列名。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async function applyDefault(queryInterface, columnName) {
|
||||
const column = await describeColumn(queryInterface, TABLE_NAME, columnName);
|
||||
if (!column) {
|
||||
console.log(`[${columnName}] skip: ${TABLE_NAME}.${columnName} 列不存在`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (String(column.columnDefault || '').toUpperCase() === FILL_VALUE) {
|
||||
console.log(`[${columnName}] skip: 默认值已是 '${FILL_VALUE}'`);
|
||||
return;
|
||||
}
|
||||
|
||||
await queryInterface.sequelize.query(
|
||||
`ALTER TABLE \`${TABLE_NAME}\` ALTER COLUMN \`${columnName}\` SET DEFAULT '${FILL_VALUE}'`
|
||||
);
|
||||
console.log(`[${columnName}] default '${FILL_VALUE}' applied`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 按主键区间分批把 NULL 回填为 'N'(已为 'Y'/'N' 的行不受影响)。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {string} columnName 列名。
|
||||
* @return {Promise<number>} 实际回填行数。
|
||||
*/
|
||||
async function backfillColumn(queryInterface, columnName) {
|
||||
const sequelize = queryInterface.sequelize;
|
||||
const [ rangeRows ] = await sequelize.query(
|
||||
`SELECT MIN(id) AS minId, MAX(id) AS maxId FROM \`${TABLE_NAME}\` `
|
||||
+ `WHERE \`${columnName}\` IS NULL`,
|
||||
{ type: sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
const range = (rangeRows && rangeRows[0]) || rangeRows || {};
|
||||
const minId = Number(range.minId);
|
||||
const maxId = Number(range.maxId);
|
||||
|
||||
if (!Number.isFinite(minId) || !Number.isFinite(maxId)) {
|
||||
console.log(`[${columnName}] skip: 无 NULL 数据`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
let filled = 0;
|
||||
for (let start = minId; start <= maxId; start += ID_WINDOW) {
|
||||
const end = start + ID_WINDOW - 1;
|
||||
const [ , affected ] = await sequelize.query(
|
||||
`UPDATE \`${TABLE_NAME}\` SET \`${columnName}\` = ? `
|
||||
+ 'WHERE `id` BETWEEN ? AND ? AND `' + columnName + '` IS NULL',
|
||||
{ replacements: [ FILL_VALUE, start, end ] }
|
||||
);
|
||||
const count = Number(affected && affected.affectedRows ? affected.affectedRows : affected) || 0;
|
||||
filled += count;
|
||||
}
|
||||
|
||||
console.log(`[${columnName}] backfilled ${filled} rows`);
|
||||
return filled;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 执行迁移:补默认值 + 存量 NULL 回填为 'N'。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async up(queryInterface) {
|
||||
for (const columnName of COLUMNS) {
|
||||
await applyDefault(queryInterface, columnName);
|
||||
await backfillColumn(queryInterface, columnName);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚迁移:仅移除列默认值;数据回填不可逆('N' 与 NULL 在查询口径上等价,
|
||||
* 反向置 NULL 会让筛选再次失效,故不还原数据)。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async down(queryInterface) {
|
||||
for (const columnName of COLUMNS) {
|
||||
const column = await describeColumn(queryInterface, TABLE_NAME, columnName);
|
||||
if (!column) continue;
|
||||
if (String(column.columnDefault || '').toUpperCase() !== FILL_VALUE) continue;
|
||||
|
||||
await queryInterface.sequelize.query(
|
||||
`ALTER TABLE \`${TABLE_NAME}\` ALTER COLUMN \`${columnName}\` DROP DEFAULT`
|
||||
);
|
||||
console.log(`[${columnName}] default dropped`);
|
||||
}
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,97 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* wms_order_express 三个 Y/N 标记列补单列索引:
|
||||
*
|
||||
* - `is_back`(是否退回)、`is_intercept`(是否拦截)、`is_galaxy_receive`(是否揽收)
|
||||
* 是运单列表的常用筛选条件,但此前均无索引;
|
||||
* - 运单表约 159 万行(生产),按单列筛选会走全表扫,且刚才的 NULL→'N' 回填里
|
||||
* `MIN(id)/MAX(id) WHERE col IS NULL` 也需要 90s+;
|
||||
* - 三列区分度不高(Y/N 两值),但查询总是叠加 warehouse_id 等前置条件时收益有限,
|
||||
* 因此按「单列索引」建,交给优化器按组合选择;
|
||||
* 选择单列而非联合索引,是为了同时服务
|
||||
* `is_galaxy_receive='N'`(未揽收待更新)、`is_back='Y'`、`is_intercept='Y'` 等
|
||||
* 各方向独立的筛选与批量更新。
|
||||
*
|
||||
* 执行方式:`ALTER TABLE ... ADD INDEX ..., ALGORITHM=INPLACE, LOCK=NONE`
|
||||
* (MySQL 5.7 在线加二级索引,不重建表、不阻塞读写)。
|
||||
* 幂等:索引已存在时跳过。
|
||||
*/
|
||||
|
||||
const TABLE_NAME = 'wms_order_express';
|
||||
const INDEXES = [
|
||||
{ name: 'idx_is_back', column: 'is_back' },
|
||||
{ name: 'idx_is_intercept', column: 'is_intercept' },
|
||||
{ name: 'idx_is_galaxy_receive', column: 'is_galaxy_receive' },
|
||||
];
|
||||
|
||||
/**
|
||||
* 判断列是否存在。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {string} tableName 表名。
|
||||
* @param {string} columnName 列名。
|
||||
* @return {Promise<boolean>} 是否存在。
|
||||
*/
|
||||
async function columnExists(queryInterface, tableName, columnName) {
|
||||
const [ rows ] = await queryInterface.sequelize.query(
|
||||
'SELECT COLUMN_NAME AS columnName FROM INFORMATION_SCHEMA.COLUMNS '
|
||||
+ 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?',
|
||||
{ replacements: [ tableName, columnName ] }
|
||||
);
|
||||
return (rows || []).length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断索引是否已存在。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {string} tableName 表名。
|
||||
* @param {string} indexName 索引名。
|
||||
* @return {Promise<boolean>} 是否存在。
|
||||
*/
|
||||
async function indexExists(queryInterface, tableName, indexName) {
|
||||
const indexes = await queryInterface.showIndex(tableName);
|
||||
return (indexes || []).some(index => {
|
||||
const name = String(index && (index.name || index.Key_name || index.key_name) || '');
|
||||
return name.toLowerCase() === String(indexName).toLowerCase();
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 执行迁移:为三个标记列分别建立单列索引。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async up(queryInterface) {
|
||||
for (const { name, column } of INDEXES) {
|
||||
if (!(await columnExists(queryInterface, TABLE_NAME, column))) {
|
||||
console.log(`[${name}] skip: ${TABLE_NAME}.${column} 列不存在`);
|
||||
continue;
|
||||
}
|
||||
if (await indexExists(queryInterface, TABLE_NAME, name)) {
|
||||
console.log(`[${name}] skip: 索引已存在`);
|
||||
continue;
|
||||
}
|
||||
|
||||
await queryInterface.sequelize.query(
|
||||
`ALTER TABLE \`${TABLE_NAME}\` ADD INDEX \`${name}\` (\`${column}\`), ALGORITHM=INPLACE, LOCK=NONE`
|
||||
);
|
||||
console.log(`[${name}] added on ${TABLE_NAME}(${column})`);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚迁移:移除三个单列索引。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async down(queryInterface) {
|
||||
for (const { name } of INDEXES) {
|
||||
if (!(await indexExists(queryInterface, TABLE_NAME, name))) continue;
|
||||
await queryInterface.sequelize.query(
|
||||
`ALTER TABLE \`${TABLE_NAME}\` DROP INDEX \`${name}\`, ALGORITHM=INPLACE, LOCK=NONE`
|
||||
);
|
||||
console.log(`[${name}] dropped`);
|
||||
}
|
||||
},
|
||||
};
|
||||
@ -347,6 +347,31 @@ app_key=APP2024011514301234&method=entryorder.confirm×tamp=1758047400&v=1.0
|
||||
}
|
||||
```
|
||||
|
||||
### 3.6 waybill.getreceive(查询型回调)
|
||||
|
||||
- label:运单揽收状态查询
|
||||
- description:按运单号批量查询是否已揽收;与 3.1~3.5 的**推送型**事件不同,本事件**消费外部响应**并回写 `wms_order_express.is_galaxy_receive`
|
||||
- 注册位置:`app/lib/callback_functions.js#CALLBACK_FUNCTIONS`(管理端应用可勾选承接该方法)
|
||||
- 实现:`app/service/systems/waybill.js#queryReceiveStatus`(底层方法);业务入口 `waybill.warehouse.updateReceive`(异步任务模式,进度走 `waybill.warehouse.updateReceiveTaskProgress`)
|
||||
- 运单号来源:显式 `waybillCodes`,或 `where`(与 `waybill.warehouse.list` 同一套筛选口径,不含分页/排序;匹配数上限 5000,超限要求缩小范围)
|
||||
- 目标应用解析:未显式传 `appKey` 时,取该仓库 `callback_functions` 勾选了 `waybill.getreceive` 的首个应用(按 `id` 升序)
|
||||
- 批量上限:单次回调**最多 10 个运单号**(外部接口上限),超出自动切批并逐批更新任务进度
|
||||
- **签名口径(与 3.1~3.5 不同)**:`sign = MD5(appSecret + timestamp + bodyJson)`,即 `methods/warehouse_notify.json` 描述的仓库通知协议,而非 2.4 节的 `MD5(canonicalQuery + appSecret + MD5(body))`;实现为 `openapi/callback.js#signCallback({ signMode: 'simple' })`。query 仍携带 `method/v/timestamp/app_key/sign`
|
||||
- 失败识别:HTTP 200 但响应体 `code` 非 `0/1/200`(如验签失败返回 `{"code":401,"msg":"签名验证失败"}`)时整批判失败,不写入揽收状态
|
||||
- `request` 结构(经 `sendByAppKey` 统一包装,线路报文为 `{ request: {...} }`):
|
||||
|
||||
```json
|
||||
{
|
||||
"request": {
|
||||
"waybill_codes": [ "YT1234567890" ]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- 外部**响应**:裸数组 `[{ "waybill_code": "YT1234567890", "is_galaxy_receive": 1 }]`;同时兼容 `{ "code": 200, "data": [...] }` 包装
|
||||
- `is_galaxy_receive` 兼容取值:`1`/`0`、`'Y'`/`'N'`(大小写不敏感)、布尔值;非法取值计入 `failed`,不写库
|
||||
- 回写口径:按 `waybill_code` + `warehouse_id` 更新 `wms_order_express.is_galaxy_receive`(`1→Y`、`0→N`),跨仓不串写
|
||||
|
||||
## 4. timestamp 规范(2026-09-12 已统一为秒)
|
||||
|
||||
`timestamp` 已统一为**秒级(10 位字符串)**规范值:`String(Math.floor(Date.now() / 1000))`。
|
||||
@ -367,7 +392,9 @@ app_key=APP2024011514301234&method=entryorder.confirm×tamp=1758047400&v=1.0
|
||||
- 调试页控制器:`app/controller/openapiCallback.js`(路由 `app/router.js`)
|
||||
- 入站方法路由文档:`AI_METHOD_ROUTING.md` 5.6 节
|
||||
- 触发实现:`app/service/systems/inbound_direct_log.js`、`app/service/systems/receiving_entry_match.js`、`app/service/systems/order_async.js`、`app/service/openapiMethods/order.js`
|
||||
- 接口文档 SSOT:`methods/openapi_callback.json`(5 个 method)
|
||||
- 查询型回调实现:`app/service/systems/waybill.js#queryReceiveStatus`(`waybill.getreceive`);同类的 `deliveryorder.getwaybill` / `deliveryorder.getprintdata` 分别见 `app/service/systems/express_platform.js`、`app/service/systems/order_print.js`
|
||||
- 回调 method 注册表(管理端可勾选):`app/lib/callback_functions.js#CALLBACK_FUNCTIONS`
|
||||
- 接口文档 SSOT:`methods/openapi_callback.json`(5 个 method;仅覆盖推送型事件,查询型回调按既有惯例不收录)
|
||||
- 变更记录:`methods/changes/openapi_callback.json`
|
||||
- 文档站页面:`/docs/api/openapi_callback`(OpenAPI 出站回调文档页)
|
||||
- 入口来源:`/docs/api/openapi` 页面头部的「→ 出站回调文档」链接
|
||||
|
||||
@ -1,4 +1,29 @@
|
||||
[
|
||||
{
|
||||
"version": "0.3.324",
|
||||
"date": "2026-11-11",
|
||||
"type": "added",
|
||||
"summary": "新增运单批量更新是否揽收:waybill.warehouse.updateReceive 与 waybill.warehouse.updateReceiveTaskProgress,链路走 OpenAPI 出站回调 waybill.getreceive(单批 10 单,按仓库通知协议签名),结果回写 wms_order_express.is_galaxy_receive(仓库隔离);支持 waybillCodes 或与 waybill.warehouse.list 一致的 where 条件圈选运单号。配套为 is_back / is_intercept / is_galaxy_receive 补默认值 N、回填存量 NULL 并建立单列索引",
|
||||
"methods": [
|
||||
"waybill.warehouse.updateReceive",
|
||||
"waybill.warehouse.updateReceiveTaskProgress"
|
||||
],
|
||||
"notes": [
|
||||
"背景:wms_order_express.is_galaxy_receive 此前只有创建默认值且实际大量为 NULL,没有任何写入来源;列表按 isGalaxyReceive=N 筛选直接返回空。本批次补齐外部回传链路,并修复默认值与历史数据。",
|
||||
"where 入参(2026-11-11):复用 systems/waybill.js#buildListQueryWhere(由 list 抽取而来),条件口径与 waybill.warehouse.list 完全一致:支持 operator/value 格式、主单号展开(mainWaybillCode)、时间范围(createdAt 数组/区间/旧写法)、关键词模糊等;不含 pagination/sort。",
|
||||
"优先级与上限:waybillCodes 非空时直接使用并忽略 where;仅传 where 时先解析运单号再走同一任务链路;匹配数 > 5000 条直接失败(不截断),匹配 0 条失败,两者都不传失败。",
|
||||
"单批上限:waybill.getreceive 每次最多 10 个运单号,超出自动切批(25 单 → 10/10/5),每批完成后按已处理数更新任务进度。",
|
||||
"签名口径(2026-11-10 调整):外部接收端按 methods/warehouse_notify.json 协议验签,故 sign = MD5(appSecret + timestamp + bodyJson)(openapi/callback.js#signCallback 的 signMode=simple);沿用 /openapi 入站的 MD5(canonicalQuery + appSecret + MD5(body)) 会被对端判为验签失败(实测 code=401)。",
|
||||
"回写口径:按 waybill_code + warehouse_id 更新 wms_order_express.is_galaxy_receive(外部 1→Y、0→N),跨仓不串写;仅当状态变化时才发 UPDATE,未变化计入 unchanged。",
|
||||
"业务失败识别:HTTP 200 但响应体 code 非 0/1/200(如验签失败 code=401)时整批计入 result.failed,不再静默当作「无数据」。",
|
||||
"未配置外部接口:仓库下没有启用应用勾选 callback_functions=waybill.getreceive 时直接返回失败并提示「如需更新运单是否揽收信息,到【设置】->【基础设置】->【API开放接口】配置相应的外部访问接口」,不创建任务、不写进度缓存。",
|
||||
"任务进度:task_id 前缀 waybill_receive_,Redis 缓存键前缀 waybill_receive_task_;状态流转 submitted → running → success/failed,与运单导出(waybill_export_)同构但互相隔离。",
|
||||
"返回值兼容:外部响应支持裸数组 [{ waybill_code, is_galaxy_receive }]、{ code, data: [...] } 与 { data: { waybills: [...] } };is_galaxy_receive 支持 1/0、'Y'/'N'、布尔,非法取值计入 failed 不写库。",
|
||||
"配套数据库变更(已执行):迁移 20261111033000 为 is_back / is_intercept / is_galaxy_receive 补 DEFAULT 'N' 并把存量 NULL 回填为 'N'(Y 不动);迁移 20261111041500 为三列分别建立单列索引 idx_is_back / idx_is_intercept / idx_is_galaxy_receive(ALGORITHM=INPLACE, LOCK=NONE)。",
|
||||
"回调方法注册:app/lib/callback_functions.js#CALLBACK_FUNCTIONS 新增 waybill.getreceive,管理端 apiApp.listCallbackFunctions 可拉取并勾选。",
|
||||
"代码依据:app/service/systemMethods/waybill/warehouse.js#updateReceive/#updateReceiveTaskProgress,app/service/systems/waybill.js#buildListQueryWhere/#resolveWaybillCodesByWhere/#queryReceiveStatus。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.322",
|
||||
"date": "2026-11-02",
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
{
|
||||
"module": "system",
|
||||
"description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内",
|
||||
"version": "0.3.322",
|
||||
"updatedAt": "2026-11-02",
|
||||
"version": "0.3.324",
|
||||
"updatedAt": "2026-11-11",
|
||||
"headers": [
|
||||
{
|
||||
"name": "platform",
|
||||
@ -42946,6 +42946,297 @@
|
||||
"message": "服务器内部错误:导出进度查询失败"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"method": "waybill.warehouse.updateReceive",
|
||||
"description": "批量更新运单是否揽收-仓库侧:按运单号(或按 where 筛选条件圈选的运单号)调用外部访问接口 waybill.getreceive 查询揽收状态(单批最多 10 单,超出自动切批),并把结果回写 wms_order_express.is_galaxy_receive(按 warehouse_id 隔离)。异步任务模式,提交后通过 updateReceiveTaskProgress 查询进度。仓库未配置承接该回调方法的 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 / logisticsInterfaceId / platformCode / status / isBack / isIntercept / isGalaxyReceive / waybillType / storeId / packageMaterialId / hasWeighingWeight / 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_receive_,用于通过 updateReceiveTaskProgress 查询进度"
|
||||
},
|
||||
{
|
||||
"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#updateReceive → systems/waybill.js#queryReceiveStatus → openapi/callback.js#sendByAppKey(不读本地库的揽收标记)",
|
||||
"where 与列表同源:复用 systems/waybill.js#buildListQueryWhere,与 waybill.warehouse.list 的筛选口径完全一致(含 operator/value 格式与主单号展开),避免两处筛选逻辑漂移",
|
||||
"where 圈选上限:匹配数 > 5000 条直接失败(不截断),避免一次性更新过多运单;运单号来源优先级 waybillCodes > where",
|
||||
"单批上限:waybill.getreceive 每次最多 10 个运单号,超出自动切批,任务进度按批更新",
|
||||
"签名口径:waybill.getreceive 按 methods/warehouse_notify.json 协议签名,sign = MD5(appSecret + timestamp + bodyJson);与 /openapi 入站的 canonicalQuery 口径不同(内部 signMode=simple)",
|
||||
"请求体:{ request: { waybill_codes: [...] } };响应为裸数组 [{ waybill_code, is_galaxy_receive }],另兼容 { code, data: [...] } 与 { data: { waybills: [...] } }",
|
||||
"回写口径:按 waybill_code + warehouse_id 更新 wms_order_express.is_galaxy_receive(1→Y、0→N),跨仓不串写",
|
||||
"HTTP 200 但业务码非 0/1/200(如验签失败 code=401)时整批计失败,失败原因写入任务 result.failed",
|
||||
"未配置外部接口时直接返回失败,不创建任务、不占用任务进度缓存",
|
||||
"目标应用:仓库下 callback_functions 勾选了 waybill.getreceive 的首个启用应用(按 id 升序)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"method": "waybill.warehouse.updateReceiveTaskProgress",
|
||||
"description": "运单揽收状态更新进度查询-仓库侧:按 task_id 或 taskId 查询异步任务执行进度。任务进度通过 Redis 缓存存储,任务 ID 前缀 waybill_receive_。",
|
||||
"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_receive_)。与 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": "updated",
|
||||
"type": "number",
|
||||
"required": false,
|
||||
"description": "实际更新揽收状态的运单数"
|
||||
},
|
||||
{
|
||||
"name": "unchanged",
|
||||
"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