'use strict'; const crypto = require('node:crypto'); const fs = require('node:fs'); const fsp = require('node:fs/promises'); const os = require('node:os'); const path = require('node:path'); const ExcelJS = require('exceljs'); const OrderBaseService = require('../systemMethods/order/base'); const DEFAULT_EXPORT_PAGE_SIZE = 200; const ORDER_EXPORT_WORKSHEET_NAME = '订单导出'; const ORDER_EXPORT_ALLOWED_TABLE_TYPES = new Set([ 'current', 'history', 'dispatch', 'outsourced' ]); const ORDER_EXPORT_MODULE_MAP = Object.freeze({ order: 'order', revieworder: 'reviewOrder', pendingorder: 'pendingOrder', outboundorder: 'outboundOrder', expectionorder: 'expectionOrder', archiveorder: 'archiveOrder', entrustorder: 'entrustOrder', deliveryorder: 'deliveryOrder', deliveryexpectionorder: 'deliveryExpectionOrder', }); const ORDER_EXPORT_COLUMNS = Object.freeze([ { header: '系统订单号', key: 'id', width: 12 }, { header: '外部订单号', key: 'delivery_order_code', width: 24 }, { header: '平台单号', key: 'external_order_code', width: 24 }, { header: '订单状态', key: 'status', width: 16 }, { header: '抓取波次号', key: 'wave_no', width: 18 }, { header: '货主', key: 'store_id', width: 20 }, { header: '平台', key: 'sys_platform_name', width: 16 }, { header: '店铺昵称', key: 'shop_nick', width: 20 }, { header: '收件人', key: 'receiver_name', width: 16 }, { header: '收件人电话', key: 'receiver_mobile', width: 18 }, { header: '省', key: 'receiver_province', width: 10 }, { header: '市', key: 'receiver_city', width: 10 }, { header: '区', key: 'receiver_district', width: 10 }, { header: '镇', key: 'receiver_town', width: 10 }, { header: '详细地址', key: 'receiver_detail', width: 30 }, { header: '商品明细', key: 'items_detail', width: 50 }, { header: '物流公司', key: 'logistics_name', width: 18 }, { header: '运单号', key: 'waybill_code', width: 24 }, { header: '业务类型', key: 'business_type', width: 12 }, { header: '运单接口', key: 'logistics_interface_name', width: 20 }, { header: '包材ID', key: 'package_material_id', width: 14 }, { header: '包材编码', key: 'package_material_code', width: 20 }, { header: '包材名称', key: 'package_material_name', width: 20 }, { header: '分配时间', key: 'waybill_allocated_at', width: 20 }, { header: '商品种数', key: 'items_count', width: 12 }, { header: '商品件数', key: 'items_total', width: 12 }, { header: '商品重量', key: 'items_weight', width: 12 }, { header: '称重重量(g)', key: 'weighing_weight', width: 14 }, { header: '订单金额', key: 'total_amount', width: 14 }, { header: '实收金额', key: 'got_amount', width: 14 }, { header: '创建时间', key: 'create_at', width: 20 }, { header: '支付时间', key: 'pay_time', width: 20 }, { header: '发货时间', key: 'delivery_time', width: 20 }, { header: '出库状态', key: 'outbound_status', width: 14 }, { header: '复核状态', key: 'inspection_status', width: 14 }, { header: '复核完成状态', key: 'recheck_status', width: 16 }, { header: '配货状态', key: 'post_status', width: 14 }, { header: '打包状态', key: 'pack_status', width: 14 }, { header: '备注', key: 'remark', width: 30 }, { header: '买家留言', key: 'buyer_message', width: 30 }, { header: '卖家留言', key: 'seller_message', width: 30 }, { header: '归档时间', key: 'archive_time', width: 20 }, ]); /** 商品明细展开列配置(item 模式) */ const ORDER_EXPORT_ITEM_COLUMNS = Object.freeze([ { header: '订单ID', key: 'id', width: 12 }, { header: '订单号', key: 'delivery_order_code', width: 24 }, { header: '外部单号', key: 'external_order_code', width: 24 }, { header: '订单状态', key: 'status', width: 16 }, { header: '波次号', key: 'wave_no', width: 18 }, { header: '货主', key: 'store_id', width: 20 }, { header: '平台', key: 'sys_platform_name', width: 16 }, { header: '店铺昵称', key: 'shop_nick', width: 20 }, { header: '收件人', key: 'receiver_name', width: 16 }, { header: '收件人电话', key: 'receiver_mobile', width: 18 }, { header: '省', key: 'receiver_province', width: 10 }, { header: '市', key: 'receiver_city', width: 10 }, { header: '区', key: 'receiver_district', width: 10 }, { header: '镇', key: 'receiver_town', width: 10 }, { header: '详细地址', key: 'receiver_detail', width: 30 }, { header: '仓库商品名称', key: 'item_name', width: 30 }, { header: '商品条码', key: 'item_barcode', width: 24 }, { header: '商品图片', key: 'item_image', width: 40 }, { header: '数量', key: 'item_quantity', width: 10 }, { header: '物流公司', key: 'logistics_name', width: 18 }, { header: '运单号', key: 'waybill_code', width: 30 }, { header: '业务类型', key: 'business_type', width: 12 }, { header: '运单接口', key: 'logistics_interface_name', width: 20 }, { header: '包材ID', key: 'package_material_id', width: 14 }, { header: '包材编码', key: 'package_material_code', width: 20 }, { header: '包材名称', key: 'package_material_name', width: 20 }, { header: '分配时间', key: 'waybill_allocated_at', width: 20 }, { header: '商品种数', key: 'items_count', width: 12 }, { header: '商品件数', key: 'items_total', width: 12 }, { header: '商品重量', key: 'items_weight', width: 12 }, { header: '称重重量(g)', key: 'weighing_weight', width: 14 }, { header: '订单金额', key: 'total_amount', width: 14 }, { header: '实收金额', key: 'got_amount', width: 14 }, { header: '创建时间', key: 'create_at', width: 20 }, { header: '支付时间', key: 'pay_time', width: 20 }, { header: '发货时间', key: 'delivery_time', width: 20 }, { header: '出库状态', key: 'outbound_status', width: 14 }, { header: '复核状态', key: 'inspection_status', width: 14 }, { header: '复核完成状态', key: 'recheck_status', width: 16 }, { header: '配货状态', key: 'post_status', width: 14 }, { header: '打包状态', key: 'pack_status', width: 14 }, { header: '备注', key: 'remark', width: 30 }, { header: '买家留言', key: 'buyer_message', width: 30 }, { header: '卖家留言', key: 'seller_message', width: 30 }, { header: '归档时间', key: 'archive_time', width: 20 }, ]); /** 订单状态中文翻译映射 */ const ORDER_STATUS_LABELS = Object.freeze({ status: { pedding: '待处理', created: '已创建', cancel: '已取消', error: '异常', finished: '已完成', }, outbound_status: { none: '无', padding: '待出库', fin: '已完成', timeout: '超时', error: '异常', }, inspection_status: { none: '无', padding: '待检验', running: '检验中', fin: '已完成', error: '异常', }, recheck_status: { none: '无', fin: '已完成', }, post_status: { none: '无', padding: '待配货', fin: '已完成', timeout: '超时', error: '异常', }, pack_status: { none: '无', padding: '待打包', fin: '已完成', error: '异常', }, }); /** * 订单导出系统服务。 * 负责复用订单列表查询语义,按页拉取数据并流式写入本地 xlsx 后上传。 */ class OrderExportService extends OrderBaseService { /** * 获取单页导出数量。 * @return {number} 单页导出数量。 */ getExportPageSize() { return DEFAULT_EXPORT_PAGE_SIZE; } /** * 规范订单导出模块名。 * @param {string} moduleName 原始模块名。 * @return {string} 规范后的模块名;为空时返回空字符串。 */ normalizeExportModuleName(moduleName = '') { const normalizedModuleName = String(moduleName || '').trim(); if (!normalizedModuleName) { return ''; } const mappedModuleName = ORDER_EXPORT_MODULE_MAP[normalizedModuleName.toLowerCase()]; if (!mappedModuleName) { throw new Error(`不支持的订单导出模块: ${normalizedModuleName}`); } return mappedModuleName; } /** * 根据表类型推导默认排序所使用的模块名。 * @param {string} tableType 订单表类型。 * @return {string} 用于排序默认值的模块名。 */ getSortModuleNameByTableType(tableType = 'current') { switch (tableType) { case 'history': return 'archiveOrder'; case 'dispatch': return 'deliveryOrder'; case 'outsourced': return 'entrustOrder'; case 'current': default: return 'order'; } } /** * 解析订单导出目标,兼容 module/module_name 与 table_type 两种写法。 * @param {Object} options 解析参数。 * @param {string} [options.moduleName] 模块名。 * @param {string} [options.tableType] 表类型。 * @return {{ tableType: string, defaultWhereModuleName: string, sortModuleName: string }} 导出目标。 */ resolveExportTarget(options = {}) { const safeOptions = this.isPlainObject(options) ? options : {}; const moduleName = this.normalizeExportModuleName(safeOptions.moduleName || ''); const rawTableType = String(safeOptions.tableType || '').trim(); const tableTypeToken = rawTableType.toLowerCase(); const moduleNameFromTableType = ORDER_EXPORT_ALLOWED_TABLE_TYPES.has(tableTypeToken) ? '' : this.normalizeExportModuleName(rawTableType); const resolvedTableType = rawTableType ? this.resolveOrderTableType({ tableType: rawTableType }) : (moduleName ? this.getModuleConfig(moduleName).modelType : 'current'); if (moduleName && moduleNameFromTableType && moduleName !== moduleNameFromTableType) { throw new Error(`module 与 table_type 不匹配: ${moduleName} / ${rawTableType}`); } if (moduleName) { const expectedTableType = this.getModuleConfig(moduleName).modelType; if (expectedTableType !== resolvedTableType) { throw new Error(`module ${moduleName} 仅支持 ${expectedTableType} 表,当前传入 ${resolvedTableType}`); } } return { tableType: resolvedTableType, defaultWhereModuleName: moduleName || moduleNameFromTableType || '', sortModuleName: moduleName || moduleNameFromTableType || this.getSortModuleNameByTableType(resolvedTableType), }; } /** * 获取订单导出列配置。 * @param {string} [mode='waybill'] 导出模式:'waybill'(按运单展开)或 'item'(按商品明细展开)。 * @return {Array} 导出列配置。 */ getOrderExportColumns(mode = 'waybill') { const columns = mode === 'item' ? ORDER_EXPORT_ITEM_COLUMNS : ORDER_EXPORT_COLUMNS; return columns.map(column => ({ ...column })); } /** * 生成订单导出文件名。 * @param {Object} target 导出目标。 * @return {string} 文件名。 */ buildOrderExportFilename(target = {}) { const safeTarget = this.isPlainObject(target) ? target : {}; const timestamp = new Date(); const year = timestamp.getFullYear(); const month = String(timestamp.getMonth() + 1).padStart(2, '0'); const day = String(timestamp.getDate()).padStart(2, '0'); const hour = String(timestamp.getHours()).padStart(2, '0'); const minute = String(timestamp.getMinutes()).padStart(2, '0'); const second = String(timestamp.getSeconds()).padStart(2, '0'); const moduleTag = safeTarget.defaultWhereModuleName || safeTarget.tableType || 'current'; return `订单导出_${moduleTag}_${year}${month}${day}${hour}${minute}${second}.xlsx`; } /** * 生成上传 key。 * @param {number|string} warehouseId 仓库ID。 * @param {string} tableType 表类型。 * @return {string} 上传 key。 */ buildUploadKey(warehouseId, tableType) { const safeWarehouseId = String(warehouseId || 'unknown').trim() || 'unknown'; const safeTableType = String(tableType || 'current').trim() || 'current'; const randomToken = crypto.randomBytes(6).toString('hex'); return `exports/order/${safeWarehouseId}/${safeTableType}/${Date.now()}_${randomToken}.xlsx`; } /** * 将模型行转换为普通对象。 * @param {Object} row 模型行或普通对象。 * @return {Object} 普通对象。 */ toPlainRow(row = {}) { if (row && typeof row.get === 'function') { return row.get({ plain: true }); } return this.isPlainObject(row) ? { ...row } : {}; } /** * 规范导出单元格值。 * @param {*} value 原始值。 * @return {string|number} 规范后的值。 */ normalizeExportCellValue(value) { if (value === null || value === undefined) { return ''; } if (Array.isArray(value)) { return value.map(item => this.normalizeExportCellValue(item)).filter(Boolean).join(','); } if (value instanceof Date) { return value.toISOString(); } if (typeof value === 'object') { return JSON.stringify(value); } return value; } /** * 映射订单导出数据行。 * - waybill 模式:按运单号展开,每个运单一组。 * - item 模式:按商品明细展开,每个商品一行;运单信息汇总填充。 * @param {Object} orderRow 订单行。 * @param {Object} [context] 导出上下文,包含批量查询的辅助数据。 * @param {Map>} [context.itemsMap] 订单ID → 商品明细列表的映射。 * @param {Map} [context.storeRemarkMap] 货主ID → 货主备注的映射。 * @param {Map} [context.stockNameMap] stockId → 仓库商品名称的映射。 * @param {Map} [context.barcodeMap] stockId → 商品条码(逗号拼接)的映射。 * @param {Map} [context.imageUrlMap] stockId → 商品图片URL的映射。 * @param {Map>} [context.expressMap] 订单ID → 运单行列表的映射。 * @param {Map} [context.packageMaterialMap] package_material_id → 包材编码的映射。 * @param {string} [mode='waybill'] 导出模式:'waybill' 或 'item'。 * @return {Array} 导出行数组。 */ mapOrderExportRow(orderRow = {}, context = {}, mode = 'waybill') { const safeOrderRow = this.isPlainObject(orderRow) ? orderRow : {}; const { itemsMap, storeRemarkMap, stockNameMap, barcodeMap, imageUrlMap, expressMap, packageMaterialMap } = context; const safeItemsMap = itemsMap instanceof Map ? itemsMap : new Map(); const safeStoreRemarkMap = storeRemarkMap instanceof Map ? storeRemarkMap : new Map(); const safeExpressMap = expressMap instanceof Map ? expressMap : new Map(); const externalOrderCode = safeOrderRow.pre_delivery_order_code || safeOrderRow.source_order_codes || ''; /** * 翻译状态字段为中文,未知值保留原始值。 * @param {string} field 状态字段名。 * @param {*} value 原始状态值。 * @return {string} 翻译后的中文状态文本。 */ const translateStatus = (field, value) => { const raw = String(value ?? '').trim(); if (!raw) return ''; const labelMap = ORDER_STATUS_LABELS[field]; return labelMap && labelMap[raw] ? labelMap[raw] : raw; }; /** * 安全格式化日期字段,空值/无效值返回空字符串。 * @param {*} value 日期原始值。 * @return {string} 格式化后的日期字符串或空字符串。 */ const formatDateSafe = value => { if (value === null || value === undefined || value === '' || value === 0) { return ''; } const d = new Date(value); if (isNaN(d.getTime()) || d.getTime() <= 0) { return ''; } return this.app.formatDate(value); }; const orderId = Number(safeOrderRow.id || 0); const storeId = Number(safeOrderRow.store_id || 0); const storeRemark = safeStoreRemarkMap.get(storeId) || ''; const items = safeItemsMap.get(orderId) || []; const safeStockNameMap = stockNameMap instanceof Map ? stockNameMap : new Map(); const safeBarcodeMap = barcodeMap instanceof Map ? barcodeMap : new Map(); const safeImageUrlMap = imageUrlMap instanceof Map ? imageUrlMap : new Map(); const itemsDetail = Array.isArray(items) && items.length > 0 ? items.map(item => { const stockId = Number(item.stock_id || 0); const warehouseItemName = stockId > 0 ? safeStockNameMap.get(stockId) : ''; const displayName = warehouseItemName || item.item_name || ''; return `${displayName} x${item.plan_qty || 1}`; }).join('; ') : ''; /** 订单公共字段(不含 items_detail,由各模式自行拼接) */ const commonFields = { id: this.normalizeExportCellValue(safeOrderRow.id), delivery_order_code: this.normalizeExportCellValue(safeOrderRow.delivery_order_code), external_order_code: this.normalizeExportCellValue(externalOrderCode), status: translateStatus('status', safeOrderRow.status), wave_no: this.normalizeExportCellValue(safeOrderRow.wave_no), store_id: this.normalizeExportCellValue(storeRemark || safeOrderRow.store_name || safeOrderRow.store_id), sys_platform_name: this.normalizeExportCellValue(safeOrderRow.sys_platform_name), shop_nick: this.normalizeExportCellValue(safeOrderRow.shop_nick), receiver_name: this.normalizeExportCellValue(safeOrderRow.name || ''), receiver_mobile: this.normalizeExportCellValue(safeOrderRow.mobile || safeOrderRow.tel || ''), receiver_province: this.normalizeExportCellValue(safeOrderRow.province || ''), receiver_city: this.normalizeExportCellValue(safeOrderRow.city || ''), receiver_district: this.normalizeExportCellValue(safeOrderRow.area || ''), receiver_town: this.normalizeExportCellValue(safeOrderRow.town || ''), receiver_detail: this.normalizeExportCellValue(safeOrderRow.detail_address || ''), logistics_name: this.normalizeExportCellValue(safeOrderRow.logistics_name), items_count: this.normalizeExportCellValue(safeOrderRow.items_count), items_total: this.normalizeExportCellValue(safeOrderRow.items_total), items_weight: this.normalizeExportCellValue(safeOrderRow.items_weight), total_amount: this.normalizeExportCellValue(safeOrderRow.total_amount), got_amount: this.normalizeExportCellValue(safeOrderRow.got_amount), remark: this.normalizeExportCellValue(safeOrderRow.remark), buyer_message: this.normalizeExportCellValue(safeOrderRow.buyer_message), seller_message: this.normalizeExportCellValue(safeOrderRow.seller_message), create_at: formatDateSafe(safeOrderRow.create_at), pay_time: formatDateSafe(safeOrderRow.pay_time), delivery_time: formatDateSafe(safeOrderRow.delivery_time), outbound_status: translateStatus('outbound_status', safeOrderRow.outbound_status), inspection_status: translateStatus('inspection_status', safeOrderRow.inspection_status), recheck_status: translateStatus('recheck_status', safeOrderRow.recheck_status), post_status: translateStatus('post_status', safeOrderRow.post_status), pack_status: translateStatus('pack_status', safeOrderRow.pack_status), archive_time: formatDateSafe(safeOrderRow.archive_time), }; const expressList = safeExpressMap.get(orderId) || []; // ★ 模式B:按商品明细展开 if (mode === 'item') { const waybillSummary = expressList.map(e => e.waybill_code).filter(Boolean).join(', '); const waybillFirstTime = expressList.length > 0 ? formatDateSafe(expressList[0].create_at) : ''; const weightSummary = expressList.reduce((sum, e) => sum + (Number(e.weighing_weight) || 0), 0); const firstExp = expressList.length > 0 ? expressList[0] : null; const businessType = firstExp ? (Number(firstExp.business_key) === 1 ? '主单号' : '子单号') : ''; const interfaceName = firstExp ? String(firstExp.logistics_interface_name || '') : ''; const materialId = firstExp ? (firstExp.package_material_id != null ? Number(firstExp.package_material_id) : '') : ''; const safePackageMaterialMap = packageMaterialMap instanceof Map ? packageMaterialMap : new Map(); const materialCode = materialId ? (safePackageMaterialMap.get(Number(materialId)) || '') : ''; if (items.length === 0) { return [{ ...commonFields, item_name: '', item_barcode: '', item_image: '', item_quantity: '', business_type: businessType, logistics_interface_name: this.normalizeExportCellValue(interfaceName), package_material_id: materialId, package_material_code: this.normalizeExportCellValue(materialCode), package_material_name: this.normalizeExportCellValue(firstExp ? firstExp.package_material_name_snapshot : ''), waybill_code: waybillSummary, waybill_allocated_at: waybillFirstTime, weighing_weight: weightSummary || '', }]; } return items.map(item => { const sid = Number(item.stock_id || 0); return { ...commonFields, item_name: (sid > 0 ? safeStockNameMap.get(sid) : '') || item.item_name || '', item_barcode: sid > 0 ? (safeBarcodeMap.get(sid) || '') : '', item_image: sid > 0 ? (safeImageUrlMap.get(sid) || '') : '', item_quantity: item.plan_qty || 1, business_type: businessType, logistics_interface_name: this.normalizeExportCellValue(interfaceName), package_material_id: materialId, package_material_code: this.normalizeExportCellValue(materialCode), package_material_name: this.normalizeExportCellValue(firstExp ? firstExp.package_material_name_snapshot : ''), waybill_code: waybillSummary, waybill_allocated_at: waybillFirstTime, weighing_weight: weightSummary || '', }; }); } // ★ 模式A(默认 waybill):按运单展开,保留 items_detail const safePackageMaterialMap = packageMaterialMap instanceof Map ? packageMaterialMap : new Map(); if (expressList.length === 0) { // 无运单的订单也输出一行(运单字段为空) return [{ ...commonFields, items_detail: this.normalizeExportCellValue(itemsDetail), waybill_code: '', business_type: '', logistics_interface_name: '', package_material_id: '', package_material_code: '', package_material_name: '', waybill_allocated_at: '', weighing_weight: '', }]; } return expressList.map(exp => ({ ...commonFields, items_detail: this.normalizeExportCellValue(itemsDetail), waybill_code: exp.waybill_code || '', business_type: Number(exp.business_key) === 1 ? '主单号' : '子单号', logistics_interface_name: this.normalizeExportCellValue(exp.logistics_interface_name), package_material_id: exp.package_material_id != null ? Number(exp.package_material_id) : '', package_material_code: this.normalizeExportCellValue( exp.package_material_id != null ? (safePackageMaterialMap.get(Number(exp.package_material_id)) || '') : '' ), package_material_name: this.normalizeExportCellValue(exp.package_material_name_snapshot), waybill_allocated_at: formatDateSafe(exp.create_at), weighing_weight: exp.weighing_weight != null ? Number(exp.weighing_weight) : '', })); } /** * 上传本地导出文件并记录文件信息。 * @param {Object} options 上传参数。 * @param {string} options.filePath 本地文件路径。 * @param {string} options.filename 文件名。 * @param {number|string} options.warehouseId 仓库ID。 * @param {string} options.tableType 表类型。 * @return {Promise} 上传结果。 */ async uploadOrderExportFile(options = {}) { const safeOptions = this.isPlainObject(options) ? options : {}; const { filePath, filename, warehouseId, tableType, } = safeOptions; const uploadService = this.ctx?.service?.systems?.upload; if (!uploadService || typeof uploadService.uploadFile !== 'function') { throw new Error('上传服务不可用'); } const stat = await fsp.stat(filePath); const uploadKey = this.buildUploadKey(warehouseId, tableType); 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', }); let fileRecord = null; if (typeof uploadService.uploadSuccessNotify === 'function') { fileRecord = await uploadService.uploadSuccessNotify({ url: uploadResult.fileName, fileKey: uploadResult.fileName, fileName: filename, fileType: 'document', mimeType: uploadStream.mimeType, fileSize: stat.size, category: 'document', businessType: 'orderExport', businessId: `${warehouseId}:${tableType}`, uploaderType: this.ctx?.user?.role || 'system_api', uploaderDept: this.ctx?.user?.department || '', }); } return { filename, fileKey: uploadResult.fileName, url: uploadResult.url || uploadResult.cdnUrl || uploadResult.cosUrl || '', cdnUrl: uploadResult.cdnUrl || uploadResult.url || '', cosUrl: uploadResult.cosUrl || '', fileRecord: fileRecord?.data || fileRecord || null, }; } /** * 导出订单列表。 * @param {Object} options 导出参数。 * @param {string} [options.tableType] 表类型。 * @param {string} [options.moduleName] 模块名。 * @param {Object} [options.where] 查询条件。 * @param {Object} [options.sort] 排序参数。 * @param {Function} [options.onProgress] 进度回调。 * @return {Promise} 上传结果与统计信息。 */ async exportOrders(options = {}) { const safeOptions = this.isPlainObject(options) ? options : {}; const target = this.resolveExportTarget({ tableType: safeOptions.tableType, moduleName: safeOptions.moduleName, }); const warehouseId = this.getWarehouseId(); const requestData = { where: this.isPlainObject(safeOptions.where) ? { ...safeOptions.where } : {}, sort: this.isPlainObject(safeOptions.sort) ? { ...safeOptions.sort } : {}, }; const progressHandler = typeof safeOptions.onProgress === 'function' ? safeOptions.onProgress : async () => {}; const { where } = this.prepareWhereContext(requestData, { specialFieldMap: { quickWhere: { bucket: 'quick', }, }, }); const { where: sanitizedWhere, expressNumbers } = this.extractOrderListExpressVirtualFilter(where); const { where: whereAfterBuyerMessage, buyerMessageHas } = this.extractBuyerMessageHasVirtualFilter(sanitizedWhere); const mergedWhere = this.mergeWhereObjects( target.defaultWhereModuleName ? this.getDefaultWhere(target.defaultWhereModuleName) : {}, whereAfterBuyerMessage ); let queryWhere = this.buildWhere(mergedWhere, warehouseId, { specialFieldMap: { quickWhere: { bucket: 'quick', }, }, }); if (expressNumbers.length > 0) { const orderIds = await this.findOrderIdsByExpressNumbers(expressNumbers, warehouseId); queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, orderIds); } if (buyerMessageHas !== null) { const buyerMessageCondition = this.buildBuyerMessageHasCondition(buyerMessageHas); queryWhere = this.appendConditionToWhere(queryWhere, buyerMessageCondition); } const orderModel = await this.getOrderModelByTableType(target.tableType, warehouseId); const pageSize = this.getExportPageSize(); const order = this.buildListOrder(requestData.sort, target.sortModuleName); const totalCount = await orderModel.count({ where: queryWhere }); const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-order-export-')); const filename = this.buildOrderExportFilename(target); const filePath = path.join(tempDir, filename); const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({ filename: filePath, useStyles: false, useSharedStrings: false, }); const worksheet = workbook.addWorksheet(ORDER_EXPORT_WORKSHEET_NAME); const exportMode = String(safeOptions.export_mode || '').trim() || 'waybill'; const mode = exportMode === 'item' ? 'item' : 'waybill'; worksheet.columns = this.getOrderExportColumns(mode); let currentCount = 0; let page = 1; try { await progressHandler({ status: 'running', progress: totalCount > 0 ? 5 : 90, currentCount, totalCount, message: totalCount > 0 ? `已命中 ${totalCount} 条订单,开始导出` : '未命中数据,开始生成空文件', }); while (currentCount < totalCount) { const rows = await orderModel.findAll({ where: queryWhere, limit: pageSize, offset: (page - 1) * pageSize, order, raw: true, }); if (!Array.isArray(rows) || rows.length === 0) { break; } const normalizedRows = rows.map(row => this.normalizeOrderListItem(this.toPlainRow(row)) ); const orderIds = normalizedRows.map(r => Number(r.id || 0)).filter(id => id > 0); // 批量查询商品明细(wms_order_items) const itemsMap = new Map(); if (orderIds.length > 0) { try { const itemsModel = await this.getOrderItemsModelByTableType(target.tableType, warehouseId); const itemsRows = await itemsModel.findAll({ where: { order_id: { [this.app.Sequelize.Op.in]: orderIds } }, attributes: [ 'order_id', 'item_name', 'plan_qty', 'stock_id' ], order: [[ 'id', 'ASC' ]], raw: true, }); for (const item of (Array.isArray(itemsRows) ? itemsRows : [])) { const oid = Number(item.order_id || 0); if (oid > 0) { if (!itemsMap.has(oid)) { itemsMap.set(oid, []); } itemsMap.get(oid).push(item); } } } catch (err) { this.app.logger.warn(`[order_export] 批量查询订单商品明细失败: ${err.message}`); } } // 批量查询仓库商品名称、条码与图片(复用 getStockDetails 缓存) const stockNameMap = new Map(); const barcodeMap = new Map(); const imageUrlMap = new Map(); if (itemsMap.size > 0 && this.ctx && this.ctx.model && this.ctx.model.StockWarehouse) { try { const stockIds = [ ...new Set( [ ...itemsMap.values() ] .flat() .map(item => Number(item.stock_id || 0)) .filter(id => id > 0) ), ]; if (stockIds.length > 0) { const stockDetails = await this.ctx.service.systems.stockWarehouse.getStockDetails( stockIds, { warehouseId } ); for (const detail of stockDetails) { const sid = Number(detail.id || 0); if (sid > 0) { stockNameMap.set(sid, String(detail.item_name || '').trim()); // 从 getStockDetails 的 barcodes 中提取条码并转为逗号拼接 const barcodesRaw = Array.isArray(detail.barcodes) ? detail.barcodes.map(bc => String(bc.barcode || '').trim()).filter(Boolean) : []; if (barcodesRaw.length > 0) { barcodeMap.set(sid, [ ...new Set(barcodesRaw) ].join(', ')); } // 图片字段(有图片标记但实际 URL 需要额外查询) if (detail.is_images === 'Y') { imageUrlMap.set(sid, ''); } } } } } catch (err) { this.app.logger.warn(`[order_export] 批量查询商品详情失败: ${err.message}`); } } // 批量查询货主备注(wms_store_warehouse.store_remask) const storeRemarkMap = new Map(); if (orderIds.length > 0 && this.ctx && this.ctx.model && this.ctx.model.StoreWarehouse) { try { const storeIds = [ ...new Set( normalizedRows .map(r => Number(r.store_id || 0)) .filter(id => id > 0) ), ]; if (storeIds.length > 0) { const swRows = await this.ctx.model.StoreWarehouse.findAll({ where: { store_id: { [this.app.Sequelize.Op.in]: storeIds }, warehouse_id: warehouseId, }, attributes: [ 'store_id', 'store_remask' ], raw: true, }); for (const sw of (Array.isArray(swRows) ? swRows : [])) { const sid = Number(sw.store_id || 0); if (sid > 0 && !storeRemarkMap.has(sid)) { storeRemarkMap.set(sid, String(sw.store_remask || '').trim()); } } } } catch (err) { this.app.logger.warn(`[order_export] 批量查询货主备注失败: ${err.message}`); } } // 批量查询运单数据(wms_order_express),按订单ID分组 const expressMap = new Map(); if (orderIds.length > 0 && this.ctx && this.ctx.model && this.ctx.model.OrderExpress) { try { const expressRows = await this.ctx.model.OrderExpress.findAll({ where: { order_id: { [this.app.Sequelize.Op.in]: orderIds }, warehouse_id: warehouseId, }, attributes: [ 'id', 'order_id', 'waybill_code', 'business_key', 'logistics_interface_name', 'package_material_id', 'package_material_name_snapshot', 'create_at', 'weighing_weight' ], order: [[ 'id', 'ASC' ]], raw: true, }); for (const exp of (Array.isArray(expressRows) ? expressRows : [])) { const oid = Number(exp.order_id || 0); if (oid > 0) { if (!expressMap.has(oid)) { expressMap.set(oid, []); } expressMap.get(oid).push(exp); } } } catch (err) { this.app.logger.warn(`[order_export] 批量查询运单数据失败: ${err.message}`); } } // 批量查询包材编码(wms_package_material),按 package_material_id 分组 const packageMaterialMap = new Map(); if (expressMap.size > 0 && this.ctx && this.ctx.model && this.ctx.model.PackageMaterial) { try { const materialIds = [ ...new Set( [ ...expressMap.values() ] .flat() .map(exp => Number(exp.package_material_id || 0)) .filter(id => id > 0) ), ]; if (materialIds.length > 0) { const pmRows = await this.ctx.model.PackageMaterial.findAll({ where: { id: { [this.app.Sequelize.Op.in]: materialIds } }, attributes: [ 'id', 'material_code' ], raw: true, }); for (const pm of (Array.isArray(pmRows) ? pmRows : [])) { const pid = Number(pm.id || 0); if (pid > 0 && !packageMaterialMap.has(pid)) { packageMaterialMap.set(pid, String(pm.material_code || '').trim()); } } } } catch (err) { this.app.logger.warn(`[order_export] 批量查询包材编码失败: ${err.message}`); } } const exportContext = { itemsMap, storeRemarkMap, stockNameMap, barcodeMap, imageUrlMap, expressMap, packageMaterialMap }; for (const row of normalizedRows) { const exportRows = this.mapOrderExportRow(row, exportContext, mode); for (const exportRow of exportRows) { worksheet.addRow(exportRow).commit(); } } currentCount += normalizedRows.length; await progressHandler({ status: 'running', progress: Math.min(99, Math.max(5, Math.round((currentCount / Math.max(totalCount, 1)) * 90))), currentCount, totalCount, message: `正在导出第 ${page} 页,共 ${Math.ceil(totalCount / pageSize) || 1} 页`, }); page += 1; } worksheet.commit(); await workbook.commit(); const uploadResult = await this.uploadOrderExportFile({ filePath, filename, warehouseId, tableType: target.tableType, }); await progressHandler({ status: 'success', progress: 100, currentCount, totalCount, message: '导出任务完成', result: uploadResult, }); return { ...uploadResult, table_type: target.tableType, module_name: target.defaultWhereModuleName || '', current_count: currentCount, total_count: totalCount, }; } catch (error) { const workbookStream = workbook.stream; if (workbookStream && typeof workbookStream.destroy === 'function') { workbookStream.destroy(); } throw error; } finally { await fsp.rm(tempDir, { recursive: true, force: true }); } } } module.exports = OrderExportService;