- storeWarehouse.store.saveApiConfig:新增 resolveContractApiInterfaceType, interface_type_id=3(OPEN_API_WAREHOUSE 仓库开放接口)自动映射为 2(OPEN_API 货主开放接口)落库, 不再要求当前主体为仓库(货主可维护自身签约关系下的接口配置) - callback_url 不再取入参(含 callbackUrl 别名),统一写入 config.openapi.defaultCallbackUrl(新增配置项,默认空) - storeWarehouse.store.listApiConfig:interface_type_id 过滤同步映射(传 3 按 2 查询) - 文档:methods/system.json 升级 0.3.350、methods/changes/system.json 变更记录、docs/openapi-callback-events.md 回调地址来源说明 - 测试:saveApiConfig 新增 4 条用例(3→2 落库、忽略入参回调地址、默认值未配置、货主主体可保存、缺失类型 404),listApiConfig 新增 1 条过滤映射用例 同时提交工作区其余在制品改动: - waybill:移除 wms_order_express_trace 模型并新增 drop 迁移,轨迹查询/取号/打印链路调整 - order:订单 SN 编码(order_item_sn / order_item_sn_log / sn_code_rule、has_sn_item 回填迁移),pendingOrder/recheckOrder/wave/base 调整 - express_platform、order_async、order_export、order_storage_allocation、storage.report、stock_store 配套修复 - lib:新增 jd_client,调整 qimen_client、callback_functions 及配套测试 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
683 lines
23 KiB
JavaScript
683 lines
23 KiB
JavaScript
'use strict';
|
||
|
||
const MainService = require('../../main');
|
||
|
||
const WAYBILL_EXPORT_TASK_CACHE_KEY_PREFIX = 'waybill_export_task_';
|
||
const WAYBILL_RECEIVE_TASK_CACHE_KEY_PREFIX = 'waybill_receive_task_';
|
||
/** 轨迹查询所依赖的出站回调 method */
|
||
const WAYBILL_TRACE_EVENT = 'waybill.getTrace';
|
||
/** 轨迹查询外部接口未配置时的失败提示 */
|
||
const WAYBILL_TRACE_NOT_CONFIGURED_MESSAGE =
|
||
'如需查询运单物流轨迹,到【设置】->【基础设置】->【API开放接口】配置相应的外部访问接口';
|
||
/** 揽收状态查询所依赖的出站回调 method */
|
||
const WAYBILL_RECEIVE_EVENT = 'waybill.getreceive';
|
||
/** 仓库未配置外部接口时的失败提示(直接失败,不进入任务流程) */
|
||
const WAYBILL_RECEIVE_NOT_CONFIGURED_MESSAGE =
|
||
'如需更新运单是否揽收信息,到【设置】->【基础设置】->【API开放接口】配置相应的外部访问接口';
|
||
|
||
/** 按 where 筛选解析运单号时允许的最大条数(超出要求缩小范围) */
|
||
const WAYBILL_RECEIVE_MAX_CODES = 5000;
|
||
|
||
/**
|
||
* 运单号仓库侧入口层。
|
||
* 负责鉴权声明、参数校验,委托 systems/waybill.js 执行业务逻辑。
|
||
*
|
||
* 所有方法均需登录但无需细粒度鉴权(与订单列表保持一致)。
|
||
*/
|
||
class WaybillWarehouseService extends MainService {
|
||
constructor(ctx) {
|
||
super(ctx);
|
||
const _noNeedLogin = '';
|
||
const _noNeedRight = 'list,detail,export,exportTaskProgress,updateReceive,updateReceiveTaskProgress,getTrace';
|
||
const _noNeedLog = '';
|
||
const _noNeedAuth = 'list,detail,export,exportTaskProgress,updateReceive,updateReceiveTaskProgress,getTrace';
|
||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||
}
|
||
|
||
/**
|
||
* 运单列表查询(仓库侧)。
|
||
* 支持分页、多条件筛选、排序。
|
||
*
|
||
* @param {Object} data 请求参数。
|
||
* @param {Object} [data.where] 筛选条件。
|
||
* @param {Object} [data.pagination] 分页参数 { page, pageSize }。
|
||
* @param {Object} [data.sort] 排序参数 { field, order }。
|
||
* @return {Promise<Object>} 运单列表与分页信息。
|
||
*/
|
||
async list(data) {
|
||
try {
|
||
const { where, pagination, sort } = data || {};
|
||
const result = await this.service.systems.waybill.list({
|
||
where: where || {},
|
||
pagination: pagination || {},
|
||
sort: sort || {},
|
||
});
|
||
return this.success('获取成功', result);
|
||
} catch (e) {
|
||
return this.fail(e.message);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 运单详情查询(仓库侧)。
|
||
* 支持按运单ID或运单号查询。
|
||
*
|
||
* @param {Object} data 请求参数。
|
||
* @param {number} [data.id] 运单记录ID。
|
||
* @param {string} [data.waybillCode] 运单号(与 id 二选一,waybillCode 优先)。
|
||
* @return {Promise<Object>} 运单详情(含订单/打印/打包信息)。
|
||
*/
|
||
async detail(data) {
|
||
try {
|
||
const { id, waybillCode } = data || {};
|
||
if (!id && !waybillCode) {
|
||
return this.fail('运单ID或运单号不能为空');
|
||
}
|
||
const result = await this.service.systems.waybill.detail({
|
||
id,
|
||
waybillCode,
|
||
});
|
||
return this.success('获取成功', result);
|
||
} catch (e) {
|
||
return this.fail(e.message);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 运单导出(仓库侧)。异步任务模式,提交后通过 exportTaskProgress 查询进度。
|
||
*
|
||
* @param {Object} data 请求参数。
|
||
* @param {Object} [data.where] 筛选条件(同 list)。
|
||
* @param {Object} [data.sort] 排序参数(同 list)。
|
||
* @param {string[]} [data.exportFields] 需要导出的字段列表。
|
||
* @return {Promise<Object>} 任务提交结果,含 task_id。
|
||
*/
|
||
async export(data) {
|
||
try {
|
||
const { where, sort, exportFields } = data || {};
|
||
const taskId = this.generateExportTaskId();
|
||
|
||
const taskPayload = {
|
||
task_id: taskId,
|
||
status: 'submitted',
|
||
progress: 0,
|
||
current_count: 0,
|
||
total_count: 0,
|
||
message: '导出任务已提交',
|
||
result: null,
|
||
error: '',
|
||
};
|
||
await this.setExportTaskProgress(taskId, taskPayload);
|
||
|
||
setImmediate(async () => {
|
||
try {
|
||
await this.setExportTaskProgress(taskId, {
|
||
task_id: taskId,
|
||
status: 'running',
|
||
progress: 5,
|
||
current_count: 0,
|
||
total_count: 0,
|
||
message: '导出任务执行中',
|
||
result: null,
|
||
error: '',
|
||
});
|
||
|
||
const result = await this.service.systems.waybill.export({
|
||
where: where || {},
|
||
sort: sort || {},
|
||
exportFields,
|
||
onProgress: async progress => {
|
||
const safeProgress = this.isPlainObject(progress) ? progress : {};
|
||
await this.setExportTaskProgress(taskId, {
|
||
task_id: taskId,
|
||
status: safeProgress.status || 'running',
|
||
progress: safeProgress.progress || 0,
|
||
current_count: safeProgress.currentCount || safeProgress.current_count || 0,
|
||
total_count: safeProgress.totalCount || safeProgress.total_count || 0,
|
||
message: safeProgress.message || '导出任务执行中',
|
||
result: safeProgress.result || null,
|
||
error: '',
|
||
});
|
||
},
|
||
});
|
||
|
||
await this.setExportTaskProgress(taskId, {
|
||
task_id: taskId,
|
||
status: 'success',
|
||
progress: 100,
|
||
current_count: result.current_count || 0,
|
||
total_count: result.total_count || 0,
|
||
message: '导出任务完成',
|
||
result,
|
||
error: '',
|
||
});
|
||
} catch (error) {
|
||
const errorMessage = error && error.message ? error.message : `${error}`;
|
||
await this.setExportTaskProgress(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 exportTaskProgress(data = {}) {
|
||
try {
|
||
const taskId = this.normalizeExportTaskId(data);
|
||
if (!taskId) {
|
||
return this.success('ok', {
|
||
task_id: '',
|
||
status: 'not_found',
|
||
progress: 0,
|
||
current_count: 0,
|
||
total_count: 0,
|
||
message: '任务不存在',
|
||
result: null,
|
||
error: '',
|
||
download_url: '',
|
||
update_time: Date.now(),
|
||
});
|
||
}
|
||
|
||
const cachedTask = await this.getExportTaskProgress(taskId);
|
||
if (!cachedTask) {
|
||
return this.success('ok', {
|
||
task_id: taskId,
|
||
status: 'not_found',
|
||
progress: 0,
|
||
current_count: 0,
|
||
total_count: 0,
|
||
message: '任务不存在',
|
||
result: null,
|
||
error: '',
|
||
download_url: '',
|
||
update_time: Date.now(),
|
||
});
|
||
}
|
||
|
||
const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {};
|
||
const downloadUrl = String(
|
||
safeResult.url
|
||
|| safeResult.cndUrl
|
||
|| safeResult.cdnUrl
|
||
|| safeResult.cosUrl
|
||
|| safeResult.fileKey
|
||
|| ''
|
||
);
|
||
|
||
return this.success('ok', {
|
||
task_id: taskId,
|
||
...cachedTask,
|
||
download_url: downloadUrl,
|
||
});
|
||
} catch (e) {
|
||
return this.fail(e.message);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 批量更新运单是否揽收(仓库侧)。
|
||
*
|
||
* 链路走 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。
|
||
* @return {string} 任务ID。
|
||
*/
|
||
generateExportTaskId() {
|
||
const warehouseId = this.ctx?.user?.store_id || 'unknown';
|
||
const timestamp = Date.now();
|
||
const randomToken = Math.random().toString(36).slice(2, 10);
|
||
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();
|
||
}
|
||
|
||
/**
|
||
* 解析仓库承接 waybill.getTrace 的 API 应用 AppKey(按 id 升序取首个)。
|
||
* 返回空字符串表示仓库未配置轨迹查询外部接口。
|
||
* @param {number} warehouseId 仓库ID。
|
||
* @return {Promise<string>} 目标应用 AppKey。
|
||
*/
|
||
async resolveTraceAppKey(warehouseId) {
|
||
const warehouseNotify = this.service.systems && this.service.systems.warehouseNotify;
|
||
if (!warehouseNotify || typeof warehouseNotify.listCallbackConfigs !== 'function') {
|
||
return '';
|
||
}
|
||
|
||
const candidates = await warehouseNotify.listCallbackConfigs(
|
||
Number(warehouseId) || 0,
|
||
WAYBILL_TRACE_EVENT
|
||
);
|
||
const first = Array.isArray(candidates) ? candidates[0] : null;
|
||
return String(first && first.appKey || '').trim();
|
||
}
|
||
|
||
/**
|
||
* 规范导出任务ID。
|
||
* @param {Object} data 请求体。
|
||
* @return {string} 规范后的任务ID。
|
||
*/
|
||
normalizeExportTaskId(data = {}) {
|
||
const normalizedData = this.isPlainObject(data) ? data : {};
|
||
return String(normalizedData.task_id || normalizedData.taskId || '').trim();
|
||
}
|
||
|
||
/**
|
||
* 获取运单任务缓存键。
|
||
* @param {string} taskId 任务ID。
|
||
* @param {string} [prefix] 缓存键前缀,区分导出/揽收状态更新等任务类型。
|
||
* @return {string} 缓存键。
|
||
*/
|
||
getTaskCacheKey(taskId = '', prefix = WAYBILL_EXPORT_TASK_CACHE_KEY_PREFIX) {
|
||
const normalizedTaskId = String(taskId || '').trim();
|
||
if (!normalizedTaskId) {
|
||
return '';
|
||
}
|
||
return `${prefix}${normalizedTaskId}`;
|
||
}
|
||
|
||
/**
|
||
* 写入运单任务进度缓存。
|
||
* @param {string} taskId 任务ID。
|
||
* @param {Object} payload 任务状态。
|
||
* @param {string} [prefix] 缓存键前缀。
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
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;
|
||
}
|
||
|
||
const safePayload = this.isPlainObject(payload) ? payload : {};
|
||
const normalizeCount = value => {
|
||
const numericValue = Number(value);
|
||
return Number.isFinite(numericValue) && numericValue >= 0 ? Math.round(numericValue) : 0;
|
||
};
|
||
const progressPayload = {
|
||
task_id: String(taskId || '').trim(),
|
||
status: String(safePayload.status || 'submitted').trim() || 'submitted',
|
||
progress: Number.isFinite(Number(safePayload.progress))
|
||
? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress))))
|
||
: 0,
|
||
current_count: normalizeCount(safePayload.current_count),
|
||
total_count: normalizeCount(safePayload.total_count),
|
||
message: String(safePayload.message || ''),
|
||
result: safePayload.result ?? null,
|
||
error: String(safePayload.error || ''),
|
||
};
|
||
|
||
await this.app.setCacheAsync(cacheKey, progressPayload);
|
||
}
|
||
|
||
/**
|
||
* 读取运单任务进度缓存。
|
||
* @param {string} taskId 任务ID。
|
||
* @param {string} [prefix] 缓存键前缀。
|
||
* @return {Promise<Object|null>} 任务状态对象或 null。
|
||
*/
|
||
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);
|
||
}
|
||
|
||
/**
|
||
* 查询单个运单的全部物流轨迹(仓库侧)。
|
||
*
|
||
* 全部回源:实时调用外部访问接口 `waybill.getTrace` 查询,不做本地存储。
|
||
* 一次返回该运单号下的所有轨迹(不分页),按操作时间倒序排列(最新的在前)。
|
||
* 命中轨迹(非空)时顺带把该运单 `is_galaxy_receive` 置为 Y(只升不降)。
|
||
*
|
||
* @param {Object} data 请求参数。
|
||
* @param {string} [data.waybillCode] 运单号(兼容 waybill_code)。
|
||
* @return {Promise<Object>} { waybill_code, total, list, received_updated }。
|
||
*/
|
||
async getTrace(data = {}) {
|
||
try {
|
||
const safeData = this.isPlainObject(data) ? data : {};
|
||
const waybillCode = String(safeData.waybillCode || safeData.waybill_code || '').trim();
|
||
if (!waybillCode) {
|
||
return this.fail('运单号不能为空');
|
||
}
|
||
|
||
const warehouseId = Number(this.ctx?.user?.store_id || 0);
|
||
if (!warehouseId) {
|
||
return this.fail('无法获取当前仓库ID');
|
||
}
|
||
|
||
const appKey = await this.resolveTraceAppKey(warehouseId);
|
||
if (!appKey) {
|
||
return this.fail(WAYBILL_TRACE_NOT_CONFIGURED_MESSAGE);
|
||
}
|
||
|
||
const fetched = await this.service.systems.waybill.fetchTracesByWaybill({
|
||
warehouseId,
|
||
waybillCode,
|
||
appKey,
|
||
});
|
||
|
||
if (!fetched.success) {
|
||
const reason = fetched.reason || fetched.error || '运单轨迹查询失败';
|
||
return this.fail(`运单轨迹查询失败: ${reason}`);
|
||
}
|
||
|
||
// 有轨迹即视为已揽收(只升不降);失败不阻断查询
|
||
let receivedUpdated = 0;
|
||
if (!fetched.empty) {
|
||
receivedUpdated = await this.service.systems.waybill.markReceiveByTraces({
|
||
warehouseId,
|
||
waybillCodes: [ waybillCode ],
|
||
});
|
||
}
|
||
|
||
return this.success('获取成功', {
|
||
waybill_code: waybillCode,
|
||
total: fetched.traces.length,
|
||
list: fetched.traces,
|
||
received_updated: receivedUpdated,
|
||
});
|
||
} catch (e) {
|
||
return this.fail(e.message);
|
||
}
|
||
}
|
||
}
|
||
|
||
module.exports = WaybillWarehouseService;
|