From 78b46a740becedd743522b997034e0bcb2876182 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 10 Oct 2026 03:34:28 +0800 Subject: [PATCH] =?UTF-8?q?feat(stock.check):=20=E6=96=B0=E5=A2=9E=20expor?= =?UTF-8?q?tDetail=20=E7=9B=98=E7=82=B9=E6=98=8E=E7=BB=86=E5=AF=BC?= =?UTF-8?q?=E5=87=BA=EF=BC=88=E5=95=86=E5=93=81=E7=9B=98=E7=82=B9=E5=BA=93?= =?UTF-8?q?=E4=BD=8D=E6=98=8E=E7=BB=86/=E6=B1=87=E6=80=BB+=E5=B7=AE?= =?UTF-8?q?=E5=BC=82=E4=B8=A4=E6=A8=A1=E5=BC=8F=EF=BC=8C=E5=BA=93=E4=BD=8D?= =?UTF-8?q?=E7=9B=98=E7=82=B9=E7=AE=80=E5=8C=96=EF=BC=8C0.3.261=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systemMethods/stock/check.js | 106 +++++- app/service/systems/stock_check.js | 457 ++++++++++++++++++++--- methods/changes/system.json | 16 + methods/system.json | 140 ++++++- 4 files changed, 668 insertions(+), 51 deletions(-) diff --git a/app/service/systemMethods/stock/check.js b/app/service/systemMethods/stock/check.js index c4ee484..0743ff7 100644 --- a/app/service/systemMethods/stock/check.js +++ b/app/service/systemMethods/stock/check.js @@ -8,8 +8,8 @@ const STOCK_CHECK_EXPORT_TASK_CACHE_TTL_SECONDS = 1800; /** 单次导出任务允许的最大盘点任务数量 */ const STOCK_CHECK_EXPORT_MAX_TASK_IDS = 50; -/** 全部 23 个 method 名(免权限/免鉴权清单共用) */ -const ALL_METHOD_NAMES = 'create,list,addDetail,addLocationDetail,detailDelete,detail,result,workData,workDataSpaceDetails,workDataDetail,report,markEmpty,recordList,recordDelete,recheckClearLocation,finish,submit,cancel,audit,batchDelete,export,exportTaskProgress,patternList,patternCreate'; +/** 全部 24 个 method 名(免权限/免鉴权清单共用) */ +const ALL_METHOD_NAMES = 'create,list,addDetail,addLocationDetail,detailDelete,detail,result,workData,workDataSpaceDetails,workDataDetail,report,markEmpty,recordList,recordDelete,recheckClearLocation,finish,submit,cancel,audit,batchDelete,export,exportDetail,exportTaskProgress,patternList,patternCreate'; /** * 系统方法层:stock.check(库存盘点模块接口包装层)。 @@ -24,7 +24,7 @@ class StockCheckMethodService extends MainService { // 免权限方法列表:全部 20 个方法免 API 权限校验(与 stock/transaction.js 口径一致) const _noNeedRight = ALL_METHOD_NAMES; // 免日志方法列表:查询类与导出类不记录操作日志(recordDelete/patternCreate 为写操作,保留操作日志) - const _noNeedLog = 'list,detail,result,workData,workDataSpaceDetails,workDataDetail,recordList,export,exportTaskProgress,patternList'; + const _noNeedLog = 'list,detail,result,workData,workDataSpaceDetails,workDataDetail,recordList,export,exportDetail,exportTaskProgress,patternList'; // 免鉴权(仓库有效期检查)方法列表:全部方法免鉴权(与 stock/transaction.js 口径一致) const _noNeedAuth = ALL_METHOD_NAMES; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); @@ -813,6 +813,106 @@ class StockCheckMethodService extends MainService { }); } + /** + * 提交盘点明细导出任务(单任务,按盘点范围分流)。 + * 异步执行:商品范围任务按 mode 导出——mode=location(缺省)Sheet「库位明细」 + * (每商品每库位一行:账面快照/盘点数量/差异);mode=summary Sheet1「明细汇总」 + * (每商品一行)+ Sheet2「商品差异」(仅差异商品);库位范围任务 Sheet「盘点明细」 + * (库位/商品/盘点数量)→ ExcelJS 流式写入 → COS 上传。 + * 进度通过 Redis 缓存追踪,立即返回任务ID;进度查询复用 exportTaskProgress。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 盘点任务ID。 + * @param {string} [data.mode] 商品盘点导出模式:location=区分库位明细(缺省)/summary=明细汇总+商品差异两 sheet;库位盘点忽略。 + * @return {Promise} 统一 success 包装,返回任务ID。 + */ + async exportDetail(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { id, mode } = data || {}; + + const checkId = Number(id); + if (!Number.isInteger(checkId) || checkId <= 0) { + return this.fail('盘点任务ID不能为空', {}, 400); + } + + const taskId = this.generateExportTaskId(); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + current_count: 0, + total_count: 0, + message: '导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 5, + current_count: 0, + total_count: 0, + message: '导出任务执行中', + result: null, + error: '', + }); + + const result = await this.service.systems.stockCheck.exportCheckDetail({ + warehouseId, + id: checkId, + mode, + onProgress: async progress => { + const safeProgress = this.isPlainObject(progress) ? progress : {}; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: safeProgress.status || 'running', + progress: safeProgress.progress, + current_count: safeProgress.currentCount || 0, + total_count: safeProgress.totalCount || 0, + message: safeProgress.message || '导出任务执行中', + result: safeProgress.result || null, + error: '', + }); + }, + }); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + current_count: result.current_count || 0, + total_count: result.total_count || 0, + message: '导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + current_count: 0, + total_count: 0, + message: '导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + /** * 查询盘点任务导出进度。 * diff --git a/app/service/systems/stock_check.js b/app/service/systems/stock_check.js index 53603e8..5b80e5d 100644 --- a/app/service/systems/stock_check.js +++ b/app/service/systems/stock_check.js @@ -4839,55 +4839,12 @@ class StockCheckService extends Service { 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', + const uploadInfo = await this._uploadExportExcelFile(filePath, filename, { + businessType: 'stockCheckExport', + description: `库存盘点导出,共 ${checks.length} 个盘点任务、${totalCount} 条盘点明细`, }); - 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 || '', - }; + return uploadInfo; } catch (error) { const workbookStream = workbook.stream; if (workbookStream && typeof workbookStream.destroy === 'function') { @@ -4899,6 +4856,412 @@ class StockCheckService extends Service { await fsp.rm(tempDir, { recursive: true, force: true }); } } + + /** + * 上传导出的 Excel 文件(与 afterSale/return_unpack 导出口径一致): + * 流式上传 → uploadFile → uploadSuccessNotify 落库,返回下载信息。 + * + * @param {string} filePath 本地临时文件路径。 + * @param {string} filename 文件名。 + * @param {Object} [options] 附加选项。 + * @param {string} [options.businessType] 业务类型(默认 stockCheckExport)。 + * @param {string} [options.description] 文件描述。 + * @return {Promise} { filename, fileKey, url, cdnUrl, cosUrl }。 + */ + async _uploadExportExcelFile(filePath, filename, options = {}) { + const { ctx } = this; + const businessType = options.businessType || 'stockCheckExport'; + const description = options.description || ''; + + 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, + description, + }); + } + + // 优先取 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 || '', + }; + } + + /** + * 盘点明细导出(单任务,按盘点范围分流): + * - 商品范围(scope_type=goods): + * mode=location(缺省):Sheet「库位明细」——每商品每库位一行 + * (盘点单号/商品编码/商品名称/规格/库位编码/账面数量(快照)/盘点数量/差异数量, + * 未盘库位盘点数量 0、差异留空); + * mode=summary:Sheet1「明细汇总」(每商品一行:账面快照合计/实盘合计/差异/盘点状态/ + * 盘点人/最近盘点时间)+ Sheet2「商品差异」(仅差异商品:账面/实盘/差异/差异类型); + * 未知商品(条码维度,无账面、差异=实盘=盘盈)追加在汇总与差异两个 sheet。 + * - 库位范围(scope_type=location):Sheet「盘点明细」——库位编码/商品编码/商品名称/盘点数量 + * (作业记录口径,未知商品编码=扫描条码,空库位标记商品为空、数量 0)。 + * 流式生成 Excel → COS 上传;通过 onProgress 回调实时推送进度。 + * + * @param {Object} params 导出参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {number} params.id 盘点任务ID。 + * @param {string} [params.mode] 商品盘点导出模式:location=区分库位明细(缺省)/summary=明细汇总+商品差异两 sheet;库位盘点忽略。 + * @param {Function} [params.onProgress] 进度回调。 + * @return {Promise} 导出结果,包含文件下载信息与 total_count。 + * @throws {Error} 任务不存在或参数非法时抛出业务错误(错误码 400)。 + */ + async exportCheckDetail(params = {}) { + const { warehouseId, id, mode, 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 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 isLocationScope = detailRows.length > 0 + && detailRows.every(row => (row.scope_type || 'goods') === 'location'); + + // 商品范围:复用 result 的商品合并聚合(账面=快照、实盘=作业记录聚合) + let goodsRows = []; + if (!isLocationScope) { + goodsRows = (await this._buildDetailAggregations({ detailRows, recordRows: records })) + .filter(row => row.scope_type === 'goods'); + } + + // 库位范围商品快照(库位行的作业记录不带商品快照列) + const stockIds = [ ...new Set(records + .map(row => Number(row.stock_id)) + .filter(stockId => Number.isInteger(stockId) && stockId > 0)) ]; + let stockMap = new Map(); + if (stockIds.length > 0) { + const stockRows = await ctx.model.StockWarehouse.findAll({ + where: { id: { [Op.in]: stockIds } }, + attributes: [ 'id', 'item_code', 'item_name' ], + raw: true, + }); + stockMap = new Map(stockRows.map(item => [ Number(item.id), item ])); + } + + const normalizedMode = isLocationScope + ? 'simple' + : (String(mode || '').trim() === 'summary' ? 'summary' : 'location'); + + const totalCount = isLocationScope + ? records.length + : (normalizedMode === 'summary' + ? goodsRows.reduce( + (sum, row) => sum + 1 + (Array.isArray(row.unknown_items) ? row.unknown_items.length : 0), + 0 + ) + : goodsRows.reduce( + (sum, row) => sum + (Array.isArray(row.locations) ? row.locations.length : 0), + 0 + )); + + await reportProgress('running', 10, `正在导出盘点明细(共 ${totalCount} 行)...`, { + totalCount, + currentCount: 0, + }); + + const exportResult = await this._generateAndUploadCheckDetailExcel({ + check: check.get({ plain: true }), + isLocationScope, + mode: normalizedMode, + goodsRows, + records, + stockMap, + totalCount, + onProgress, + }); + + await reportProgress('success', 100, '导出完成', { + totalCount, + currentCount: totalCount, + result: exportResult, + }); + + return { + ...exportResult, + total_count: totalCount, + current_count: totalCount, + }; + } + + /** + * 生成盘点明细导出 Excel 并上传 COS(Sheet 结构随盘点范围与导出模式变化,见 exportCheckDetail)。 + * + * @param {Object} params 生成参数。 + * @param {Object} params.check 盘点主表行。 + * @param {boolean} params.isLocationScope 是否库位范围盘点。 + * @param {string} params.mode 导出模式:simple(库位范围)/location(商品库位明细)/summary(商品汇总+差异)。 + * @param {Array} params.goodsRows 商品范围聚合行(result 口径)。 + * @param {Array} params.records 作业记录原始行。 + * @param {Map} params.stockMap 商品快照映射(库位范围用)。 + * @param {number} params.totalCount 总行数(进度计算用)。 + * @param {Function} [params.onProgress] 进度回调。 + * @return {Promise} { filename, fileKey, url, cdnUrl, cosUrl }。 + */ + async _generateAndUploadCheckDetailExcel(params = {}) { + const { + check, + isLocationScope, + mode, + goodsRows = [], + records = [], + stockMap = new Map(), + totalCount = 0, + onProgress, + } = params; + 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-detail-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 = `盘点明细导出_${check.check_no || check.id}_${dateToken}.xlsx`; + const filePath = path.join(tempDir, filename); + + const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({ + filename: filePath, + useStyles: false, + useSharedStrings: false, + }); + + try { + const checkNo = String(check.check_no || ''); + let currentCount = 0; + const reportRowProgress = async () => { + currentCount++; + 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, + }); + } + }; + + if (isLocationScope) { + // ---- 库位范围:库位 / 商品 / 盘点数量 ---- + const sheet = workbook.addWorksheet('盘点明细'); + sheet.addRow([ '库位编码', '商品编码', '商品名称', '盘点数量' ]).commit(); + for (const record of records) { + const recordStockId = Number(record.stock_id); + const isUnknownGoods = !Number.isInteger(recordStockId) || recordStockId <= 0; + const stock = stockMap.get(recordStockId) || {}; + sheet.addRow([ + String(record.location_code || '').trim(), + record.is_empty ? '' : (isUnknownGoods ? String(record.barcode || '').trim() : (stock.item_code || '')), + record.is_empty ? '' : (isUnknownGoods ? String(record.item_name || record.barcode || '').trim() : (stock.item_name || '')), + record.is_empty ? 0 : (Number(record.quantity) || 0), + ]).commit(); + await reportRowProgress(); + } + sheet.commit(); + } else if (mode === 'summary') { + // ---- 商品范围 mode=summary:明细汇总 + 商品差异 两个 sheet ---- + const summarySheet = workbook.addWorksheet('明细汇总'); + summarySheet.addRow([ + '盘点单号', + '商品编码', + '商品名称', + '规格', + '账面数量', + '盘点数量', + '差异数量', + '盘点状态', + '盘点人', + '最近盘点时间', + ]).commit(); + const diffSheet = workbook.addWorksheet('商品差异'); + diffSheet.addRow([ + '盘点单号', + '商品编码', + '商品名称', + '规格', + '账面数量', + '盘点数量', + '差异数量', + '差异类型', + ]).commit(); + + for (const row of goodsRows) { + const hasRecords = Array.isArray(row.records) && row.records.length > 0; + summarySheet.addRow([ + checkNo, + row.item_code || '', + row.item_name || '', + row.spec || '', + Number(row.system_quantity) || 0, + hasRecords ? (Number(row.checked_quantity) || 0) : '', + hasRecords ? (Number(row.diff_quantity) || 0) : '', + hasRecords ? '已盘' : '未盘', + Array.isArray(row.checkers) ? row.checkers.join('、') : '', + row.last_checked_at ? this._formatLocalDateTime(row.last_checked_at) : '', + ]).commit(); + if (hasRecords && row.is_diff === 1) { + const diffQuantity = Number(row.diff_quantity) || 0; + diffSheet.addRow([ + checkNo, + row.item_code || '', + row.item_name || '', + row.spec || '', + Number(row.system_quantity) || 0, + Number(row.checked_quantity) || 0, + diffQuantity, + diffQuantity > 0 ? '盘盈' : '盘亏', + ]).commit(); + } + // 未知商品(条码维度,无账面,差异=实盘=盘盈) + for (const unknownItem of (Array.isArray(row.unknown_items) ? row.unknown_items : [])) { + const checkedQuantity = Number(unknownItem.checked_quantity) || 0; + summarySheet.addRow([ + checkNo, + unknownItem.barcode || '', + unknownItem.item_name || '', + '', + 0, + checkedQuantity, + checkedQuantity, + '已盘', + '', + '', + ]).commit(); + diffSheet.addRow([ + checkNo, + unknownItem.barcode || '', + unknownItem.item_name || '', + '', + 0, + checkedQuantity, + checkedQuantity, + '盘盈', + ]).commit(); + } + await reportRowProgress(); + } + summarySheet.commit(); + diffSheet.commit(); + } else { + // ---- 商品范围 mode=location:库位明细(每商品每库位一行)---- + const sheet = workbook.addWorksheet('库位明细'); + sheet.addRow([ + '盘点单号', + '商品编码', + '商品名称', + '规格', + '库位编码', + '账面数量', + '盘点数量', + '差异数量', + ]).commit(); + for (const row of goodsRows) { + const hasRecords = Array.isArray(row.records) && row.records.length > 0; + for (const location of (Array.isArray(row.locations) ? row.locations : [])) { + const systemQuantity = Number(location.system_quantity) || 0; + const quantity = Number(location.quantity) || 0; + sheet.addRow([ + checkNo, + row.item_code || '', + row.item_name || '', + row.spec || '', + location.location_code || '', + systemQuantity, + quantity, + hasRecords ? quantity - systemQuantity : '', + ]).commit(); + await reportRowProgress(); + } + } + sheet.commit(); + } + + await workbook.commit(); + + await reportProgress('running', 90, '正在上传文件...', { totalCount, currentCount: totalCount }); + + const uploadInfo = await this._uploadExportExcelFile(filePath, filename, { + businessType: 'stockCheckDetailExport', + description: `盘点明细导出 ${check.check_no || check.id},共 ${totalCount} 行`, + }); + + return uploadInfo; + } catch (error) { + const workbookStream = workbook.stream; + if (workbookStream && typeof workbookStream.destroy === 'function') { + workbookStream.destroy(); + } + ctx.logger.error(`[stock.check.exportDetail] 生成/上传 Excel 失败: ${error.message}`); + throw error; + } finally { + await fsp.rm(tempDir, { recursive: true, force: true }); + } + } } module.exports = StockCheckService; diff --git a/methods/changes/system.json b/methods/changes/system.json index 37ef7ea..58d0ecd 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,20 @@ [ + { + "version": "0.3.261", + "date": "2026-10-10", + "type": "added", + "summary": "新增 stock.check.exportDetail 盘点明细导出接口(异步,按盘点范围分流:商品盘点分库位明细/汇总+差异两模式,库位盘点简化)", + "methods": [ + "stock.check.exportDetail" + ], + "notes": [ + "接口:stock.check.exportDetail,入参 id(盘点任务ID,必填)+ mode(可选,仅商品盘点生效:location=区分库位明细(缺省)/summary=明细汇总+商品差异两 sheet;库位盘点忽略);异步执行,立即返回 task_id,进度查询复用 stock.check.exportTaskProgress。", + "商品盘点 mode=location:Sheet「库位明细」每商品每库位一行(盘点单号/商品编码/商品名称/规格/库位编码/账面数量(明细行 system_quantity 快照,提交审核时刷新)/盘点数量/差异数量;未盘库位盘点数量 0、差异留空);mode=summary:Sheet1「明细汇总」(每商品一行:账面快照合计/实盘合计/差异/盘点状态/盘点人/最近盘点时间)+ Sheet2「商品差异」(仅差异商品:账面/实盘/差异/差异类型盘盈|盘亏);未知商品追加在汇总与差异两 sheet(无账面、差异=实盘=盘盈)。", + "库位盘点:Sheet「盘点明细」作业记录口径(库位编码/商品编码/商品名称/盘点数量),未知商品编码=扫描条码、空库位标记商品为空数量 0。", + "代码依据:app/service/systems/stock_check.js#exportCheckDetail/#_generateAndUploadCheckDetailExcel(商品范围复用 result 的商品合并聚合)/#_uploadExportExcelFile(原 _generateAndUploadStockCheckExcel 上传段抽为公共方法,两处导出一致复用)+ app/service/systemMethods/stock/check.js#exportDetail(ALL_METHOD_NAMES/_noNeedLog 已加入);回归测试 4 用例(location/summary/库位任务三口径回读 Excel 断言 + 方法层异步任务轮询至 success),stock_check 全量 235 用例通过、ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=stock.check 分组新增 stock.check.exportDetail 一条(位于 stock.check.export 之后,分组由 24 条增至 25 条);根版本 0.3.260 → 0.3.261、updatedAt 保持 2026-10-10;methods/changes/system.json 新增本条(插入数组首位);其余 24 条 method 未改动。" + ] + }, { "version": "0.3.260", "date": "2026-10-10", diff --git a/methods/system.json b/methods/system.json index e9e50c1..8015247 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,7 +1,7 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.260", + "version": "0.3.261", "updatedAt": "2026-10-10", "headers": [ { @@ -40451,6 +40451,144 @@ "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库(显式 WMS_DB_TARGET=local,127.0.0.1:3307/wms)与生产库(显式 WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致;stock.check 分组共 20 条 method 无损。" ] }, + { + "method": "stock.check.exportDetail", + "description": "提交盘点明细导出任务(异步,单任务,按盘点范围分流):商品范围任务(scope_type=goods)按 mode 导出——mode=location(缺省)Sheet「库位明细」(每商品每库位一行,列:盘点单号/商品编码/商品名称/规格/库位编码/账面数量(明细行 system_quantity 快照,提交审核时刷新)/盘点数量/差异数量;未盘库位盘点数量 0、差异留空);mode=summary 两个 Sheet——Sheet1「明细汇总」(每商品一行,列:盘点单号/商品编码/商品名称/规格/账面数量(快照合计)/盘点数量/差异数量/盘点状态(已盘|未盘)/盘点人/最近盘点时间)+ Sheet2「商品差异」(仅差异商品,列:盘点单号/商品编码/商品名称/规格/账面数量/盘点数量/差异数量/差异类型(盘盈|盘亏));未知商品(条码维度,无账面、差异=实盘=盘盈)追加在汇总与差异两个 sheet;库位范围任务(scope_type=location)Sheet「盘点明细」(作业记录口径,列:库位编码/商品编码/商品名称/盘点数量;未知商品编码=扫描条码、空库位标记商品编码为空数量 0)。ExcelJS 流式生成后上传 COS;进度通过 Redis 缓存(key stock_check_export_task_*,TTL 1800 秒)追踪,立即返回任务ID;进度查询复用 stock.check.exportTaskProgress。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "盘点任务ID" + }, + { + "name": "mode", + "type": "string", + "required": false, + "source": "body", + "description": "商品盘点导出模式:location=区分库位明细(缺省)/summary=明细汇总+商品差异两 sheet;库位盘点忽略该参数" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "请求结果标记:success=成功 / failure=失败" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:成功为 1;失败为具体业务错误码(如 400/500)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息:成功为 ok;失败为具体错误文案" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "业务数据对象(统一 data 层封装:本方法全部业务数据整体位于 data 内,data 内字段口径与改造前完全一致;失败时 data=null)", + "children": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "导出任务ID(格式 stock_check_export_{warehouseId}_{时间戳}_{随机串})" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted/running/success/failed/not_found" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "进度百分比(0-100)" + }, + { + "name": "current_count", + "type": "number", + "required": true, + "description": "当前已处理明细行数" + }, + { + "name": "total_count", + "type": "number", + "required": true, + "description": "导出总行数(库位范围=作业记录数;商品范围 location 模式=库位明细行数、summary 模式=商品数+未知商品数,导出前即确定)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务提示信息" + }, + { + "name": "result", + "type": "object", + "required": false, + "description": "任务成功时的结果对象(含 filename/fileKey/url/cdnUrl/cosUrl)" + }, + { + "name": "error", + "type": "string", + "required": true, + "description": "任务失败时的错误信息(成功时为空串)" + }, + { + "name": "update_time", + "type": "number", + "required": true, + "description": "缓存更新时间(毫秒时间戳)" + } + ] + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "服务器时间戳(秒)" + } + ], + "errors": [ + { + "code": 400, + "message": "盘点任务ID不能为空 / 盘点任务不存在" + }, + { + "code": 500, + "message": "服务器内部错误" + } + ], + "notes": [ + "权限口径:随 ALL_METHOD_NAMES 免 API 权限(isNeedAuth=false)、免仓库有效期鉴权、必须登录(isNeedLogin=true);加入免日志清单 _noNeedLog。", + "异步执行:查询任务/明细/作业记录 → 商品范围复用 result 的商品合并聚合(账面=明细行 system_quantity 快照、实盘=作业记录聚合)→ ExcelJS 流式写入 → COS 上传;进度缓存 Redis key stock_check_export_task_{taskId},TTL 1800 秒;进度查询复用 stock.check.exportTaskProgress(task_id 通用)。", + "商品盘点 mode=location:Sheet「库位明细」每商品每库位一行(快照库位按明细 id 升序、仅作业记录存在的库位追加末尾),未盘商品行仍输出全部快照库位(盘点数量 0、差异留空),差异数量仅商品有作业记录时计算(盘点-账面)。", + "商品盘点 mode=summary:Sheet1「明细汇总」每商品一行(账面=各库位快照合计、盘点=实盘合计、差异=盘点-账面,未盘商品盘点/差异留空);Sheet2「商品差异」仅 is_diff=1 的商品(差异类型:正=盘盈、负=盘亏);未知商品(stock_id 为空按条码归组)无账面,追加在汇总与差异两个 sheet(差异=实盘=盘盈)。", + "库位范围任务:Sheet「盘点明细」作业记录口径(库位编码/商品编码/商品名称/盘点数量),已知商品编码名称从 wms_stock_warehouse 补齐、未知商品编码=扫描条码(barcode)、名称=上报名称快照;空库位标记记录商品编码为空、盘点数量 0;mode 入参忽略。", + "代码依据:app/service/systems/stock_check.js#exportCheckDetail/#_generateAndUploadCheckDetailExcel/#_uploadExportExcelFile(原 _generateAndUploadStockCheckExcel 上传段抽为公共方法复用)+ app/service/systemMethods/stock/check.js#exportDetail。", + "响应统一 data 层封装(2026-10-02 起):成功 { flag:\"success\", code:1, message:\"ok\", data:<业务数据整体>, timestamp };失败 { flag:\"failure\", code:<业务错误码>, message:<错误文案>, data:null, timestamp }。本方法业务数据整体位于 data 内,data 内字段口径与改造前一致(原顶层业务字段全部移入 data.children)。代码依据:app/service/systemMethods/stock/check.js#_call(23 个方法共用统一包装)+ app/lib/api_response.js#toSuccess(识别标准载荷后顶层补充 timestamp)。", + "文档变更范围:methods/system.json 的 module=stock.check 分组新增 stock.check.exportDetail 一条(位于 stock.check.export 之后);根版本 0.3.260 → 0.3.261、updatedAt 保持 2026-10-10;methods/changes/system.json 新增本条(插入数组首位);其余 24 条 method 未改动(stock.check 分组由 24 条增至 25 条)。" + ] + }, { "method": "stock.check.exportTaskProgress", "description": "查询盘点任务导出进度:按 task_id(兼容 taskId 驼峰写法)读取 Redis 任务缓存;任务不存在时正常返回(status=not_found),不视为错误;任务成功时 download_url 从 result 兜底提取(url/cdnUrl/cosUrl/fileKey)。",