From a69fd3f3934058e35ff9ae2eb8b5306f6e0c76f1 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 23 Jul 2026 17:42:28 +0800 Subject: [PATCH] =?UTF-8?q?fix(storage.entry):=20=E5=85=A5=E5=BA=93?= =?UTF-8?q?=E8=B6=85=E9=87=8F=E9=9D=99=E9=BB=98=E8=A3=81=E5=89=AA=20+=20co?= =?UTF-8?q?ntainerList=20=E6=8C=89=E5=8F=AF=E7=94=A8=E9=87=8F=E8=BF=87?= =?UTF-8?q?=E6=BB=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. inbound_direct_log._addSingleItem: 入库数量超过计划时不再拒绝,改为静默裁剪为 maxAllowed(仅无可入数量时拒绝) 2. storage/entry.containerList: NOT EXISTS 一刀切排除改为计算 actual_quantity - SUM(已占用),只返回可用量>0的收货明细 --- app/service/systems/inbound_direct_log.js | 279 +++--- app/service/systems/storage/entry.js | 995 +++++++++++++++++++++- 2 files changed, 1131 insertions(+), 143 deletions(-) diff --git a/app/service/systems/inbound_direct_log.js b/app/service/systems/inbound_direct_log.js index d495c85..db37198 100644 --- a/app/service/systems/inbound_direct_log.js +++ b/app/service/systems/inbound_direct_log.js @@ -373,23 +373,26 @@ class InboundDirectLogService extends Service { // CREATED 人工导入允许超过计划数量 const isManualImport = entryOrder.order_status === 'CREATED' && !isBindingMode; if (!isManualImport) { - const newTotal = existingTotal + effectiveQuantity; - if (newTotal > totalPlanQty) { + const maxAllowed = totalPlanQty - existingTotal; + if (maxAllowed <= 0) { return { ok: false, error: { code: 400, - message: `入库数量超过计划:商品计划 ${totalPlanQty},已入库 ${existingTotal},本次 ${effectiveQuantity},合计 ${newTotal}`, + message: `入库数量超过计划:商品计划 ${totalPlanQty},已入库 ${existingTotal},本次 ${effectiveQuantity},合计 ${existingTotal + effectiveQuantity}`, data: { stock_id: stockId, plan_quantity: totalPlanQty, existing_quantity: existingTotal, requested_quantity: effectiveQuantity, - exceeded_by: newTotal - totalPlanQty, + exceeded_by: effectiveQuantity, }, }, }; } + if (effectiveQuantity > maxAllowed) { + effectiveQuantity = maxAllowed; + } } // 剩余可入库数 = 计划数 - max(已收货量, 已写入 direct_log 的待入库量) @@ -853,7 +856,7 @@ class InboundDirectLogService extends Service { itemId: item.item_id || '', inventoryType: item.inventory_type || 'ZP', planQty: Number(item.count) || 0, - actualQty: Number(item.count) || 0, + actualQty: stockSummary[String(item.stock_id)] || 0, })); const syncResult = await this.qimenEntrySync({ @@ -957,11 +960,18 @@ class InboundDirectLogService extends Service { transaction, }); - // 同一 stock_id 只写一次库存 - if (processedStockIds.has(String(stockId))) continue; - processedStockIds.add(String(stockId)); - if (!isBinding) { - nonBindingStockProcessed.add(String(stockId)); + // 同一 stock_id 只写一次 StockWarehouse 总库存(聚合量),但 Storage 按入库记录逐条写入 + const isStockWarehouseDone = processedStockIds.has(String(stockId)); + if (isStockWarehouseDone && !isBinding) { + // 非绑定模式:StockWarehouse 已写但 Storage 还未写,不能 continue,继续写 Storage + } else if (isStockWarehouseDone) { + continue; + } + if (!isStockWarehouseDone) { + processedStockIds.add(String(stockId)); + if (!isBinding) { + nonBindingStockProcessed.add(String(stockId)); + } } // 使用入库单号作为批次号;若有收货绑定则使用收货明细信息 @@ -972,137 +982,162 @@ class InboundDirectLogService extends Service { const batchNo = eo.entry_order_code; const inventoryType = item.inventory_type || 'ZP'; - // 从该 stock_id 的入库记录中取第一个非空 space_id,兜底 1 - const logForSpace = directLogs.find(l => String(l.stock_id) === String(stockId) && l.space_id); - const spaceId = logForSpace ? Number(logForSpace.space_id) : 1; + // StockWarehouse 总库存:每个 stock_id 聚合写入一次 + if (!isStockWarehouseDone) { + // 锁定并更新 StockWarehouse 总库存 + const stockRecord = await ctx.model.StockWarehouse.findOne({ + where: { id: stockId, is_valid: 'Y', deleted_at: null }, + lock: transaction.LOCK.UPDATE, + transaction, + }); - // 锁定并更新 StockWarehouse 总库存 - const stockRecord = await ctx.model.StockWarehouse.findOne({ - where: { id: stockId, is_valid: 'Y', deleted_at: null }, - lock: transaction.LOCK.UPDATE, - transaction, - }); + if (stockRecord) { + const beforeQuantity = Number(stockRecord.quantity) || 0; + const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0; - if (stockRecord) { - const beforeQuantity = Number(stockRecord.quantity) || 0; - const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0; + await stockRecord.increment('quantity', { by: inboundQty, transaction, silent: true }); + await stockRecord.reload({ transaction }); - await stockRecord.increment('quantity', { by: inboundQty, transaction, silent: true }); - await stockRecord.reload({ transaction }); + const afterQuantity = Number(stockRecord.quantity) || 0; + const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0; - const afterQuantity = Number(stockRecord.quantity) || 0; - const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0; + // 写入库存流水(聚合维度) + await ctx.service.systems.stockTransaction.create({ + transaction_type: 'INBOUND', + warehouse_id: warehouseId, + store_id: storeId, + stock_id: stockId, + quantity: inboundQty, + batch_no: batchNo, + inventory_type: inventoryType, + order_type: eo.order_type, + order_no: eo.entry_order_code, + entry_order_id: eo.id, + operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), + operator_name: ctx.user?.employees_name || '', + remark: '导入/PDA直接入库提交', + before_quantity: beforeQuantity, + after_quantity: afterQuantity, + before_locked_quantity: beforeLockedQuantity, + after_locked_quantity: afterLockedQuantity, + created_at: new Date(), + }, { transaction }); + } + } - // 写入库存流水 - await ctx.service.systems.stockTransaction.create({ + /** + * 写入 Storage 库位库存 + storage_transaction 的通用函数 + * @param {number} spaceId 库位ID + * @param {number} qty 入库数量 + * @param {number|null} rdId 收货单ID + * @param {string|null} prodDate 生产日期 + * @param {string|null} expDate 到期日期 + */ + const writeStorageRecord = async (spaceId, qty, rdId, prodDate, expDate) => { + if (qty <= 0) return; + + const sRecord = await ctx.model.Storage.findOne({ + where: { + space_id: spaceId, + stock_id: stockId, + batch_no: batchNo, + inventory_type: inventoryType, + is_enabled: 1, + delete_at: null, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + let sId = null; + let sBeforeQty = 0; + let sAfterQty = 0; + + if (sRecord) { + sBeforeQty = Number(sRecord.quantity) || 0; + sAfterQty = sBeforeQty + qty; + + await ctx.model.Storage.update({ + quantity: app.Sequelize.literal(`quantity + ${qty}`), + available_quantity: app.Sequelize.literal(`available_quantity + ${qty}`), + entry_order_id: eo.id, + inbound_time: new Date(), + inbound_order_no: eo.entry_order_code, + production_date: prodDate, + expiry_date: expDate, + receiving_id: rdId, + updated_at: new Date(), + }, { + where: { id: sRecord.id }, + transaction, + }); + sId = sRecord.id; + } else { + sBeforeQty = 0; + sAfterQty = qty; + + const createdStorage = await ctx.model.Storage.create({ + warehouse_id: warehouseId, + store_id: storeId, + space_id: spaceId, + stock_id: stockId, + batch_no: effectiveBatchNo, + inventory_type: inventoryType, + quantity: qty, + locked_quantity: 0, + available_quantity: qty, + inbound_time: new Date(), + inbound_order_no: eo.entry_order_code, + receiving_id: rdId, + entry_order_id: eo.id, + supplier_id: null, + supplier_batch_no: null, + production_date: prodDate, + expiry_date: expDate, + is_enabled: 1, + created_at: new Date(), + updated_at: new Date(), + }, { transaction }); + sId = createdStorage.id; + } + + // 写入库位维度库存流水 + await ctx.model.StorageTransaction.create({ transaction_type: 'INBOUND', warehouse_id: warehouseId, store_id: storeId, stock_id: stockId, - quantity: inboundQty, - batch_no: batchNo, + storage_id: sId, + space_id: spaceId, + quantity: qty, + before_quantity: sBeforeQty, + after_quantity: sAfterQty, + batch_no: effectiveBatchNo, inventory_type: inventoryType, - order_type: eo.order_type, + order_type: 'entry_order', order_no: eo.entry_order_code, - entry_order_id: eo.id, + order_id: eo.id, operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), operator_name: ctx.user?.employees_name || '', remark: '导入/PDA直接入库提交', - before_quantity: beforeQuantity, - after_quantity: afterQuantity, - before_locked_quantity: beforeLockedQuantity, - after_locked_quantity: afterLockedQuantity, created_at: new Date(), }, { transaction }); - } + }; - // 创建/更新 Storage 库位库存 - const storageRecord = await ctx.model.Storage.findOne({ - where: { - space_id: spaceId, - stock_id: stockId, - batch_no: batchNo, - inventory_type: inventoryType, - is_enabled: 1, - delete_at: null, - }, - lock: transaction.LOCK.UPDATE, - transaction, - }); - - let storageId = null; - let storageBeforeQty = 0; - let storageAfterQty = 0; - - if (storageRecord) { - storageBeforeQty = Number(storageRecord.quantity) || 0; - storageAfterQty = storageBeforeQty + inboundQty; - - await ctx.model.Storage.update({ - quantity: app.Sequelize.literal(`quantity + ${inboundQty}`), - available_quantity: app.Sequelize.literal(`available_quantity + ${inboundQty}`), - entry_order_id: eo.id, - inbound_time: new Date(), - inbound_order_no: eo.entry_order_code, - production_date: rdProductionDate, - expiry_date: rdExpiryDate, - receiving_id: rdReceivingId, - updated_at: new Date(), - }, { - where: { id: storageRecord.id }, - transaction, - }); - storageId = storageRecord.id; + if (isBinding) { + // 绑定模式:按 entryItem 维度写 Storage(与收货明细绑定,space_id 取第一条入库记录的库位) + const logForSpace = directLogs.find(l => String(l.stock_id) === String(stockId) && l.space_id); + const spaceId = logForSpace ? Number(logForSpace.space_id) : 1; + await writeStorageRecord(spaceId, inboundQty, rdReceivingId, rdProductionDate, rdExpiryDate); } else { - storageBeforeQty = 0; - storageAfterQty = inboundQty; - - const createdStorage = await ctx.model.Storage.create({ - warehouse_id: warehouseId, - store_id: storeId, - space_id: spaceId, - stock_id: stockId, - batch_no: effectiveBatchNo, - inventory_type: inventoryType, - quantity: inboundQty, - locked_quantity: 0, - available_quantity: inboundQty, - inbound_time: new Date(), - inbound_order_no: eo.entry_order_code, - receiving_id: rdReceivingId, - entry_order_id: eo.id, - supplier_id: null, - supplier_batch_no: null, - production_date: rdProductionDate, - expiry_date: rdExpiryDate, - is_enabled: 1, - created_at: new Date(), - updated_at: new Date(), - }, { transaction }); - storageId = createdStorage.id; + // 非绑定模式:按每个 InboundDirectLog 记录独立写 Storage,每条记录保有自己指定的 space_id 和 quantity + const stockDirectLogs = directLogs.filter(l => String(l.stock_id) === String(stockId) && Number(l.quantity) > 0); + for (const dlog of stockDirectLogs) { + const dlogSpaceId = dlog.space_id || 1; + const dlogQty = Number(dlog.quantity) || 0; + await writeStorageRecord(dlogSpaceId, dlogQty, null, null, null); + } } - - // 写入库位维度库存流水 - await ctx.model.StorageTransaction.create({ - transaction_type: 'INBOUND', - warehouse_id: warehouseId, - store_id: storeId, - stock_id: stockId, - storage_id: storageId, - space_id: spaceId, - quantity: inboundQty, - before_quantity: storageBeforeQty, - after_quantity: storageAfterQty, - batch_no: effectiveBatchNo, - inventory_type: inventoryType, - order_type: 'entry_order', - order_no: eo.entry_order_code, - order_id: eo.id, - operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), - operator_name: ctx.user?.employees_name || '', - remark: '导入/PDA直接入库提交', - created_at: new Date(), - }, { transaction }); } // 将 pending 绑定升级为 committed(在 InboundDirectLog 中更新状态) diff --git a/app/service/systems/storage/entry.js b/app/service/systems/storage/entry.js index 802ffd7..466187c 100644 --- a/app/service/systems/storage/entry.js +++ b/app/service/systems/storage/entry.js @@ -1,8 +1,17 @@ '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 Service = require('egg').Service; const { parseWhereConditions } = require('../../../lib/query_condition_parser'); +const ENTRY_EXPORT_PAGE_SIZE = 200; +const ENTRY_ITEMS_FETCH_BATCH_SIZE = 100; + class EntryService extends Service { /** * 将费用记录筛选值归一化为 0/1。 @@ -1290,23 +1299,36 @@ class EntryService extends Service { return { code: 200, message: 'ok', data: { list: [], total: 0 } }; } - // 3. 排除已绑定的收货明细(wms_inbound_direct_log 中有记录且未软删除) - const notBoundCondition = app.Sequelize.literal( - 'NOT EXISTS (SELECT 1 FROM wms_inbound_direct_log erb WHERE erb.receiving_detail_id = wms_receiving_detail.id AND erb.deleted_at IS NULL)' - ); - - // 4. 查询指定商品的未绑定收货明细 + // 3. 查询指定商品的所有收货明细(不再一刀切排除已绑定,改为按可用量过滤) const details = await ctx.model.ReceivingDetail.findAll({ where: { - [app.Sequelize.Op.and]: [ - { system_product_id: stockId }, - { receiving_id: { [app.Sequelize.Op.in]: receivingIds } }, - notBoundCondition, - ], + system_product_id: stockId, + receiving_id: { [app.Sequelize.Op.in]: receivingIds }, }, raw: true, }); + // 4. 查询每个明细的已入库数量(pending + committed,与 getReceivingDetailsForBind 一致) + const detailIds = details.map(d => d.id); + const usedMap = new Map(); + if (detailIds.length > 0) { + const usedRows = await ctx.model.query( + `SELECT receiving_detail_id, COALESCE(SUM(quantity), 0) AS used_qty + FROM wms_inbound_direct_log + WHERE receiving_detail_id IN (:ids) + AND status IN ('pending', 'committed') + AND deleted_at IS NULL + GROUP BY receiving_detail_id`, + { + replacements: { ids: detailIds }, + type: ctx.model.QueryTypes.SELECT, + } + ); + for (const row of usedRows) { + usedMap.set(row.receiving_detail_id, Number(row.used_qty)); + } + } + // 5. 收集所有明细的 system_product_id,批量获取 stock 详情 const stockIdSet = new Set(); for (const d of details) { @@ -1327,16 +1349,22 @@ class EntryService extends Service { } } - // 6. 组装返回结果 - const list = details.map(detail => ({ - detail_id: detail.id, - receiving_id: detail.receiving_id, - barcode: detail.barcode || '', - product_name: detail.product_name || '', - actual_quantity: detail.actual_quantity || 0, - receiving_status: detail.receiving_status || '', - stock: stockDetailMap.get(Number(detail.system_product_id)) || null, - })); + // 6. 组装返回结果:actual_quantity 扣除已入库数量,只返回有可用量的明细 + const list = details + .map(detail => { + const used = usedMap.get(detail.id) || 0; + const available = Math.max(0, (detail.actual_quantity || 0) - used); + return { + detail_id: detail.id, + receiving_id: detail.receiving_id, + barcode: detail.barcode || '', + product_name: detail.product_name || '', + actual_quantity: available, + receiving_status: detail.receiving_status || '', + stock: stockDetailMap.get(Number(detail.system_product_id)) || null, + }; + }) + .filter(detail => detail.actual_quantity > 0); return { code: 200, @@ -1951,6 +1979,931 @@ class EntryService extends Service { }; } + /** + * 导出入库单列表及明细(两 Sheet)。 + * Sheet1: 入库单列表(wms_entry_order 关键字段) + * Sheet2: 入库单明细(wms_entry_items + wms_stock_warehouse) + * + * @param {Object} options 导出参数 + * @param {Object} [options.where] 筛选条件(与 list 一致) + * @param {Object} [options.sort] 排序参数 + * @param {Function} [options.onProgress] 进度回调 + * @return {Promise} 上传结果与统计信息 + */ + async exportEntryOrders(options = {}) { + const { ctx, app } = this; + const { Sequelize } = app; + const { Op } = Sequelize; + const safeOptions = this.isPlainObject ? (this.isPlainObject(options) ? options : {}) : (options && typeof options === 'object' ? options : {}); + const where = safeOptions.where && typeof safeOptions.where === 'object' ? { ...safeOptions.where } : {}; + const sort = safeOptions.sort && typeof safeOptions.sort === 'object' ? { ...safeOptions.sort } : {}; + const progressHandler = typeof safeOptions.onProgress === 'function' + ? safeOptions.onProgress + : async () => {}; + + const warehouseId = Number(ctx.user && ctx.user.store_id); + if (!warehouseId) { + throw new Error('用户未绑定仓库,无法导出'); + } + + const sortField = sort.sortField || 'created_at'; + const sortOrder = String(sort.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; + const validSortFields = [ + 'id', 'entry_order_code', 'order_type', 'order_status', + 'order_create_time', 'created_at', 'updated_at', 'total_order_lines', + ]; + const actualSortField = validSortFields.includes(sortField) ? sortField : 'created_at'; + + const baseWhere = { warehouse_id: warehouseId, is_enabled: 1, deleted_at: null }; + + // ---- 复用 list 的 where 构建逻辑 ---- + const normalizedWhere = { ...where }; + const { + where: parsedSourceWhere, + extraConditions, + errorMessage, + } = await this.preprocessEntryListWhere(normalizedWhere); + + if (errorMessage) { + throw new Error(errorMessage); + } + + const parsed = parseWhereConditions({ + where: parsedSourceWhere, + app, + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + + if (!parsed.ok) { + throw new Error(`筛选条件解析失败: ${parsed.reason}`); + } + const parsedResult = parsed.result; + + const quickWhereInput = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere) + || parsedSourceWhere.quickWhere + || null; + const quickWhereValue = quickWhereInput && typeof quickWhereInput === 'object' + ? quickWhereInput.value + : null; + + const andConditions = [ baseWhere ]; + if (quickWhereValue !== undefined && quickWhereValue !== null && String(quickWhereValue).trim() !== '') { + const kw = String(quickWhereValue).trim(); + const receivingDetailId = Number(kw); + const escapedKw = app.model.escape(`%${kw}%`); + const orConditions = [ + { entry_order_code: { [Op.like]: `%${kw}%` } }, + { purchase_order_code: { [Op.like]: `%${kw}%` } }, + { supplier_name: { [Op.like]: `%${kw}%` } }, + { store_name: { [Op.like]: `%${kw}%` } }, + { warehouse_name: { [Op.like]: `%${kw}%` } }, + Sequelize.where(Sequelize.literal( + `EXISTS ( + SELECT 1 FROM wms_entry_order_receiving eor + JOIN wms_receiving r ON r.id = eor.receiving_id + WHERE eor.entry_order_id = wms_entry_order.id + AND eor.deleted_at IS NULL + AND r.receiving_number LIKE ${escapedKw} + )` + ), 1), + ...(Number.isFinite(receivingDetailId) && receivingDetailId > 0 ? [ + Sequelize.where(Sequelize.literal( + `EXISTS ( + SELECT 1 FROM wms_entry_order_receiving eor + JOIN wms_receiving_detail rd ON rd.receiving_id = eor.receiving_id + WHERE eor.entry_order_id = wms_entry_order.id + AND eor.deleted_at IS NULL + AND rd.id = ${receivingDetailId} + )` + ), 1), + ] : []), + ]; + andConditions.push({ [Op.or]: orConditions }); + } + + const dynamicConditions = parsedResult.dynamicConditions || []; + if (dynamicConditions.length > 0) { + andConditions.push({ [Op.and]: dynamicConditions }); + } + if (extraConditions.length > 0) { + andConditions.push({ [Op.and]: extraConditions }); + } + + const finalWhere = { [Op.and]: andConditions }; + + // ---- 分页拉取入库单列表 ---- + const pageSize = ENTRY_EXPORT_PAGE_SIZE; + const totalCount = await ctx.model.EntryOrder.count({ where: finalWhere }); + + await progressHandler({ + status: 'running', + progress: totalCount > 0 ? 10 : 90, + message: totalCount > 0 ? `已命中 ${totalCount} 条入库单,开始导出` : '未命中数据,开始生成空文件', + }); + + // 收集所有入库单 ID,供后续批量查明细 + const allEntryOrders = []; + let page = 1; + let fetchedCount = 0; + + while (fetchedCount < totalCount) { + const rows = await ctx.model.EntryOrder.findAll({ + where: finalWhere, + order: [[ actualSortField, sortOrder ]], + limit: pageSize, + offset: (page - 1) * pageSize, + raw: true, + }); + + if (!Array.isArray(rows) || rows.length === 0) { + break; + } + + allEntryOrders.push(...rows); + fetchedCount += rows.length; + page += 1; + + await progressHandler({ + status: 'running', + progress: Math.min(30, 10 + Math.round((fetchedCount / Math.max(totalCount, 1)) * 20)), + message: `正在拉取入库单列表,已完成 ${fetchedCount}/${totalCount}`, + }); + } + + // 收集所有入库单 ID + const allEntryOrderIds = allEntryOrders.map(r => Number(r.id)).filter(Boolean); + + // ---- 分批拉取入库单明细 ---- + /** @type {Map>} entry_order_id → items */ + const itemsMap = new Map(); + /** @type {Set} 所有涉及的商品 stock_id */ + const allStockIds = new Set(); + + if (allEntryOrderIds.length > 0) { + const batchSize = ENTRY_ITEMS_FETCH_BATCH_SIZE; + const totalBatches = Math.ceil(allEntryOrderIds.length / batchSize); + + for (let batchIdx = 0; batchIdx < allEntryOrderIds.length; batchIdx += batchSize) { + const batchIds = allEntryOrderIds.slice(batchIdx, batchIdx + batchSize); + + const items = await ctx.model.EntryItems.findAll({ + where: { order_id: { [Op.in]: batchIds } }, + order: [[ 'order_id', 'ASC' ], [ 'order_line_no', 'ASC' ]], + raw: true, + }); + + for (const item of items) { + const eid = Number(item.order_id); + if (!itemsMap.has(eid)) { + itemsMap.set(eid, []); + } + itemsMap.get(eid).push(item); + if (item.stock_id) { + allStockIds.add(Number(item.stock_id)); + } + } + + const currentBatch = Math.floor(batchIdx / batchSize) + 1; + await progressHandler({ + status: 'running', + progress: Math.min(50, 30 + Math.round((currentBatch / totalBatches) * 20)), + message: `正在拉取入库单明细,已完成批次 ${currentBatch}/${totalBatches}`, + }); + } + } + + // ---- 批量查询商品名称(wms_stock_warehouse) ---- + /** @type {Map} stock_id → { item_name, sku_property, item_code } */ + const stockInfoMap = new Map(); + if (allStockIds.size > 0) { + const stockIdsArr = [ ...allStockIds ]; + try { + const stockRows = await ctx.model.StockWarehouse.findAll({ + where: { id: { [Op.in]: stockIdsArr }, warehouse_id: warehouseId }, + attributes: [ 'id', 'item_code', 'item_name', 'sku_property' ], + raw: true, + }); + for (const s of stockRows) { + stockInfoMap.set(Number(s.id), { + item_code: s.item_code || '', + item_name: s.item_name || '', + sku_property: s.sku_property || '', + }); + } + } catch (err) { + ctx.logger.warn(`[exportEntryOrders] 批量查询商品信息失败: ${err.message}`); + } + } + + await progressHandler({ + status: 'running', + progress: 55, + message: '正在生成 Excel 文件...', + }); + + // ---- 生成 Excel(流式写入,两个 Sheet) ---- + const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-entry-export-')); + const now = new Date(); + const dateToken = `${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 = `入库单导出_${dateToken}.xlsx`; + const filePath = path.join(tempDir, filename); + const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({ + filename: filePath, + useStyles: false, + useSharedStrings: false, + }); + + // Sheet 1: 入库单列表 + const sheet1 = workbook.addWorksheet('入库单列表'); + const entryOrderColumns = [ + { header: '入库单号', key: 'entry_order_code', width: 22 }, + { header: '业务类型', key: 'order_type', width: 10 }, + { header: '采购单号', key: 'purchase_order_code', width: 22 }, + { header: '订单状态', key: 'order_status', width: 12 }, + { header: '供应商编码', key: 'supplier_code', width: 16 }, + { header: '供应商名称', key: 'supplier_name', width: 24 }, + { header: '物流公司', key: 'logistics_name', width: 20 }, + { header: '运单号', key: 'express_code', width: 22 }, + { header: '货主', key: 'store_name', width: 24 }, + { header: '仓库', key: 'warehouse_name', width: 24 }, + { header: '总行数', key: 'total_order_lines', width: 10 }, + { header: '来源类型', key: 'source_type', width: 10 }, + { header: '状态', key: 'sync_status', width: 12 }, + { header: 'ERP备注', key: 'remark', width: 30 }, + { header: '费用记录', key: 'expense_record', width: 10 }, + { header: '预期到货时间', key: 'expect_start_time', width: 20 }, + { header: '最迟预期到货时间', key: 'expect_end_time', width: 20 }, + { header: '订单创建时间', key: 'order_create_time', width: 20 }, + { header: '创建时间', key: 'created_at', width: 20 }, + { header: '更新时间', key: 'updated_at', width: 20 }, + ]; + sheet1.columns = entryOrderColumns; + + const statusLabelMap = { + CREATING: '创建中', + CREATED: '已创建', + PENDING: '已审核', + COMPLETED: '已完成', + CANCELLED: '已作废', + }; + + const syncStatusLabelMap = { + PENDING: '待同步', + SUCCESS: '成功', + FAILED: '失败', + }; + + const normalizeCellValue = value => { + if (value === null || value === undefined) return ''; + if (value instanceof Date) return app.formatDate ? app.formatDate(value) : value.toISOString(); + return value; + }; + + const orderTypeLabelMap = { + SCRK: '收货入库', + LYRK: '领用入库', + CCRK: '残次入库', + CGRK: '采购入库', + DBRK: '调拨入库', + QTRK: '其他入库', + B2BRK: 'B2B入库', + XNRK: '虚拟入库', + SHRK: '损耗入库', + }; + + for (const row of allEntryOrders) { + sheet1.addRow({ + entry_order_code: normalizeCellValue(row.entry_order_code), + order_type: orderTypeLabelMap[row.order_type] || row.order_type || '', + purchase_order_code: normalizeCellValue(row.purchase_order_code), + order_status: statusLabelMap[row.order_status] || row.order_status || '', + supplier_code: normalizeCellValue(row.supplier_code), + supplier_name: normalizeCellValue(row.supplier_name), + logistics_name: normalizeCellValue(row.logistics_name), + express_code: normalizeCellValue(row.express_code), + store_name: normalizeCellValue(row.store_name), + warehouse_name: normalizeCellValue(row.warehouse_name), + total_order_lines: row.total_order_lines, + source_type: normalizeCellValue(row.source_type), + sync_status: syncStatusLabelMap[row.sync_status] || row.sync_status || '', + remark: normalizeCellValue(row.remark), + expense_record: row.expense_record === 1 ? '是' : (row.expense_record === 0 ? '否' : ''), + expect_start_time: normalizeCellValue(row.expect_start_time), + expect_end_time: normalizeCellValue(row.expect_end_time), + order_create_time: normalizeCellValue(row.order_create_time), + created_at: normalizeCellValue(row.created_at), + updated_at: normalizeCellValue(row.updated_at), + }).commit(); + } + sheet1.commit(); + + await progressHandler({ + status: 'running', + progress: 70, + message: '正在写入入库单明细...', + }); + + // Sheet 2: 入库单明细 + const sheet2 = workbook.addWorksheet('入库单明细'); + const entryItemColumns = [ + { header: '入库单号', key: 'entry_order_code', width: 22 }, + { header: '入库单ID', key: 'entry_order_id', width: 12 }, + { header: '行号', key: 'order_line_no', width: 8 }, + { header: '商品编码', key: 'item_code', width: 20 }, + { header: '商品名称', key: 'item_name', width: 28 }, + { header: '商品规格', key: 'sku_property', width: 24 }, + { header: '计划入库数量', key: 'plan_quantity', width: 14 }, + { header: '已收货数量', key: 'received_quantity', width: 14 }, + { header: '已通知数量', key: 'confirm_quantity', width: 14 }, + { header: '库存类型', key: 'inventory_type', width: 14 }, + { header: '外部业务编码', key: 'out_biz_code', width: 24 }, + { header: '货主编码', key: 'owner_code', width: 16 }, + { header: '商品ID', key: 'item_id', width: 12 }, + { header: '商品SKU ID', key: 'stock_id', width: 12 }, + ]; + sheet2.columns = entryItemColumns; + + // 构建 entry_order_code 映射 + const entryOrderCodeMap = new Map(); + for (const row of allEntryOrders) { + entryOrderCodeMap.set(Number(row.id), row.entry_order_code || ''); + } + + // 按入库单分页写入明细 + const itemBatchSize = ENTRY_ITEMS_FETCH_BATCH_SIZE; + let itemWrittenCount = 0; + const totalEntryOrders = allEntryOrderIds.length; + + for (let batchIdx = 0; batchIdx < allEntryOrderIds.length; batchIdx += itemBatchSize) { + const batchIds = allEntryOrderIds.slice(batchIdx, batchIdx + itemBatchSize); + + for (const eid of batchIds) { + const entryOrderCode = entryOrderCodeMap.get(eid) || ''; + const items = itemsMap.get(eid) || []; + + for (const item of items) { + const stockId = Number(item.stock_id || 0); + const stockInfo = stockInfoMap.get(stockId) || {}; + + sheet2.addRow({ + entry_order_code: entryOrderCode, + entry_order_id: eid, + order_line_no: item.order_line_no ?? '', + item_code: stockInfo.item_code || item.item_code || '', + item_name: stockInfo.item_name || '', + sku_property: stockInfo.sku_property || '', + plan_quantity: item.count ?? 0, + received_quantity: item.received_quantity ?? 0, + confirm_quantity: item.confirm_quantity ?? 0, + inventory_type: normalizeCellValue(item.inventory_type), + out_biz_code: normalizeCellValue(item.out_biz_code), + owner_code: normalizeCellValue(item.owner_code), + item_id: normalizeCellValue(item.item_id), + stock_id: item.stock_id ?? '', + }).commit(); + } + + itemWrittenCount += 1; + } + + const currentBatch = Math.floor(batchIdx / itemBatchSize) + 1; + const totalBatches = Math.ceil(totalEntryOrders / itemBatchSize); + await progressHandler({ + status: 'running', + progress: Math.min(90, 70 + Math.round((currentBatch / totalBatches) * 20)), + message: `正在写入入库单明细,已完成 ${itemWrittenCount}/${totalEntryOrders} 条入库单`, + }); + } + sheet2.commit(); + + await workbook.commit(); + + await progressHandler({ + status: 'running', + progress: 92, + message: '正在上传文件...', + }); + + // ---- 上传文件 ---- + const uploadService = ctx?.service?.systems?.upload; + if (!uploadService || typeof uploadService.uploadFile !== 'function') { + throw new Error('上传服务不可用'); + } + + const stat = await fsp.stat(filePath); + const randomToken = crypto.randomBytes(6).toString('hex'); + const uploadKey = `exports/entry/${warehouseId}/${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', + }); + + 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: 'entryExport', + businessId: `${warehouseId}`, + uploaderType: ctx?.user?.role || 'system_api', + uploaderDept: ctx?.user?.department || '', + }); + } + + const result = { + filename, + fileKey: uploadResult.fileName, + url: uploadResult.url || uploadResult.cdnUrl || uploadResult.cosUrl || '', + cdnUrl: uploadResult.cdnUrl || uploadResult.url || '', + cosUrl: uploadResult.cosUrl || '', + total_count: totalCount, + fileRecord: fileRecord?.data || fileRecord || null, + }; + + // 清理临时目录 + await fsp.rm(tempDir, { recursive: true, force: true }); + + await progressHandler({ + status: 'success', + progress: 100, + message: '导出完成', + result, + }); + + return result; + } + + /** + * 导出货主侧入库单列表(双 sheet:入库单列表 + 入库单明细)。 + * 复用 list 的筛选与排序语义,以货主维度(store_id)过滤,分页拉取全量数据后生成 Excel 并上传。 + * @param {Object} options 导出选项 + * @param {Object} [options.where] 筛选条件(与 listStore 一致) + * @param {Object} [options.sort] 排序参数 + * @param {Function} [options.onProgress] 进度回调 + * @return {Promise} 上传结果与统计信息 + */ + async exportStoreEntryOrders(options = {}) { + const { ctx, app } = this; + const { Sequelize } = app; + const { Op } = Sequelize; + const safeOptions = options && typeof options === 'object' ? options : {}; + const where = safeOptions.where && typeof safeOptions.where === 'object' ? { ...safeOptions.where } : {}; + const sort = safeOptions.sort && typeof safeOptions.sort === 'object' ? { ...safeOptions.sort } : {}; + const progressHandler = typeof safeOptions.onProgress === 'function' + ? safeOptions.onProgress + : async () => {}; + + const storeId = Number(ctx.user && ctx.user.store_id); + if (!storeId) { + throw new Error('用户未绑定货主,无法导出'); + } + + const sortField = sort.sortField || 'created_at'; + const sortOrder = String(sort.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; + const validSortFields = [ + 'id', 'entry_order_code', 'order_type', 'order_status', + 'order_create_time', 'created_at', 'updated_at', 'total_order_lines', + ]; + const actualSortField = validSortFields.includes(sortField) ? sortField : 'created_at'; + + const baseWhere = { store_id: storeId, is_enabled: 1, deleted_at: null }; + + // ---- 复用 listStore 的 where 构建逻辑 ---- + const normalizedWhere = { ...where }; + const { + where: parsedSourceWhere, + extraConditions, + errorMessage, + } = await this.preprocessEntryListWhere(normalizedWhere); + + if (errorMessage) { + throw new Error(errorMessage); + } + + const parsed = parseWhereConditions({ + where: parsedSourceWhere, + app, + specialFieldMap: { + quickWhere: { bucket: 'quick' }, + }, + }); + + if (!parsed.ok) { + throw new Error(`筛选条件解析失败: ${parsed.reason}`); + } + const parsedResult = parsed.result; + + const quickWhereInput = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere) + || parsedSourceWhere.quickWhere + || null; + const quickWhereValue = quickWhereInput && typeof quickWhereInput === 'object' + ? quickWhereInput.value + : null; + + const andConditions = [ baseWhere ]; + if (quickWhereValue !== undefined && quickWhereValue !== null && String(quickWhereValue).trim() !== '') { + const kw = String(quickWhereValue).trim(); + const receivingDetailId = Number(kw); + const escapedKw = app.model.escape(`%${kw}%`); + const orConditions = [ + { entry_order_code: { [Op.like]: `%${kw}%` } }, + { purchase_order_code: { [Op.like]: `%${kw}%` } }, + { supplier_name: { [Op.like]: `%${kw}%` } }, + { store_name: { [Op.like]: `%${kw}%` } }, + { warehouse_name: { [Op.like]: `%${kw}%` } }, + Sequelize.where(Sequelize.literal( + `EXISTS ( + SELECT 1 FROM wms_entry_order_receiving eor + JOIN wms_receiving r ON r.id = eor.receiving_id + WHERE eor.entry_order_id = wms_entry_order.id + AND eor.deleted_at IS NULL + AND r.receiving_number LIKE ${escapedKw} + )` + ), 1), + ...(Number.isFinite(receivingDetailId) && receivingDetailId > 0 ? [ + Sequelize.where(Sequelize.literal( + `EXISTS ( + SELECT 1 FROM wms_entry_order_receiving eor + JOIN wms_receiving_detail rd ON rd.receiving_id = eor.receiving_id + WHERE eor.entry_order_id = wms_entry_order.id + AND eor.deleted_at IS NULL + AND rd.id = ${receivingDetailId} + )` + ), 1), + ] : []), + ]; + andConditions.push({ [Op.or]: orConditions }); + } + + const dynamicConditions = parsedResult.dynamicConditions || []; + if (dynamicConditions.length > 0) { + andConditions.push({ [Op.and]: dynamicConditions }); + } + if (extraConditions.length > 0) { + andConditions.push({ [Op.and]: extraConditions }); + } + + const finalWhere = { [Op.and]: andConditions }; + + // ---- 分页拉取入库单列表 ---- + const pageSize = ENTRY_EXPORT_PAGE_SIZE; + const totalCount = await ctx.model.EntryOrder.count({ where: finalWhere }); + + await progressHandler({ + status: 'running', + progress: totalCount > 0 ? 10 : 90, + message: totalCount > 0 ? `已命中 ${totalCount} 条货主侧入库单,开始导出` : '未命中数据,开始生成空文件', + }); + + const allEntryOrders = []; + let page = 1; + let fetchedCount = 0; + + while (fetchedCount < totalCount) { + const rows = await ctx.model.EntryOrder.findAll({ + where: finalWhere, + order: [[ actualSortField, sortOrder ]], + limit: pageSize, + offset: (page - 1) * pageSize, + raw: true, + }); + + if (!Array.isArray(rows) || rows.length === 0) { + break; + } + + allEntryOrders.push(...rows); + fetchedCount += rows.length; + page += 1; + + await progressHandler({ + status: 'running', + progress: Math.min(30, 10 + Math.round((fetchedCount / Math.max(totalCount, 1)) * 20)), + message: `正在拉取货主侧入库单列表,已完成 ${fetchedCount}/${totalCount}`, + }); + } + + const allEntryOrderIds = allEntryOrders.map(r => Number(r.id)).filter(Boolean); + + // ---- 分批拉取入库单明细 ---- + /** @type {Map>} */ + const itemsMap = new Map(); + /** @type {Set} */ + const allStockIds = new Set(); + + if (allEntryOrderIds.length > 0) { + const batchSize = ENTRY_ITEMS_FETCH_BATCH_SIZE; + const totalBatches = Math.ceil(allEntryOrderIds.length / batchSize); + + for (let batchIdx = 0; batchIdx < allEntryOrderIds.length; batchIdx += batchSize) { + const batchIds = allEntryOrderIds.slice(batchIdx, batchIdx + batchSize); + + const items = await ctx.model.EntryItems.findAll({ + where: { order_id: { [Op.in]: batchIds } }, + order: [[ 'order_id', 'ASC' ], [ 'order_line_no', 'ASC' ]], + raw: true, + }); + + for (const item of items) { + const eid = Number(item.order_id); + if (!itemsMap.has(eid)) { + itemsMap.set(eid, []); + } + itemsMap.get(eid).push(item); + if (item.stock_id) { + allStockIds.add(Number(item.stock_id)); + } + } + + const currentBatch = Math.floor(batchIdx / batchSize) + 1; + await progressHandler({ + status: 'running', + progress: Math.min(50, 30 + Math.round((currentBatch / totalBatches) * 20)), + message: `正在拉取货主侧入库单明细,已完成批次 ${currentBatch}/${totalBatches}`, + }); + } + } + + // ---- 批量查询商品名称(按 store_id) ---- + /** @type {Map} */ + const stockInfoMap = new Map(); + if (allStockIds.size > 0) { + const stockIdsArr = [ ...allStockIds ]; + try { + const stockRows = await ctx.model.StockWarehouse.findAll({ + where: { id: { [Op.in]: stockIdsArr }, store_id: storeId }, + attributes: [ 'id', 'item_code', 'item_name', 'sku_property' ], + raw: true, + }); + for (const s of stockRows) { + stockInfoMap.set(Number(s.id), { + item_code: s.item_code || '', + item_name: s.item_name || '', + sku_property: s.sku_property || '', + }); + } + } catch (err) { + ctx.logger.warn(`[exportStoreEntryOrders] 批量查询商品信息失败: ${err.message}`); + } + } + + await progressHandler({ + status: 'running', + progress: 55, + message: '正在生成 Excel 文件...', + }); + + // ---- 生成 Excel ---- + const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-store-entry-export-')); + const now = new Date(); + const dateToken = `${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 = `货主侧入库单导出_${dateToken}.xlsx`; + const filePath = path.join(tempDir, filename); + const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({ + filename: filePath, + useStyles: false, + useSharedStrings: false, + }); + + const normalizeCellValue = value => { + if (value === null || value === undefined) return ''; + if (value instanceof Date) return app.formatDate ? app.formatDate(value) : value.toISOString(); + return value; + }; + + const statusLabelMap = { + CREATING: '创建中', + CREATED: '已创建', + PENDING: '已审核', + COMPLETED: '已完成', + CANCELLED: '已作废', + }; + + const syncStatusLabelMap = { + PENDING: '待同步', + SUCCESS: '成功', + FAILED: '失败', + }; + + const orderTypeLabelMap = { + SCRK: '收货入库', + LYRK: '领用入库', + CCRK: '残次入库', + CGRK: '采购入库', + DBRK: '调拨入库', + QTRK: '其他入库', + B2BRK: 'B2B入库', + XNRK: '虚拟入库', + SHRK: '损耗入库', + }; + + // Sheet 1: 入库单列表(货主侧,不显示仓库字段) + const sheet1 = workbook.addWorksheet('入库单列表'); + const entryOrderColumns = [ + { header: '入库单号', key: 'entry_order_code', width: 22 }, + { header: '业务类型', key: 'order_type', width: 10 }, + { header: '采购单号', key: 'purchase_order_code', width: 22 }, + { header: '订单状态', key: 'order_status', width: 12 }, + { header: '供应商编码', key: 'supplier_code', width: 16 }, + { header: '供应商名称', key: 'supplier_name', width: 24 }, + { header: '物流公司', key: 'logistics_name', width: 20 }, + { header: '运单号', key: 'express_code', width: 22 }, + { header: '仓库', key: 'warehouse_name', width: 24 }, + { header: '总行数', key: 'total_order_lines', width: 10 }, + { header: '来源类型', key: 'source_type', width: 10 }, + { header: '状态', key: 'sync_status', width: 12 }, + { header: 'ERP备注', key: 'remark', width: 30 }, + { header: '费用记录', key: 'expense_record', width: 10 }, + { header: '预期到货时间', key: 'expect_start_time', width: 20 }, + { header: '最迟预期到货时间', key: 'expect_end_time', width: 20 }, + { header: '订单创建时间', key: 'order_create_time', width: 20 }, + { header: '创建时间', key: 'created_at', width: 20 }, + { header: '更新时间', key: 'updated_at', width: 20 }, + ]; + sheet1.columns = entryOrderColumns; + + for (const row of allEntryOrders) { + sheet1.addRow({ + entry_order_code: normalizeCellValue(row.entry_order_code), + order_type: orderTypeLabelMap[row.order_type] || row.order_type || '', + purchase_order_code: normalizeCellValue(row.purchase_order_code), + order_status: statusLabelMap[row.order_status] || row.order_status || '', + supplier_code: normalizeCellValue(row.supplier_code), + supplier_name: normalizeCellValue(row.supplier_name), + logistics_name: normalizeCellValue(row.logistics_name), + express_code: normalizeCellValue(row.express_code), + warehouse_name: normalizeCellValue(row.warehouse_name), + total_order_lines: row.total_order_lines, + source_type: normalizeCellValue(row.source_type), + sync_status: syncStatusLabelMap[row.sync_status] || row.sync_status || '', + remark: normalizeCellValue(row.remark), + expense_record: row.expense_record === 1 ? '是' : (row.expense_record === 0 ? '否' : ''), + expect_start_time: normalizeCellValue(row.expect_start_time), + expect_end_time: normalizeCellValue(row.expect_end_time), + order_create_time: normalizeCellValue(row.order_create_time), + created_at: normalizeCellValue(row.created_at), + updated_at: normalizeCellValue(row.updated_at), + }).commit(); + } + sheet1.commit(); + + await progressHandler({ + status: 'running', + progress: 70, + message: '正在写入入库单明细...', + }); + + // Sheet 2: 入库单明细 + const sheet2 = workbook.addWorksheet('入库单明细'); + const entryItemColumns = [ + { header: '入库单号', key: 'entry_order_code', width: 22 }, + { header: '入库单ID', key: 'entry_order_id', width: 12 }, + { header: '行号', key: 'order_line_no', width: 8 }, + { header: '商品编码', key: 'item_code', width: 20 }, + { header: '商品名称', key: 'item_name', width: 28 }, + { header: '商品规格', key: 'sku_property', width: 24 }, + { header: '计划入库数量', key: 'plan_quantity', width: 14 }, + { header: '已收货数量', key: 'received_quantity', width: 14 }, + { header: '已通知数量', key: 'confirm_quantity', width: 14 }, + { header: '库存类型', key: 'inventory_type', width: 14 }, + { header: '外部业务编码', key: 'out_biz_code', width: 24 }, + { header: '货主编码', key: 'owner_code', width: 16 }, + { header: '商品ID', key: 'item_id', width: 12 }, + { header: '商品SKU ID', key: 'stock_id', width: 12 }, + ]; + sheet2.columns = entryItemColumns; + + const entryOrderCodeMap = new Map(); + for (const row of allEntryOrders) { + entryOrderCodeMap.set(Number(row.id), row.entry_order_code || ''); + } + + const itemBatchSize = ENTRY_ITEMS_FETCH_BATCH_SIZE; + let itemWrittenCount = 0; + const totalEntryOrders = allEntryOrderIds.length; + + for (let batchIdx = 0; batchIdx < allEntryOrderIds.length; batchIdx += itemBatchSize) { + const batchIds = allEntryOrderIds.slice(batchIdx, batchIdx + itemBatchSize); + + for (const eid of batchIds) { + const entryOrderCode = entryOrderCodeMap.get(eid) || ''; + const items = itemsMap.get(eid) || []; + + for (const item of items) { + const stockId = Number(item.stock_id || 0); + const stockInfo = stockInfoMap.get(stockId) || {}; + + sheet2.addRow({ + entry_order_code: entryOrderCode, + entry_order_id: eid, + order_line_no: item.order_line_no ?? '', + item_code: stockInfo.item_code || item.item_code || '', + item_name: stockInfo.item_name || '', + sku_property: stockInfo.sku_property || '', + plan_quantity: item.count ?? 0, + received_quantity: item.received_quantity ?? 0, + confirm_quantity: item.confirm_quantity ?? 0, + inventory_type: normalizeCellValue(item.inventory_type), + out_biz_code: normalizeCellValue(item.out_biz_code), + owner_code: normalizeCellValue(item.owner_code), + item_id: normalizeCellValue(item.item_id), + stock_id: item.stock_id ?? '', + }).commit(); + } + + itemWrittenCount += 1; + } + + const currentBatch = Math.floor(batchIdx / itemBatchSize) + 1; + const totalBatches = Math.ceil(totalEntryOrders / itemBatchSize); + await progressHandler({ + status: 'running', + progress: Math.min(90, 70 + Math.round((currentBatch / totalBatches) * 20)), + message: `正在写入入库单明细,已完成 ${itemWrittenCount}/${totalEntryOrders} 条入库单`, + }); + } + sheet2.commit(); + + await workbook.commit(); + + await progressHandler({ + status: 'running', + progress: 92, + message: '正在上传文件...', + }); + + // ---- 上传文件 ---- + const uploadService = ctx?.service?.systems?.upload; + if (!uploadService || typeof uploadService.uploadFile !== 'function') { + throw new Error('上传服务不可用'); + } + + const stat = await fsp.stat(filePath); + const randomToken = crypto.randomBytes(6).toString('hex'); + const uploadKey = `exports/entry/store/${storeId}/${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', + }); + + 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, + userId: ctx.userId, + description: `货主侧入库单导出(货主${storeId}),共${totalCount}条入库单`, + }); + } + + // 清理临时文件 + try { await fsp.rm(tempDir, { recursive: true, force: true }); } catch (_) { /* ignore */ } + + const uploadInfo = fileRecord || uploadResult; + const fileUrl = typeof uploadInfo === 'object' && uploadInfo.url + ? uploadInfo.url + : (typeof uploadResult === 'object' ? uploadResult.fileName : ''); + + await progressHandler({ + status: 'running', + progress: 100, + message: '货主侧导出完成', + result: { url: fileUrl, fileKey: uploadKey }, + }); + + return { + url: fileUrl, + fileKey: uploadKey, + total: totalCount, + totalDetails: allEntryOrderIds.reduce((sum, eid) => sum + (itemsMap.get(eid) || []).length, 0), + }; + } + } module.exports = EntryService;