liufumingren 0fe43c87b1 fix: 跨仓 order_express 校验与 recheckOrder 原生 SQL 表名修复
- 跨仓 bug 修复:order_express 读取强制校验订单所属仓库 id(order.detail 与全部订单列表等 17 处)

- recheckOrder 原生 SQL 表名补 wms_ 前缀,修复 queryRecheckOrderSingleList 恒 500

- 同步 methods 文档与变更记录
2026-09-10 03:46:41 +08:00

1156 lines
44 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');
/**
* 业务逻辑层: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,
},
],
};
}
/**
* 运单列表查询(仓库侧)。
* 按仓库维度查询运单号列表,支持分页、多条件筛选、排序。
* 核心查询仅使用 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;
// 标准化 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 warehouseId = Number(ctx.user && ctx.user.store_id);
if (!warehouseId) {
this.throwError('用户未绑定仓库,无法查询运单');
}
// 分页参数
const page = Math.max(Number(pagination.page) || 1, 1);
const pageSize = Math.min(Math.max(Number(pagination.pageSize) || 20, 1), 500);
// 排序参数
const allowedSortFields = [ 'create_at', 'weighing_weight', 'id' ];
const sortField = allowedSortFields.includes(sort.field) ? sort.field : 'create_at';
const sortOrder = sort.order === 'asc' ? 'ASC' : 'DESC';
// 构建查询条件
const queryWhere = { warehouse_id: warehouseId };
// 主单号查询:先通过主单号定位 order_id,再查该 order 下所有运单
const mainWaybillCode = val(where.mainWaybillCode);
if (mainWaybillCode && String(mainWaybillCode).trim()) {
const mainCode = String(mainWaybillCode).trim();
const mainRecord = await ctx.model.OrderExpress.findOne({
where: {
waybill_code: mainCode,
business_key: 1,
warehouse_id: warehouseId,
},
attributes: [ 'order_id' ],
raw: true,
});
if (mainRecord) {
queryWhere.order_id = mainRecord.order_id;
} else {
// 主单号不存在,直接返回空结果
return {
list: [],
pagination: { page, pageSize, total: 0, totalPages: 0 },
};
}
}
// 运单号搜索:数组精确匹配(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 };
}
}
// 核心查询:仅查 wms_order_express 单表
// TODO: warehouse_name_snapshot / store_id_snapshot / store_name_snapshot / delivery_order_code
// 快照列未落库,暂时只查已有字段;快照列就绪后替换为快照直读
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 };
}
}
// 主单号查询
const mainWaybillCodeExport = val(where.mainWaybillCode);
if (mainWaybillCodeExport && String(mainWaybillCodeExport).trim()) {
const mainCode = String(mainWaybillCodeExport).trim();
const mainRecord = await ctx.model.OrderExpress.findOne({
where: {
waybill_code: mainCode,
business_key: 1,
warehouse_id: warehouseId,
},
attributes: [ 'order_id' ],
raw: true,
});
if (mainRecord) {
queryWhere.order_id = mainRecord.order_id;
} else {
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: '' };
}
}
// 运单号搜索:数组精确匹配(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,
};
}
}
module.exports = WaybillService;