From 2597faac4c04e869cf549116e701cebe68293507 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Tue, 1 Sep 2026 00:42:30 +0800 Subject: [PATCH] =?UTF-8?q?feat(report):=20stockFlow=20=E6=8A=A5=E8=A1=A8?= =?UTF-8?q?=209=20=E5=88=97=E6=96=B0=E9=A1=BA=E5=BA=8F=E9=87=8D=E6=9E=84?= =?UTF-8?q?=E4=B8=8E=E6=8A=95=E9=80=92=E8=B4=A7=E4=B8=BB=E9=9A=94=E7=A6=BB?= =?UTF-8?q?=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1) 报表导出列重构为 9 组列(产品名称/条码/外部编码/每日出入库/待处理订单占用数/可用库存/7日总出库数量/推荐采购量/是否触发预警),外部编码 stock_store 优先 fallback,新增 pending_occupy 取仓库主表锁定数量;2) 投递货主隔离修复(上传目录按货主/仓库隔离、投递与通知幂等键含 storeId、processOne 货主维度强校验);3) 文档与 methods 变更记录同步。 --- app/service/systems/report.js | 16 +++- app/service/systems/report/queries/index.js | 4 +- .../report/queries/sevenDayStockFlow.js | 75 +++++++++++------ app/service/systems/reportDelivery.js | 42 ++++++---- docs/report-config-guide.md | 84 ++++++++++++------- methods/changes/system.json | 35 ++++++++ methods/system.json | 12 +-- 7 files changed, 186 insertions(+), 82 deletions(-) diff --git a/app/service/systems/report.js b/app/service/systems/report.js index 024f0e9..55336b8 100644 --- a/app/service/systems/report.js +++ b/app/service/systems/report.js @@ -235,10 +235,11 @@ class ReportService extends Service { /** * 生成报表 Excel 并上传,返回 fileKey/url(供手动导出与货主投递复用)。 + * 上传目录按(报表定义 + 货主/仓库)隔离,保证不同货主的报表文件互不覆盖。 * @param {Object} options 入参 * @param {number|string} options.reportId 报表定义ID - * @param {number|null} [options.storeId] 货主ID - * @param {number|null} [options.warehouseId] 仓库ID + * @param {number|null} [options.storeId] 货主ID(货主维度报表必传,有效时按货主隔离上传目录) + * @param {number|null} [options.warehouseId] 仓库ID(货主维度缺省时按仓库隔离上传目录) * @param {Object} [options.params] 查询器业务参数(如 bizDate) * @return {Promise<{fileKey: string, url: string, filename: string, size: number}>} 上传结果 */ @@ -250,9 +251,18 @@ class ReportService extends Service { params, }); + // 上传目录按(报表定义 + 货主/仓库)隔离:同一报表定义下不同货主不得共用同一文件 key, + // 避免后投递货主的文件覆盖先投递货主的文件(货主限制不符缺陷)。 + // storeId 缺省时退化为仓库维度,未传货主/仓库时按 common 兜底(保持手动导出兼容)。 + const normalizedStoreId = Number(storeId) || 0; + const normalizedWarehouseId = Number(warehouseId) || 0; + const ownerSegment = normalizedStoreId > 0 + ? `store-${normalizedStoreId}` + : (normalizedWarehouseId > 0 ? `warehouse-${normalizedWarehouseId}` : 'common'); + const uploadResult = await this.ctx.service.systems.excel.generateAndUpload({ filename, - dir: `exports/report/${String(reportId).trim()}`, + dir: `exports/report/${String(reportId).trim()}/${ownerSegment}`, category: 'document', sheets, }); diff --git a/app/service/systems/report/queries/index.js b/app/service/systems/report/queries/index.js index 36d80f2..03c2bc2 100644 --- a/app/service/systems/report/queries/index.js +++ b/app/service/systems/report/queries/index.js @@ -26,8 +26,8 @@ const DESCRIPTIONS = [ { key: 'stockFlow', title: '库存变化以及补货报表', - description: '按日窗口聚合出入库流水与正品库存,输出每 SKU 每日出/入库、可用/总库存、' - + '锁定数、待出、日均出/入库、预计可售天数、建议补货量与库存预警', + description: '按日窗口聚合出入库流水与正品库存,输出每 SKU 每日出/入库、外部编码、' + + '待处理订单占用数、可用库存、7日总出库数量、推荐采购量与是否触发预警', window: { ...(sevenDayStockFlow.defaultWindow || { dayCount: 7, cutoverHour: 7 }), }, diff --git a/app/service/systems/report/queries/sevenDayStockFlow.js b/app/service/systems/report/queries/sevenDayStockFlow.js index c18d620..e6a615f 100644 --- a/app/service/systems/report/queries/sevenDayStockFlow.js +++ b/app/service/systems/report/queries/sevenDayStockFlow.js @@ -4,17 +4,19 @@ const { buildDayWindows, resolveWindowConfig } = require('../../../../lib/report const { avgDaysPerWeek, suggestWithCompensate, warnOf } = require('../../../../lib/report/formatters'); /** - * 库存变化以及补货报表查询器的静态字段清单(前端可读列元数据)。 + * 库存变化以及补货报表查询器的静态字段清单(前端可读列元数据,决定导出列顺序)。 + * 仅保留以下 9 组导出列:产品名称/条码/外部编码/每日出入库/待处理订单占用数/ + * 可用库存/7日总出库数量/推荐采购量/是否触发预警。 * key 与查询器返回的行字段一一对应;computed=true 表示由查询器预计算、非原始表字段; * asText=true 表示渲染层将该列落地为 Excel 文本单元格(长数字串防科学计数法); - * daily 为数组类型,children 描述每日出入库子字段。 + * daily 为数组类型,children 描述每日出入库子字段; + * item_code 列复用原“商品编码”key 以兼容既有报表定义的 fields 勾选,label 改为“外部编码”。 * @type {Array} */ const FIELDS = Object.freeze([ - { key: 'stock_id', label: '库存ID', type: 'number' }, - { key: 'item_code', label: '商品编码', type: 'string', asText: true }, - { key: 'item_name', label: '商品名称', type: 'string' }, + { key: 'item_name', label: '产品名称', type: 'string' }, { key: 'barcode', label: '条码', type: 'string', asText: true }, + { key: 'item_code', label: '外部编码', type: 'string', asText: true }, { key: 'daily', label: '每日出入库', @@ -24,17 +26,11 @@ const FIELDS = Object.freeze([ { key: 'rk', label: '入库数', type: 'number' }, ], }, - { key: 'ck_total', label: '出库合计', type: 'number' }, - { key: 'rk_total', label: '入库合计', type: 'number' }, + { key: 'pending_occupy', label: '待处理订单占用数', type: 'number' }, { key: 'available', label: '可用库存', type: 'number' }, - { key: 'total', label: '总库存', type: 'number' }, - { key: 'pending', label: '待出库存', type: 'number' }, - { key: 'locked', label: '锁定数', type: 'number' }, - { key: 'ck_avg', label: '出库日均(×10)', type: 'number', computed: true }, - { key: 'rk_avg', label: '入库日均(×10)', type: 'number', computed: true }, - { key: 'stock_days', label: '预计可售天数', type: 'number', computed: true }, - { key: 'suggest', label: '建议补货量', type: 'number', computed: true }, - { key: 'warn', label: '库存预警', type: 'boolean', computed: true }, + { key: 'ck_total', label: '7日总出库数量', type: 'number' }, + { key: 'suggest', label: '推荐采购量', type: 'number', computed: true }, + { key: 'warn', label: '是否触发预警', type: 'boolean', computed: true }, ]); /** @@ -51,14 +47,18 @@ const DEFAULT_WINDOW = Object.freeze({ dayCount: 7, cutoverHour: 7 }); * (缺省 7 天、07:00 切点,可由 params.dayCount/cutoverHour 覆盖); * 2. 流水:wms_stock_transaction,transaction_type IN (INBOUND, OUTBOUND),显式排除 LOCK/UNLOCK, * 按 created_at 落入窗口,INBOUND→rk、OUTBOUND→ck; - * 3. 可用/总库存口径:wms_storage(库位级正品明细),inventory_type='ZP'、is_enabled=1、未删除, - * SUM(quantity)=总库存、SUM(available_quantity)=可用库存、SUM(locked_quantity)=锁定数, - * 待出库存=总库存-可用库存;与 wms_stock_warehouse 主表的 quantity/locked_quantity 可能存在口径差异; + * 3. 可用库存口径:wms_storage(库位级正品明细),inventory_type='ZP'、is_enabled=1、未删除, + * SUM(available_quantity)=可用库存(行内 available 列); + * SUM(quantity)/SUM(locked_quantity)/待出库存等仅保留为行内内部计算字段,已不在导出列清单中; * 4. 条码口径:wms_stock_barcodes 多值取字典序第一条(表内无主条码标志,旧 PHP 取 MIN(barcode) 语义); - * 5. 行范围:窗口内有流水 或 有正品库存 的 SKU 均出列,按 item_code 升序、stock_id 升序; - * 6. 日均口径:ck_avg/rk_avg = int(合计/天数×10)(formatters.avgDaysPerWeek); - * 7. 预计可售天数:出库日均>0 时 int(可用库存×10/出库日均×10),无出库时为 null; - * 8. suggest/warn 由 formatters 注册表计算(低库存补偿:available<20 且 rk_total<20)。 + * 5. 外部编码口径:优先 wms_stock_store.item_code(按 stock_id 关联 wms_stock_warehouse.id, + * stock_store 同 stock_id 多条时按 id 升序取第一条非空 item_code,stock_id 为空的记录不参与匹配), + * 未匹配则回落 wms_stock_warehouse.item_code,再无则留空; + * 6. 待处理订单占用数口径:取 wms_stock_warehouse.locked_quantity(仓库商品主表锁定数量, + * 不是 wms_storage 聚合的 locked_quantity 口径); + * 7. 行范围:窗口内有流水 或 有正品库存 的 SKU 均出列,按 item_code 升序、stock_id 升序; + * 8. suggest/warn 由 formatters 注册表计算(低库存补偿:available<20 且 rk_total<20), + * 内部仍计算 rk_total/日均/预计可售天数等字段供判定与复核,但不进入导出列清单。 * * @param {Object} args 查询器入参 * @param {Object} args.ctx Egg 上下文 @@ -183,12 +183,19 @@ async function sevenDayStockFlow({ ctx, storeId = null, warehouseId = null, para // 3) 商品资料与条码(条码多值取字典序第一条,假设:无主条码标志,等价旧 PHP MIN(barcode)) const stockIds = [ ...new Set([ ...flowMap.keys(), ...inventoryMap.keys() ]) ]; let stockRows = []; + let stockStoreRows = []; let barcodeRows = []; if (stockIds.length > 0) { - [ stockRows, barcodeRows ] = await Promise.all([ + [ stockRows, stockStoreRows, barcodeRows ] = await Promise.all([ ctx.model.StockWarehouse.findAll({ where: { id: { [Op.in]: stockIds } }, - attributes: [ 'id', 'item_code', 'item_name' ], + attributes: [ 'id', 'item_code', 'item_name', 'locked_quantity' ], + raw: true, + }), + ctx.model.StockStore.findAll({ + where: { stock_id: { [Op.in]: stockIds } }, + attributes: [ 'id', 'stock_id', 'item_code' ], + order: [[ 'id', 'ASC' ]], raw: true, }), ctx.model.StockBarcode.findAll({ @@ -205,9 +212,23 @@ async function sevenDayStockFlow({ ctx, storeId = null, warehouseId = null, para stockMap.set(Number(row.id), { itemCode: String(row.item_code || '').trim(), itemName: String(row.item_name || '').trim(), + lockedQuantity: Number(row.locked_quantity) || 0, }); } + // 外部编码映射:同 stock_id 多条记录时按 id 升序取第一条非空 item_code(stock_id 为空记录不参与) + const externalCodeMap = new Map(); + for (const row of stockStoreRows) { + const stockId = Number(row.stock_id); + if (!Number.isInteger(stockId) || stockId <= 0) { + continue; + } + const itemCode = String(row.item_code || '').trim(); + if (!externalCodeMap.has(stockId) && itemCode) { + externalCodeMap.set(stockId, itemCode); + } + } + const barcodeMap = new Map(); for (const row of barcodeRows) { const stockId = Number(row.stock_id); @@ -226,7 +247,7 @@ async function sevenDayStockFlow({ ctx, storeId = null, warehouseId = null, para rkTotal: 0, }; const inventory = inventoryMap.get(stockId) || { total: 0, available: 0, locked: 0, pending: 0 }; - const stock = stockMap.get(stockId) || { itemCode: '', itemName: '' }; + const stock = stockMap.get(stockId) || { itemCode: '', itemName: '', lockedQuantity: 0 }; const available = inventory.available; const total = inventory.total; const ckTotal = flow.ckTotal; @@ -238,7 +259,8 @@ async function sevenDayStockFlow({ ctx, storeId = null, warehouseId = null, para return { stock_id: stockId, - item_code: stock.itemCode, + // 外部编码:优先 stock_store.item_code,未匹配则回落 stock_warehouse.item_code,再无则留空 + item_code: externalCodeMap.get(stockId) || stock.itemCode, item_name: stock.itemName, barcode: barcodeMap.get(stockId) || '', daily: flow.daily, @@ -248,6 +270,7 @@ async function sevenDayStockFlow({ ctx, storeId = null, warehouseId = null, para total, pending: inventory.pending, locked: inventory.locked, + pending_occupy: stock.lockedQuantity, ck_avg: ckAvg, rk_avg: rkAvg, stock_days: stockDays, diff --git a/app/service/systems/reportDelivery.js b/app/service/systems/reportDelivery.js index 9fed600..2066159 100644 --- a/app/service/systems/reportDelivery.js +++ b/app/service/systems/reportDelivery.js @@ -938,7 +938,9 @@ class ReportDeliveryService extends Service { * ext_id 幂等复用同一条消息记录,不重复写); * 3. 重推仍失败(retry 自身抛错)时向上抛错,交由上层 failed 退避循环 * (MAX_RETRY=3,退避 = retry_count × 60s); - * 4. 完成后按计划配置附带发送文本通知(与投递渠道独立)。 + * 4. 完成后按计划配置附带发送文本通知(与投递渠道独立); + * 5. 幂等键含货主维度(report:{store_id}:{report_definition_id}:{biz_date}:{time_point}), + * 不同货主的投递消息互不复用。 * * @param {Object} options 入参 * @param {Object} options.plan 投递计划 @@ -957,7 +959,8 @@ class ReportDeliveryService extends Service { const rawChannel = String(plan.channel || DEFAULT_CHANNEL).trim().toLowerCase() || DEFAULT_CHANNEL; const fileUrl = String(fileResult.url || fileResult.fileKey || ''); const reportDefinitionId = Number(plan.report_definition_id) || 0; - const idempotentKey = `report:${reportDefinitionId}:${bizDate}:${timePoint}`; + // 幂等键含货主维度:不同货主的投递消息不得互相复用/串扰(货主限制不符缺陷) + const idempotentKey = `report:${storeId}:${reportDefinitionId}:${bizDate}:${timePoint}`; // 渠道收敛:wecom/link 已弃用,历史残留数据按 inbox 兜底执行,避免历史计划投递卡死 if (rawChannel !== 'inbox') { @@ -1070,7 +1073,8 @@ class ReportDeliveryService extends Service { * 3. 通知成员(notify_member_ids 外部IM用户ID)→ 推送体 user_id 直接传数组,不循环拆发; * 选择群时成员数组随每个群推送携带,未选择群时单独做一次仅成员推送; * 4. {url} 为空时由渲染器替换为兜底文案(生成中占位),不阻断投递; - * 5. 推送失败抛出异常交由上层走失败退避重试(消息落库按 ext_id 幂等防重)。 + * 5. 推送失败抛出异常交由上层走失败退避重试(消息落库按 ext_id 幂等防重); + * 6. 幂等键含货主维度(report:notify:{store_id}:...),不同货主的文本通知互不复用。 * * @param {Object} options 入参 * @param {Object} options.plan 投递计划 @@ -1135,7 +1139,8 @@ class ReportDeliveryService extends Service { throw new Error('通知推送服务 warehouseNotify.pushSystemMessage 不可用'); } - const notifyExtId = `report:notify:${reportDefinitionId}:${bizDate}:${timePoint}`; + // 幂等键含货主维度:不同货主的文本通知不得互相复用/串扰(货主限制不符缺陷) + const notifyExtId = `report:notify:${storeId}:${reportDefinitionId}:${bizDate}:${timePoint}`; const commonOptions = { warehouseId, storeId, @@ -1184,6 +1189,7 @@ class ReportDeliveryService extends Service { /** * 处理单个(计划 × 时间点)的幂等生成与投递。 + * 货主维度强校验:store_id/report_definition_id 无效时直接抛错,绝不生成跨货主报表。 * @param {Object} options 入参 * @param {Object} options.plan 投递计划 * @param {number} options.storeId 货主ID @@ -1192,6 +1198,7 @@ class ReportDeliveryService extends Service { * @param {string} options.bizDate 数据日期 * @param {Date} options.now 触发时刻 * @return {Promise} 处理结果标记(delivered/failed/skipped) + * @throws {Error} 货主/报表定义维度非法时抛出 */ async processOne({ plan, storeId, reportId, timePoint, bizDate, now }) { const { ctx } = this; @@ -1200,9 +1207,16 @@ class ReportDeliveryService extends Service { throw new Error('投递记录模型 ReportDeliveryLog 不可用'); } + // 货主维度强校验:投递报表必须限定货主,避免 store_id 缺失时生成跨货主数据(货主限制不符缺陷) + const normalizedStoreId = Number(storeId) || 0; + const normalizedReportId = Number(reportId) || 0; + if (normalizedStoreId <= 0 || normalizedReportId <= 0) { + throw new Error(`投递计划维度非法(store_id=${storeId}, report_definition_id=${reportId}),拒绝生成报表`); + } + const uniqueWhere = { - store_id: storeId, - report_definition_id: reportId, + store_id: normalizedStoreId, + report_definition_id: normalizedReportId, biz_date: bizDate, time_point: timePoint, }; @@ -1249,22 +1263,22 @@ class ReportDeliveryService extends Service { return 'skipped'; } - const warehouseId = await this.resolveStoreWarehouse(storeId); + const warehouseId = await this.resolveStoreWarehouse(normalizedStoreId); if (warehouseId <= 0) { - await this.markFailed(log, `货主 ${storeId} 未找到有效合约仓库`); + await this.markFailed(log, `货主 ${normalizedStoreId} 未找到有效合约仓库`); return 'failed'; } // 读取报表定义一次(报表名称快照 + 投递通知文案共用,生成步骤内部会再按 id 读取) - const definition = await ctx.service.systems.report.getDefinition(reportId); + const definition = await ctx.service.systems.report.getDefinition(normalizedReportId); await this.markExporting(log, warehouseId, definition.name); // 生成上传(失败进入退避重试) let fileResult; try { fileResult = await ctx.service.systems.report.generate({ - reportId, - storeId, + reportId: normalizedReportId, + storeId: normalizedStoreId, warehouseId, params: { bizDate, @@ -1273,7 +1287,7 @@ class ReportDeliveryService extends Service { }); } catch (error) { const errorMessage = error && error.message ? error.message : `${error}`; - this.ctx.logger.error(`[reportDelivery] 报表生成失败 ${reportId}/${storeId}/${bizDate}/${timePoint}: ${errorMessage}`); + this.ctx.logger.error(`[reportDelivery] 报表生成失败 ${normalizedReportId}/${normalizedStoreId}/${bizDate}/${timePoint}: ${errorMessage}`); await this.markFailed(log, `报表生成失败: ${errorMessage}`); return 'failed'; } @@ -1285,7 +1299,7 @@ class ReportDeliveryService extends Service { definition, fileResult, warehouseId, - storeId, + storeId: normalizedStoreId, bizDate, timePoint, now, @@ -1294,7 +1308,7 @@ class ReportDeliveryService extends Service { return 'delivered'; } catch (error) { const errorMessage = error && error.message ? error.message : `${error}`; - this.ctx.logger.error(`[reportDelivery] 报表投递失败 ${reportId}/${storeId}/${bizDate}/${timePoint}: ${errorMessage}`); + this.ctx.logger.error(`[reportDelivery] 报表投递失败 ${normalizedReportId}/${normalizedStoreId}/${bizDate}/${timePoint}: ${errorMessage}`); await this.markFailed(log, `报表投递失败: ${errorMessage}`); return 'failed'; } diff --git a/docs/report-config-guide.md b/docs/report-config-guide.md index 6c7e328..5cae862 100644 --- a/docs/report-config-guide.md +++ b/docs/report-config-guide.md @@ -49,46 +49,48 @@ report.generate(method 层,异步任务,入参 report_id) | key | 标题 | 说明 | |---|---|---| -| `stockFlow` | 库存变化以及补货报表 | 按日窗口聚合出入库流水与正品库存,输出每 SKU 每日出/入库、可用/总库存、锁定数、待出、日均出/入库、预计可售天数、建议补货量与库存预警 | +| `stockFlow` | 库存变化以及补货报表 | 按日窗口聚合出入库流水与正品库存,输出每 SKU 产品名称/条码/外部编码/每日出入库/待处理订单占用数/可用库存/7日总出库数量/推荐采购量与是否触发预警 | `stockFlow` 缺省窗口参数:`window = { dayCount: 7, cutoverHour: 7 }`。 -`stockFlow` 全量字段清单(16 个顶层字段,`report.definition.typeList` 直接返回该规格): +`stockFlow` 全量字段清单(9 组列,顺序固定,`report.definition.typeList` 直接返回该规格): | key | label | type | computed | asText | 说明 | |---|---|---|---|---|---| -| `stock_id` | 库存ID | number | - | - | | -| `item_code` | 商品编码 | string | - | ✅ | 文本单元格落地,防科学计数法 | -| `item_name` | 商品名称 | string | - | - | | +| `item_name` | 产品名称 | string | - | - | | | `barcode` | 条码 | string | - | ✅ | 文本单元格落地,防科学计数法 | +| `item_code` | 外部编码 | string | - | ✅ | 文本单元格落地,防科学计数法;key 复用旧「商品编码」列(label 变更,兼容既有定义 fields 勾选) | | `daily` | 每日出入库 | array | - | - | children:`ck`(出库数,number)/ `rk`(入库数,number) | -| `ck_total` | 出库合计 | number | - | - | | -| `rk_total` | 入库合计 | number | - | - | | -| `available` | 可用库存 | number | - | - | | -| `total` | 总库存 | number | - | - | | -| `pending` | 待出库存 | number | - | - | | -| `locked` | 锁定数 | number | - | - | | -| `ck_avg` | 出库日均(×10) | number | ✅ | - | 预计算字段 | -| `rk_avg` | 入库日均(×10) | number | ✅ | - | 预计算字段 | -| `stock_days` | 预计可售天数 | number | ✅ | - | 预计算字段 | -| `suggest` | 建议补货量 | number | ✅ | - | 预计算字段 | -| `warn` | 库存预警 | boolean | ✅ | - | 预计算字段 | +| `pending_occupy` | 待处理订单占用数 | number | - | - | 口径:`wms_stock_warehouse.locked_quantity`(仓库商品主表锁定数量,非 `wms_storage` 聚合口径) | +| `available` | 可用库存 | number | - | - | `wms_storage` 正品库位明细 `SUM(available_quantity)` | +| `ck_total` | 7日总出库数量 | number | - | - | 窗口内 OUTBOUND 流水变更数量 `quantity` 合计 | +| `suggest` | 推荐采购量 | number | ✅ | - | 预计算字段(formatters 注册表,低库存补偿口径见 2.1 第 8 条) | +| `warn` | 是否触发预警 | boolean | ✅ | - | 预计算字段 | + +外部编码(`item_code`)取值口径:优先 `wms_stock_store.item_code`(按 stock_id 关联 `wms_stock_warehouse.id`,同 stock_id 多条时按 id 升序取第一条非空 item_code,stock_id 为空的记录不参与匹配)→ 回落 `wms_stock_warehouse.item_code` → 均无则留空。 + +已移除旧列(不再导出,共 8 个):`stock_id`、`rk_total`、`total`、`pending`、`locked`、`ck_avg`、`rk_avg`、`stock_days`; +行内仍计算 `rk_total`/日均/预计可售天数等字段供 `suggest`/`warn` 判定与测试复核,但不进入导出列清单。 ### 2.1 stockFlow 口径与假设(8 条,供测试复核) 1. **窗口**:`dayCount` 个 `[D cutoverHour:00, D+1 cutoverHour:00)` 本地时区半开区间 (缺省 7 天、07:00 切点,可由请求 `params.dayCount/cutoverHour` 覆盖)。 2. **流水**:`wms_stock_transaction`,`transaction_type IN (INBOUND, OUTBOUND)`,显式排除 LOCK/UNLOCK, - 按 `created_at` 落入窗口,INBOUND→rk、OUTBOUND→ck。 -3. **库存口径**:`wms_storage`(库位级正品明细),`inventory_type='ZP'`、`is_enabled=1`、未删除, - `SUM(quantity)`=总库存、`SUM(available_quantity)`=可用库存、`SUM(locked_quantity)`=锁定数、 - 待出库存=总库存-可用库存;与 `wms_stock_warehouse` 主表的 `quantity/locked_quantity` 可能存在口径差异。 + 按 `created_at` 落入窗口,INBOUND→rk、OUTBOUND→ck(变更数量 `quantity` 即出入库数)。 +3. **可用库存**:`wms_storage`(库位级正品明细),`inventory_type='ZP'`、`is_enabled=1`、未删除, + `SUM(available_quantity)`=可用库存(行内 `available` 列);`SUM(quantity)`/`SUM(locked_quantity)`/ + 待出库存等仅保留为行内内部计算字段,已不在导出列清单中。 4. **条码**:`wms_stock_barcodes` 多值取字典序第一条(表内无主条码标志,等价旧 PHP `MIN(barcode)` 语义)。 -5. **行范围**:窗口内有流水或有正品库存的 SKU 均出列,按 `item_code` 升序、`stock_id` 升序。 -6. **日均口径**:`ck_avg/rk_avg = int(合计/天数×10)`(`formatters.avgDaysPerWeek`)。 -7. **预计可售天数**:出库日均>0 时 `int(可用库存×10/出库日均×10)`(`available×10/ckAvg` 取整),无出库时为 null。 +5. **外部编码**:优先 `wms_stock_store.item_code`(按 stock_id 关联 `wms_stock_warehouse.id`,同 stock_id 多条时 + 按 id 升序取第一条非空 item_code,stock_id 为空的记录不参与匹配),未匹配则回落 + `wms_stock_warehouse.item_code`,再无则留空。 +6. **待处理订单占用数**:取 `wms_stock_warehouse.locked_quantity`(仓库商品主表锁定数量, + 不是 `wms_storage` 聚合的 locked_quantity 口径)。 +7. **行范围**:窗口内有流水或有正品库存的 SKU 均出列,按 `item_code` 升序、`stock_id` 升序。 8. **suggest/warn**:由 `formatters` 注册表计算。低库存补偿:`available < 20` 且 `rk_total < 20` 时 - 建议补货量补偿到不低于 30;预警判定由 `warnOf(ck_total, available, rk_total)` 计算。 + 推荐采购量补偿到不低于 30;预警判定由 `warnOf(ck_total, available, rk_total)` 计算。 + 行内仍计算 `rk_total`/日均/预计可售天数等字段供判定与复核,但不进入导出列清单。 ## 3. 渲染规则(renderSheetByType,无 sheet_config) @@ -106,17 +108,25 @@ report.generate(method 层,异步任务,入参 report_id) - **asText(文本单元格)**:由类型字段规格硬编码(如 `item_code`/`barcode` 声明 `asText: true`), 渲染层 `renderSheetByType` 将声明 `asText` 的列收集为 `textColumns`(0 基列索引数组,未声明任何 `asText` 列时不输出该字段), 由 `app/service/systems/excel.js` 落地:ExcelJS 路径逐单元格 `numFmt='@'` 并把值转为字符串(原始对象除外), - SheetJS 路径逐单元格 `t:'s'`、`z:'@'` 并把值字符串化。适用于条码、商品编码等长数字串 + SheetJS 路径逐单元格 `t:'s'`、`z:'@'` 并把值字符串化。适用于条码、外部编码等长数字串 (防止被 Excel 按数值展示成科学计数法),**无需**再配合 `textPrefix` 的 `'` 前缀 (`textPrefix` 格式化器保留注册仅向后兼容)。 - sheet 名称为类型标题(如「库存变化以及补货报表」);`columns` 恒输出空数组 (数据以 AOA 二维数组形式输出,表头行内联在 rows 首位)。 -## 4. 导出文件名(file_name) +## 4. 导出文件名(file_name)与上传目录(fileKey) - `file_name` 为文件名模板,`{date}` 替换为数据日期(请求 `params.bizDate`,缺省服务器当天,`YYYY-MM-DD`)。 - 缺省模板:`_.xlsx`;不以 `.xlsx`/`.xls` 结尾时自动补 `.xlsx`。 -- 上传目录:`exports/report//`。 +- 上传目录(COS 文件 key)按「报表定义 + 货主/仓库」维度隔离(2026-08-31 修复「货主限制不符」缺陷: + 修复前统一为 `exports/report//`,不同货主的报表文件会互相覆盖): + - `store_id` 有效(>0):`exports/report//store-/`; + - `store_id` 缺省且 `warehouse_id` 有效(>0):`exports/report//warehouse-/`; + - 两者均缺省:`exports/report//common/`(手动导出兼容兜底)。 +- 完整 COS key 由 `app/service/systems/excel.js` `generateAndUpload` 在上述目录后追加 `{YYYYMMDD}/` 日期目录与文件名; + `report.generate` 任务结果 `result.fileKey` / `download_url` 即该隔离 key。 +- 货主定时投递固定走 `store-` 隔离(`reportDelivery.processOne` 必传货主并强校验); + 手动导出未传 `store_id` 时按 `warehouse-`(登录上下文仓库)或 `common` 兜底。 ## 5. 货主定时投递(wms_report_delivery_plan / wms_report_delivery_log) @@ -148,6 +158,12 @@ report.generate(method 层,异步任务,入参 report_id) `report_name` 为投递时报表名称快照(审计回放,定义删除后仍可追溯)。 - **调度**(`reportDelivery.dispatch`,分钟级):按 HH:mm + 宽限窗口命中后, 对每个 `(store_id, report_definition_id, biz_date, time_point)` 幂等生成报表并投递(防重不防漏)。 +- **投递/通知幂等键含货主维度**(2026-08-31 修复「货主限制不符」缺陷):inbox 投递消息 `ext_id` 为 + `report:{store_id}:{report_definition_id}:{biz_date}:{time_point}`,文本通知幂等键为 + `report:notify:{store_id}:{report_definition_id}:{biz_date}:{time_point}`; + 修复前不含 `store_id`,不同货主的投递/通知消息会互相复用、串扰。 +- **货主维度强校验**(2026-08-31):`processOne` 对 `store_id`/`report_definition_id` 强校验, + 任一无效直接抛错「投递计划维度非法(…),拒绝生成报表」,绝不生成跨货主报表。 - **失败自动重推**:inbox 推送失败(`success=false` 或消息回写 `push_status=3`)时,立即复用 `inbox.message.retry` **重推一次**(`ext_id` 幂等复用同一条消息记录,不重复写);重推仍失败进入 `failed` 退避重试:`MAX_RETRY=3`,退避 `retry_count × 60s`;重试扫描条件 @@ -213,14 +229,14 @@ report.generate(method 层,异步任务,入参 report_id) "name": "库存变化以及补货报表", "type": "stockFlow", "fileName": "库存变化_{date}.xlsx", - "fields": ["item_code", "item_name", "barcode", "daily", "ck_total", "rk_total", "available", "total", "pending", "locked", "ck_avg", "suggest", "warn"], + "fields": ["item_name", "barcode", "item_code", "daily", "pending_occupy", "available", "ck_total", "suggest", "warn"], "is_enabled": 1, "remark": "" } ``` - `type` 必须命中注册表(当前仅 `stockFlow`,未知报「未知的报表类型: 」); - `fields` 必须为该类型注册字段子集(16 个顶层字段任意勾选,含非法 key 报可读错误并列出可用字段)。 + `fields` 必须为该类型注册字段子集(9 组列任意勾选,含非法 key 报可读错误并列出可用字段)。 - `file_name` 兼容 `fileName` 驼峰写法(驼峰优先);新增必填 `name`/`type`/`file_name`/`fields`; 更新按 `id` upsert,未传字段不覆盖;软删记录命中时自动恢复。 - 保存成功后响应即报表定义视图: @@ -266,12 +282,18 @@ report.generate(method 层,异步任务,入参 report_id) "description": "按日窗口聚合出入库流水与正品库存,……", "window": { "dayCount": 7, "cutoverHour": 7 }, "fields": [ - { "key": "item_code", "label": "商品编码", "type": "string", "asText": true }, + { "key": "item_name", "label": "产品名称", "type": "string" }, + { "key": "barcode", "label": "条码", "type": "string", "asText": true }, + { "key": "item_code", "label": "外部编码", "type": "string", "asText": true }, { "key": "daily", "label": "每日出入库", "type": "array", "children": [ { "key": "ck", "label": "出库数", "type": "number" }, { "key": "rk", "label": "入库数", "type": "number" } ]}, - { "key": "suggest", "label": "建议补货量", "type": "number", "computed": true } + { "key": "pending_occupy", "label": "待处理订单占用数", "type": "number" }, + { "key": "available", "label": "可用库存", "type": "number" }, + { "key": "ck_total", "label": "7日总出库数量", "type": "number" }, + { "key": "suggest", "label": "推荐采购量", "type": "number", "computed": true }, + { "key": "warn", "label": "是否触发预警", "type": "boolean", "computed": true } ] } ] diff --git a/methods/changes/system.json b/methods/changes/system.json index 61979c9..dc7452e 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,39 @@ [ + { + "version": "2026.08.31-report-stockflow-export-columns-restructure", + "date": "2026-08-31", + "type": "changed", + "summary": "stockFlow 报表(库存变化以及补货报表)导出列结构调整:静态字段清单由 16 个顶层字段收敛为 9 组列(顺序固定:item_name 产品名称 / barcode 条码 / item_code 外部编码 / daily 每日出入库(children ck/rk) / pending_occupy 待处理订单占用数 / available 可用库存 / ck_total 7日总出库数量 / suggest 推荐采购量 / warn 是否触发预警);item_code 复用为外部编码列(key 不变、label 由「商品编码」改为「外部编码」,取值优先 wms_stock_store.item_code 按 stock_id 关联、回落 wms_stock_warehouse.item_code);新增 pending_occupy(取 wms_stock_warehouse.locked_quantity,非 wms_storage 聚合口径);移除 stock_id/rk_total/total/pending/locked/ck_avg/rk_avg/stock_days 共 8 个旧列不再导出(rk_total/日均/预计可售天数等仍内部计算供 suggest/warn 判定与复核,不进入导出列)。", + "methods": [ + "report.definition.typeList" + ], + "notes": [ + "app/service/systems/report/queries/sevenDayStockFlow.js:FIELDS 静态字段清单由 16 个顶层字段收敛为 9 组列(item_name/barcode/item_code(asText=true)/daily(children ck/rk)/pending_occupy/available/ck_total/suggest(computed=true)/warn(computed=true),顺序固定),item_code 复用旧「商品编码」key、label 改为「外部编码」;头部口径注释同步重写(外部编码优先 wms_stock_store.item_code 按 stock_id 关联 wms_stock_warehouse.id、同 stock_id 多条按 id 升序取第一条非空、stock_id 为空不参与匹配,未匹配回落 wms_stock_warehouse.item_code,再无留空;pending_occupy 取 wms_stock_warehouse.locked_quantity;出入库仍用 wms_stock_transaction 变更数量 quantity;内部仍计算 rk_total/ck_avg/rk_avg/stock_days 供 suggest/warn 判定与复核,不进入导出列)", + "app/service/systems/report/queries/index.js:注册表 stockFlow 类型 description 已随查询器口径更新为「…每日出/入库、外部编码、待处理订单占用数、可用库存、7日总出库数量、推荐采购量与是否触发预警」;fields 动态取自查询器 fields 常量,无需单独维护", + "methods/system.json 通用报表模块(module=report):report.definition.typeList response 的 fields 描述由「含 16 个字段」更新为「共 9 组列,顺序固定」,fields[].label 示例由「商品编码」更新为「外部编码」;description/params/headers/errors/isNeedAuth/isNeedLogin 不变;版本 0.3.64 -> 0.3.65(docMeta.version),updatedAt 保持 2026-08-31", + "docs/report-config-guide.md:第 2 节 stockFlow 全量字段清单表由 16 个顶层字段改写为 9 组列(新顺序/新 label/新 key,附 pending_occupy 口径与外部编码 fallback 口径、8 个旧列移除说明);第 2.1 节口径与假设按查询器头部注释重写(外部编码口径、待处理订单占用数口径、内部计算字段不导出);第 3 节 asText 适用对象改为「条码、外部编码」;第 6 节保存示例 fields 更新为 9 组列、勾选说明由「16 个顶层字段」改为「9 组列」;第 7.3 节 typeList 响应示例字段顺序与 label 同步(外部编码/推荐采购量/是否触发预警)", + "AI_METHOD_ROUTING.md 本次未同步(report 能力清单不含 stockFlow 字段列表,仅指向 docs/report-config-guide.md,无需改动)", + "本次仅文档同步(业务代码由开发完成),未修改 app/ 下任何代码,未执行数据库/Redis 操作,未运行测试;测试数据保留不清理" + ], + "module": "report" + }, + { + "version": "2026.08.31-report-generate-store-dimension-file-key", + "date": "2026-08-31", + "type": "changed", + "summary": "修复「货主限制不符」缺陷(报表文件 key 与投递/通知幂等键补充货主维度隔离):systems/report.generate 上传目录由 exports/report/{report_id} 改为 exports/report/{report_id}/store-{store_id}(storeId 有效时)/ warehouse-{warehouse_id}(storeId 缺省且 warehouseId 有效时)/ common(两者均缺省,手动导出兼容兜底),避免不同货主的报表文件在 COS 上互相覆盖;reportDelivery 投递幂等键由 report:{report_definition_id}:{biz_date}:{time_point} 改为 report:{store_id}:{report_definition_id}:{biz_date}:{time_point}、文本通知幂等键 report:notify:... 同步加入 store_id 维度,并在 processOne 增加 store_id/report_definition_id 强校验(任一无效拒绝生成跨货主报表)。", + "methods": [ + "report.generate" + ], + "notes": [ + "app/service/systems/report.js generate:新增 ownerSegment 计算——normalizedStoreId>0 时 store-{storeId},否则 normalizedWarehouseId>0 时 warehouse-{warehouseId},否则 common;dir 由 exports/report/{reportId} 改为 exports/report/{reportId}/{ownerSegment}(经 excel.generateAndUpload 追加 {YYYYMMDD} 日期目录与文件名),JSDoc 同步更新隔离语义", + "app/service/systems/reportDelivery.js deliverByChannel:投递幂等键 idempotentKey 加入 store_id 维度(report:{store_id}:{report_definition_id}:{biz_date}:{time_point}),ext_id 幂等复用口径不变,不同货主的投递消息互不复用/串扰;sendNotifyIfConfigured:文本通知幂等键 report:notify:{store_id}:{report_definition_id}:{biz_date}:{time_point} 同步加入 store_id 维度;processOne:新增 store_id/report_definition_id 强校验(任一无效抛「投递计划维度非法(…),拒绝生成报表」),uniqueWhere 与 generate/投递调用统一使用归一化后的 normalizedStoreId/normalizedReportId", + "methods/system.json 通用报表模块(module=report):report.generate description 补充上传目录按(报表定义 + 货主/仓库)隔离口径与 common 兜底、免权限说明移除已下线的 meta(仅 generate/generateTaskProgress 免权限);store_id/storeId 参数描述补货主维度隔离语义;response result 描述补 fileKey 含货主/仓库隔离目录说明;params/headers/errors/isNeedAuth/isNeedLogin 口径不变;版本 0.3.63 -> 0.3.64(docMeta.version),updatedAt 保持 2026-08-31", + "docs/report-config-guide.md:第 4 节上传目录由 exports/report// 更新为按货主/仓库维度隔离的三级目录格式(store-{store_id} / warehouse-{warehouse_id} / common,含 excel.generateAndUpload 追加的 {YYYYMMDD} 日期目录);第 5 节补充投递/通知幂等键格式(含 store_id 维度)与 processOne 货主维度强校验说明", + "本次仅文档同步(业务代码由开发完成),未修改 app/ 下任何代码,未执行数据库/Redis 操作,未运行测试;测试数据保留不清理" + ], + "module": "report" + }, { "version": "2026.08.31-storeWarehouse.store.openAccount-remask", "date": "2026-08-31", diff --git a/methods/system.json b/methods/system.json index 3bdebe4..42ffecf 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,7 +1,7 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.63", + "version": "0.3.65", "updatedAt": "2026-08-31", "headers": [ { @@ -39040,7 +39040,7 @@ "list": [ { "method": "report.generate", - "description": "提交报表导出异步任务(手动导出):按报表定义ID读取 wms_report_definition(is_enabled=1)配置,经注册类型对应的内置查询器(type=stockFlow 等)取数,并按类型硬编码字段规格(app/lib/report/render.js renderSheetByType)渲染 Excel 上传。立即返回任务受理信息(task_id/status=submitted),后台异步执行(执行中的错误体现在任务进度 error 字段),完成后可通过 report.generateTaskProgress 轮询进度并获取下载链接。warehouse_id 由服务端从登录上下文(ctx.user.store_id)自动注入,前端无需传递。仅登录即可调用(免权限:systemInit 声明 generate/generateTaskProgress/meta 免权限;generate 不写审计日志)。", + "description": "提交报表导出异步任务(手动导出):按报表定义ID读取 wms_report_definition(is_enabled=1)配置,经注册类型对应的内置查询器(type=stockFlow 等)取数,并按类型硬编码字段规格(app/lib/report/render.js renderSheetByType)渲染 Excel 上传。上传目录按(报表定义 + 货主/仓库)维度隔离:store_id 有效时为 exports/report/{report_id}/store-{store_id},store_id 缺省且 warehouse_id 有效时为 exports/report/{report_id}/warehouse-{warehouse_id},两者均缺省时按 exports/report/{report_id}/common 兜底(保持手动导出兼容),避免不同货主的报表文件在 COS 上互相覆盖。立即返回任务受理信息(task_id/status=submitted),后台异步执行(执行中的错误体现在任务进度 error 字段),完成后可通过 report.generateTaskProgress 轮询进度并获取下载链接。warehouse_id 由服务端从登录上下文(ctx.user.store_id)自动注入,前端无需传递。仅登录即可调用(免权限:systemInit 声明 generate/generateTaskProgress 免权限;generate 不写审计日志)。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -39071,7 +39071,7 @@ "type": "number", "required": false, "source": "body", - "description": "货主ID(可选,货主维度报表时传入;>0 生效,<=0 视为不按货主过滤)" + "description": "货主ID(可选,货主维度报表时传入;>0 生效,<=0 视为不按货主过滤)。有效时报表文件 key 按 store-{store_id} 目录隔离(缺省时按 warehouse-{warehouse_id} 或 common 兜底),避免不同货主的报表文件互相覆盖" }, { "name": "storeId", @@ -39138,7 +39138,7 @@ "name": "result", "type": "object|null", "required": true, - "description": "任务结果对象;导出成功后为 { fileKey, url, filename, size },未完成或失败时为 null" + "description": "任务结果对象;导出成功后为 { fileKey, url, filename, size },fileKey 为 COS 文件 key(含 exports/report/{report_id}/store-{store_id} 或 warehouse-{warehouse_id} 或 common 隔离目录,经 excel.generateAndUpload 追加 {YYYYMMDD} 日期目录与文件名),未完成或失败时为 null" }, { "name": "error", @@ -40374,7 +40374,7 @@ "name": "fields", "type": "array", "required": true, - "description": "全量注册字段清单(该类型的可用字段,含 16 个字段)" + "description": "全量注册字段清单(该类型可用列元数据,当前 stockFlow 共 9 组列,顺序固定;daily 为数组类型列,含 children 子字段)" }, { "name": "fields[].key", @@ -40386,7 +40386,7 @@ "name": "fields[].label", "type": "string", "required": true, - "description": "字段中文名(如 商品编码)" + "description": "字段中文名(如 外部编码)" }, { "name": "fields[].type",