'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: '订单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: 'step', width: 10 }, { header: '波次号', key: 'wave_no', width: 18 }, { header: '仓库ID', key: 'warehouse_id', width: 12 }, { header: '货主ID', key: 'store_id', width: 12 }, { header: '平台', key: 'sys_platform_name', width: 16 }, { header: '店铺昵称', key: 'shop_nick', width: 20 }, { header: '卖家昵称', key: 'seller_nick', width: 20 }, { header: '买家昵称', key: 'buyer_nick', width: 20 }, { header: '物流公司', key: 'logistics_name', width: 18 }, { header: '运单号', key: 'express_numbers', width: 28 }, { header: '商品种数', key: 'items_count', width: 12 }, { header: '商品件数', key: 'items_total', width: 12 }, { header: '总重量', key: 'items_weight', width: 12 }, { 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: 'post_status', width: 14 }, { header: '打包状态', key: 'pack_status', width: 14 }, { header: '归档时间', key: 'archive_time', width: 20 }, ]); /** * 订单导出系统服务。 * 负责复用订单列表查询语义,按页拉取数据并流式写入本地 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), }; } /** * 获取订单导出列配置。 * @return {Array} 导出列配置。 */ getOrderExportColumns() { return ORDER_EXPORT_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; } /** * 映射单行订单导出数据。 * @param {Object} orderRow 订单行。 * @return {Object} 导出行。 */ mapOrderExportRow(orderRow = {}) { const safeOrderRow = this.isPlainObject(orderRow) ? orderRow : {}; const expressNumbers = Array.isArray(safeOrderRow.express_numbers) ? safeOrderRow.express_numbers : Array.isArray(safeOrderRow.waybill_codes) ? safeOrderRow.waybill_codes : []; const externalOrderCode = safeOrderRow.pre_delivery_order_code || safeOrderRow.source_order_codes || ''; return { id: this.normalizeExportCellValue(safeOrderRow.id), delivery_order_code: this.normalizeExportCellValue(safeOrderRow.delivery_order_code), external_order_code: this.normalizeExportCellValue(externalOrderCode), status: this.normalizeExportCellValue(safeOrderRow.status), step: this.normalizeExportCellValue(safeOrderRow.step), wave_no: this.normalizeExportCellValue(safeOrderRow.wave_no), warehouse_id: this.normalizeExportCellValue(safeOrderRow.warehouse_id), store_id: this.normalizeExportCellValue(safeOrderRow.store_id), sys_platform_name: this.normalizeExportCellValue(safeOrderRow.sys_platform_name), shop_nick: this.normalizeExportCellValue(safeOrderRow.shop_nick), seller_nick: this.normalizeExportCellValue(safeOrderRow.seller_nick), buyer_nick: this.normalizeExportCellValue(safeOrderRow.buyer_nick), logistics_name: this.normalizeExportCellValue(safeOrderRow.logistics_name), express_numbers: this.normalizeExportCellValue(expressNumbers), 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), create_at: this.normalizeExportCellValue(safeOrderRow.create_at), pay_time: this.normalizeExportCellValue(safeOrderRow.pay_time), delivery_time: this.normalizeExportCellValue(safeOrderRow.delivery_time), outbound_status: this.normalizeExportCellValue(safeOrderRow.outbound_status), inspection_status: this.normalizeExportCellValue(safeOrderRow.inspection_status), post_status: this.normalizeExportCellValue(safeOrderRow.post_status), pack_status: this.normalizeExportCellValue(safeOrderRow.pack_status), archive_time: this.normalizeExportCellValue(safeOrderRow.archive_time), }; } /** * 上传本地导出文件并记录文件信息。 * @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 mergedWhere = this.mergeWhereObjects( target.defaultWhereModuleName ? this.getDefaultWhere(target.defaultWhereModuleName) : {}, sanitizedWhere ); 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); } 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); worksheet.columns = this.getOrderExportColumns(); 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 = await this.attachOrderExpressNumbers( rows.map(row => this.normalizeOrderListItem(this.toPlainRow(row))) ); for (const row of normalizedRows) { worksheet.addRow(this.mapOrderExportRow(row)).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;