liufumingren 9af7dcf8fb feat(storeWarehouse): 签约关系接口配置按货主开放接口落库且回调地址统一取配置
- 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>
2026-11-14 17:14:04 +08:00

1910 lines
74 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const MainService = require('../main');
const ExcelJS = require('exceljs');
const fs = require('fs');
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';
/** 出站回调 method:查询运单物流轨迹 */
const WAYBILL_TRACE_EVENT = 'waybill.getTrace';
/** 轨迹查询回调签名模式:与揽收查询一致(仓库通知协议) */
const WAYBILL_TRACE_SIGN_MODE = WAYBILL_RECEIVE_SIGN_MODE;
/**
* 业务逻辑层:waybill(运单号快速查询)。
*/
class WaybillService extends MainService {
/**
* 根据运单号查询有效订单ID,并返回该订单所属波次下所有订单ID列表。
*
* 查询流程:
* 1. 通过运单号查询 wms_order_express 表获取 order_id 和 warehouse_id。
* 2. 通过 order_id 遍历多表(current/history/dispatch)获取 wave_id 和 wave_no。
* 3. 若有有效波次(wave_id > 0),遍历多表查询该波次下所有订单的 ID 列表。
*
* @param {Object} params 查询参数。
* @param {string} params.waybill_code 运单号,不可为空。
* @return {Promise<Object>} 包含 order_id 和 waves 数组的对象。
* @throws {Error} 当 waybill_code 为空或未找到匹配记录时抛出业务错误。
*/
async toOrder({ waybill_code: waybillCode }) {
const { ctx } = this;
if (!waybillCode || !String(waybillCode).trim()) {
this.throwError('运单号不能为空');
}
const userWarehouseId = ctx.user && ctx.user.store_id ? ctx.user.store_id : null;
const expressWhere = {
waybill_code: String(waybillCode).trim(),
status: 1,
};
if (userWarehouseId) {
expressWhere.warehouse_id = userWarehouseId;
}
const record = await ctx.model.OrderExpress.findOne({
where: expressWhere,
attributes: [ 'order_id', 'warehouse_id' ],
raw: true,
});
if (!record) {
this.throwError('未找到该运单号对应的订单');
}
const { order_id: orderId, warehouse_id: expressWarehouseId } = record;
// 获取 warehouse_id:优先从 ctx.user.store_id,回退到运单记录中的 warehouse_id
const warehouseId =
(ctx.user && ctx.user.store_id) ? ctx.user.store_id : expressWarehouseId;
// 构建多表遍历查询队列:current → history → dispatch
const orderDeliveryFactory =
ctx.model && ctx.model.OrderDeliveryFactory;
const tableOrders = [
{
label: 'current',
getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId),
},
{
label: 'history',
getModel: () => orderDeliveryFactory.getHistoryModel(warehouseId),
},
{
label: 'dispatch',
getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId),
},
];
// 序列表定位优先:命中则先查对应分表,未命中(存量订单)按原顺序回退遍历
try {
if (orderDeliveryFactory && typeof orderDeliveryFactory.getOrderLocation === 'function') {
const preferredLocation = await orderDeliveryFactory.getOrderLocation(orderId, warehouseId);
if (preferredLocation) {
tableOrders.sort((a, b) => (a.label === preferredLocation ? -1 : b.label === preferredLocation ? 1 : 0));
}
}
} catch (_err) { /* 定位失败,保持原遍历顺序 */ }
// 遍历多表查询订单的 wave_id 和 wave_no
let orderRow = null;
for (const entry of tableOrders) {
try {
const model = await entry.getModel();
if (!model || typeof model.findOne !== 'function') {
continue;
}
const row = await model.findOne({
where: { id: orderId, warehouse_id: warehouseId },
attributes: [ 'id', 'wave_id', 'wave_no' ],
raw: true,
});
if (row) {
orderRow = row;
break;
}
} catch (_err) {
continue;
}
}
// 无订单记录或 wave_id 无效,返回空 waves
if (!orderRow || !orderRow.wave_id || Number(orderRow.wave_id) <= 0) {
return { order_id: orderId, waves: [] };
}
const { wave_id: waveId, wave_no: waveNo } = orderRow;
// 遍历多表查询该波次下所有订单的 ID 列表
const orderIds = [];
for (const entry of tableOrders) {
try {
const model = await entry.getModel();
if (!model || typeof model.findAll !== 'function') {
continue;
}
const rows = await model.findAll({
where: { wave_id: waveId, warehouse_id: warehouseId },
attributes: [ 'id' ],
raw: true,
});
for (const row of rows) {
if (!orderIds.includes(row.id)) {
orderIds.push(row.id);
}
}
} catch (_err) {
continue;
}
}
return {
order_id: orderId,
waves: [
{
wave_id: waveId,
wave_no: waveNo,
order_ids: orderIds,
},
],
};
}
/**
* 解析主单号筛选条件(单值 / 数组 / 标准 where 对象),返回对应订单ID列表。
* 先按主单号(business_key=1)在 wms_order_express 中定位 order_id,调用方再据此查询订单下所有运单(主+子)。
*
* @param {*} mainWaybillCode 主单号条件值(字符串 / 字符串数组 / {operator,value} 标准化对象)。
* @param {number} warehouseId 仓库ID(仓库隔离)。
* @return {Promise<{empty: boolean, orderIds: number[]}>} empty=true 表示所有主单号均不存在,调用方应直接返回空结果;orderIds 去重后的订单ID列表。
*/
async resolveMainWaybillOrderIds(mainWaybillCode, warehouseId) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const codes = (Array.isArray(mainWaybillCode) ? mainWaybillCode : [ mainWaybillCode ])
.map(code => (code === undefined || code === null ? '' : String(code).trim()))
.filter(code => code !== '');
if (codes.length === 0) {
return { empty: false, orderIds: [] };
}
const mainRecords = await ctx.model.OrderExpress.findAll({
where: {
waybill_code: { [Op.in]: codes },
business_key: 1,
warehouse_id: warehouseId,
},
attributes: [ 'order_id' ],
raw: true,
});
if (!mainRecords || mainRecords.length === 0) {
return { empty: true, orderIds: [] };
}
const orderIds = [];
for (const record of mainRecords) {
const orderId = Number(record.order_id);
if (Number.isFinite(orderId) && !orderIds.includes(orderId)) {
orderIds.push(orderId);
}
}
if (orderIds.length === 0) {
return { empty: true, orderIds: [] };
}
return { empty: false, orderIds };
}
/**
* 构建运单查询条件(与 waybill.warehouse.list 完全一致的筛选口径,不含分页与排序)。
* 供列表查询与「按条件批量更新揽收状态」共用,避免两处筛选逻辑漂移。
*
* @param {Object} [rawWhere={}] 原始筛选条件(支持 operator/value 格式)。
* @param {number} warehouseId 仓库ID(强制隔离,非空)。
* @return {Promise<{ empty: boolean, queryWhere: Object }>} empty=true 表示条件已确定无匹配(如主单号均不存在)。
*/
async buildListQueryWhere(rawWhere = {}, warehouseId) {
const { app } = this;
const { Op } = app.Sequelize;
// 标准化 where 条件:将前端 operator/value 格式(如 {operator:"contains", value:"YT..."})统一转为标准条件对象
const where = this.normalizeWhereParams(rawWhere);
/**
* 从 where 条件中提取实际值。
* 标准化后的条件为 {operator, value} 对象,本函数提取 .value;
* 对于未标准化的原始值(string/number)直接返回。
* @param {*} c 条件值
* @param {*} defaultValue 默认值
* @return {*} 提取后的实际值
*/
const val = (c, defaultValue) => {
if (c === undefined || c === null) return defaultValue;
if (typeof c === 'object' && !Array.isArray(c) && 'value' in c) return c.value;
return c;
};
// 构建查询条件
const queryWhere = { warehouse_id: warehouseId };
// 主单号查询:先通过主单号(支持单值/数组)定位 order_id,再查这些订单下所有运单(主+子)
const mainResolved = await this.resolveMainWaybillOrderIds(val(where.mainWaybillCode), warehouseId);
if (mainResolved.empty) {
// 主单号均不存在,条件已确定无匹配
return { empty: true, queryWhere };
}
if (mainResolved.orderIds.length > 0) {
// 单主单保持标量 order_id(向后兼容),多主单使用 Op.in
queryWhere.order_id = mainResolved.orderIds.length === 1
? mainResolved.orderIds[0]
: { [Op.in]: mainResolved.orderIds };
}
// 运单号搜索:数组精确匹配(Op.in),字符串保持模糊匹配(Op.like)
const waybillCode = val(where.waybillCode);
if (Array.isArray(waybillCode)) {
const waybillCodeList = waybillCode
.map(item => (item === undefined || item === null ? '' : String(item).trim()))
.filter(item => item !== '');
if (waybillCodeList.length > 0) {
queryWhere.waybill_code = { [Op.in]: waybillCodeList };
}
} else if (waybillCode && String(waybillCode).trim()) {
queryWhere.waybill_code = { [Op.like]: `%${String(waybillCode).trim()}%` };
}
// 订单ID等值
const orderId = val(where.orderId);
if (orderId !== undefined && orderId !== null && String(orderId).trim() !== '') {
queryWhere.order_id = Number(orderId);
}
// 订单号模糊搜索
// TODO: 快照字段 delivery_order_code 未落库,暂跳过订单号筛选;快照列就绪后取消注释
// if (where.orderNo && String(where.orderNo).trim()) {
// queryWhere.delivery_order_code = { [Op.like]: `%${String(where.orderNo).trim()}%` };
// }
// 物流公司编码等值
const logisticsCode = val(where.logisticsCode);
if (logisticsCode && String(logisticsCode).trim()) {
queryWhere.logistics_code = String(logisticsCode).trim();
}
// 物流接口ID等值
const logisticsInterfaceId = val(where.logisticsInterfaceId);
if (logisticsInterfaceId !== undefined && logisticsInterfaceId !== null && String(logisticsInterfaceId).trim() !== '') {
queryWhere.logistics_interface_id = Number(logisticsInterfaceId);
}
// 平台编码等值
const platformCode = val(where.platformCode);
if (platformCode && String(platformCode).trim()) {
queryWhere.platform_code = String(platformCode).trim();
}
// 运单状态等值
const statusVal = val(where.status);
if (statusVal !== undefined && statusVal !== null && String(statusVal).trim() !== '') {
queryWhere.status = Number(statusVal);
}
// 是否退回
const isBack = val(where.isBack);
if (isBack && String(isBack).trim()) {
queryWhere.is_back = String(isBack).trim();
}
// 是否拦截
const isIntercept = val(where.isIntercept);
if (isIntercept && String(isIntercept).trim()) {
queryWhere.is_intercept = String(isIntercept).trim();
}
// 是否揽收
const isGalaxyReceive = val(where.isGalaxyReceive);
if (isGalaxyReceive && String(isGalaxyReceive).trim()) {
queryWhere.is_galaxy_receive = String(isGalaxyReceive).trim();
}
// 运单类型:主单号 / 子单号
const waybillType = val(where.waybillType);
if (waybillType && String(waybillType).trim()) {
const type = String(waybillType).trim();
if (type === 'main' || type === '1') {
queryWhere.business_key = 1;
} else if (type === 'child' || type === '2') {
queryWhere.business_key = { [Op.gt]: 1 };
}
}
// 货主ID等值
const storeId = val(where.storeId);
if (storeId !== undefined && storeId !== null && String(storeId).trim() !== '') {
queryWhere.store_id = Number(storeId);
}
// 包材ID等值
const packageMaterialId = val(where.packageMaterialId);
if (packageMaterialId !== undefined && packageMaterialId !== null && String(packageMaterialId).trim() !== '') {
queryWhere.package_material_id = Number(packageMaterialId);
}
// 是否已称重
const hasWeighingWeight = val(where.hasWeighingWeight);
if (hasWeighingWeight !== undefined && hasWeighingWeight !== null && String(hasWeighingWeight).trim() !== '') {
const hasWeight = String(hasWeighingWeight).trim();
if (hasWeight === 'true') {
queryWhere.weighing_weight = { [Op.gt]: 0 };
} else if (hasWeight === 'false') {
queryWhere.weighing_weight = { [Op.eq]: 0 };
}
}
// 关键词模糊搜索
const keyword = val(where.keyword);
if (keyword && String(keyword).trim()) {
queryWhere.waybill_code = { [Op.like]: `%${String(keyword).trim()}%` };
}
// 创建时间范围:createdAt 支持 {operator:'between', value:[start,end]}(兼容 createAt 别名)
const createdAtRange = val(where.createdAt) ?? val(where.createAt);
if (Array.isArray(createdAtRange)) {
const [ unifiedCreateAtStart, unifiedCreateAtEnd ] = createdAtRange;
if (unifiedCreateAtStart && String(unifiedCreateAtStart).trim()) {
queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.gte]: new Date(unifiedCreateAtStart) };
}
if (unifiedCreateAtEnd && String(unifiedCreateAtEnd).trim()) {
queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.lte]: new Date(unifiedCreateAtEnd) };
}
}
// 兼容旧写法:createdAtStart / createdAtEnd
const createdAtStart = val(where.createdAtStart);
if (createdAtStart && String(createdAtStart).trim()) {
const startDate = this.normalizeDate(String(createdAtStart).trim(), false);
if (startDate) {
queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.gte]: startDate };
}
}
const createdAtEnd = val(where.createdAtEnd);
if (createdAtEnd && String(createdAtEnd).trim()) {
const endDate = this.normalizeDate(String(createdAtEnd).trim(), true);
if (endDate) {
queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.lte]: endDate };
}
}
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: [
'id', 'waybill_code', 'order_id', 'business_key', 'status',
'warehouse_id', 'store_id',
'delivery_order_code', 'source_order_codes',
'logistics_code', 'logistics_name',
'logistics_interface_id', 'logistics_interface_name',
'platform_code',
'is_back', 'is_intercept', 'is_galaxy_receive',
'weighing_weight',
'package_material_id', 'package_material_name_snapshot',
'create_at',
],
order: [[ sortField, sortOrder ]],
limit: pageSize,
offset: (page - 1) * pageSize,
raw: true,
});
if (rows.length === 0) {
return {
list: [],
pagination: { page, pageSize, total: count, totalPages: Math.ceil(count / pageSize) },
};
}
// 提取所有唯一的 order_id
const orderIds = [ ...new Set(rows.map(r => r.order_id).filter(Boolean)) ];
// SELF JOIN:查询同 order_id 下 business_key=1 的主单号(强制同仓校验,避免跨仓串读)
const mainWaybillMap = new Map();
if (orderIds.length > 0) {
const mainRecords = await ctx.model.OrderExpress.findAll({
where: {
order_id: { [Op.in]: orderIds },
business_key: 1,
warehouse_id: warehouseId,
},
attributes: [ 'order_id', 'waybill_code' ],
raw: true,
});
for (const rec of mainRecords) {
if (!mainWaybillMap.has(rec.order_id)) {
mainWaybillMap.set(rec.order_id, rec.waybill_code);
}
}
}
// 提取运单号列表,用于查询打印信息
const waybillCodes = rows.map(r => r.waybill_code).filter(Boolean);
// 查询货主备注名称(store_warehouse.store_remask)
const storeRemarkMap = new Map();
const storeWarehouseKeys = rows
.filter(r => r.store_id && r.warehouse_id)
.map(r => `${r.store_id}:${r.warehouse_id}`);
const uniqueKeys = [ ...new Set(storeWarehouseKeys) ];
if (uniqueKeys.length > 0 && ctx.model.StoreWarehouse) {
const swConditions = uniqueKeys.map(key => {
const [ storeId, whId ] = key.split(':');
return { store_id: Number(storeId), warehouse_id: Number(whId) };
});
const swRows = await ctx.model.StoreWarehouse.findAll({
where: { [Op.or]: swConditions },
attributes: [ 'store_id', 'warehouse_id', 'store_remask' ],
raw: true,
});
for (const sw of swRows) {
storeRemarkMap.set(`${sw.store_id}:${sw.warehouse_id}`, sw.store_remask || '');
}
}
// 查询打印记录(次数和最近打印时间)
const printInfoMap = new Map();
if (waybillCodes.length > 0) {
const printRecords = await ctx.model.ExpressPrintRecord.findAll({
where: { express_no: { [Op.in]: waybillCodes } },
attributes: [
'express_no',
[ app.Sequelize.fn('COUNT', app.Sequelize.col('id')), 'print_count' ],
[ app.Sequelize.fn('MAX', app.Sequelize.col('print_time')), 'last_print_at' ],
],
group: [ 'express_no' ],
raw: true,
});
for (const pr of printRecords) {
printInfoMap.set(pr.express_no, {
print_count: Number(pr.print_count) || 0,
last_print_at: pr.last_print_at || null,
});
}
}
// 组装响应列表
const list = rows.map(row => {
const wbCode = row.waybill_code || '';
const mainCode = mainWaybillMap.get(row.order_id) || wbCode;
const printInfo = printInfoMap.get(wbCode) || { print_count: 0, last_print_at: null };
return {
id: row.id,
waybill_code: wbCode,
main_waybill_code: mainCode,
waybill_type: Number(row.business_key) === 1 ? '主单号' : '子单号',
order_id: row.order_id,
order_no: row.delivery_order_code || row.source_order_codes || '',
source_order_codes: row.source_order_codes || '',
warehouse_id: row.warehouse_id,
warehouse_name: '',
store_id: row.store_id || 0,
store_name: '',
store_remark_name: storeRemarkMap.get(`${row.store_id}:${row.warehouse_id}`) || '',
business_key: row.business_key,
status: row.status,
status_text: row.status === 1 ? '已分配' : '未分配',
logistics_code: row.logistics_code || '',
logistics_name: row.logistics_name || '',
logistics_interface_id: row.logistics_interface_id || 0,
logistics_interface_name: row.logistics_interface_name || '',
platform_code: row.platform_code || '',
is_back: row.is_back || 'N',
is_intercept: row.is_intercept || 'N',
is_galaxy_receive: row.is_galaxy_receive || 'N',
weighing_weight: row.weighing_weight || 0,
weighing_weight_display: row.weighing_weight > 0 ? `${(row.weighing_weight / 1000).toFixed(2)} kg` : '0 kg',
package_material_id: row.package_material_id || 0,
package_material_name: row.package_material_name_snapshot || '',
print_count: printInfo.print_count,
last_print_at: printInfo.last_print_at ? this.app.formatDate(printInfo.last_print_at) : null,
create_at: row.create_at ? this.app.formatDate(row.create_at) : null,
};
});
return {
list,
pagination: {
page,
pageSize,
total: count,
totalPages: Math.ceil(count / pageSize),
},
};
}
/**
* 运单详情查询(仓库侧)。
* 查询单个运单的完整信息,包含关联订单、兄弟运单、打印记录、打包信息。
*
* @param {Object} options 查询参数。
* @param {number} [options.id] 运单记录ID。
* @param {string} [options.waybillCode] 运单号(与 id 二选一,waybillCode 优先)。
* @return {Promise<Object>} 运单详情。
* @throws {Error} 当运单不存在或参数无效时抛出业务错误。
*/
async detail({ id, waybillCode } = {}) {
const { ctx } = this;
// 仓库隔离
const warehouseId = Number(ctx.user && ctx.user.store_id);
if (!warehouseId) {
this.throwError('用户未绑定仓库,无法查询运单');
}
// 构建查询条件
const expressWhere = { warehouse_id: warehouseId };
if (waybillCode && String(waybillCode).trim()) {
expressWhere.waybill_code = String(waybillCode).trim();
} else if (id !== undefined && id !== null && String(id).trim() !== '') {
expressWhere.id = Number(id);
} else {
this.throwError('运单ID或运单号不能为空');
}
// 查询运单主记录
const record = await ctx.model.OrderExpress.findOne({
where: expressWhere,
raw: true,
});
if (!record) {
this.throwError('未找到该运单');
}
const orderId = record.order_id;
// 查询同订单下所有运单(兄弟运单)
const siblingWaybills = await ctx.model.OrderExpress.findAll({
where: { order_id: orderId, warehouse_id: warehouseId },
attributes: [ 'id', 'waybill_code', 'business_key' ],
order: [[ 'business_key', 'ASC' ]],
raw: true,
});
const mainWaybillRecord = siblingWaybills.find(s => Number(s.business_key) === 1);
const mainWaybillCode = mainWaybillRecord ? mainWaybillRecord.waybill_code : (record.waybill_code || '');
const siblingList = siblingWaybills.map(s => ({
waybill_code: s.waybill_code || '',
business_key: s.business_key,
waybill_type: Number(s.business_key) === 1 ? '主单号' : '子单号',
}));
// 通过 OrderDeliveryFactory 多表遍历查询订单信息
const orderDeliveryFactory = ctx.model && ctx.model.OrderDeliveryFactory;
let orderInfo = null;
if (orderDeliveryFactory && typeof orderDeliveryFactory.getCurrentModel === 'function') {
const tableOrders = [
{ label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) },
{ label: 'history', getModel: () => orderDeliveryFactory.getHistoryModel(warehouseId) },
{ label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) },
];
for (const entry of tableOrders) {
try {
const model = await entry.getModel();
if (!model || typeof model.findOne !== 'function') {
continue;
}
const row = await model.findOne({
where: { id: orderId, warehouse_id: warehouseId },
attributes: [
'id', 'delivery_order_code', 'warehouse_id', 'store_id',
'wave_id', 'wave_no', 'order_type', 'store_name',
],
raw: true,
});
if (row) {
orderInfo = {
order_id: row.id,
order_no: row.delivery_order_code || '',
warehouse_id: row.warehouse_id,
// TODO: 快照列未落库,暂时填空;快照就绪后替换为 record.warehouse_name_snapshot
warehouse_name: '',
store_id: row.store_id || 0,
store_name: row.store_name || '',
wave_id: row.wave_id || 0,
wave_no: row.wave_no || '',
order_type: row.order_type || 'delivery',
};
break;
}
} catch (_err) {
continue;
}
}
}
// 若遍历失败,用已有信息兜底
// TODO: 快照列未落库,暂用空值兜底;快照就绪后替换为 record.xxx_snapshot
if (!orderInfo) {
orderInfo = {
order_id: orderId,
order_no: '',
warehouse_id: record.warehouse_id,
warehouse_name: '',
store_id: 0,
store_name: '',
wave_id: 0,
wave_no: '',
order_type: 'delivery',
};
}
// 查询打印记录
let printRecords = [];
if (record.waybill_code) {
printRecords = await ctx.model.ExpressPrintRecord.findAll({
where: { express_no: record.waybill_code },
attributes: [
'id', 'printer_name', 'template_id', 'platform',
'print_time',
],
order: [[ 'print_time', 'DESC' ]],
raw: true,
});
}
// 组装详情响应
return {
id: record.id,
waybill_code: record.waybill_code || '',
main_waybill_code: mainWaybillCode,
waybill_type: Number(record.business_key) === 1 ? '主单号' : '子单号',
business_key: record.business_key,
sibling_waybills: siblingList,
order: orderInfo,
logistics: {
logistics_code: record.logistics_code || '',
logistics_name: record.logistics_name || '',
logistics_interface_id: record.logistics_interface_id || 0,
logistics_interface_name: record.logistics_interface_name || '',
platform_code: record.platform_code || '',
},
status_info: {
status: record.status,
status_text: record.status === 1 ? '已分配' : '未分配',
is_back: record.is_back || 'N',
is_intercept: record.is_intercept || 'N',
is_galaxy_receive: record.is_galaxy_receive || 'N',
},
weight: {
weighing_weight: record.weighing_weight || 0,
weighing_weight_display: record.weighing_weight > 0
? `${(record.weighing_weight / 1000).toFixed(2)} kg`
: '0 kg',
},
package: {
package_material_id: record.package_material_id || 0,
package_material_name: record.package_material_name_snapshot || '',
},
print_records: printRecords.map(pr => ({
id: pr.id,
printer_name: pr.printer_name || '',
template_id: pr.template_id || 0,
template_name: '',
platform: pr.platform || '',
printed_at: pr.print_time ? this.app.formatDate(pr.print_time) : null,
})),
print_count: printRecords.length,
printinfo: record.printinfo || null,
ver: record.ver || '',
retry_count: record.retry_count || 0,
create_at: record.create_at ? this.app.formatDate(record.create_at) : null,
delete_at: record.delete_at ? this.app.formatDate(record.delete_at) : null,
};
}
/**
* 运单导出(仓库侧)。
* 复用 list 的筛选逻辑,分批查询,支持进度回调。
*
* @param {Object} options 导出参数。
* @param {Object} [options.where={}] 筛选条件(同 list,另支持 ids:运单ID数组,精确过滤)。
* @param {Object} [options.sort={}] 排序参数(同 list)。
* @param {string[]} [options.exportFields] 需要导出的字段列表,不传则导出全部字段。
* @param {Function} [options.onProgress] 进度回调,接收 `{ status, progress, currentCount, totalCount, message, result }`。
* @return {Promise<Object>} 导出结果 { list, current_count, total_count, url }。
*/
async export({ where: rawWhere = {}, sort = {}, exportFields, onProgress } = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
// 标准化 where 条件
const where = this.normalizeWhereParams(rawWhere);
/**
* 从标准化后的 where 条件中提取实际值。
* @param {*} c 条件值
* @param {*} defaultValue 默认值
* @return {*} 提取后的实际值
*/
const val = (c, defaultValue) => {
if (c === undefined || c === null) return defaultValue;
if (typeof c === 'object' && !Array.isArray(c) && 'value' in c) return c.value;
return c;
};
// 仓库隔离
const warehouseId = Number(ctx.user && ctx.user.store_id);
if (!warehouseId) {
this.throwError('用户未绑定仓库,无法导出运单');
}
// 排序参数
const allowedSortFields = [ 'create_at', 'weighing_weight', 'id' ];
const sortField = allowedSortFields.includes(sort.field) ? sort.field : 'create_at';
const sortOrder = sort.order === 'asc' ? 'ASC' : 'DESC';
// 构建查询条件(同 list)
const queryWhere = { warehouse_id: warehouseId };
// 指定运单ID列表(勾选导出,按 wms_order_express.id 精确过滤)
const idsExport = val(where.ids);
if (Array.isArray(idsExport) && idsExport.length > 0) {
const idList = idsExport
.map(id => Number(id))
.filter(id => Number.isFinite(id) && id > 0);
if (idList.length > 0) {
queryWhere.id = { [Op.in]: idList };
}
}
// 主单号查询(支持单值/数组,与 list 保持一致)
const mainResolvedExport = await this.resolveMainWaybillOrderIds(val(where.mainWaybillCode), warehouseId);
if (mainResolvedExport.empty) {
if (typeof onProgress === 'function') {
await onProgress({ status: 'success', progress: 100, currentCount: 0, totalCount: 0, message: '导出完成', result: { list: [], url: '' } });
}
return { list: [], current_count: 0, total_count: 0, url: '' };
}
if (mainResolvedExport.orderIds.length > 0) {
// 单主单保持标量 order_id(向后兼容),多主单使用 Op.in
queryWhere.order_id = mainResolvedExport.orderIds.length === 1
? mainResolvedExport.orderIds[0]
: { [Op.in]: mainResolvedExport.orderIds };
}
// 运单号搜索:数组精确匹配(Op.in),字符串保持模糊匹配(Op.like),与 list 保持一致
const waybillCodeExport = val(where.waybillCode);
if (Array.isArray(waybillCodeExport)) {
const waybillCodeListExport = waybillCodeExport
.map(item => (item === undefined || item === null ? '' : String(item).trim()))
.filter(item => item !== '');
if (waybillCodeListExport.length > 0) {
queryWhere.waybill_code = { [Op.in]: waybillCodeListExport };
}
} else if (waybillCodeExport && String(waybillCodeExport).trim()) {
queryWhere.waybill_code = { [Op.like]: `%${String(waybillCodeExport).trim()}%` };
}
const orderIdExport = val(where.orderId);
if (orderIdExport !== undefined && orderIdExport !== null && String(orderIdExport).trim() !== '') {
queryWhere.order_id = Number(orderIdExport);
}
// TODO: 快照字段 delivery_order_code 未落库,暂跳过订单号筛选;快照列就绪后取消注释
const logisticsCodeExport = val(where.logisticsCode);
if (logisticsCodeExport && String(logisticsCodeExport).trim()) {
queryWhere.logistics_code = String(logisticsCodeExport).trim();
}
const logisticsInterfaceIdExport = val(where.logisticsInterfaceId);
if (logisticsInterfaceIdExport !== undefined && logisticsInterfaceIdExport !== null && String(logisticsInterfaceIdExport).trim() !== '') {
queryWhere.logistics_interface_id = Number(logisticsInterfaceIdExport);
}
const platformCodeExport = val(where.platformCode);
if (platformCodeExport && String(platformCodeExport).trim()) {
queryWhere.platform_code = String(platformCodeExport).trim();
}
const statusExport = val(where.status);
if (statusExport !== undefined && statusExport !== null && String(statusExport).trim() !== '') {
queryWhere.status = Number(statusExport);
}
const isBackExport = val(where.isBack);
if (isBackExport && String(isBackExport).trim()) {
queryWhere.is_back = String(isBackExport).trim();
}
const isInterceptExport = val(where.isIntercept);
if (isInterceptExport && String(isInterceptExport).trim()) {
queryWhere.is_intercept = String(isInterceptExport).trim();
}
const isGalaxyReceiveExport = val(where.isGalaxyReceive);
if (isGalaxyReceiveExport && String(isGalaxyReceiveExport).trim()) {
queryWhere.is_galaxy_receive = String(isGalaxyReceiveExport).trim();
}
const waybillTypeExport = val(where.waybillType);
if (waybillTypeExport && String(waybillTypeExport).trim()) {
const type = String(waybillTypeExport).trim();
if (type === 'main' || type === '1') {
queryWhere.business_key = 1;
} else if (type === 'child' || type === '2') {
queryWhere.business_key = { [Op.gt]: 1 };
}
}
// 货主ID等值
const storeIdExport = val(where.storeId);
if (storeIdExport !== undefined && storeIdExport !== null && String(storeIdExport).trim() !== '') {
queryWhere.store_id = Number(storeIdExport);
}
const packageMaterialIdExport = val(where.packageMaterialId);
if (packageMaterialIdExport !== undefined && packageMaterialIdExport !== null && String(packageMaterialIdExport).trim() !== '') {
queryWhere.package_material_id = Number(packageMaterialIdExport);
}
const hasWeighingWeightExport = val(where.hasWeighingWeight);
if (hasWeighingWeightExport !== undefined && hasWeighingWeightExport !== null && String(hasWeighingWeightExport).trim() !== '') {
const hasWeight = String(hasWeighingWeightExport).trim();
if (hasWeight === 'true') {
queryWhere.weighing_weight = { [Op.gt]: 0 };
} else if (hasWeight === 'false') {
queryWhere.weighing_weight = { [Op.eq]: 0 };
}
}
const keywordExport = val(where.keyword);
if (keywordExport && String(keywordExport).trim()) {
queryWhere.waybill_code = { [Op.like]: `%${String(keywordExport).trim()}%` };
}
// 创建时间范围:createdAt 支持 {operator:'between', value:[start,end]}(兼容 createAt 别名)
const createdAtRangeExport = val(where.createdAt) ?? val(where.createAt);
if (Array.isArray(createdAtRangeExport)) {
const [ unifiedCreateAtStartExport, unifiedCreateAtEndExport ] = createdAtRangeExport;
if (unifiedCreateAtStartExport && String(unifiedCreateAtStartExport).trim()) {
queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.gte]: new Date(unifiedCreateAtStartExport) };
}
if (unifiedCreateAtEndExport && String(unifiedCreateAtEndExport).trim()) {
queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.lte]: new Date(unifiedCreateAtEndExport) };
}
}
// 兼容旧写法:createdAtStart / createdAtEnd
const createdAtStartExport = val(where.createdAtStart);
if (createdAtStartExport && String(createdAtStartExport).trim()) {
const startDate = this.normalizeDate(String(createdAtStartExport).trim(), false);
if (startDate) {
queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.gte]: startDate };
}
}
const createdAtEndExport = val(where.createdAtEnd);
if (createdAtEndExport && String(createdAtEndExport).trim()) {
const endDate = this.normalizeDate(String(createdAtEndExport).trim(), true);
if (endDate) {
queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.lte]: endDate };
}
}
// 先统计总数
if (typeof onProgress === 'function') {
await onProgress({ status: 'running', progress: 10, currentCount: 0, totalCount: 0, message: '正在统计数据…' });
}
const totalCount = await ctx.model.OrderExpress.count({ where: queryWhere });
if (totalCount === 0) {
if (typeof onProgress === 'function') {
await onProgress({ status: 'success', progress: 100, currentCount: 0, totalCount: 0, message: '导出完成', result: { list: [], url: '' } });
}
return { list: [], current_count: 0, total_count: 0, url: '' };
}
if (typeof onProgress === 'function') {
await onProgress({ status: 'running', progress: 15, currentCount: 0, totalCount, message: `共 ${totalCount} 条,正在导出…` });
}
// 分批查询(避免大数据量内存溢出)
const EXPORT_PAGE_SIZE = 500;
const allRows = [];
const totalPages = Math.ceil(totalCount / EXPORT_PAGE_SIZE);
for (let page = 0; page < totalPages; page++) {
const pageRows = await ctx.model.OrderExpress.findAll({
where: queryWhere,
attributes: [
'id', 'waybill_code', 'order_id', 'business_key', 'status',
'warehouse_id', 'store_id',
'delivery_order_code', 'source_order_codes',
'logistics_code', 'logistics_name',
'logistics_interface_id', 'logistics_interface_name',
'platform_code',
'is_back', 'is_intercept', 'is_galaxy_receive',
'weighing_weight',
'package_material_id', 'package_material_name_snapshot',
'create_at',
],
order: [[ sortField, sortOrder ]],
limit: EXPORT_PAGE_SIZE,
offset: page * EXPORT_PAGE_SIZE,
raw: true,
});
allRows.push(...pageRows);
// 进度回调(15% ~ 90%)
if (typeof onProgress === 'function') {
const progress = 15 + Math.round(75 * (page + 1) / totalPages);
await onProgress({
status: 'running',
progress,
currentCount: allRows.length,
totalCount,
message: `已导出 ${allRows.length} / ${totalCount} 条`,
});
}
}
// 提取所有唯一的 order_id,SELF JOIN 主单号
const orderIds = [ ...new Set(allRows.map(r => r.order_id).filter(Boolean)) ];
const mainWaybillMap = new Map();
if (orderIds.length > 0) {
const mainRecords = await ctx.model.OrderExpress.findAll({
where: {
order_id: { [Op.in]: orderIds },
business_key: 1,
},
attributes: [ 'order_id', 'waybill_code' ],
raw: true,
});
for (const rec of mainRecords) {
if (!mainWaybillMap.has(rec.order_id)) {
mainWaybillMap.set(rec.order_id, rec.waybill_code);
}
}
}
// 预定义全部导出字段映射
const allFieldMap = {
id: r => r.id,
waybill_code: r => r.waybill_code || '',
main_waybill_code: r => mainWaybillMap.get(r.order_id) || r.waybill_code || '',
waybill_type: r => (Number(r.business_key) === 1 ? '主单号' : '子单号'),
order_id: r => r.order_id,
order_no: r => r.delivery_order_code || r.source_order_codes || '',
source_order_codes: r => r.source_order_codes || '',
warehouse_id: r => r.warehouse_id,
warehouse_name: () => '',
store_id: r => r.store_id || 0,
store_name: () => '',
business_key: r => r.business_key,
status: r => r.status,
status_text: r => (r.status === 1 ? '已分配' : '未分配'),
logistics_code: r => r.logistics_code || '',
logistics_name: r => r.logistics_name || '',
logistics_interface_id: r => r.logistics_interface_id || 0,
logistics_interface_name: r => r.logistics_interface_name || '',
platform_code: r => r.platform_code || '',
is_back: r => r.is_back || 'N',
is_intercept: r => r.is_intercept || 'N',
is_galaxy_receive: r => r.is_galaxy_receive || 'N',
weighing_weight: r => r.weighing_weight || 0,
weighing_weight_display: r => (r.weighing_weight > 0 ? `${(r.weighing_weight / 1000).toFixed(2)} kg` : '0 kg'),
package_material_id: r => r.package_material_id || 0,
package_material_name: r => r.package_material_name_snapshot || '',
create_at: r => (r.create_at ? this.app.formatDate(r.create_at) : null),
};
// 确定导出字段集
const fields = Array.isArray(exportFields) && exportFields.length > 0
? exportFields.filter(f => allFieldMap[f])
: Object.keys(allFieldMap);
const list = allRows.map(row => {
const item = {};
for (const field of fields) {
item[field] = allFieldMap[field](row);
}
return item;
});
if (typeof onProgress === 'function') {
await onProgress({
status: 'running',
progress: 95,
currentCount: allRows.length,
totalCount,
message: '正在生成导出文件…',
});
}
// 生成 Excel 文件并上传
const result = await this.buildWaybillExportFile({
list,
fields,
warehouseId,
totalCount: allRows.length,
});
if (typeof onProgress === 'function') {
await onProgress({
status: 'success',
progress: 100,
currentCount: allRows.length,
totalCount,
message: '导出完成',
result,
});
}
return result;
}
/**
* 生成运单导出 Excel 文件并上传,返回下载链接。
* @param {Object} options 导出选项。
* @param {Array} options.list 导出数据列表。
* @param {string[]} options.fields 导出字段列表。
* @param {number} options.warehouseId 仓库ID。
* @param {number} options.totalCount 总条数。
* @return {Promise<Object>} { current_count, total_count, url }。
*/
async buildWaybillExportFile({ list, fields, warehouseId, totalCount } = {}) {
const { ctx } = this;
// 列名中文映射
const COLUMN_LABELS = {
id: 'ID',
waybill_code: '运单号',
main_waybill_code: '主单号',
waybill_type: '运单类型',
order_id: '订单ID',
order_no: '订单号',
source_order_codes: '原始订单号',
warehouse_id: '仓库ID',
warehouse_name: '仓库名称',
store_id: '货主ID',
store_name: '货主名称',
business_key: '拆单序号',
status: '状态',
status_text: '状态',
logistics_code: '物流编码',
logistics_name: '物流名称',
logistics_interface_id: '物流接口ID',
logistics_interface_name: '物流接口名称',
platform_code: '平台编码',
is_back: '是否退回',
is_intercept: '是否拦截',
is_galaxy_receive: '是否揽收',
weighing_weight: '称重重量(g)',
weighing_weight_display: '称重重量',
package_material_id: '包材ID',
package_material_name: '包材名称',
create_at: '创建时间',
};
// 生成 Excel
const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet('运单导出');
// 写表头
const headerRow = worksheet.addRow(fields.map(f => COLUMN_LABELS[f] || f));
headerRow.font = { bold: true };
headerRow.alignment = { horizontal: 'center' };
// 写数据
for (const row of list) {
worksheet.addRow(fields.map(f => (row[f] !== undefined && row[f] !== null ? row[f] : '')));
}
// 保存到临时文件
const now = new Date();
const dateStr = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`;
const filename = `运单导出_${dateStr}.xlsx`;
const tmpDir = os.tmpdir();
const filePath = path.join(tmpDir, `waybill_export_${Date.now()}_${Math.random().toString(36).slice(2, 8)}.xlsx`);
await workbook.xlsx.writeFile(filePath);
// 上传文件
const uploadService = ctx?.service?.systems?.upload;
let url = '';
let fileKey = '';
if (uploadService && typeof uploadService.uploadFile === 'function') {
try {
const stat = await fsp.stat(filePath);
const safeWarehouseId = String(warehouseId || 'unknown');
const randomToken = Math.random().toString(36).slice(2, 8);
const uploadKey = `exports/waybill/${safeWarehouseId}/${Date.now()}_${randomToken}.xlsx`;
const uploadStream = fs.createReadStream(filePath);
uploadStream.filename = filename;
uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
uploadStream.fileSize = stat.size;
const uploadResult = await uploadService.uploadFile(uploadStream, {
key: uploadKey,
category: 'document',
mimetype: 'xls,xlsx,csv',
});
url = uploadResult.url || uploadResult.cdnUrl || uploadResult.cosUrl || '';
fileKey = uploadResult.fileName || '';
// 记录上传文件
if (typeof uploadService.uploadSuccessNotify === 'function') {
await uploadService.uploadSuccessNotify({
url: uploadResult.fileName,
fileKey: uploadResult.fileName,
fileName: filename,
fileType: 'document',
mimeType: uploadStream.mimeType,
fileSize: stat.size,
category: 'document',
businessType: 'waybillExport',
businessId: `${warehouseId}`,
uploaderType: ctx?.user?.role || 'system_api',
uploaderDept: ctx?.user?.department || '',
});
}
} catch (uploadError) {
ctx.logger.error('[WaybillService.buildWaybillExportFile] 文件上传失败', {
error: uploadError.message,
filename,
});
}
}
// 清理临时文件
try {
await fsp.unlink(filePath);
} catch (_e) {
// 忽略清理错误
}
return {
current_count: totalCount,
total_count: totalCount,
url,
fileKey,
filename,
};
}
/**
* 批量查询运单揽收状态(出站回调 waybill.getreceive)。
*
* 业务报文:`{ waybill_codes: [...] }`,经 `openapi.callback.sendByAppKey` 统一
* 包装为 `{ request: { waybill_codes: [...] } }` 发送(与其它出站回调一致)。
* 运单号会按 `buildWaybillQueryCodeMap` 规则补寄件电话后四位(`运单号|后四位`)。
* 外部返回 `[{ 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 = [];
const queryCodeMap = await this.buildWaybillQueryCodeMap({
warehouseId: normalizedWarehouseId,
waybillCodes: codes,
});
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.map(code => queryCodeMap.get(code) || code) },
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 = this.stripWaybillCodeSuffix(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)) ];
}
/**
* 去掉运单号上的 `|电话后四位` 查询后缀,还原成纯运单号。
* @param {string} code 运单号(可能带后缀)。
* @return {string} 纯运单号。
*/
stripWaybillCodeSuffix(code) {
const text = String(code === undefined || code === null ? '' : code).trim();
const index = text.indexOf('|');
return index === -1 ? text : text.slice(0, index).trim();
}
/**
* 取寄件电话的后四位(非数字字符先剔除)。
* @param {string} tel 寄件电话。
* @return {string} 后四位数字,位数不足时返回空字符串。
*/
extractSenderTelLast4(tel) {
const digits = String(tel === undefined || tel === null ? '' : tel).replace(/\D/g, '');
return digits.length >= 4 ? digits.slice(-4) : '';
}
/**
* 构建出站查询的运单号映射(原始运单号 → 出站查询值)。
*
* 外部快递接口(中通轨迹/揽收查询)要求 `运单号|收寄件人手机号后四位` 才能查询:
* 按 warehouse_id 命中 `wms_order_express` 后,用 `logistics_interface_id` 取
* `wms_express_interface.sender_tel` 的后四位拼接。未命中运单、未关联物流接口
* 或接口未配置电话时,保持原始运单号发送。
*
* @param {Object} options 参数。
* @param {number} options.warehouseId 仓库 ID。
* @param {Array<string>} options.waybillCodes 原始运单号列表。
* @return {Promise<Map<string, string>>} 原始运单号 → 出站查询运单号。
*/
async buildWaybillQueryCodeMap({ warehouseId, waybillCodes = [] } = {}) {
const { ctx } = this;
const codes = this.normalizeWaybillCodes(waybillCodes);
const map = new Map(codes.map(code => [ code, code ]));
if (codes.length === 0) return map;
const OrderExpress = ctx.model && ctx.model.OrderExpress;
const ExpressInterface = ctx.model && ctx.model.ExpressInterface;
if (!OrderExpress || !ExpressInterface) return map;
const { Op } = this.app.Sequelize;
const normalizedWarehouseId = Number(warehouseId) || 0;
const expressWhere = { waybill_code: { [Op.in]: codes } };
if (normalizedWarehouseId) {
expressWhere.warehouse_id = normalizedWarehouseId;
}
let expressRows = [];
try {
expressRows = await OrderExpress.findAll({
attributes: [ 'waybill_code', 'logistics_interface_id' ],
where: expressWhere,
raw: true,
});
} catch (e) {
ctx.logger.warn('[WaybillService.buildWaybillQueryCodeMap] 查询运单快递信息失败', {
warehouseId: normalizedWarehouseId,
error: e && e.message ? e.message : `${e}`,
});
return map;
}
const interfaceIdByCode = new Map();
for (const row of expressRows || []) {
const code = this.stripWaybillCodeSuffix(String(row && row.waybill_code || '').trim());
const interfaceId = Number(row && row.logistics_interface_id) || 0;
if (!code || !interfaceId || interfaceIdByCode.has(code)) continue;
interfaceIdByCode.set(code, interfaceId);
}
if (interfaceIdByCode.size === 0) return map;
let interfaceRows = [];
try {
interfaceRows = await ExpressInterface.findAll({
attributes: [ 'id', 'sender_tel' ],
where: { id: { [Op.in]: [ ...new Set(interfaceIdByCode.values()) ] } },
raw: true,
});
} catch (e) {
ctx.logger.warn('[WaybillService.buildWaybillQueryCodeMap] 查询快递接口配置失败', {
warehouseId: normalizedWarehouseId,
error: e && e.message ? e.message : `${e}`,
});
return map;
}
const telById = new Map(
(interfaceRows || []).map(row => [ Number(row && row.id) || 0, row && row.sender_tel ])
);
for (const [ code, interfaceId ] of interfaceIdByCode.entries()) {
const last4 = this.extractSenderTelLast4(telById.get(interfaceId));
if (last4) {
map.set(code, `${code}|${last4}`);
}
}
return map;
}
/**
* 解析揽收查询的目标应用:取仓库下勾选了 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;
}
/**
* 实时查询单个运单的物流轨迹(出站回调 waybill.getTrace)。
*
* 纯回源:不落库、不读本地表;请求与 `waybill.getreceive` 一致
* (`{ request: { waybill_codes: [waybillCode] } }`,运单号同样会补寄件电话后四位
* `运单号|后四位`),响应兼容
* `[{ waybillNo, trace }]` / `{ waybillNo, trace }` / `{ code, data: [...] }`。
*
* @param {Object} options 查询参数。
* @param {number} options.warehouseId 仓库 ID(仅用于日志与揽收联动)。
* @param {string} options.waybillCode 运单号。
* @param {string} [options.appKey] 指定目标应用 AppKey,不传则按仓库订阅关系解析。
* @return {Promise<{success: boolean, traces: Array<Object>, app_key: string, empty: boolean, reason?: string, error?: string}>} 轨迹列表。
*/
async fetchTracesByWaybill({ warehouseId, waybillCode, appKey = '' } = {}) {
const { ctx } = this;
const normalizedWarehouseId = Number(warehouseId) || 0;
const normalizedCode = String(waybillCode || '').trim();
if (!normalizedCode) {
return { success: false, traces: [], app_key: '', empty: false, reason: '运单号不能为空' };
}
if (!normalizedWarehouseId) {
return { success: false, traces: [], app_key: '', empty: false, reason: '缺少仓库ID' };
}
const targetAppKey = String(appKey || '').trim()
|| await this.resolveTraceQueryAppKey(normalizedWarehouseId);
if (!targetAppKey) {
return {
success: false,
traces: [],
app_key: '',
empty: false,
reason: '无应用承接该回调 method(callback_functions 未勾选或应用未启用)',
};
}
const callbackService = ctx.service.openapi && ctx.service.openapi.callback;
if (!callbackService || typeof callbackService.sendByAppKey !== 'function') {
return { success: false, traces: [], app_key: targetAppKey, empty: false, reason: 'OpenAPI 回调服务不可用' };
}
const queryCodeMap = await this.buildWaybillQueryCodeMap({
warehouseId: normalizedWarehouseId,
waybillCodes: [ normalizedCode ],
});
const result = await callbackService.sendByAppKey({
appKey: targetAppKey,
event: WAYBILL_TRACE_EVENT,
request: { waybill_codes: [ queryCodeMap.get(normalizedCode) || normalizedCode ] },
signMode: WAYBILL_TRACE_SIGN_MODE,
});
if (!result || result.success !== true) {
const error = String(result && result.error || '未知错误');
ctx.logger.warn('[WaybillService.fetchTracesByWaybill] 轨迹查询回调失败', {
warehouseId: normalizedWarehouseId,
appKey: targetAppKey,
waybillCode: normalizedCode,
error,
});
return { success: false, traces: [], app_key: targetAppKey, empty: false, error };
}
const businessError = this.extractReceiveError(result.response);
if (businessError) {
ctx.logger.warn('[WaybillService.fetchTracesByWaybill] 外部接口返回业务失败', {
warehouseId: normalizedWarehouseId,
appKey: targetAppKey,
waybillCode: normalizedCode,
error: businessError,
});
return { success: false, traces: [], app_key: targetAppKey, empty: false, error: businessError };
}
const rows = this.extractTraceRows(result.response);
const matched = rows.find(row => {
const code = this.stripWaybillCodeSuffix(
String(row && (row.waybillNo || row.waybill_no || row.waybillCode) || '').trim()
);
return code === normalizedCode;
}) || rows[0] || null;
const traces = this.normalizeTraceList(matched)
.map(trace => this.normalizeTraceItem(trace))
.sort((a, b) => {
const timeA = a.op_time_raw ? a.op_time_raw.getTime() : 0;
const timeB = b.op_time_raw ? b.op_time_raw.getTime() : 0;
return timeB - timeA;
})
.map(item => {
const output = { ...item };
delete output.op_time_raw;
return output;
});
return {
success: true,
traces,
app_key: targetAppKey,
empty: traces.length === 0,
};
}
/**
* 归一单条轨迹字段(外部字段名 → 接口输出字段名)。
* @param {Object} trace 外部轨迹对象。
* @return {Object} 归一后的轨迹(含内部排序用 op_time_raw)。
*/
normalizeTraceItem(trace = {}) {
const opTime = this.parseTraceTime(trace.opTime || trace.op_time);
return {
op_time: opTime ? this.formatTimestamp(opTime) : '',
op_time_raw: opTime,
out_biz_code: String(trace.outBizCode || trace.out_biz_code || '').trim(),
memo: String(trace.memo || '').trim(),
op_org_city_name: String(trace.opOrgCityName || trace.op_org_city_name || '').trim(),
weight: this.parseTraceWeight(trace.weight),
scan_type: String(trace.scanType || trace.scan_type || '').trim(),
raw_data: trace,
};
}
/**
* 把时间格式化为 'YYYY-MM-DD HH:mm:ss'(本地时间)。
* @param {Date} date 时间对象。
* @return {string} 格式化后的时间字符串。
*/
formatTimestamp(date) {
const pad = num => String(num).padStart(2, '0');
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} `
+ `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
}
/**
* 解析轨迹查询的目标应用:取仓库下勾选了 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;
if (response.data && typeof response.data === 'object') return [ response.data ];
if (response.waybillNo || response.waybill_no || response.trace || response.traces) return [ response ];
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;
}
/**
* 解析轨迹重量:外部可能返回数字或字符串(如 "0.99"),统一转保留 3 位小数的数字。
* @param {*} value 外部返回值。
* @return {number} 重量,非法值返回 0。
*/
parseTraceWeight(value) {
if (value === undefined || value === null || value === '') return 0;
const num = Number(String(value).trim().replace(/,/g, ''));
if (!Number.isFinite(num)) return 0;
return Math.round(num * 1000) / 1000;
}
/**
* 解析轨迹操作时间:支持 '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;
}
/**
* 按轨迹把运单标记为已揽收(is_galaxy_receive='Y')。
* 仅把非 Y(含 NULL)的行升级为 Y,已为 Y 的不重复更新;按仓库隔离。
*
* @param {Object} options 参数。
* @param {number} options.warehouseId 仓库 ID。
* @param {Array<string>} options.waybillCodes 有轨迹的运单号。
* @return {Promise<number>} 实际更新行数。
*/
async markReceiveByTraces({ warehouseId, waybillCodes = [] } = {}) {
const { ctx } = this;
const { Op } = this.app.Sequelize;
const codes = [ ...new Set((waybillCodes || []).map(code => String(code || '').trim()).filter(Boolean)) ];
if (codes.length === 0) return 0;
try {
const [ affected ] = await ctx.model.OrderExpress.update(
{ is_galaxy_receive: 'Y' },
{
where: {
waybill_code: { [Op.in]: codes },
warehouse_id: Number(warehouseId) || 0,
[Op.or]: [
{ is_galaxy_receive: { [Op.ne]: 'Y' } },
{ is_galaxy_receive: { [Op.is]: null } },
],
},
}
);
const count = Number(affected) || 0;
if (count > 0) {
ctx.logger.info('[WaybillService.markReceiveByTraces] 轨迹命中,揽收状态已置 Y', {
warehouseId,
waybills: codes.length,
updated: count,
});
}
return count;
} catch (error) {
// 揽收状态是轨迹查询的附带收益,失败只记日志,不影响轨迹返回
ctx.logger.warn(`[WaybillService.markReceiveByTraces] 更新揽收状态失败: ${error.message}`);
return 0;
}
}
}
module.exports = WaybillService;