liufumingren e3eff20aaa 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>
2026-11-11 04:22:30 +08:00

1536 lines
59 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';
/**
* 业务逻辑层: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: [...] } }` 发送(与其它出站回调一致)。
* 外部返回 `[{ 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;