'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; /** 盘点范围类型枚举(wms_stock_check.type) */ const STOCK_CHECK_TYPES = Object.freeze([ 'all', 'store', 'goods', 'location' ]); /** 盘点方式枚举(wms_stock_check.mode) */ const STOCK_CHECK_MODES = Object.freeze([ 'open', 'blind' ]); /** 允许添加明细的主表状态 */ const ADD_DETAIL_ALLOWED_STATUSES = Object.freeze([ 'created', 'rejected' ]); /** 允许盘点作业上报/完成的主表状态 */ const REPORT_ALLOWED_STATUSES = Object.freeze([ 'approved', 'checking' ]); /** 允许提交审核的主表状态 */ const SUBMIT_ALLOWED_STATUSES = Object.freeze([ 'created', 'rejected' ]); /** 允许取消的主表状态 */ const CANCEL_ALLOWED_STATUSES = Object.freeze([ 'created', 'submitted', 'rejected' ]); /** 盘点范围类型中文标签 */ const STOCK_CHECK_TYPE_LABELS = Object.freeze({ all: '全盘', store: '按货主', goods: '按商品', location: '按库位', }); /** 盘点方式中文标签 */ const STOCK_CHECK_MODE_LABELS = Object.freeze({ open: '明盘', blind: '盲盘', }); /** 主表状态中文标签 */ const STOCK_CHECK_STATUS_LABELS = Object.freeze({ created: '已创建', submitted: '待审核', rejected: '已驳回', approved: '审核完成', checking: '盘点作业中', completed: '已完成', cancelled: '已取消', }); /** 明细盘点进度中文标签(主表 detail_status) */ const STOCK_CHECK_DETAIL_PROGRESS_LABELS = Object.freeze({ none_checked: '未盘', partial_checked: '部分已盘', all_checked: '全部已盘', }); /** * 库存盘点模块业务逻辑层。 * 负责 wms_stock_check(主表)/ wms_stock_check_detail(明细)的状态机流转与增删查, * 以及导出 Excel 生成与 COS 上传等核心操作。 * 所有数据库交互集中在此层,供 systemMethods/stock/check.js 调用。 */ class StockCheckService extends Service { /** * 创建带业务错误码的异常对象。 * * @param {string} message 错误信息。 * @param {number} [code=400] 业务错误码。 * @return {Error} 包含 code 的异常对象。 */ createBusinessError(message, code = 400) { const error = new Error(`${message}`); error.code = code; return error; } /** * 获取当前日期片段(YYYYMMDD)。 * * @return {string} 当前日期片段。 */ _getCurrentDatePart() { const now = new Date(); const year = now.getFullYear(); const month = String(now.getMonth() + 1).padStart(2, '0'); const day = String(now.getDate()).padStart(2, '0'); return `${year}${month}${day}`; } /** * 生成盘点单号。 * 格式:PD + YYYYMMDD + 6位序号(如 PD20260929000001)。 * 序号全局递增(不按仓库隔离):uk_check_no 为全局唯一索引,按仓各自从 1 起会跨仓撞号; * 并发创建时的撞号由 create 方法的唯一键重试兜底(参照收货单 receiving_number 口径)。 * * @return {Promise} 盘点单号。 */ async generateCheckNo() { const { ctx } = this; const datePart = this._getCurrentDatePart(); const prefix = 'PD'; const pattern = `${prefix}${datePart}%`; const rows = await ctx.model.query( ` SELECT check_no FROM wms_stock_check WHERE check_no LIKE :pattern ORDER BY check_no DESC LIMIT 1 `, { replacements: { pattern }, type: ctx.model.QueryTypes.SELECT, } ); const latestNo = String(rows && rows[0] && rows[0].check_no || '').trim(); let sequence = 1; if (latestNo) { const match = latestNo.match(/(\d{6})$/); const lastSequence = match ? Number(match[1]) : 0; if (Number.isInteger(lastSequence) && lastSequence > 0) { sequence = lastSequence + 1; } } return `${prefix}${datePart}${String(sequence).padStart(6, '0')}`; } /** * 判断创建盘点任务异常是否由单号唯一键冲突引起。 * 参照收货单 isReceivingNumberDuplicateError 口径:ER_DUP_ENTRY 且命中 check_no 唯一索引。 * * @param {Error} error 创建异常。 * @return {boolean} 是单号重复错误返回 true。 */ isCheckNoDuplicateError(error) { const parentCode = error && error.parent && error.parent.code; const sqlMessage = String((error && error.parent && error.parent.sqlMessage) || error.message || ''); return parentCode === 'ER_DUP_ENTRY' && /uk_check_no|check_no/i.test(sqlMessage); } /** * 将主表行格式化为对外输出结构(补齐可空字段默认值)。 * * @param {Object} row 主表原始行数据。 * @return {Object} 格式化后的主表行。 */ _formatCheckRow(row = {}) { return { id: row.id, check_no: row.check_no, title: row.title || '', type: row.type || 'all', mode: row.mode || 'open', store_id: row.store_id || null, status: row.status || 'created', detail_status: row.detail_status || 'none_checked', check_date: row.check_date || null, start_time: row.start_time || null, end_time: row.end_time || null, creator_id: row.creator_id || 0, creator_name: row.creator_name || '', total_items: row.total_items || 0, checked_items: row.checked_items || 0, diff_items: row.diff_items || 0, remark: row.remark || '', created_at: row.created_at || null, updated_at: row.updated_at || null, }; } /** * 将 ID 入参(单值或数组)归一化为去重后的正整数列表。 * * @param {number|Array} values 原始 ID 入参。 * @return {Array} 去重后的正整数 ID 列表。 */ _normalizeIdList(values) { const list = Array.isArray(values) ? values : [ values ]; return [ ...new Set(list.map(value => Number(value)).filter(value => Number.isInteger(value) && value > 0)) ]; } /** * 将日期值格式化为本地时间字符串(YYYY-MM-DD HH:mm:ss),供 Excel 导出使用。 * * @param {*} value 日期值(Date 实例或可解析字符串/数字)。 * @return {string} 格式化后的本地时间字符串,非法值返回空字符串。 */ _formatLocalDateTime(value) { if (!value) { return ''; } const date = value instanceof Date ? value : new Date(value); if (Number.isNaN(date.getTime())) { return ''; } const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); const hours = String(date.getHours()).padStart(2, '0'); const minutes = String(date.getMinutes()).padStart(2, '0'); const seconds = String(date.getSeconds()).padStart(2, '0'); return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`; } /** * 按仓库隔离维度查询盘点主表。 * * @param {number} warehouseId 仓库ID。 * @param {number} id 主表ID。 * @return {Promise} 主表模型实例,不存在时返回 null。 */ async _findCheck(warehouseId, id) { return this.ctx.model.StockCheck.findOne({ where: { id: Number(id), warehouse_id: Number(warehouseId) }, }); } /** * 重算盘点主表的盘点进度汇总(checked_items / diff_items / detail_status)。 * 明细已盘口径:该明细存在盘点作业记录(wms_stock_check_record); * 差异口径:明细实盘合计(记录 quantity 求和)与账面快照 system_quantity 不一致。 * detail_status 按已盘明细占比自动重算:none_checked → partial_checked → all_checked。 * * @param {number} checkId 盘点任务ID。 * @return {Promise} 重算后的汇总信息。 */ async _recalcCheckSummary(checkId) { const { ctx } = this; const { fn, col } = ctx.app.Sequelize; const detailWhere = { check_id: Number(checkId) }; const totalItems = await ctx.model.StockCheckDetail.count({ where: detailWhere }); // 有作业记录的明细数(DISTINCT detail_id) const checkedCountRows = await ctx.model.StockCheckRecord.findAll({ where: { check_id: Number(checkId) }, attributes: [[ fn('COUNT', fn('DISTINCT', col('detail_id'))), 'checkedCount' ]], raw: true, }); const checkedItems = Number(checkedCountRows && checkedCountRows[0] && checkedCountRows[0].checkedCount) || 0; // 差异明细数:实盘合计与账面不一致的明细数 const diffCountRows = await ctx.model.StockCheckRecord.findAll({ where: { check_id: Number(checkId) }, attributes: [ 'detail_id', [ fn('SUM', col('quantity')), 'checkedQuantity' ], ], group: [ 'detail_id' ], raw: true, }); const checkedQuantityByDetail = new Map(); for (const row of diffCountRows) { checkedQuantityByDetail.set(Number(row.detail_id), Number(row.checkedQuantity) || 0); } let diffItems = 0; if (checkedQuantityByDetail.size > 0) { const detailRows = await ctx.model.StockCheckDetail.findAll({ where: detailWhere, attributes: [ 'id', 'system_quantity' ], raw: true, }); for (const detailRow of detailRows) { const checkedQuantity = checkedQuantityByDetail.get(Number(detailRow.id)); if (checkedQuantity === undefined) continue; const diffQuantity = checkedQuantity - Number(detailRow.system_quantity || 0); if (diffQuantity !== 0) { diffItems++; } } } const detailStatus = totalItems === 0 || checkedItems === 0 ? 'none_checked' : (checkedItems >= totalItems ? 'all_checked' : 'partial_checked'); await ctx.model.StockCheck.update( { checked_items: checkedItems, diff_items: diffItems, detail_status: detailStatus, }, { where: { id: Number(checkId) } } ); return { total_items: totalItems, checked_items: checkedItems, diff_items: diffItems, detail_status: detailStatus, checked_quantity_by_detail: checkedQuantityByDetail, }; } /** * 创建盘点任务(空任务)。 * 生成单号 PD+YYYYMMDD+6位序号,初始状态 created,明细进度 none_checked。 * * @param {Object} params 创建参数。 * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 * @param {string} [params.title] 盘点名称/主题。 * @param {string} [params.type='all'] 盘点范围类型:all/store/goods/location。 * @param {string} [params.mode='open'] 盘点方式:open=明盘/blind=盲盘。 * @param {number} [params.storeId] 货主ID(按货主盘点时必填)。 * @param {string} [params.checkDate] 盘点日期。 * @param {string} [params.remark] 备注。 * @param {number} params.creatorId 创建人账户ID(由方法层从上下文注入)。 * @param {string} [params.creatorName] 创建人名称快照(由方法层从上下文注入)。 * @return {Promise} 新建的盘点任务信息。 * @throws {Error} 参数非法时抛出业务错误(错误码 400)。 */ async create(params = {}) { const { warehouseId, title, type, mode, storeId, checkDate, remark, creatorId, creatorName, } = params; const { ctx } = this; const normalizedWarehouseId = Number(warehouseId); if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { throw this.createBusinessError('无法获取当前仓库上下文'); } const normalizedType = type ? String(type).trim() : 'all'; if (!STOCK_CHECK_TYPES.includes(normalizedType)) { throw this.createBusinessError(`盘点范围类型不合法,仅支持 ${STOCK_CHECK_TYPES.join('/')}`); } const normalizedMode = mode ? String(mode).trim() : 'open'; if (!STOCK_CHECK_MODES.includes(normalizedMode)) { throw this.createBusinessError(`盘点方式不合法,仅支持 ${STOCK_CHECK_MODES.join('/')}`); } const normalizedStoreId = storeId !== undefined && storeId !== null && storeId !== '' ? Number(storeId) : null; if (normalizedType === 'store' && (!Number.isInteger(normalizedStoreId) || normalizedStoreId <= 0)) { throw this.createBusinessError('按货主盘点时必须指定货主'); } const checkDateValue = checkDate ? new Date(checkDate) : null; if (!checkDateValue || Number.isNaN(checkDateValue.getTime())) { throw this.createBusinessError('盘点日期不能为空且格式必须合法'); } // 创建盘点任务(并发下撞 uk_check_no 唯一键时自动重取单号,参照收货单口径,最多重试 5 次) const maxCreateRetries = 5; let record = null; for (let attempt = 1; attempt <= maxCreateRetries; attempt++) { const checkNo = await this.generateCheckNo(); try { record = await ctx.model.StockCheck.create({ warehouse_id: normalizedWarehouseId, check_no: checkNo, title: title ? String(title).trim() : null, type: normalizedType, mode: normalizedMode, store_id: normalizedStoreId, scope_snapshot: null, status: 'created', detail_status: 'none_checked', check_date: checkDateValue, creator_id: creatorId ? Number(creatorId) : 0, creator_name: creatorName || null, remark: remark ? String(remark).trim() : null, }); break; } catch (error) { if (this.isCheckNoDuplicateError(error) && attempt < maxCreateRetries) { ctx.logger.warn(`[StockCheckCreateRetry] check_no 冲突,准备重试第 ${attempt + 1} 次`, { warehouse_id: normalizedWarehouseId, }); continue; } throw error; } } return this._formatCheckRow(record.get({ plain: true })); } /** * 拉取盘点任务列表。 * 支持 status 筛选(单值或数组)、store_id 货主筛选、keyword(单号/标题模糊)、分页。 * * @param {Object} params 查询参数。 * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 * @param {string|Array} [params.status] 状态筛选。 * @param {number|string} [params.storeId] 货主筛选。 * @param {string} [params.keyword] 关键字(盘点单号/标题模糊匹配)。 * @param {Object} [params.pagination] 分页参数。 * @return {Promise} { rows, total, page, pageSize }。 */ async list(params = {}) { const { warehouseId, status, storeId, keyword, pagination = {} } = params; const { ctx } = this; const { Op } = ctx.app.Sequelize; const page = Math.max(1, Number(pagination.page) || 1); const pageSize = Math.min(200, Math.max(1, Number(pagination.pageSize) || 20)); const where = { warehouse_id: Number(warehouseId) }; if (status !== undefined && status !== null && status !== '') { if (Array.isArray(status)) { const statusList = status.map(item => String(item).trim()).filter(Boolean); if (statusList.length > 0) { where.status = { [Op.in]: statusList }; } } else { where.status = String(status).trim(); } } if (storeId !== undefined && storeId !== null && storeId !== '') { where.store_id = Number(storeId); } const keywordValue = keyword ? String(keyword).trim() : ''; if (keywordValue) { where[Op.or] = [ { check_no: { [Op.like]: `%${keywordValue}%` } }, { title: { [Op.like]: `%${keywordValue}%` } }, ]; } const { count, rows } = await ctx.model.StockCheck.findAndCountAll({ where, order: [[ 'id', 'DESC' ]], offset: (page - 1) * pageSize, limit: pageSize, raw: true, }); return { rows, total: count, page, pageSize }; } /** * 添加盘点明细。 * 仅 created/rejected 状态允许;按 stock_ids 查询 wms_stock_warehouse 生成明细快照行, * 已存在同 stock_id 的明细跳过(幂等),重算主表 total_items。 * * @param {Object} params 添加明细参数。 * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 * @param {number} params.id 盘点任务ID。 * @param {number|Array} params.stockIds 商品库存ID列表(wms_stock_warehouse.id)。 * @return {Promise} { added, skipped, invalid_stock_ids, total_items }。 * @throws {Error} 状态不允许或参数非法时抛出业务错误(错误码 400)。 */ async addDetail(params = {}) { const { warehouseId, id, stockIds } = params; const { ctx } = this; const { Op } = ctx.app.Sequelize; const checkId = Number(id); if (!Number.isInteger(checkId) || checkId <= 0) { throw this.createBusinessError('盘点任务ID不能为空'); } const check = await this._findCheck(warehouseId, checkId); if (!check) { throw this.createBusinessError('盘点任务不存在'); } if (!ADD_DETAIL_ALLOWED_STATUSES.includes(check.status)) { throw this.createBusinessError(`当前状态(${check.status})不允许添加明细`); } const numericStockIds = this._normalizeIdList(stockIds); if (numericStockIds.length === 0) { throw this.createBusinessError('请至少选择一个商品'); } // 按 stock_ids 查询库存商品快照(限定当前仓库,自动过滤已删除) const stockRows = await ctx.model.StockWarehouse.findAll({ where: { id: { [Op.in]: numericStockIds }, warehouse_id: Number(warehouseId), }, raw: true, }); const stockMap = new Map(stockRows.map(item => [ Number(item.id), item ])); // 幂等:已存在同 stock_id 的明细跳过 const existingRows = await ctx.model.StockCheckDetail.findAll({ where: { check_id: checkId, stock_id: { [Op.in]: numericStockIds }, }, attributes: [ 'stock_id' ], raw: true, }); const existingStockIds = new Set(existingRows.map(item => Number(item.stock_id))); const toCreate = []; const skippedStockIds = []; const invalidStockIds = []; for (const stockId of numericStockIds) { const stock = stockMap.get(stockId); if (!stock) { invalidStockIds.push(stockId); continue; } if (existingStockIds.has(stockId)) { skippedStockIds.push(stockId); continue; } toCreate.push({ check_id: checkId, warehouse_id: Number(warehouseId), stock_id: stockId, item_code: stock.item_code, item_name: stock.item_name || null, spec: stock.sku_property || null, batch_no: null, system_quantity: Number(stock.quantity) || 0, }); } if (toCreate.length > 0) { await ctx.model.StockCheckDetail.bulkCreate(toCreate); } // 重算主表 total_items const totalItems = await ctx.model.StockCheckDetail.count({ where: { check_id: checkId }, }); await check.update({ total_items: totalItems }); return { added: toCreate.length, skipped: skippedStockIds.length, invalid_stock_ids: invalidStockIds, total_items: totalItems, }; } /** * 删除盘点明细(从任务中移除某个商品)。 * 仅主表状态 created/rejected(ADD_DETAIL_ALLOWED_STATUSES)允许删除; * 明细存在作业记录(wms_stock_check_record)时一并防御性删除(正常流程该状态不应有记录); * 删除后重算主表 total_items。 * * @param {Object} params 删除参数。 * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 * @param {number} params.id 盘点任务ID。 * @param {number} params.detailId 盘点明细ID(方法层已兼容 detail_id/detailId 写法)。 * @return {Promise} { detail_id, deleted, total_items }。 * @throws {Error} 参数非法、任务/明细不存在或状态不允许时抛出业务错误(错误码 400)。 */ async detailDelete(params = {}) { const { warehouseId, id, detailId } = params; const { ctx } = this; const checkId = Number(id); const normalizedDetailId = Number(detailId); if (!Number.isInteger(checkId) || checkId <= 0) { throw this.createBusinessError('盘点任务ID不能为空'); } if (!Number.isInteger(normalizedDetailId) || normalizedDetailId <= 0) { throw this.createBusinessError('盘点明细ID不能为空'); } const check = await this._findCheck(warehouseId, checkId); if (!check) { throw this.createBusinessError('盘点任务不存在'); } if (!ADD_DETAIL_ALLOWED_STATUSES.includes(check.status)) { throw this.createBusinessError(`当前状态(${check.status})不允许删除明细`); } const detail = await ctx.model.StockCheckDetail.findOne({ where: { id: normalizedDetailId, check_id: checkId, warehouse_id: Number(warehouseId), }, }); if (!detail) { throw this.createBusinessError('盘点明细不存在'); } await detail.destroy(); // 防御性处理:若该明细存在作业记录(正常流程 created/rejected 不应有记录),一并删除 await ctx.model.StockCheckRecord.destroy({ where: { detail_id: normalizedDetailId, check_id: checkId, warehouse_id: Number(warehouseId), }, }); // 删除明细后重算主表 total_items const totalItems = await ctx.model.StockCheckDetail.count({ where: { check_id: checkId }, }); await check.update({ total_items: totalItems }); return { detail_id: normalizedDetailId, deleted: true, total_items: totalItems, }; } /** * 拉取盘点任务的全部明细行(商品清单)及其盘点作业记录(库位+数量)。 * * @param {Object} params 查询参数。 * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 * @param {number} params.id 盘点任务ID。 * @return {Promise} { check, rows, total };rows 每条含商品快照 + 已盘聚合 * (checked_quantity=记录数量合计、diff_quantity=实盘-账面、is_diff、location_codes、 * checkers、last_checked_at)、records(该明细全部作业记录)与 locations * (按库位聚合 [{ location_id, location_code, quantity }],按首条记录 id 升序)。 * @throws {Error} 任务不存在时抛出业务错误(错误码 400)。 */ async detail(params = {}) { const { warehouseId, id } = params; const { ctx } = this; const checkId = Number(id); if (!Number.isInteger(checkId) || checkId <= 0) { throw this.createBusinessError('盘点任务ID不能为空'); } const check = await this._findCheck(warehouseId, checkId); if (!check) { throw this.createBusinessError('盘点任务不存在'); } const detailRows = await ctx.model.StockCheckDetail.findAll({ where: { check_id: checkId, warehouse_id: Number(warehouseId) }, order: [[ 'id', 'ASC' ]], raw: true, }); const records = await ctx.model.StockCheckRecord.findAll({ where: { check_id: checkId, warehouse_id: Number(warehouseId) }, order: [[ 'id', 'ASC' ]], raw: true, }); // 按明细聚合作业记录 const recordsByDetail = new Map(); for (const record of records) { const detailRowId = Number(record.detail_id); if (!recordsByDetail.has(detailRowId)) { recordsByDetail.set(detailRowId, []); } recordsByDetail.get(detailRowId).push(record); } const rows = detailRows.map(detailRow => { const detailRowId = Number(detailRow.id); const detailRecords = recordsByDetail.get(detailRowId) || []; const checkedQuantity = detailRecords.reduce((sum, record) => sum + (Number(record.quantity) || 0), 0); const diffQuantity = checkedQuantity - Number(detailRow.system_quantity || 0); const locationCodes = [ ...new Set(detailRecords .map(record => String(record.location_code || '').trim()) .filter(Boolean)) ]; const checkers = [ ...new Set(detailRecords .map(record => String(record.checker_name || '').trim()) .filter(Boolean)) ]; const lastCheckedAt = detailRecords.length > 0 ? detailRecords[detailRecords.length - 1].checked_at : null; // 按库位聚合作业记录(库位为空归入"无库位"分组,location_code 为 null),按首条记录 id 升序 const locationGroups = new Map(); for (const record of detailRecords) { const recordLocationCode = record.location_code !== null && record.location_code !== undefined ? String(record.location_code).trim() : ''; if (!locationGroups.has(recordLocationCode)) { locationGroups.set(recordLocationCode, { location_id: recordLocationCode ? (Number(record.location_id) || null) : null, location_code: recordLocationCode || null, quantity: 0, first_record_id: Number(record.id) || 0, }); } const locationGroup = locationGroups.get(recordLocationCode); locationGroup.quantity += Number(record.quantity) || 0; } const locations = [ ...locationGroups.values() ] .sort((left, right) => left.first_record_id - right.first_record_id) .map(locationGroup => ({ location_id: locationGroup.location_id, location_code: locationGroup.location_code, quantity: locationGroup.quantity, })); return { ...detailRow, checked_quantity: detailRecords.length > 0 ? checkedQuantity : null, diff_quantity: detailRecords.length > 0 ? diffQuantity : null, is_diff: detailRecords.length > 0 && diffQuantity !== 0 ? 1 : 0, status: detailRecords.length > 0 ? 'checked' : 'unchecked', location_codes: locationCodes, checkers, last_checked_at: lastCheckedAt, records: detailRecords, locations, }; }); return { check: this._formatCheckRow(check.get({ plain: true })), rows, total: rows.length, }; } /** * 盘点作业上报(覆盖式)。 * 仅 approved/checking 状态允许;同明细 + 同库位编码重复上报时更新已有记录的 * quantity/checker_id/checker_name/checked_at(保留原 location_id,若本次新匹配到 location_id 则回填), * 不再新增;未传库位归入"无库位"分组(location_code 存空串); * 库位编码匹配 wms_location_space.space_code 时回填 location_id; * 主表 approved 自动转 checking;重算 checked_items / diff_items / detail_status。 * 数据库层由唯一索引 uk_detail_location(detail_id, location_code) 保证并发下不产生重复记录。 * * @param {Object} params 上报参数。 * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 * @param {number} params.id 盘点任务ID。 * @param {number} params.detailId 明细ID。 * @param {string} [params.location] 库位编码(可空)。 * @param {number} params.quantity 实盘数量(>=0)。 * @param {number} [params.checkerId] 盘点人账户ID(由方法层从上下文注入)。 * @param {string} [params.checkerName] 盘点人名称快照(由方法层从上下文注入)。 * @return {Promise} { record, detail_id, mode, total_items, checked_items, diff_items, detail_status }。 * @throws {Error} 状态不允许或参数非法时抛出业务错误(错误码 400)。 */ async report(params = {}) { const { warehouseId, id, detailId, location, quantity, checkerId, checkerName, } = params; const { ctx } = this; const checkId = Number(id); const detailRowId = Number(detailId); if (!Number.isInteger(checkId) || checkId <= 0) { throw this.createBusinessError('盘点任务ID不能为空'); } if (!Number.isInteger(detailRowId) || detailRowId <= 0) { throw this.createBusinessError('盘点明细ID不能为空'); } const check = await this._findCheck(warehouseId, checkId); if (!check) { throw this.createBusinessError('盘点任务不存在'); } if (!REPORT_ALLOWED_STATUSES.includes(check.status)) { throw this.createBusinessError(`当前状态(${check.status})不允许盘点作业`); } const quantityValue = Number(quantity); if (!Number.isInteger(quantityValue) || quantityValue < 0) { throw this.createBusinessError('实盘数量必须为不小于0的整数'); } const detail = await ctx.model.StockCheckDetail.findOne({ where: { id: detailRowId, check_id: checkId, warehouse_id: Number(warehouseId) }, }); if (!detail) { throw this.createBusinessError('盘点明细不存在'); } // 库位编码匹配 wms_location_space.space_code 时回填 location_id; // 未传库位归一为空串("无库位"分组,配合 uk_detail_location 唯一索引) const locationCode = location !== undefined && location !== null && String(location).trim() !== '' ? String(location).trim() : ''; let locationId = null; if (locationCode) { const space = await ctx.model.LocationSpace.findOne({ where: { warehouse_id: Number(warehouseId), space_code: locationCode, }, attributes: [ 'id' ], raw: true, }); if (space) { locationId = space.id; } } const now = new Date(); // 覆盖式上报:同明细 + 同库位编码(未传库位为空串"无库位"分组)更新已有记录; // 依赖唯一索引 uk_detail_location(detail_id, location_code) 保证并发安全 const existingRecordWhere = { detail_id: detailRowId, location_code: locationCode }; const existingRecord = await ctx.model.StockCheckRecord.findOne({ where: existingRecordWhere, }); const normalizedCheckerId = checkerId ? Number(checkerId) : null; const normalizedCheckerName = checkerName || null; let record = null; let mode = 'created'; if (existingRecord) { // 保留原 location_id,若本次新匹配到 location_id 则回填 const resolvedLocationId = locationId !== null && locationId !== undefined ? locationId : existingRecord.location_id; await existingRecord.update({ quantity: quantityValue, checker_id: normalizedCheckerId, checker_name: normalizedCheckerName, checked_at: now, location_id: resolvedLocationId, }); record = existingRecord.get({ plain: true }); mode = 'updated'; } else { try { const createdRecord = await ctx.model.StockCheckRecord.create({ check_id: checkId, warehouse_id: Number(warehouseId), detail_id: detailRowId, stock_id: Number(detail.stock_id), location_id: locationId, location_code: locationCode, quantity: quantityValue, checker_id: normalizedCheckerId, checker_name: normalizedCheckerName, checked_at: now, }); record = createdRecord.get({ plain: true }); } catch (error) { // 并发下撞唯一索引 uk_detail_location:降级为更新已有记录,避免调用方收到 500 const isDuplicate = (error && error.name === 'SequelizeUniqueConstraintError') || (error && error.original && error.original.code === 'ER_DUP_ENTRY'); if (!isDuplicate) { throw error; } const latestRecord = await ctx.model.StockCheckRecord.findOne({ where: existingRecordWhere, }); if (!latestRecord) { throw error; } const resolvedLocationId = locationId !== null && locationId !== undefined ? locationId : latestRecord.location_id; await latestRecord.update({ quantity: quantityValue, checker_id: normalizedCheckerId, checker_name: normalizedCheckerName, checked_at: now, location_id: resolvedLocationId, }); record = latestRecord.get({ plain: true }); mode = 'updated'; } } // 主表 approved → checking 自动转移(首次上报) if (check.status === 'approved') { await check.update({ status: 'checking', start_time: check.start_time || now, }); } // 重算 checked_items / diff_items / detail_status const summary = await this._recalcCheckSummary(checkId); return { record, detail_id: detailRowId, mode, ...summary, }; } /** * 拉取盘点作业记录列表。 * 至少传 id(盘点任务ID)或 detail_id(明细ID)之一;rows 每条为作业记录全字段 + * 商品快照列(item_code/item_name,从明细表查得);按记录 id 倒序。 * * @param {Object} params 查询参数。 * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 * @param {number} [params.id] 盘点任务ID(可选)。 * @param {number} [params.detailId] 明细ID(可选)。 * @param {Object} [params.pagination] 分页参数。 * @return {Promise} { rows, total, page, pageSize }。 * @throws {Error} 未传任务ID或明细ID时抛出业务错误(错误码 400)。 */ async recordList(params = {}) { const { warehouseId, id, detailId, pagination = {} } = params; const { ctx } = this; const { Op } = ctx.app.Sequelize; const checkId = id !== undefined && id !== null && id !== '' ? Number(id) : 0; const normalizedDetailId = detailId !== undefined && detailId !== null && detailId !== '' ? Number(detailId) : 0; const hasCheckId = Number.isInteger(checkId) && checkId > 0; const hasDetailId = Number.isInteger(normalizedDetailId) && normalizedDetailId > 0; if (!hasCheckId && !hasDetailId) { throw this.createBusinessError('请至少提供盘点任务ID或明细ID'); } const page = Math.max(1, Number(pagination.page) || 1); const pageSize = Math.min(200, Math.max(1, Number(pagination.pageSize) || 20)); const where = { warehouse_id: Number(warehouseId) }; if (hasCheckId) { where.check_id = checkId; } if (hasDetailId) { where.detail_id = normalizedDetailId; } const { count, rows } = await ctx.model.StockCheckRecord.findAndCountAll({ where, order: [[ 'id', 'DESC' ]], offset: (page - 1) * pageSize, limit: pageSize, raw: true, }); // 商品快照列(item_code/item_name)从明细表补齐 const detailIds = [ ...new Set(rows.map(row => Number(row.detail_id))) ]; let itemByDetailId = new Map(); if (detailIds.length > 0) { const detailRows = await ctx.model.StockCheckDetail.findAll({ where: { id: { [Op.in]: detailIds } }, attributes: [ 'id', 'item_code', 'item_name' ], raw: true, }); itemByDetailId = new Map(detailRows.map(item => [ Number(item.id), item ])); } const formattedRows = rows.map(row => { const item = itemByDetailId.get(Number(row.detail_id)) || {}; return { ...row, // 空串表示"无库位"分组,接口返回口径统一为 null location_code: String(row.location_code || '').trim() !== '' ? row.location_code : null, item_code: item.item_code || null, item_name: item.item_name || null, }; }); return { rows: formattedRows, total: count, page, pageSize }; } /** * 删除盘点作业记录。 * 仅主表状态 approved/checking 允许删除;记录不存在或不属于该任务/仓库时报 400; * 删除后重算 checked_items/diff_items/detail_status(明细记录删光后该明细回到未盘),主表状态不回退。 * * @param {Object} params 删除参数。 * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 * @param {number} params.id 盘点任务ID。 * @param {number} params.recordId 作业记录ID(方法层已兼容 record_id/recordId 写法)。 * @return {Promise} { record_id, deleted, total_items, checked_items, diff_items, detail_status }。 * @throws {Error} 状态不允许或记录不存在时抛出业务错误(错误码 400)。 */ async recordDelete(params = {}) { const { warehouseId, id, recordId } = params; const { ctx } = this; const checkId = Number(id); const normalizedRecordId = Number(recordId); if (!Number.isInteger(checkId) || checkId <= 0) { throw this.createBusinessError('盘点任务ID不能为空'); } if (!Number.isInteger(normalizedRecordId) || normalizedRecordId <= 0) { throw this.createBusinessError('作业记录ID不能为空'); } const check = await this._findCheck(warehouseId, checkId); if (!check) { throw this.createBusinessError('盘点任务不存在'); } if (!REPORT_ALLOWED_STATUSES.includes(check.status)) { throw this.createBusinessError(`当前状态(${check.status})不允许删除作业记录`); } const record = await ctx.model.StockCheckRecord.findOne({ where: { id: normalizedRecordId, check_id: checkId, warehouse_id: Number(warehouseId), }, }); if (!record) { throw this.createBusinessError('作业记录不存在或不属于该盘点任务'); } await record.destroy(); // 重算 checked_items / diff_items / detail_status(明细记录删光后该明细回到未盘),主表状态不回退 const summary = await this._recalcCheckSummary(checkId); return { record_id: normalizedRecordId, deleted: true, ...summary, }; } /** * 完成盘点作业(允许部分未盘完成)。 * 仅 approved/checking 状态允许;未盘明细按实盘 0 处理(差异 = -账面快照,计入盘亏与 diff_items); * 已盘明细按作业记录聚合差异(盘盈合计 / 盘亏合计); * 完成后主表置 completed、写 end_time、detail_status=all_checked,并返回差异汇总与未盘明细数。 * * @param {Object} params 完成参数。 * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 * @param {number} params.id 盘点任务ID。 * @return {Promise} { id, status, total_items, checked_items, unchecked_items, diff_items, profit_total, loss_total }。 * @throws {Error} 状态不允许时抛出业务错误(错误码 400)。 */ async finish(params = {}) { const { warehouseId, id } = params; const { ctx } = this; const { fn, col } = ctx.app.Sequelize; const checkId = Number(id); if (!Number.isInteger(checkId) || checkId <= 0) { throw this.createBusinessError('盘点任务ID不能为空'); } const check = await this._findCheck(warehouseId, checkId); if (!check) { throw this.createBusinessError('盘点任务不存在'); } if (!REPORT_ALLOWED_STATUSES.includes(check.status)) { throw this.createBusinessError(`当前状态(${check.status})不允许完成盘点`); } const totalItems = await ctx.model.StockCheckDetail.count({ where: { check_id: checkId }, }); // 已盘明细数:存在作业记录(wms_stock_check_record)的明细数 const checkedCountRows = await ctx.model.StockCheckRecord.findAll({ where: { check_id: checkId }, attributes: [[ fn('COUNT', fn('DISTINCT', col('detail_id'))), 'checkedCount' ]], raw: true, }); const checkedItems = Number(checkedCountRows && checkedCountRows[0] && checkedCountRows[0].checkedCount) || 0; const uncheckedItems = totalItems - checkedItems; // 差异汇总:按明细聚合实盘数量与账面快照对比,盘盈合计 / 盘亏合计 const summary = await this._recalcCheckSummary(checkId); const checkedQuantityByDetail = summary.checked_quantity_by_detail || new Map(); const detailRows = await ctx.model.StockCheckDetail.findAll({ where: { check_id: checkId }, attributes: [ 'id', 'system_quantity' ], raw: true, }); let profitTotal = 0; let lossTotal = 0; let diffItems = 0; for (const detailRow of detailRows) { const checkedQuantity = checkedQuantityByDetail.get(Number(detailRow.id)); const systemQuantity = Number(detailRow.system_quantity || 0); // 已盘明细按记录聚合差异;未盘明细按实盘 0 处理(差异 = -账面快照,即盘亏) const diffQuantity = checkedQuantity === undefined ? -systemQuantity : checkedQuantity - systemQuantity; if (diffQuantity > 0) { profitTotal += diffQuantity; diffItems++; } else if (diffQuantity < 0) { lossTotal += Math.abs(diffQuantity); diffItems++; } } await check.update({ status: 'completed', end_time: new Date(), detail_status: 'all_checked', checked_items: checkedItems, diff_items: diffItems, }); return { id: checkId, status: 'completed', total_items: totalItems, checked_items: checkedItems, unchecked_items: uncheckedItems, diff_items: diffItems, profit_total: profitTotal, loss_total: lossTotal, }; } /** * 完成盘点任务(提交审核)。 * 仅 created/rejected 状态允许;校验 total_items>0 后置为 submitted。 * * @param {Object} params 提交参数。 * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 * @param {number} params.id 盘点任务ID。 * @return {Promise} { id, status }。 * @throws {Error} 状态不允许或没有明细时抛出业务错误(错误码 400)。 */ async submit(params = {}) { const { warehouseId, id } = params; const checkId = Number(id); if (!Number.isInteger(checkId) || checkId <= 0) { throw this.createBusinessError('盘点任务ID不能为空'); } const check = await this._findCheck(warehouseId, checkId); if (!check) { throw this.createBusinessError('盘点任务不存在'); } if (!SUBMIT_ALLOWED_STATUSES.includes(check.status)) { throw this.createBusinessError(`当前状态(${check.status})不允许提交审核`); } if (Number(check.total_items) <= 0) { throw this.createBusinessError('盘点任务还没有明细行,无法提交审核'); } await check.update({ status: 'submitted' }); return { id: checkId, status: 'submitted', }; } /** * 取消盘点任务。 * 仅 created/submitted/rejected 状态允许;取消后置为 cancelled(终态)。 * * @param {Object} params 取消参数。 * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 * @param {number} params.id 盘点任务ID。 * @return {Promise} { id, status }。 * @throws {Error} 状态不允许时抛出业务错误(错误码 400)。 */ async cancel(params = {}) { const { warehouseId, id } = params; const checkId = Number(id); if (!Number.isInteger(checkId) || checkId <= 0) { throw this.createBusinessError('盘点任务ID不能为空'); } const check = await this._findCheck(warehouseId, checkId); if (!check) { throw this.createBusinessError('盘点任务不存在'); } if (!CANCEL_ALLOWED_STATUSES.includes(check.status)) { throw this.createBusinessError(`当前状态(${check.status})不允许取消`); } await check.update({ status: 'cancelled' }); return { id: checkId, status: 'cancelled', }; } /** * 审核盘点任务。 * 仅 submitted 状态允许;approve → approved,reject → rejected(reason 可选写入备注)。 * * @param {Object} params 审核参数。 * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 * @param {number} params.id 盘点任务ID。 * @param {string} params.action 审核动作:approve=通过,reject=驳回。 * @param {string} [params.reason] 驳回原因(写入备注)。 * @return {Promise} { id, status }。 * @throws {Error} 状态不允许或动作非法时抛出业务错误(错误码 400)。 */ async audit(params = {}) { const { warehouseId, id, action, reason } = params; const checkId = Number(id); if (!Number.isInteger(checkId) || checkId <= 0) { throw this.createBusinessError('盘点任务ID不能为空'); } const actionValue = action ? String(action).trim() : ''; if (actionValue !== 'approve' && actionValue !== 'reject') { throw this.createBusinessError('审核动作仅支持 approve/reject'); } const check = await this._findCheck(warehouseId, checkId); if (!check) { throw this.createBusinessError('盘点任务不存在'); } if (check.status !== 'submitted') { throw this.createBusinessError(`当前状态(${check.status})不允许审核`); } if (actionValue === 'approve') { await check.update({ status: 'approved' }); } else { const reasonValue = reason !== undefined && reason !== null && String(reason).trim() !== '' ? String(reason).trim() : check.remark; await check.update({ status: 'rejected', remark: reasonValue, }); } return { id: checkId, status: actionValue === 'approve' ? 'approved' : 'rejected', }; } /** * 盘点任务导出:查询任务与明细 → Sheet1「盘点单」一行一个盘点任务、 * Sheet2「盘点明细」一行一条明细(首列盘点单号)→ 流式生成 Excel → COS 上传。 * 通过 onProgress 回调实时推送进度。 * * @param {Object} params 导出参数。 * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 * @param {Array} params.ids 盘点任务ID数组。 * @param {Function} [params.onProgress] 进度回调。 * @return {Promise} 导出结果,包含文件下载信息与数量统计。 * @throws {Error} 没有可导出的任务时抛出业务错误(错误码 400)。 */ async exportStockChecks(params = {}) { const { warehouseId, ids, onProgress } = params; const { ctx } = this; const { Op } = ctx.app.Sequelize; const reportProgress = async (status, progress, message, extra = {}) => { if (typeof onProgress === 'function') { await onProgress({ status, progress, message, ...extra }); } }; await reportProgress('running', 5, '正在准备导出数据...'); const numericIds = this._normalizeIdList(ids); if (numericIds.length === 0) { throw this.createBusinessError('请至少选择一个盘点任务'); } const checks = await ctx.model.StockCheck.findAll({ where: { id: { [Op.in]: numericIds }, warehouse_id: Number(warehouseId), }, order: [[ 'id', 'ASC' ]], raw: true, }); if (checks.length === 0) { throw this.createBusinessError('未找到可导出的盘点任务'); } // 明细与作业记录统一拉取,明细行聚合作业记录(已盘数量/差异/库位列表) const detailRows = await ctx.model.StockCheckDetail.findAll({ where: { check_id: { [Op.in]: numericIds } }, order: [[ 'check_id', 'ASC' ], [ 'id', 'ASC' ]], raw: true, }); const recordRows = await ctx.model.StockCheckRecord.findAll({ where: { check_id: { [Op.in]: numericIds } }, order: [[ 'detail_id', 'ASC' ], [ 'id', 'ASC' ]], raw: true, }); const recordsByDetail = new Map(); for (const record of recordRows) { const detailRowId = Number(record.detail_id); if (!recordsByDetail.has(detailRowId)) { recordsByDetail.set(detailRowId, []); } recordsByDetail.get(detailRowId).push(record); } const detailsGrouped = new Map(); for (const row of detailRows) { const checkId = Number(row.check_id); if (!detailsGrouped.has(checkId)) { detailsGrouped.set(checkId, []); } const detailRecords = recordsByDetail.get(Number(row.id)) || []; const checkedQuantity = detailRecords.length > 0 ? detailRecords.reduce((sum, record) => sum + (Number(record.quantity) || 0), 0) : null; const diffQuantity = checkedQuantity === null ? null : checkedQuantity - Number(row.system_quantity || 0); detailsGrouped.get(checkId).push({ ...row, checked_quantity: checkedQuantity, diff_quantity: diffQuantity, is_diff: checkedQuantity === null ? 0 : (diffQuantity !== 0 ? 1 : 0), status: detailRecords.length > 0 ? 'checked' : 'unchecked', location_codes: [ ...new Set(detailRecords .map(record => String(record.location_code || '').trim()) .filter(Boolean)) ], checkers: [ ...new Set(detailRecords .map(record => String(record.checker_name || '').trim()) .filter(Boolean)) ], last_checked_at: detailRecords.length > 0 ? detailRecords[detailRecords.length - 1].checked_at : null, }); } const totalCount = detailRows.length; await reportProgress('running', 10, `共 ${checks.length} 个盘点任务、${totalCount} 条明细,开始导出...`, { totalCount, currentCount: 0, }); const exportResult = await this._generateAndUploadStockCheckExcel(checks, detailsGrouped, { totalCount, onProgress, }); await reportProgress('success', 100, '导出完成', { totalCount, currentCount: totalCount, result: exportResult, }); return { ...exportResult, total_count: totalCount, current_count: totalCount, }; } /** * 生成盘点导出 Excel(Sheet1=盘点单行,Sheet2=明细行)并上传 COS,返回下载信息。 * 与售后/退回拆包导出口径一致:流式写临时文件 → uploadFile → uploadSuccessNotify。 * * @param {Array} checks 盘点任务主表行。 * @param {Map>} detailsGrouped 按 check_id 分组的明细行。 * @param {Object} [options] 附加选项。 * @param {number} [options.totalCount] 明细总行数(用于进度计算)。 * @param {Function} [options.onProgress] 进度回调。 * @return {Promise} { filename, fileKey, url, cdnUrl, cosUrl }。 */ async _generateAndUploadStockCheckExcel(checks = [], detailsGrouped = new Map(), options = {}) { const { totalCount = 0, onProgress } = options; const { ctx } = this; const reportProgress = async (status, progress, message, extra = {}) => { if (typeof onProgress === 'function') { await onProgress({ status, progress, message, ...extra }); } }; const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-stock-check-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, }); try { // ---- Sheet1:盘点单行(一行一个盘点任务) ---- const checksSheet = workbook.addWorksheet('盘点单'); checksSheet.addRow([ '盘点单号', '盘点名称', '盘点范围', '盘点方式', '盘点状态', '盘点进度', '盘点日期', '货主ID', '创建人', '明细行数', '已盘行数', '差异行数', '开始时间', '结束时间', '备注', ]).commit(); for (const check of checks) { checksSheet.addRow([ check.check_no || '', check.title || '', STOCK_CHECK_TYPE_LABELS[check.type] || check.type || '', STOCK_CHECK_MODE_LABELS[check.mode] || check.mode || '', STOCK_CHECK_STATUS_LABELS[check.status] || check.status || '', STOCK_CHECK_DETAIL_PROGRESS_LABELS[check.detail_status] || check.detail_status || '', this._formatLocalDateTime(check.check_date), check.store_id === null || check.store_id === undefined ? '' : Number(check.store_id), check.creator_name || '', Number(check.total_items) || 0, Number(check.checked_items) || 0, Number(check.diff_items) || 0, this._formatLocalDateTime(check.start_time), this._formatLocalDateTime(check.end_time), check.remark || '', ]).commit(); } checksSheet.commit(); // ---- Sheet2:明细行(一行一条明细,首列带盘点单号便于对照) ---- const detailsSheet = workbook.addWorksheet('盘点明细'); detailsSheet.addRow([ '盘点单号', '商品编码', '商品名称', '规格', '账面数量', '已盘数量', '差异数量', '是否有差异', '库位编码', '盘点人', '最近盘点时间', ]).commit(); let currentCount = 0; for (const check of checks) { const checkId = Number(check.id); const rows = detailsGrouped.get(checkId) || []; for (const row of rows) { detailsSheet.addRow([ check.check_no || '', row.item_code || '', row.item_name || '', row.spec || '', Number(row.system_quantity) || 0, row.checked_quantity === null || row.checked_quantity === undefined ? '' : Number(row.checked_quantity), row.diff_quantity === null || row.diff_quantity === undefined ? '' : Number(row.diff_quantity), Number(row.is_diff) === 1 ? '是' : '否', Array.isArray(row.location_codes) ? row.location_codes.join('、') : '', Array.isArray(row.checkers) ? row.checkers.join('、') : '', this._formatLocalDateTime(row.last_checked_at), ]).commit(); currentCount++; // 每 200 行汇报一次进度 if (currentCount % 200 === 0 || currentCount === totalCount) { const progress = 10 + Math.floor((currentCount / Math.max(1, totalCount)) * 80); await reportProgress('running', progress, `正在导出... (${currentCount}/${totalCount})`, { totalCount, currentCount, }); } } } detailsSheet.commit(); await workbook.commit(); await reportProgress('running', 90, '正在上传文件...', { totalCount, currentCount: totalCount }); // ---- 上传文件(与 afterSale/return_unpack 导出口径一致)---- const uploadService = ctx && ctx.service && ctx.service.systems && 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/stock_check/${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: 'stockCheckExport', description: `库存盘点导出,共 ${checks.length} 个盘点任务、${totalCount} 条明细`, }); } // 优先取 uploadFile 返回的完整 URL,其次取 uploadSuccessNotify 落库记录,最后回退 COS key const safeUploadResult = typeof uploadResult === 'object' && uploadResult !== null ? uploadResult : {}; const resolvedFileRecord = (fileRecord && (fileRecord.data || fileRecord)) || null; const fileUrlFromRecord = resolvedFileRecord ? (resolvedFileRecord.file_url || resolvedFileRecord.fileUrl || resolvedFileRecord.url || '') : ''; const uploadResultUrl = safeUploadResult.url || safeUploadResult.cdnUrl || safeUploadResult.cosUrl || ''; return { filename, fileKey: safeUploadResult.fileName || uploadKey, url: uploadResultUrl || fileUrlFromRecord || safeUploadResult.fileName || uploadKey, cdnUrl: safeUploadResult.cdnUrl || safeUploadResult.url || '', cosUrl: safeUploadResult.cosUrl || '', }; } catch (error) { const workbookStream = workbook.stream; if (workbookStream && typeof workbookStream.destroy === 'function') { workbookStream.destroy(); } ctx.logger.error(`[stock.check.export] 生成/上传 Excel 失败: ${error.message}`); throw error; } finally { await fsp.rm(tempDir, { recursive: true, force: true }); } } } module.exports = StockCheckService;