'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} 包含 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), }, ]; // 遍历多表查询订单的 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 / createdAtStart / createdAtEnd。 * @param {Object} [options.pagination] 分页参数 { page, pageSize },默认 page=1, pageSize=20。 * @param {Object} [options.sort] 排序参数 { field, order },默认 create_at desc。 * @return {Promise} 运单列表与分页信息 { list, pagination }。 */ async list({ where = {}, 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 queryWhere = { warehouse_id: warehouseId }; // 主单号查询:先通过主单号定位 order_id,再查该 order 下所有运单 if (where.mainWaybillCode && String(where.mainWaybillCode).trim()) { const mainCode = String(where.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 }, }; } } // 运单号模糊搜索 if (where.waybillCode && String(where.waybillCode).trim()) { queryWhere.waybill_code = { [Op.like]: `%${String(where.waybillCode).trim()}%` }; } // 订单ID等值 if (where.orderId !== undefined && where.orderId !== null && String(where.orderId).trim() !== '') { queryWhere.order_id = Number(where.orderId); } // 订单号模糊搜索 // TODO: 快照字段 delivery_order_code 未落库,暂跳过订单号筛选;快照列就绪后取消注释 // if (where.orderNo && String(where.orderNo).trim()) { // queryWhere.delivery_order_code = { [Op.like]: `%${String(where.orderNo).trim()}%` }; // } // 物流公司编码等值 if (where.logisticsCode && String(where.logisticsCode).trim()) { queryWhere.logistics_code = String(where.logisticsCode).trim(); } // 物流接口ID等值 if (where.logisticsInterfaceId !== undefined && where.logisticsInterfaceId !== null && String(where.logisticsInterfaceId).trim() !== '') { queryWhere.logistics_interface_id = Number(where.logisticsInterfaceId); } // 平台编码等值 if (where.platformCode && String(where.platformCode).trim()) { queryWhere.platform_code = String(where.platformCode).trim(); } // 运单状态等值 if (where.status !== undefined && where.status !== null && String(where.status).trim() !== '') { queryWhere.status = Number(where.status); } // 是否退回 if (where.isBack && String(where.isBack).trim()) { queryWhere.is_back = String(where.isBack).trim(); } // 是否拦截 if (where.isIntercept && String(where.isIntercept).trim()) { queryWhere.is_intercept = String(where.isIntercept).trim(); } // 是否揽收 if (where.isGalaxyReceive && String(where.isGalaxyReceive).trim()) { queryWhere.is_galaxy_receive = String(where.isGalaxyReceive).trim(); } // 运单类型:主单号 / 子单号 if (where.waybillType && String(where.waybillType).trim()) { const type = String(where.waybillType).trim(); if (type === 'main' || type === '1') { queryWhere.business_key = 1; } else if (type === 'child' || type === '2') { queryWhere.business_key = { [Op.gt]: 1 }; } } // 货主ID等值 if (where.storeId !== undefined && where.storeId !== null && String(where.storeId).trim() !== '') { queryWhere.store_id = Number(where.storeId); } // 包材ID等值 if (where.packageMaterialId !== undefined && where.packageMaterialId !== null && String(where.packageMaterialId).trim() !== '') { queryWhere.package_material_id = Number(where.packageMaterialId); } // 是否已称重 if (where.hasWeighingWeight !== undefined && where.hasWeighingWeight !== null && String(where.hasWeighingWeight).trim() !== '') { const hasWeight = String(where.hasWeighingWeight).trim(); if (hasWeight === 'true') { queryWhere.weighing_weight = { [Op.gt]: 0 }; } else if (hasWeight === 'false') { queryWhere.weighing_weight = { [Op.eq]: 0 }; } } // 关键词模糊搜索 if (where.keyword && String(where.keyword).trim()) { queryWhere.waybill_code = { [Op.like]: `%${String(where.keyword).trim()}%` }; } // 创建时间范围 if (where.createdAtStart && String(where.createdAtStart).trim()) { const startDate = this.normalizeDate(String(where.createdAtStart).trim(), false); if (startDate) { queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.gte]: startDate }; } } if (where.createdAtEnd && String(where.createdAtEnd).trim()) { const endDate = this.normalizeDate(String(where.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', '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, }, 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, // TODO: 快照列未落库,暂时填空;快照就绪后替换为 row.delivery_order_code order_no: '', warehouse_id: row.warehouse_id, // TODO: 快照列未落库,暂时填空;快照就绪后替换为 row.warehouse_name_snapshot warehouse_name: '', store_id: row.store_id || 0, // TODO: 快照列未落库,暂时填空;快照就绪后替换为 row.store_name_snapshot 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} 运单详情。 * @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)。 * @param {Object} [options.sort={}] 排序参数(同 list)。 * @param {string[]} [options.exportFields] 需要导出的字段列表,不传则导出全部字段。 * @param {Function} [options.onProgress] 进度回调,接收 `{ status, progress, currentCount, totalCount, message, result }`。 * @return {Promise} 导出结果 { list, current_count, total_count, url }。 */ async export({ where = {}, sort = {}, exportFields, onProgress } = {}) { const { ctx, app } = this; const { Op } = app.Sequelize; // 仓库隔离 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 }; // 主单号查询 if (where.mainWaybillCode && String(where.mainWaybillCode).trim()) { const mainCode = String(where.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 { 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 (where.waybillCode && String(where.waybillCode).trim()) { queryWhere.waybill_code = { [Op.like]: `%${String(where.waybillCode).trim()}%` }; } if (where.orderId !== undefined && where.orderId !== null && String(where.orderId).trim() !== '') { queryWhere.order_id = Number(where.orderId); } // TODO: 快照字段 delivery_order_code 未落库,暂跳过订单号筛选;快照列就绪后取消注释 if (where.logisticsCode && String(where.logisticsCode).trim()) { queryWhere.logistics_code = String(where.logisticsCode).trim(); } if (where.logisticsInterfaceId !== undefined && where.logisticsInterfaceId !== null && String(where.logisticsInterfaceId).trim() !== '') { queryWhere.logistics_interface_id = Number(where.logisticsInterfaceId); } if (where.platformCode && String(where.platformCode).trim()) { queryWhere.platform_code = String(where.platformCode).trim(); } if (where.status !== undefined && where.status !== null && String(where.status).trim() !== '') { queryWhere.status = Number(where.status); } if (where.isBack && String(where.isBack).trim()) { queryWhere.is_back = String(where.isBack).trim(); } if (where.isIntercept && String(where.isIntercept).trim()) { queryWhere.is_intercept = String(where.isIntercept).trim(); } if (where.isGalaxyReceive && String(where.isGalaxyReceive).trim()) { queryWhere.is_galaxy_receive = String(where.isGalaxyReceive).trim(); } if (where.waybillType && String(where.waybillType).trim()) { const type = String(where.waybillType).trim(); if (type === 'main' || type === '1') { queryWhere.business_key = 1; } else if (type === 'child' || type === '2') { queryWhere.business_key = { [Op.gt]: 1 }; } } // 货主ID等值 if (where.storeId !== undefined && where.storeId !== null && String(where.storeId).trim() !== '') { queryWhere.store_id = Number(where.storeId); } if (where.packageMaterialId !== undefined && where.packageMaterialId !== null && String(where.packageMaterialId).trim() !== '') { queryWhere.package_material_id = Number(where.packageMaterialId); } if (where.hasWeighingWeight !== undefined && where.hasWeighingWeight !== null && String(where.hasWeighingWeight).trim() !== '') { const hasWeight = String(where.hasWeighingWeight).trim(); if (hasWeight === 'true') { queryWhere.weighing_weight = { [Op.gt]: 0 }; } else if (hasWeight === 'false') { queryWhere.weighing_weight = { [Op.eq]: 0 }; } } if (where.keyword && String(where.keyword).trim()) { queryWhere.waybill_code = { [Op.like]: `%${String(where.keyword).trim()}%` }; } if (where.createdAtStart && String(where.createdAtStart).trim()) { const startDate = this.normalizeDate(String(where.createdAtStart).trim(), false); if (startDate) { queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.gte]: startDate }; } } if (where.createdAtEnd && String(where.createdAtEnd).trim()) { const endDate = this.normalizeDate(String(where.createdAtEnd).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, // TODO: 快照列未落库,暂时只查已有字段;快照就绪后补充 attributes: [ 'id', 'waybill_code', 'order_id', 'business_key', 'status', 'warehouse_id', 'store_id', '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, // TODO: 快照列未落库,暂时填空;快照就绪后替换 order_no: () => '', 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} { 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: '订单号', 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;