merge(shortage): release daily shortage orders and report on main
This commit is contained in:
commit
83e5a16b44
@ -0,0 +1,31 @@
|
||||
# 原换货库存为零、货号有库存的分类修正(2026-11-20)
|
||||
|
||||
## 规则与实现
|
||||
|
||||
用户要求所有编码统一执行:`combinedStock === 0 && skuStock !== 0` 时,缺货类型为“异常订单-待核实处理”。原实现先以两者较大值进入库存分类,可能将同货号其他编码的库存当作当前可发库存。
|
||||
|
||||
在既有服务端分类函数中,完成关键数值校验后、停产与销售的库存分支前,统一识别该条件;不设置编码白名单。退款关闭、信誉/虚拟以及产品状态缺失的未拆商品保留优先级。比较已知、有限的原始库存计算值;未知库存仍待核实,负库存的显示归零不改变内部计算值。
|
||||
|
||||
处理建议为“异常订单-待核实处理”,部门为如懿,AY 为 0。页面、筛选及导出复用服务返回结果;后续报表生成继续使用 AY 汇总。历史报表和人工填报不重建。
|
||||
|
||||
修改范围为分类纯函数、分类与订单服务回归测试及需求文档。保持 Route → Service → Repository 分层,无页面布局或数据库结构变化。
|
||||
|
||||
## 验证
|
||||
|
||||
- 10 个缺货相关测试套件共 157 项通过;新增覆盖销售、停产、退市、特殊发货标签、替换款有库存、换货规则、优先异常、已知零/非零与未知边界。
|
||||
- 服务集成测试验证原编码库存为 0、同货号其他编码库存为 8 时,全部明细均标为待核实、AY 为 0,报表不纳入这些件数。
|
||||
- `npx tsc --noEmit` 和修改的三个 TypeScript 文件 ESLint(含 `--no-ignore` 检查测试)通过。
|
||||
- 本地首次读取遇到源 OTHER 候选查询超时;重试后在北京时间 2026-11-20 13:08:52 成功取得完整快照 567 条。对相同快照比较修改前后分类,2 条匹配新规则并改变标签,其余 565 条不变。
|
||||
- 两条实际匹配明细的编码均为 `DNZ013402N1100V02`,原编码加换货编码总库存为 0,货号库存为 18;页面中的分类、建议、部门及 AY 校验通过。真实页面导出全量 567 行、筛选 2 行,分类与 API 一致,无响应拦截。Z 件数合计、AE 行数、AY、库存非负显示及空白无横线检查通过。
|
||||
- 用户示例 `SG007025N223V01`、`ZSJ000660N430V01` 在本次最新完整明细结果中均为 0 行,不能据此声称已验证这两个编码的当前库存。新规则覆盖其后符合抓取条件的记录。
|
||||
- 浏览器 DOM 和实际下载已验证;截图工具 `Page.captureScreenshot` 超时,未取得截图。此次不涉及视觉变更。
|
||||
|
||||
本机证据保存在运行项目忽略目录 `.codex-runtime/shortage-style-stock-20261120/` 的 `after.json`、`browser-evidence.json`、`integrity-evidence.json`、`all-details.xlsx`、`filtered-details.xlsx`。原始订单、导出和凭据不提交 Git。
|
||||
|
||||
## 分支与审查
|
||||
|
||||
继续用户指定的如懿分支。开工已 fetch,相对共享开发主线独有 21 个提交、落后 382 个提交;本次局部修复未合并跨模块变化。同步运行项目之前按原 HEAD 核对三个代码文件的 Git 内容哈希;需求文档仅应用本次段落补丁,保留运行目录其他开发改动。
|
||||
|
||||
结论:`passed with warnings`。架构、既有视觉及通用根因修正符合要求;警告为共享开发主线尚未整合、两个用户示例不在本次结果中,以及未取得浏览器截图。已在本地应用,未发布生产。
|
||||
|
||||
这是自审,不是独立复审。
|
||||
39
furniture-3d-system/docs/workflow/已拆组合装原行剔除验收-20261116.md
Normal file
39
furniture-3d-system/docs/workflow/已拆组合装原行剔除验收-20261116.md
Normal file
@ -0,0 +1,39 @@
|
||||
# 已拆组合装原行剔除验收(2026-11-16)
|
||||
|
||||
## 需求和来源核查
|
||||
|
||||
用户反馈:订单已经包含组合装拆出的子件,明细表仍保留套装原编码行,要求去掉已拆原行。
|
||||
|
||||
只读核查 SQL Server 订单商品明细:示例订单共五行,一行套装原编码、四行真实子件。原行 `sku_type=combine`、`item_status=Replaced`、`qty=0`;四条子件 `src_combine_sku_id` 均指向原套装编码,且 `outer_oi_id` 与原行一致。两种平台明细视图都提供 `sku_type`、`src_combine_sku_id`、`outer_oi_id`。此前 Repository 未读取这三个关联字段,Service 无法识别已拆原行。
|
||||
|
||||
## 规则和实现
|
||||
|
||||
- Repository 额外读取三个源字段及明确的来源标识,仍先按源 Id 选取最新商品明细版本。
|
||||
- Service 在 ZH 编码展开、产品匹配、分类和所有汇总前调用纯函数移除已拆原行。
|
||||
- 关联范围为同一来源、内部订单号、平台商品明细号 `outer_oi_id`,并以子件 `src_combine_sku_id` 精确匹配原行商品编码。编码去首尾空格并忽略大小写;平台明细号保持文本。
|
||||
- 只有原行 `sku_type=combine` 且已有不同商品编码的关联子件时才移除原行。原行数量不参与判断,因此源数据保留非零套数也不会重复进入明细与汇总。
|
||||
- 未拆套装、普通零数量商品、其他订单或平台明细行均保留;子件的原有数量、行数和身份保持不变。没有平台明细号的记录只能与同订单中同样没有该号的显式组合关系匹配。
|
||||
- 已有真实子件时先去掉源套装,再执行原有 ZH 编码展开,避免再次复制子件。
|
||||
- 新增的来源/组合关联字段只供服务器内部使用,返回页面的 DTO 继续保持原字段。页面与 Excel 导出共用完整处理结果;报表生成也使用同一 Service 快照。历史报表未重建。
|
||||
|
||||
Route → Service → Repository 分层保持,页面、样式、共享表格和数据库结构未修改。
|
||||
|
||||
## 验证
|
||||
|
||||
- 10 个相关套件、140 项测试全部通过。新增覆盖真实四子件结构、原行非零或未知数量、乱序、跨来源/订单/平台明细号隔离、自引用、普通零数量商品、未拆套装、无平台明细号关系,以及去原行后件数、行数和报表汇总。
|
||||
- `npx tsc --noEmit` 通过。
|
||||
- 修改的三个实现文件 ESLint 通过。
|
||||
- localhost:3000 真实登录和 API 完整读取成功,815 条明细,耗时 46.031 秒;全表 Excel 导出为 815 行。未拦截 API 或替换响应。
|
||||
- 用户指定订单的页面筛选结果从五条变为四条;四个真实子件完整保留,每条数量为一,套装原编码消失。实际点击导出得到四行,编码与 API 和页面完全一致。
|
||||
- Z 全货号件数、AE 订单货号行数、AY 分类缺货量、库存导出非负、空值无横线检查全部通过。
|
||||
- 浏览器无脚本异常;已检查 1083×848 筛选页面截图。通用真实页面验证同时覆盖 1920 和 982 像素宽度。
|
||||
|
||||
本地证据存放于忽略目录:`.codex-runtime/shortage-performance-combo-parent-links.json`(隔离工作树)、`.codex-runtime/shortage-combo-parent-browser-evidence.json`、`.codex-runtime/shortage-performance-api-browser-evidence.json`、`.codex-runtime/shortage-performance-integrity-evidence.json` 和 `.codex-logs/shortage-combo-parent-1083.png`。原始订单、截图、导出与连接凭据均未提交。
|
||||
|
||||
## 分支和审查
|
||||
|
||||
继续用户指定的 `如懿` 分支;已 fetch,开工时相对共享开发主线独有 25 个提交、落后 251 个提交。本次局部修复未合入这些跨模块变化。修改文件经过原提交哈希核对后同步到 localhost:3000 运行目录,其余未提交开发内容保持原样。
|
||||
|
||||
规范审查结论:`passed with warnings`。分层与视觉符合既有规范,修复源组合关系缺失导致的原行保留问题。警告为尚未整合共享开发主线,回流时需要复核兼容性;外部数据库读取耗时仍取决于上游。
|
||||
|
||||
这是自审,不是独立复审。
|
||||
37
furniture-3d-system/docs/workflow/拆单已替换原明细剔除验收-20261116.md
Normal file
37
furniture-3d-system/docs/workflow/拆单已替换原明细剔除验收-20261116.md
Normal file
@ -0,0 +1,37 @@
|
||||
# 拆单已替换原明细剔除验收(2026-11-16)
|
||||
|
||||
## 问题和修正依据
|
||||
|
||||
用户要求统一剔除同类型拆单前的原明细。只读核查示例订单,来源共有三行:原行数量为零、`sku_type=normal`、`item_status=Replaced`;两条子件数量各为一,状态为空。三行的 `outer_oi_id` 相同,但均没有 `src_combine_sku_id`。
|
||||
|
||||
上一版按 `sku_type=combine` 与子件组合关联移除原行,漏掉普通商品类型的已替换记录。此类记录应以明细状态 `item_status` 判断,不能依赖套装类型、编码中的加号、数量是否为零或是否存在组合关联。
|
||||
|
||||
## 实现
|
||||
|
||||
- Repository 在两个来源的商品明细查询中读取 `item_status AS itemStatus`。仍先按来源、内部订单、明细号选取最大源 Id 对应的最新版本,随后交给 Service 处理,避免过滤后重新使用旧版本。
|
||||
- Service 在组合装展开、产品匹配、分类及全部汇总之前,统一剔除 `itemStatus` 去首尾空格且忽略大小写后等于 `Replaced` 的明细。
|
||||
- 新规则覆盖所有订单、两个来源、所有商品类型;无需在当前缺货集合中再次找到后继子件。已替换原行不能继续参加统计或再次展开成子件。
|
||||
- 原有已拆组合装关系规则继续适用于其他有效明细,但已替换子件不能再作为移除有效套装原行的证据。
|
||||
- 普通有效记录保留,数量零、未知或编码含加号不会单独触发剔除。订单主表的 Question 状态和缺货类型、刷单及补发排除规则保持原口径。
|
||||
- `itemStatus` 是内部处理字段,不返回页面 DTO;页面、筛选、导出和新生成的报表快照共用处理后的数据。历史报表未重建。
|
||||
|
||||
修改仅涉及缺货订单 Repository、Service、既有组合处理纯函数和相关测试。无页面布局或数据库结构变更,保持 Route → Service → Repository 分层。
|
||||
|
||||
## 验证结果
|
||||
|
||||
- 10 个相关套件、147 项测试通过。新增覆盖两个来源的普通 Replaced 原行、无后继/无平台明细号、原行非零数量、ZH 展开前剔除、有效零数量和加号编码保留、最新状态版本选择、汇总和报表共用快照。
|
||||
- `npx tsc --noEmit` 通过,三个修改实现文件 ESLint 通过。
|
||||
- 全量真实来源核查读取 849 条最新原始明细;其中 Replaced 共 66 条:combine 为 41 条,normal 为 25 条;OTHER 为 47 条,TAOBAO 为 19 条。统一剔除后 783 条,ZH 展开后 790 条。检查通过:所有 Replaced 原行及其可能生成的子件都不进入结果。核查耗时 9.165 秒。
|
||||
- localhost:3000 真实登录、实际 API 和页面、实际 Excel 下载通过,无响应拦截。完整读取 50.027 秒、790 条,导出为 790 行;页面缓存显示 2.274 秒,无脚本异常。
|
||||
- 本次示例订单实际页面筛选和导出均为两条子件,数量各一,已替换原编码消失。上次四子件套装订单回归仍为四条、数量各一。
|
||||
- Z 货号件数合计、AE 订单货号行数、AY 分类缺货量、库存导出非负与空白无横线检查通过。已检查 1083×848 筛选截图;通用页面验证覆盖 1920 与 982 像素宽度。
|
||||
|
||||
证据保存在本机忽略目录:隔离工作树 `.codex-runtime/shortage-performance-replaced-parent-lines.json`、`.codex-runtime/shortage-replaced-items-audit.json`;运行目录 `.codex-runtime/shortage-replaced-parent-browser-evidence.json`、`.codex-runtime/shortage-performance-api-browser-evidence.json`、`.codex-runtime/shortage-performance-integrity-evidence.json` 及 `.codex-logs/shortage-replaced-parent-*.png`。原始订单、凭据与导出不提交。
|
||||
|
||||
## 分支和规范审查
|
||||
|
||||
继续用户指定的 `如懿` 分支;已 fetch,开工时相对共享开发主线独有 26 个提交、落后 251 个提交。本次局部修复未合并这些跨模块变化。修改文件与上一提交逐一比对后同步至 localhost:3000 项目,保留其余开发改动;未部署生产。
|
||||
|
||||
结论:`passed with warnings`。保持架构分层和既有视觉,通过读取源明细的已替换状态修复识别遗漏。警告为共享开发主线尚未整合,回流前需核对兼容性。
|
||||
|
||||
这是自审,不是独立复审。
|
||||
55
furniture-3d-system/docs/workflow/缺货原编码库存充足优先级验收-20261121.md
Normal file
55
furniture-3d-system/docs/workflow/缺货原编码库存充足优先级验收-20261121.md
Normal file
@ -0,0 +1,55 @@
|
||||
# 缺货原编码库存充足优先级验收(2026-11-21)
|
||||
|
||||
## 规则与现有逻辑的关系
|
||||
|
||||
用户要求:原编码库存严格大于缺货总量时,统一标为“非真实缺货-原商品编码大货仓有库存且能补齐缺货”。比较 `originalStock > totalShortage`,后者为完整明细按货号汇总的M数量件数,不是单行数量,也不使用换货合计或货号其他编码库存代替原编码库存。
|
||||
|
||||
该规则与原特殊发货标签、分仓、换货/替换款及停产清货分支存在优先级重叠。处理方式是将新规则放在这些分支之前,原编码库存足够时直接返回:
|
||||
|
||||
- 分类:非真实缺货-原商品编码大货仓有库存且能补齐缺货。
|
||||
- 处理建议:核实有库存未锁定原因并处理异常。
|
||||
- 部门:如懿。
|
||||
- AY缺货数量:0。
|
||||
|
||||
退款关闭、信誉/虚拟及未拆特殊/组合商品仍优先。库存与需求必须是已知有限数;等于时不命中新规则,继续既有分类。换货库存为负数导致合计抵消为0时,若原编码自身已足够,按本次明确的新规则处理;原编码不足则继续原“合计0且货号非0”待核实规则。
|
||||
|
||||
分类名称中的“大货仓”沿用用户指定文案。本规则的库存范围是五类指定属性仓库加南昌樵舍仓共同合计,不要求库存仅来自“成品发货仓-真实库存”。正常大货仓和前置仓两个分仓列保持各自定义。
|
||||
|
||||
## 真实数据结果
|
||||
|
||||
初查页面使用11月20日冻结数据,`SG010508N1436V01` 原编码库存18、货号需求2。其中18件来自“渠道专用仓-真实库存”,正常大货仓和前置仓均为0;旧算法因此命中特殊标签或前置仓/替换款分支。
|
||||
|
||||
11月21日15:58:03(Asia/Shanghai)重新完整读取订单及全部关联来源后,该编码为3条明细、货号需求3、原编码库存18。3条都命中新分类,缺货数量均为0。未将11月20日数据改为实时数据,也未回写历史日期。
|
||||
|
||||
对同一批今日数据比较新旧分类结果:
|
||||
|
||||
| 项目 | 结果 |
|
||||
| --- | --- |
|
||||
| 今日完整明细 | 525条 |
|
||||
| 分类改变 | 38个编码、45条明细 |
|
||||
| 新旧算法分别汇总的今日报表 | 原规则60条,新规则51条 |
|
||||
| 明细AY件数合计 | 原规则259,新规则229 |
|
||||
| 原高优先级异常 | 2条均保持原分类 |
|
||||
|
||||
45条变化均满足原编码库存大于货号需求。部分旧停产分支的AY本来为0,因此45条分类变化不代表45条报表变化。订单总行数与前日不同来自完整重新读取源数据,不是本规则删除订单。
|
||||
|
||||
## 本地发布与验证
|
||||
|
||||
- 原生计算函数增加原编码库存判断,Service保持全量资料计算后分类的顺序;没有新API、表结构、迁移或前端布局改动。
|
||||
- 15套缺货相关Jest测试、205项通过;TypeScript检查通过;三个代码/测试文件ESLint通过。
|
||||
- 测试覆盖原编码大于/等于/小于需求、有限数校验、全货号需求与单行数量区别、特殊标签、换货与替换款、停产清货、负数抵消、保留高优先级异常及报表AY联动。
|
||||
- 更新前对专用本地开发库完成32,024,996字节标准备份,`pg_restore --list`验证通过。外部源只读。
|
||||
- 15:58:32以事务、明细/报表双生成锁及前置数据哈希核对,发布11月21日525条明细与51条报表。完整读取失败不发布部分数据;历史明细、历史报表及人工填报逐项哈希校验一致。
|
||||
- 今日原本没有快照或人工填报,创建今日数据;报表保存流程仍保护同日已有记录的人工字段。Windows任务`FurnitureRuyi-ShortageReportDaily`保持Disabled。
|
||||
- 同步运行目录前逐文件验证与任务前基线一致,仅同步3个代码/测试文件及需求文档。
|
||||
- ego-browser TaskSpace 3真实读取明细API,525条与发布提案完全一致;`refresh=1`仍返回相同固定读取时间与数据。报表API的今日51条计算字段与提案一致。
|
||||
- 真实页面筛选示例编码,3条明细的库存、缺货总量、分类、建议、部门、缺货数量均正确。真实下载Excel3行49列、147个单元格逐格验证通过。浏览器任务已关闭。
|
||||
- 备份、输入快照、提案、影响分析及回滚材料保留在忽略目录`.codex-runtime/shortage-original-stock-20261121/`,不提交Git。
|
||||
|
||||
## 规范审查
|
||||
|
||||
结论:`passed with warnings`。这是自审,不是独立复审。
|
||||
|
||||
架构:业务判断在既有纯计算层内,源筛选、快照、报表及权限边界不变。视觉:沿用既有49列表格,实际页面及导出通过。根因:调整原编码库存充足判断的输入与优先级,覆盖全部同类编码,没有编码白名单。
|
||||
|
||||
警告:分类文案“大货仓”的字面范围小于本次用户指定的库存判断范围,按用户明确要求保留;任务分支开工时相对共享主线27 ahead / 430 behind,本次不合入数百条无关提交,不宣称完成主线同步或生产部署。
|
||||
43
furniture-3d-system/docs/workflow/缺货库存范围与替换款选码验收-20261120.md
Normal file
43
furniture-3d-system/docs/workflow/缺货库存范围与替换款选码验收-20261120.md
Normal file
@ -0,0 +1,43 @@
|
||||
# 缺货库存范围与替换款选码验收(2026-11-20)
|
||||
|
||||
## 变更与边界
|
||||
|
||||
用户指定库存仅纳入五类仓库属性,或名称为“三方-南昌樵舍仓”的仓库。两条件为或关系,重叠仓库只计一次;其余仓库及未知仓库归属排除。公有可用数仍为 `qty - order_lock - 原云仓 order_able_qty`,库存源仍为 `JSReportReplica.rpt.jst_inventoryInfo`。原编码、换货编码、全货号及替换款总库存共用范围;正常大货仓、前置仓保持各自分组定义,清货库存仍按供应商清货进度计算。
|
||||
|
||||
PM替换关系同时读取商品编码及货号。精确商品编码关系优先,未命中时按货号确定替换货号,再从目标货号全部编码中选取限定范围公有可用库存最高者。相同库存按规范化编码字典序确定,未知库存不冒充0。自定义换货关系仍独立读取 `rpt.jst_sku_replace_rule`,不与PM替换关系混用。
|
||||
|
||||
规则实现在原有纯计算函数、Repository与Service内,无新增路由、Prisma模型或迁移。保留订单最新版本筛选、刷单和补发排除、组合装拆解、拆单原单剔除、缺货分类及空值/负数展示规则。页面仍为49列,重新读取仍只读存档。
|
||||
|
||||
## 真实来源与发布
|
||||
|
||||
- PM表真实存在有效关系 `DNZ028907 → DNZ028915`,原实现仅用编码查询,遗漏了该货号关系。
|
||||
- 2026-11-20 16:53:43(Asia/Shanghai)完整重新读取订单、产品档案、规则、库存及清货进度。
|
||||
- 目标货号 `DNZ028915` 下,`DNZ028915N866V01` 的范围内公有可用库存为25,`DNZ028915N887V01` 为0。最终 `DNZ028907N866V01` 匹配替换货号 `DNZ028915`、编码 `DNZ028915N866V01`;页面DOM实际显示替换款库存25。
|
||||
- 按独立逐仓累加逻辑核对718个档案编码的库存,与业务计算结果一致。
|
||||
- 外部源全程只读;写入目标严格校验为专用本地开发库。更新前完成标准PostgreSQL全库备份(31,948,154字节),`pg_restore --list`验证通过;提案、备份及回滚前数据仅保留在忽略目录 `.codex-runtime/shortage-scope-replacement-20261120/`。
|
||||
- 2026-11-20 16:55:12以单一事务、双生成锁及旧快照哈希校验发布当日600条明细与79条报表,二者共用同一批档案/库存。对71条仍存在的报表保留预计到货时间、备注、替换款在途数量及操作者,版本递增;没有带人工填报的记录被移出。历史快照保持一致。
|
||||
- 测试期间任务 `FurnitureRuyi-ShortageReportDaily` 保持Disabled;本次仅手动发布今日数据,不改变定时配置。
|
||||
|
||||
## 验证
|
||||
|
||||
| 验证 | 结果 |
|
||||
| --- | --- |
|
||||
| 全部缺货相关Jest套件 | 15套、194项通过 |
|
||||
| TypeScript `tsc --noEmit --incremental` | 通过 |
|
||||
| 本次6个代码/测试文件ESLint | 通过 |
|
||||
| 真实页面与明细API | 600条,与持久化提案逐行一致;`refresh=1`仍返回同一读取时间与内容 |
|
||||
| 真实报表API | 当日79条计算字段与提案一致 |
|
||||
| 示例筛选与单元格 | 替换货号、编码及库存25均正确 |
|
||||
| 浏览器实际下载Excel | 600行、49列、29,400个单元格逐格一致;4,465个空值保持空白,344个负库存单元格最终为0 |
|
||||
| 运行目录同步 | 先比较6个文件与任务前基线一致,再精确同步;保留运行树其他修改 |
|
||||
|
||||
浏览器验收使用ego-browser TaskSpace 10,完成后已关闭。此次为计算规则修改,使用DOM、真实接口和实际下载验收,未新增视觉截图。
|
||||
|
||||
## 规范审查
|
||||
|
||||
结论:`passed with warnings`。这是自审,不是独立复审。
|
||||
|
||||
- 架构:在既有缺货模块分层内修正数据读取与计算,无外部源写入,无共享模型变更。
|
||||
- 视觉:沿用现有表格与49列配置,真实页面、筛选和导出通过。
|
||||
- 根因:修复库存全仓汇总与货号替换规则未被读取两处原因,实际重新生成今日快照。
|
||||
- 警告:提交至用户指定“如懿”分支。开工时该分支相对共享开发主线为26 ahead / 382 behind,本次不整合数百条无关提交,也不据此宣称已同步共享主线或完成生产部署。人工是否可替换等原有未接入业务继续保持原有空值。
|
||||
70
furniture-3d-system/docs/workflow/缺货明细每日固定快照验收-20261120.md
Normal file
70
furniture-3d-system/docs/workflow/缺货明细每日固定快照验收-20261120.md
Normal file
@ -0,0 +1,70 @@
|
||||
# 缺货订单明细每日固定快照验收(2026-11-20)
|
||||
|
||||
## 用户要求与实现
|
||||
|
||||
缺货订单明细每天北京时间09:00全量生成一份,全部字段重新计算,日内不再实时更新。
|
||||
|
||||
新增独立的 `ShortageOrderDailySnapshot`,按业务日期唯一保存完整55项内部DTO字段、实际读取时间及发布时间,包含52个页面/导出字段。定时任务绕过原实时服务的内存缓存,重新读取订单、商品全量档案、换货与替换规则、库存、云仓、仓库档案、清货库存并执行现有派生规则。只有所有来源成功且日期未跨天才一次发布;同日重复运行不覆盖已发布明细。空结果与尚未生成分别处理;失败保留最近成功快照。
|
||||
|
||||
Route继续鉴权和参数校验,Service负责权限、09:00边界与生成编排,Repository负责数据库访问。明细接口、页面重新读取、筛选和导出均只读持久化快照;旧 `refresh=1` 不再触发源抓取。页面不轮询,展示真实快照读取时间,导出文件名采用快照业务日期。标题操作区支持换行以容纳完整日期时间。
|
||||
|
||||
每日脚本先冻结明细再生成独立报表,报表重建也只用当天已冻结的明细。已存在的报表、历史计算及人工填报继续沿用原保护规则,不因本次实施而重建。源订单过滤、拆组合装、剔除已替换原单、库存来源与计算、分类优先级、空白与负库存显示规则不变。
|
||||
|
||||
## 本地迁移与调度
|
||||
|
||||
- 新迁移:`prisma/migrations/20261120140000_add_shortage_order_daily_snapshot/migration.sql`,仅新增日期主键、JSONB明细及数组约束。
|
||||
- 仅对专用本地开发库应用迁移;严格核对本机地址、端口和库名,迁移前完整备份并通过 `pg_restore --list`,事务执行DDL并记录迁移历史。未使用 `db push`,外部数据库保持只读。
|
||||
- 备份位于本机忽略目录 `.codex-logs/before-shortage-order-daily-1795152887067.dump`,大小31,869,181字节。
|
||||
- 已安装 `FurnitureRuyi-ShortageReportDaily`,下一次常规触发为2026-11-21 09:00,中国标准时间。错过后补执行,失败间隔15分钟重试三次,忽略重叠实例,最长执行一小时。
|
||||
- 隐藏PowerShell运行器启动Node并返回实际退出码,每次输出/错误单独保存于 `.codex-logs/shortage-daily-*.log`。要求机器开机、安装用户保持登录、本地数据库运行且源库可达,页面无需打开。本次为本地开发部署。
|
||||
- 后台明细源单次SQL查询预算120秒,默认Repository仍为30秒。保留原超时重试与批次拆分,不改变SQL条件、数量范围或读取隔离级别。
|
||||
|
||||
## 已完成的验证
|
||||
|
||||
- 15个缺货相关测试套件,共187项通过。包含09:00边界、权限、跨天不实时读取、首次无快照、同日不覆盖、生成锁、源失败与发布失败、跨午夜拒绝发布、报表只读当天冻结明细、旧刷新参数兼容、停止页面轮询、请求取消以及后台120秒预算。
|
||||
- 全量 `npx tsc --noEmit` 通过,修改范围15个TypeScript/TSX文件的ESLint(含测试 `--no-ignore`)通过。Prisma生成和校验、两个PowerShell脚本语法检查通过。
|
||||
- 使用本日13:08既有的567条真实完整明细验证新JSON校验与序列化,55项字段全部保留;未将该旧结果冒充本次新抓取。
|
||||
- 在本地数据库事务中使用这些既有明细验证567行完整JSON存取、实际读取时间、日期唯一约束及重复插入不覆盖。事务主动回滚,并验证无探针记录残留;没有向页面发布测试数据。
|
||||
- localhost:3000真实登录会话验证无参数、`refresh=0`、`refresh=1` 均返回HTTP200的明确empty状态;`generate=1` 返回400。点击“重新读取”不启动源任务,没有接口响应替换。无快照时导出禁用。
|
||||
- 1920与982像素视口的实际DOM检查无全页水平溢出,标题操作均在标题区域内。浏览器 `Page.captureScreenshot` 超时,未取得截图,因此没有完成截图视觉验收。
|
||||
- 本轮20个代码、迁移及脚本文件与实际运行目录逐一比较,文本一致;需求文档仅精确应用本轮段落修改,保留运行工作树其他开发改动。
|
||||
|
||||
## 当前外部阻塞与验证限制
|
||||
|
||||
2026-11-20多次实际触发同一个Windows定时任务,淘宝订单候选读取持续超时,失败退出码为1;其他来源完成也不会发布部分明细。将后台预算从30秒延长到120秒后仍复现,未将延长超时视作源问题已修复。
|
||||
|
||||
只读诊断设置5秒锁等待上限后,上游 `rpt.jst_qmcust_orderlist` 查询返回SQL Server 1222锁超时。源库的读提交快照和快照隔离均关闭;当前只读账号不能据此解除其他会话持有的锁。未采用NOLOCK、跳过锁、截断订单或历史缓存替代完整结果。
|
||||
|
||||
截至本次验收,今日首份最新明细快照仍未成功生成,页面明确显示“尚未生成每日快照”。自动失败重试已配置;需要源库释放锁才能继续生成。没有完成真实最新快照的ready页面、实际Excel导出、重启后同一已发布结果以及同日重复任务成功退出的端到端验收。相关存取、同日保护和只读行为已由本地回滚事务及自动测试验证,不将这些结果冒充源库全量读取成功。
|
||||
|
||||
本机证据:`.codex-runtime/shortage-daily-20261120/` 下的只读接口结果、响应与布局记录,以及 `.codex-logs/shortage-daily-20261120-*.log`。原始订单、导出、备份及连接凭据均在忽略目录,不提交Git。
|
||||
|
||||
## 分支与规范审查
|
||||
|
||||
继续用户指定的“如懿”分支。开工已fetch,相对共享开发主线独有22个提交、落后382个提交,本次未整合跨模块主线变化。实际运行目录的其他未提交改动保留。
|
||||
|
||||
结论:`passed with warnings`。架构保持Route → Service → Repository,复用现有工作台组件,采用持久化每日快照消除页面实时抓取。警告为源库锁等待使首份最新快照尚未生成、真实ready/导出端到端验收未完成、浏览器截图不可用,以及共享开发主线尚未整合。上线前须在源库恢复后补齐完整任务与ready页面验收。
|
||||
|
||||
这是自审,不是独立复审。
|
||||
|
||||
## 14:08手动补生成恢复记录
|
||||
|
||||
上述阻塞记录对应2026-11-20 13:55时的现场,以下为同日恢复后的实际结果。
|
||||
|
||||
用户要求测试期间取消定时,`FurnitureRuyi-ShortageReportDaily` 已保持 `State=Disabled / Enabled=False`。本次只手动执行现有运行器,没有恢复定时或页面实时抓取。
|
||||
|
||||
源库只读候选诊断本次4.36秒成功,返回2515条候选,原锁等待已解除。随后全量读取订单、档案、规则及库存成功,于北京时间2026-11-20 14:08:03发布今日585条缺货订单明细,14:08:06发布73条缺货报表汇总。源库未做写入、解除会话锁或隔离级别调整;后续源库仍可能再次出现锁等待。
|
||||
|
||||
恢复验证:
|
||||
|
||||
- 手动运行器退出0,明细与报表均为 `published`;再次手动运行退出0,均为 `exists`,没有重复源抓取或覆盖当日快照。
|
||||
- 真实登录会话中,无参数及旧 `refresh=0/1` 均HTTP200 ready,返回同一完整585条快照,读取约0.6秒。明细页面点击“重新读取”显示585条、快照时间14:08:03,无读取错误。
|
||||
- 实际下载 `缺货订单明细-2026-11-20.xlsx`。585行、52列逐格与API转换结果一致,持久化完整DTO与API严格一致;源订单过滤、数量及分类汇总检查通过。今日报表与明细使用同一份源读取结果。
|
||||
- 正确报表接口返回HTTP200 ready,历史存档共357条,其中今日73条;报表页面生成日期起止均选2026-11-20后,实际显示“共73条”,无错误。
|
||||
- 完整快照校验值:`e8ddefbf75e7a8807a662c7e0bfafad677a1ae54616dc5f940e98a8f3e8eabe0`。本机证据位于运行应用忽略目录 `.codex-runtime/shortage-today-read-20261120-1408/`;两次手动运行日志位于 `.codex-logs/shortage-daily-20261120-140728-133.out.log` 和 `.codex-logs/shortage-daily-20261120-141005-883.out.log`。
|
||||
|
||||
本次恢复没有修改应用源码或新增迁移,沿用此前187项相关测试结果,并补做真实生成、页面、接口、导出及同日幂等验收。本次没有重启应用,未执行重启后读取验收。浏览器截图仍受先前超时限制,未声称完成截图视觉验收。
|
||||
|
||||
恢复后的规范审查结论:`passed with warnings`。架构分层、工作台视觉及现有业务规则保持;通过现有完整生成流程补齐缺失的今日快照,未用旧缓存或部分结果替代。剩余警告为源库锁等待可能复发、截图与重启验收未完成,以及共享开发主线尚未整合;本地定时任务继续禁用。此次仅追加恢复记录,保留前述失败现场。
|
||||
|
||||
这是自审,不是独立复审。
|
||||
75
furniture-3d-system/docs/workflow/缺货订单网页导入与每日快照.md
Normal file
75
furniture-3d-system/docs/workflow/缺货订单网页导入与每日快照.md
Normal file
@ -0,0 +1,75 @@
|
||||
# 缺货订单网页导入与每日快照
|
||||
|
||||
订单明细的订单类型、内部订单号、线上订单号、分类、货号、商品编码、商品名称、生产状态、供应商、单双包、数量、异常类型、平台站点、店铺名称、付款日期、店铺商品编码、标签,共17列,唯一来源为聚水潭网页导出的“缺货报表看板”模板。文件中的空值保留为空,不再用旧订单数据库或档案资料填补这些基础字段。采购列和采购筛选已移除。
|
||||
|
||||
## 网页读取和文件导入
|
||||
|
||||
“网页读取”启动服务器后台任务,通过 ego-browser 沿用本机浏览器登录,进入聚水潭订单页面,清空条件,选择异常下的真实缺货、缺货、预售,确认异常订单状态,组合查询,导出所有符合条件的订单。只接受“缺货报表看板”模板及文件名以“订单”开头的xlsx文件,日期后缀不固定。文件保存至本机忽略目录 `.codex-runtime/jst-shortage-exports/<北京时间日期>/`。
|
||||
|
||||
“导入订单”允许选择同模板文件,最多20MB,展开最多80MB。支持聚水潭ZIP64及CDATA格式,校验完整且唯一的17列表头、文本订单号及有效数量。内部订单号保持文本,避免长订单号精度丢失。刷单标签和配件类型按整个内部订单号排除,补发订单保留;配件判断只读取订单类型,不按商品名称或分类误判。只接受缺货、真实缺货、预售。若文件另含状态列,仅允许Question或异常状态。
|
||||
|
||||
基础字段导入后,沿用现有组合装拆分、库存、换货规则、替换款、清货库存、缺货分类及报表计算。数据库只提供这些后续计算需要的资料。库存仍读取现有只读库存源和已确认的仓库范围。
|
||||
|
||||
本地 `.env.local` 可设置 `SHORTAGE_JST_LOGIN_ID`、`SHORTAGE_JST_LOGIN_PASSWORD`、`SHORTAGE_EGO_BROWSER_EXECUTABLE`。凭据只保存在忽略的本地私有配置,不写入代码、文档或Git。浏览器持久会话有效时直接使用;会话失效时按配置登录,有记住密码或保持登录选项时勾选。验证码或其他人工验证需要人员在浏览器完成后重试。
|
||||
|
||||
## 快照与日期
|
||||
|
||||
制表时间在订单类型前显示,使用保存快照的生成时间,页面和导出统一按北京时间展示。制表日期筛选查询已保存的指定日期,切换或重新打开页面不触发网页读取或计算。缺失日期明确显示未生成,不用其他日期冒充。
|
||||
|
||||
手动网页读取、导入订单只更新当天;锁定明细与报表任务,计算全部成功后,在同一事务发布当天明细和报表,并沿用报表人工填报保留规则。导出、解析或计算失败时保留原完整快照,允许更换文件或再次读取。历史日期不被覆盖。
|
||||
|
||||
Windows执行 `scripts/install-shortage-report-daily-task.ps1` 安装两个本地任务:
|
||||
|
||||
- `FurnitureRuyi-ShortageOrdersDownloadDaily`:每日北京时间08:50运行 `scripts/run-shortage-daily-download.ps1`,从聚水潭网页下载并校验订单文件;不计算库存、不提前修改页面快照。
|
||||
- `FurnitureRuyi-ShortageReportDaily`:每日北京时间09:00运行 `scripts/run-shortage-daily-snapshot.ps1`,读取08:50任务准备好的当日文件,计算并保存完整明细,然后生成缺货报表;不重复网页下载。
|
||||
|
||||
下载文件校验成功后保存至忽略目录 `.codex-runtime/jst-shortage-prepared/<北京时间日期>/`,先保存完整文件,再原子发布含原文件名、日期、时间及SHA256的完成标记。09:00任务只读取当天完成标记并核对文件哈希;缺少文件、日期错误或内容校验失败时停止,不沿用昨日文件,原完整快照保留。手动“网页读取”仍会即时下载并更新当天数据。
|
||||
|
||||
设备需开机并处于已登录的Windows用户会话,ego-browser可运行且聚水潭会话可用。错过时间后登录时会补跑,失败按任务配置重试;下载任务最多重试2次、每隔5分钟,快照任务最多重试3次、每隔15分钟。日志在忽略目录 `.codex-logs`;已保存的当日数据不被定时任务覆盖。
|
||||
|
||||
## 验证入口
|
||||
|
||||
- `npm test -- --runInBand --testPathPatterns=shortage`
|
||||
- `npm run verify:clearance-import-dialogs`
|
||||
- `npm run type-check` 与生产构建
|
||||
- 真实页面:导入文件、错误文件后重试、网页读取、历史日期切换、首列制表时间及导出
|
||||
|
||||
主要边界:API负责收参和认证,快照Service负责权限、并发和发布,WebSource Service负责文件解析及计算编排,WebExport Repository负责浏览器导出进程和读取本地文件。未修改数据库表结构。
|
||||
|
||||
## 2026-11-24本地验证记录
|
||||
|
||||
真实网页按钮导出 `订单_20261124181129_212124941_1.xlsx`,文件导入278条、排除16条,组合装拆分后发布279条明细及39条报表。277条非拆分行的17个基础字段与该文件逐项相同。页面导出279条,首列为制表时间且没有采购列。11月20日、11月21日的明细、报表和人工字段与更新前备份的哈希一致。无效文件导入显示原因并保留原快照,随后网页读取重试成功。
|
||||
|
||||
缺货相关249项测试通过,随后补充浏览器空间清理测试通过;导入交互回归18项通过,类型检查与改动文件ESLint通过。生产构建在Webpack下通过编译与类型阶段,在收集其他模块页面数据时被既有图纸系统 `DRAWING_SYSTEM_*` 凭据缺失阻断;默认Turbopack另受本机依赖目录软链接限制。未将测试占位凭据写入配置。浏览器完成真实导入、历史切换、失败重试、网页读取、导出操作;截图工具持续报告页面截图超时,未取得可审阅截图。本地09:00任务已恢复,运行验证返回成功且保留当天现有快照,下次运行2026-11-25 09:00。
|
||||
|
||||
规范结论:`passed with warnings`。架构保持API/Service/Repository边界,沿用平台表格和筛选样式,数据源在导入及计算入口修正。警告为上述全项目构建环境和截图验证限制。这是自审,不是独立复审。
|
||||
|
||||
## 2026-11-24筛选与下载时间调整
|
||||
|
||||
补发订单改为保留,配件订单及刷单订单剔除;网页文件导入和旧数据源适用相同筛选。新增08:50下载任务,09:00任务只读取当日已校验完成的文件。两个任务均已安装到本地运行目录,按北京时间执行,下次计划为2026-11-25 08:50和09:00。
|
||||
|
||||
下载任务实跑成功,取得 `订单_20261124182831_212128500_1.xlsx`:284条,含9条补发明细;当天未出现配件或刷单订单。经页面导入、组合装拆分后保存285条明细、39条报表,页面显示快照时间2026/11/24 18:29:30。283条非拆分记录的17个基础字段与文件一致,9条补发记录全部保留;历史数据哈希一致,仍在报表中的37条原有记录的人工字段不变。09:00任务实跑识别当日已有快照并成功退出,未覆盖已保存结果。
|
||||
|
||||
20组缺货测试共259项通过,导入交互回归18项、类型检查及改动文件ESLint通过。新增回归覆盖配件整单剔除、补发保留、刷单优先排除、下载不提前计算、09:00不重复下载、文件缺失/日期错误/篡改拒绝及手动读取保留即时下载。
|
||||
|
||||
本次Webpack生产构建通过编译和TypeScript阶段,收集 `/api/intake/non-integrated/installation-drawing-replace` 页面数据时再次被既有图纸系统 `DRAWING_SYSTEM_*` 凭据缺失阻断。PowerShell脚本语法校验通过,两个任务实跑均返回0。已核对本地运行目录与本次提交范围中的代码一致。
|
||||
|
||||
本次规范结论:`passed with warnings`。筛选规则在源数据入口修改,08:50下载落盘由Repository负责,09:00计算继续由Service编排;页面沿用现有组件。警告仅为上述其他模块配置造成的完整构建限制。这是自审,不是独立复审。
|
||||
|
||||
## 2026-11-25缺货报表列精简
|
||||
|
||||
缺货报表移除“替换货号”“叫货在途-替换款”“替换货号库存”三列,统一字段配置由16列减至13列,表格、列设置和Excel导出同步生效。已有浏览器列偏好会丢弃这三个已移除字段。人工填报弹窗仅保留预计到货时间和备注,保存时保留原有替换款在途值。
|
||||
|
||||
本地页面验证:列设置显示13/13列且无已移除字段,填报弹窗只有预计到货时间和备注;实际导出500条、13列,确认三个已移除字段不存在。20组缺货测试259项、导入交互回归18项、类型检查及本次改动ESLint通过。页面截图工具再次在 `Page.captureScreenshot` 超时,已通过真实DOM交互及导出文件核对。
|
||||
|
||||
Webpack构建通过编译和TypeScript阶段,收集图纸替换接口页面数据时因既有 `DRAWING_SYSTEM_*` 凭据缺失停止。未同步共享主线,继续在用户指定的“如懿”分支处理本次报表调整。
|
||||
|
||||
本次规范结论:`passed with warnings`。显示字段从统一配置移除,沿用既有表格和弹窗组件,后端数据契约及历史快照保留;警告为其他模块配置导致的完整构建阻断和截图工具限制。这是自审,不是独立复审。
|
||||
|
||||
## 2026-11-25 缺货原因与供应商排序
|
||||
|
||||
缺货报表将“备注”统一显示为“缺货原因”,表头、列设置、人工填报与手动导出使用新名称,继续读写 `notes` 字段并保留历史填报。按供应商优先、采购其次的顺序排列筛选结果;同一供应商内相同采购连续显示,组内保留原有日期和商品顺序。未填写的供应商或采购排在相应层级末尾。
|
||||
|
||||
缺货报表和相关字段测试共40项通过,类型检查和改动业务文件ESLint通过。真实页面核对500条、3页的供应商及采购连续性,并打开填报弹窗检查新名称后取消。未触发下载或修改填报。
|
||||
|
||||
本次规范结论:`passed`。沿用现有表格和弹窗,集中调整报表显示顺序与文案,保留归档计算和数据契约。这是自审,不是独立复审。
|
||||
40
furniture-3d-system/docs/workflow/缺货订单读取超时恢复验收-20261116.md
Normal file
40
furniture-3d-system/docs/workflow/缺货订单读取超时恢复验收-20261116.md
Normal file
@ -0,0 +1,40 @@
|
||||
# 缺货订单读取超时恢复验收(2026-11-16)
|
||||
|
||||
## 问题与原因
|
||||
|
||||
本地缺货订单明细页面间歇性读取失败。服务日志连续三次记录订单主表阶段 `ETIMEOUT`,当时进度为 `orders: 1/2`。原流程在候选订单或最新订单版本查询发生一次超时后直接终止整次读取,必须由用户再次刷新。
|
||||
|
||||
同一天未改代码的实际接口读取也成功返回 886 条明细,耗时 33.29 秒;独立只读来源核查返回 854 条原始明细,耗时 33.514 秒,组合装拆分后为 886 条。证据表明数据库查询时间存在波动,而非来源恒定不可用。仅凭原有日志无法还原三次失败的具体 SQL。
|
||||
|
||||
还比较了候选查询的默认并行度与 `MAXDOP 1`:两种查询返回记录的排序后摘要完全一致,但交替执行三轮后单线程并未稳定更快,因此没有引入这个查询提示,也未延长原有单次 30 秒超时。
|
||||
|
||||
## 实现
|
||||
|
||||
- 候选集合读取遇到 `ETIMEOUT` 时,用新 Request 重试一次;非超时错误立即抛出。
|
||||
- 最新订单版本查询与明细查询采用同一批次读取流程。批次超时后依次读取两个子批次,最小为单订单;单订单最多重试一次。
|
||||
- 恢复日志仅记录来源、查询阶段和批次大小,不记录订单号、SQL 参数或连接凭据。
|
||||
- 所有来源、批次、商品档案与库存补齐成功后才发布快照。任一子批次最终失败,整次读取仍失败,不返回部分数据。
|
||||
- 保持最新版本判断、Question 状态、三种缺货类型、刷单和补发排除,以及组合装、库存、汇总规则。
|
||||
|
||||
修改局限于缺货订单 Repository 及其测试。Route、Service、页面布局、报表手填与历史存档没有修改。
|
||||
|
||||
## 验证
|
||||
|
||||
- 10 个相关测试套件、132 项测试通过;包括候选读取的新 Request 重试、连续超时停止、主表批次拆分、取消订单不复活、单订单重试次数,以及部分子批次成功后整体失败。
|
||||
- `npx tsc --noEmit` 通过。
|
||||
- Repository 的 ESLint 检查通过。
|
||||
- localhost:3000 真实登录、真实 API、真实页面和 Excel 导出通过,无接口响应拦截。首次完整读取 60.590 秒,886 条;缓存读取 805 毫秒;页面显示 5.600 秒;导出 886 行。页面无脚本异常,1920 和 982 像素宽度无全页水平溢出。
|
||||
- 随后连续三次 `refresh=1` 强制重新读取,分别为 18.890 秒、6.028 秒、6.914 秒;每次都返回 886 条,并产生不同的来源快照时间。
|
||||
- 全量结果通过状态、缺货类型、刷单与补发排除、行 ID 唯一性检查。Z 件数合计、AE 订单货号行数、AY 分类缺货量检查通过;库存导出无负数、空值无横线占位。
|
||||
|
||||
本次真实读取没有再次触发超时;恢复与最终失败路径由故障注入单元测试验证,不能将连续成功等同于外部数据库永不超时。数据库持续不可用时仍会显示读取失败;未修改外部数据库结构或数据。
|
||||
|
||||
证据位于本机忽略目录 `.codex-runtime/shortage-repeat-refresh-evidence.json`、`.codex-runtime/shortage-performance-api-browser-evidence.json`、`.codex-runtime/shortage-performance-integrity-evidence.json` 及 `.codex-logs/shortage-performance-*.png`。原始订单、截图、导出文件和凭据不提交 Git。
|
||||
|
||||
## 分支与规范审查
|
||||
|
||||
用户指定分支为 `如懿`,本地运行目录仍使用原 localhost:3000 项目,相关文件已按旧提交哈希核对后同步,保留其余开发改动。已 fetch;当前基线相对共享开发主线有 24 个独有提交、落后 251 个提交。本次未合并跨模块主线变化,未发布生产环境。
|
||||
|
||||
结论:`passed with warnings`。Route → Service → Repository 边界与原有视觉保持一致,修复瞬时超时导致整个读取立即终止的问题。警告为外部数据库耗时仍有波动,以及当前分支尚未整合共享主线,回流前需复核兼容性。
|
||||
|
||||
这是自审,不是独立复审。
|
||||
28
furniture-3d-system/docs/排障记录/2026-11-12-缺货订单读取优化.md
Normal file
28
furniture-3d-system/docs/排障记录/2026-11-12-缺货订单读取优化.md
Normal file
@ -0,0 +1,28 @@
|
||||
# 缺货订单读取优化
|
||||
|
||||
## 问题与调整
|
||||
|
||||
订单明细原来先读取两个订单源的Id上下界,再查询约69个历史Id分段。每次重读都重复访问历史订单,最近出现多次30秒查询超时,无法发布完整结果。
|
||||
|
||||
保持原四个只读视图和数据库连接地址。候选查询每个平台仅按绑定的`status=Question`读取订单号、异常类型,在应用中保留缺货、真实缺货、预售。实测在当前视图中叠加异常类型IN、类型或标签筛选会显著变慢,因此这些条件在最新记录读取后执行。未能获取底层索引或执行计划权限,本次依据真实查询结果与耗时选择读取方式,未修改外部视图、表或索引。
|
||||
|
||||
每批100个bigint订单号读取候选订单的全部版本,按修改时间、源Id取最新,再检查Question、三种异常类型、刷单标签和补发类型。这样最新版本改为Sent、其他异常类型或补发后,不会退回旧的缺货记录。商品明细继续分批读取并取最新源Id;任一来源失败不发布部分结果。没有新增日期、订单数或最终行数限制。
|
||||
|
||||
两个读取工作槽、单次30秒预算、商品明细超时拆批、60秒完整快照缓存及并发请求合并保持原有规则。组合装拆分、换货和替换款、JSReportReplica库存来源及云仓扣减、分类、Z/AE/AY汇总和每日报表存档仍由原有服务处理。
|
||||
|
||||
## 实际验证
|
||||
|
||||
- 2026-11-12 16:37:42(北京时间),直接使用实际Repository完整读取1183条原始明细:OTHER 409条、TAOBAO 774条,耗时59.842秒。候选查询2次,最新订单版本查询11次,商品明细查询11次,全部成功。两个源候选集合分别为2869、3167条Question记录,最终只取符合指定异常类型及排除规则的订单明细。
|
||||
- 2026-11-12 16:40:51,本地localhost:3000真实登录后强制重读,接口完成1227条组合拆分后明细及全部资料、库存、换货字段匹配,用时26.200秒;缓存内再次读取1.008秒,时间戳和行数相同。页面读取并展示3.695秒。以上是本次开发环境观测值,上游数据库和网络负载变化会影响耗时。
|
||||
- 使用真实页面与接口,未拦截或替换响应。1227条记录逐条满足Question、三类异常、无刷单标签及补发;行ID无重复。9项库存DTO字段均为空或有限数值。
|
||||
- Excel导出1227条,与接口一致。逐条核对Z为完整明细同货号M件数合计、AE为线上订单号和货号的行数、AY按缺货分类取M数量或0。当前导出的9个库存列无负数和横杠占位,数值0和空值均保留。
|
||||
- 浏览器1920和982宽度截图正常,无页面运行错误或横向溢出。查询和导出继续使用现有页面组件。
|
||||
- 10组缺货相关测试125项通过;类型检查和实现文件ESLint通过。回归覆盖双来源、bigint精度、最新状态/异常/补发/刷单不回退、1201候选跨批完整读取、明细去重、空集合及来源失败。
|
||||
|
||||
证据保存于本地忽略目录`.codex-runtime`及`.codex-logs`,包括真实完整接口快照、查询耗时、Excel导出和截图,不提交订单原始数据或连接密钥。
|
||||
|
||||
## 交接与审查
|
||||
|
||||
继续使用用户指定的“如懿”分支。本次已fetch远端,未合并共享开发主线的251个独有提交;本地运行目录仅同步当前任务对应的Repository与测试,保留其他并行开发改动。未发布生产,未写入外部数据源,未重建每日缺货报表。
|
||||
|
||||
规范审查:passed。架构保持Route → Service → Repository;页面沿用现有视觉;修复重复历史查询及慢筛选的读取方式,并以真实完整接口与导出验证。**这是自审,不是独立复审**。
|
||||
99
furniture-3d-system/docs/需求设计/缺货报表实现口径.md
Normal file
99
furniture-3d-system/docs/需求设计/缺货报表实现口径.md
Normal file
@ -0,0 +1,99 @@
|
||||
# 缺货报表实现口径
|
||||
|
||||
依据《上午九点缺货报表-需求.xlsx》“4.缺货报表”及用户已确认规则,入口为经营管理 → 缺货订单明细 → 缺货报表。
|
||||
|
||||
## 数据与计算
|
||||
|
||||
- 明细数据源不变。只保留当前订单状态 `status=Question` 且异常类型 `question_type` 为缺货、真实缺货、预售的订单,排除标签含“刷单”的订单,继续剔除补发。同一平台同一订单先按修改时间及源Id取最新记录,再检查状态和刷单标签;在商品明细读取、货号需求汇总和分类之前执行,两个平台口径一致。明细分类继续遵循“逻辑总结”,退款关闭、信誉/虚拟订单优先。
|
||||
- 组合装在订单筛选完成后、任何商品资料匹配及计算之前拆行。`ZH-商品编码-件数`按件数生成独立明细,支持连续多个子编码及编码内部的字母前缀/连字符。例如`ZH-SJ009523N430V01-2`拆为两条`SJ009523N430V01`;每行M数量保留原购买套数(买3套即两行各3件,共6件),0和空数量保持原值。拆后继承订单号、标签、退款状态等来源信息,生成稳定且不重复的行ID;普通编码和无法完整解析的组合编码保留原明细。资料、换货规则、库存、AE行数、Z件数、分类和AY报表汇总统一使用拆后的明细。
|
||||
- 明细与报表的商品编码、货号筛选忽略大小写,仍按完整编码匹配。候选搜索、批量输入和选中值统一按大写去重;保留前导零和编码精度,供应商等其他文本字段沿用原有匹配规则。
|
||||
- 每个商品编码一行,按完整明细 AY 缺货数量合计;不使用 M 数量或 Z 缺货总量替代 AY。AY合计明确小于等于0的编码不属于缺货报表,避免资料缺失或负库存把非缺货记录引入。
|
||||
- 清货状态0/1对应明确的文字“未填报清货库存”,不满足停产分类的清货库存≤0条件,应继续后续库存分类;不能直接将其拦截为待核实。清货记录缺失、状态无效或状态2数量缺失仍保持未知;状态3按已确认规则取0。退款关闭、信誉/虚拟和库存缺失的处理优先级不变。
|
||||
- 商品名称、供应商、条码状态由产品档案按编码读取。货号生产状态聚合该货号在档案中的全部编码,含销售优先销售;仅退市/停产且含退市为退市;全停产为停产。
|
||||
- 采购按供应商匹配报表源 `rpt.js_supplier.scmname → buyer`,重复记录取 `local_updated、Id` 最新记录。没有匹配供应商时按 Excel I10 的明确公式取宁珂;匹配到采购为空则保留空白。
|
||||
- 现有库存按 Excel K10 的货号粒度,汇总该货号全部编码在仓库属性为“成品发货仓-真实库存”的公有可用数;库存只计一次,不随订单重复。与订单明细共用显式的 `JSReportReplica.rpt.jst_inventoryInfo` 库存来源及同库仓库档案;公有可用数按用户确认继续使用实际库存减订单占用再减原运营云仓可用数。执行逻辑优先于映射行中“运营云仓可用数”的冲突说明。
|
||||
- 真实缺货 = AY 编码合计 − 现有库存,剔除小于等于0的记录。未知库存保持空白。沿用已确认规则:保留内部有符号计算,最终库存显示和导出负数为0。
|
||||
- 替换货号复用明细 PM 替换款规则得到的目标货号;多个目标去重。替换货号库存按目标货号全编码库存汇总并去重。自定义换货编码仍由 `rpt.jst_sku_replace_rule` 提供,不与 PM 替换款混用。
|
||||
- 替换货号与原货号相同时,只清空替换信息,保留原缺货记录。
|
||||
- 预计到货时间、备注、叫货在途-替换款由人员手工填报,用户已明确确认。到货时间支持日期或交期文字(最多120字),备注最多2000字,在途数量为0至10亿的整数或空。空与0分别保存。
|
||||
|
||||
## 每日存档与填报
|
||||
|
||||
`ShortageReportSnapshot` 保存生成日期、实际生成时间与明细读取时间;`ShortageReportEntry` 保存计算结果和三个人工字段,日期与编码唯一。
|
||||
|
||||
每天北京时间09:00执行 `scripts/generate-shortage-report-daily-snapshot.ts`。先重新读取所有明细来源及支持数据、计算全部字段,完整成功后发布当天的 `ShortageOrderDailySnapshot`;再以该份冻结明细生成报表,在事务中发布并清理六个自然月以前的报表存档(月底按目标月最后一天计算)。明细和报表均按日期唯一,空结果也保存成功记录;同日重跑不覆盖明细,不用当日数据伪造历史存档。任何源失败都不发布部分明细,已有完整快照继续可读。
|
||||
|
||||
明细由服务器定时任务生成,页面与旧 `refresh=1` 请求仅读取最近成功快照,不触发抓取或实时更新。明细与报表分别使用 PostgreSQL 会话锁,避免并发发布。报表页面在09:00后发现当日报表缺失时可从当天已冻结的明细补跑报表;不会重新抓取明细,也不会拿昨日明细伪造今日结果。明细尚未生成时须等待定时任务成功。
|
||||
|
||||
填报继承缺货订单明细的编辑权限;按日期与编码持久化,使用版本号拒绝覆盖其他人员已保存的内容。保存失败时保留当前草稿并提示;计算字段不能通过填报接口修改。
|
||||
|
||||
## 本地运行
|
||||
|
||||
迁移:`prisma/migrations/20261112090000_add_shortage_report_archive/migration.sql` 创建报表存档;`prisma/migrations/20261120140000_add_shortage_order_daily_snapshot/migration.sql` 新增独立的明细快照表及JSON数组约束,不改外部数据源。
|
||||
|
||||
生成:在主应用目录执行 `node node_modules/tsx/dist/cli.mjs scripts/generate-shortage-report-daily-snapshot.ts`。
|
||||
|
||||
后台明细任务单次 SQL Server 查询预算为120秒;Repository 的默认预算仍为30秒,沿用原有超时重试和批次缩小机制。读取完整性、来源、SQL条件及数量范围保持原口径;超时不以旧内存缓存代替当天全量读取。
|
||||
|
||||
需要重建当日报表时,在备份后显式执行相同命令加 `--rebuild-today`。该命令仍使用当天已冻结的明细,事务替换报表计算结果并移除不再符合条件的行;仍在报表中的记录保留原有人工填报并递增版本号,失败保留旧报表。该参数不会重新抓取或覆盖明细。普通每日任务保持幂等;不重建历史日期。
|
||||
|
||||
Windows 安装任务:`powershell -NoProfile -ExecutionPolicy Bypass -File scripts/install-shortage-report-daily-task.ps1`。复用 `FurnitureRuyi-ShortageReportDaily`,每日09:00触发,错过后补执行,失败间隔15分钟重试三次,忽略重叠实例。通过隐藏的PowerShell运行器启动Node,并将每次执行的输出及错误分别保存在本机忽略目录 `.codex-logs/shortage-daily-*.log`。要求Windows中国标准时间、机器运行且安装任务的用户已登录、数据库已启动且来源可达;页面是否打开不影响任务触发。
|
||||
|
||||
Linux 部署时使用现有部署体系安排相同脚本在 `Asia/Shanghai` 09:00执行;本次仅安装本地 Windows 任务,未发布生产。
|
||||
|
||||
页面保留16列及生成日期、货号、商品编码、供应商、采购筛选,支持查询、重置、列显示/排序/宽度保存和按当前筛选列导出。订单明细移除处理视图、库存核对、替换款核对三个预设,仅保留全部字段和列设置;旧预设偏好迁移为全部字段。
|
||||
|
||||
## 本地验证记录(2026-11-12)
|
||||
|
||||
- 12组缺货相关测试,共99项通过;类型检查及改动范围的 ESLint 通过。
|
||||
- 首份报表完成后排除AY为0的记录,保留125条;逐条与当时1586条完整明细的AY编码汇总核对一致,13条有替换货号。商品名称、状态、供应商、库存均有值;9条采购为空,对应供应商源记录没有采购值,保持空白。
|
||||
- 浏览器验证匿名访问拦截、旧视图偏好迁移、16列报表、三个人工字段保存及刷新恢复、并发版本冲突、非法字段拒绝、保存失败保留草稿、日期与编码筛选、列设置、125条Excel导出及1920/982/390宽度。
|
||||
- 验证使用的人工填报已恢复为空;当天存档实际生成时间保存在数据库,不伪称首次生成于09:00。
|
||||
- 本地任务已实际执行,返回码0;下次运行2026-11-13 09:00。只对本地开发库应用新增迁移,应用前已生成并验证备份,外部数据库保持只读。
|
||||
- 规范审查:passed。架构保持Route → Service → Repository,视觉复用工作台组件,数据从源读取并按规则计算。这是自审,不是独立复审。
|
||||
|
||||
## Question 与刷单筛选修正验证(2026-11-12)
|
||||
|
||||
- 两个平台均只读取符合最终筛选口径的商品明细。新增测试覆盖非 Question 状态、空状态、各类含“刷单”的标签,以及最新记录被排除后不得回退旧 Question 记录;12组相关测试共106项通过,类型检查及实现文件 ESLint 通过。
|
||||
- 更正前已生成并验证本地 PostgreSQL 完整备份。显式重建当日报表成功,125条调整为103条;历史日期不回填。
|
||||
- 实际接口完整读取1154条明细,逐条确认状态均为Question、异常类型均在指定三类、无标签含刷单的订单;103条报表与明细AY编码汇总全部一致。`GBSFY-SJ033203N1280V01`原860件对应的20笔Sent且带刷单标签订单已全部排除,该编码不再出现在本次明细及报表中。
|
||||
- 在独立临时 PostgreSQL 库验证重建事务:保留人工字段(含0)、递增版本、移除失效记录、保留历史、失败回滚、普通每日任务幂等及空报表发布均通过,临时库已移除。
|
||||
- 使用实际页面验证103条报表、人工填报保存后恢复、版本冲突、保存失败保留草稿、筛选、103条Excel导出及1920/982/390宽度;页面无运行时错误。
|
||||
- 规范审查:passed。筛选在数据访问层及汇总前统一执行,重建由服务编排并事务发布,页面复用原有工作台组件。这是自审,不是独立复审。
|
||||
|
||||
## 组合装拆分验证(2026-11-12)
|
||||
|
||||
- 13组缺货相关测试共123项通过,类型检查及实现文件ESLint通过。覆盖同款多件装、多编码组合、带连字符的子编码、原数量为0或空、重复组件、行ID唯一、资料匹配及AE/Z/AY汇总。
|
||||
- 实际读取的32条组合明细展开为74条子编码明细,1122条普通明细保留,合计1196条。逐条对照拆前来源,组件和件数、订单号、数量、标签、退款状态等继承正确,行ID无重复;Question及三种异常类型和刷单排除条件仍全部满足。
|
||||
- `ZH-SJ009523N430V01-2`的5条来源明细展开为10条`SJ009523N430V01`,每行数量为1;该编码合并原有单件订单后共51行、52件,Z及AY均为52。
|
||||
- 已验证本地完整数据库备份,并使用刚完成的完整接口结果重建当日报表,仍为103条;所有编码的报表AY与拆后明细合计一致,示例编码缺货数量由42更新为52。
|
||||
- 浏览器按示例线上订单号和子编码筛选显示2行,导出也是2行且编码、数量正确;1920/982/390宽度验证通过,页面无运行时错误。
|
||||
- 规范审查:passed。服务在资料查询前应用组合拆分规则,后续计算共用拆后结果;沿用现有表格与导出。这是自审,不是独立复审。
|
||||
|
||||
## 编码筛选大小写修正验证(2026-11-12)
|
||||
|
||||
- `DNZ004409N1222V01`已存在当日报表,缺货26件、现有库存0件、真实缺货26件;对应完整明细26行,源编码同时存在大写和小写前缀。
|
||||
- 修正前在真实页面复现:输入`dnz004409N1222V01`无候选且查询0行,输入全大写可查询1行。统一编码筛选后,原输入、全大写、全小写均查询到同一行,小写货号也能匹配,混合大小写批量值只保留一个选中项。
|
||||
- 13组相关测试共125项通过,类型检查及实现文件ESLint通过。浏览器验证三种编码写法、货号组合筛选、候选勾选状态、批量去重、导出1行及1920/982/390宽度,页面无运行时错误。
|
||||
- 规范审查:passed。修正共享筛选组件及两页筛选函数,沿用原有表格和数据计算。这是自审,不是独立复审。
|
||||
|
||||
## 未填报清货库存分类修正验证(2026-11-12)
|
||||
|
||||
- 五个`MKHDNZ040926100`编码(尾号0068、0030、0080、0055、0065)在产品档案中均为退市,清货源记录均为状态0、剩余库存为空。原实现将明确的“未填报清货库存”与数据缺失一起提前拦截,导致分类为待核实、AY为0;需求公式在清货库存≤0条件不成立时继续后续库存判断。现按此逻辑分类,保留未填报文字,并继续区分真实未知数据。
|
||||
- 10组缺货相关测试共118项通过,类型检查和实现文件ESLint通过。覆盖状态0/1继续分类、状态2空数量保持未知、状态2数量0及状态3保持停产分类,以及退款关闭、虚拟商品和库存未知的优先级。
|
||||
- 已生成并验证本地完整数据库备份。北京时间15:12:58完成1215条完整明细读取,所有行均满足Question、指定三种异常类型及刷单排除条件;使用同一份新鲜结果事务重建当日报表,111条全部与明细AY及真实缺货公式一致。
|
||||
- 同类9个编码恢复,新增AY合计10件。用户给出的五个编码按上述顺序分别为1、2、1、1、1件。与上次103条报表相比另移除1个编码,其来源订单当前为Cancelled且异常类型为空,符合当前抓取条件;不是本次分类修正导致移除。
|
||||
- 浏览器实际查询五个编码并导出,页面5条和Excel5条的缺货数量一致,最终库存负数仍显示0,页面无运行时错误。人工填报字段保留,外部源保持只读。
|
||||
- Git已核对`如懿`与远端一致后开展本次修正;已读取最新共享开发主线状态,本次未合并其无关变更。
|
||||
- 规范审查:passed。仅修正既有分类函数的判断条件,复用原有汇总、事务存档及页面。这是自审,不是独立复审。
|
||||
|
||||
## 仓库库存来源固定验证(2026-11-12)
|
||||
|
||||
- 用户指定仓库库存统一读取`JSReportReplica.rpt.jst_inventoryInfo`,并确认继续使用`qty - order_lock - 原云仓可用数`。Repository显式使用三段式库表名,仓库档案也固定为同库`rpt.jst_warehouseInfo`;原编码、换货编码、货号、替换款及分仓共用该读取函数。供应商清货剩余库存仍按已有清货状态规则读取。
|
||||
- 本地原连接默认库已经是JSReportReplica;本次明确固定SQL目标,避免部署配置改变默认库或Schema后读取其他同名表,不改变库存公式或已有每日存档。
|
||||
- 10组相关测试共119项通过,类型检查及实现文件ESLint通过。新增回归验证连接默认库及Schema不同仍查询指定目标,原云仓查询及参数绑定保留。
|
||||
- 真实数据库读取在补全PM替换目标全货号编码后覆盖745个请求编码、3589条库存、166条仓库档案,原云仓读取572条;抽样逐项核对实际库存、订单占用、云仓扣减及公有可用数。例如某编码实际25、订单占用0、云仓可用28,内部结果-3,按原显示规则最终为0。
|
||||
- 原工作区同时存在其他页面的未提交开发,本次在独立工作目录的如懿分支验证和提交,并仅同步相关4个文件到原本地运行目录,保留其他开发内容。
|
||||
- 页面与Excel定向验证采用已保存的1215条订单及新读取的库存,在独立服务的浏览器测试中拦截明细响应,覆盖原编码、换货及替换款3个编码、3行数据的9个仓库库存字段;显示、负数归零和导出均一致,页面无运行时错误。该验证不代表当前订单完整刷新通过。
|
||||
- 当前完整刷新在进入库存查询前的订单源分段查询中多次发生`ETIMEOUT`(30秒);一次已推进至50/69分段后失败。库存源真实读取正常,整表页面验收仍受此限制;未发布不完整订单快照、未改写当日或历史报表。
|
||||
- 规范审查:passed with warnings。数据读取保持Repository边界,共享库存链路统一固定指定表;页面和公式沿用现有规则。警告为订单源超时导致完整刷新未验收。这是自审,不是独立复审。
|
||||
201
furniture-3d-system/docs/需求设计/缺货订单明细页面设计.md
Normal file
201
furniture-3d-system/docs/需求设计/缺货订单明细页面设计.md
Normal file
@ -0,0 +1,201 @@
|
||||
# 缺货订单明细页面设计与字段口径
|
||||
|
||||
来源:用户提供的《上午九点缺货报表-需求.xlsx》。本文只记录字段和规则,不包含历史订单行。
|
||||
|
||||
## 本次页面交付
|
||||
|
||||
- 经营管理 → 缺货订单明细,路由 `/supply-chain/management/shortage-order-details`。使用独立权限节点 `shortageOrderDetails`;继续遵守查看、下载权限。
|
||||
- 页面内提供“订单明细 / 缺货报表”子导航;独立汇总报表路由为 `/supply-chain/management/shortage-order-details/report`,继承同一查看、下载权限。
|
||||
- 8 项筛选均支持多个值、粘贴批量值及清空:货号、商品编码、供应商、采购、内部订单号、线上订单号、店铺名称、处理部门。同字段按或匹配,不同字段按且匹配;处理部门可匹配组合部门中的单个部门。查询后应用,重置后清空。
|
||||
- 页面使用“全部字段”视图,支持列设置;已删除库存核对、替换款核对等三个预设子表。
|
||||
- Excel B:BD 共 55 列,R/AM 付款日期合并,并按用户要求移除“状态”“退款状态”“辅助”“是否已解决”“处理进度反馈”,当前保留 49 个页面及导出字段。V 列“缺货类型达标”按内容命名为“缺货类型打标”。
|
||||
- 列设置支持显隐、拖动或按钮排序、恢复当前视图;表头支持拖动和键盘左右键调宽。偏好按用户保存在当前浏览器。
|
||||
- 导出当前筛选结果及显示列;空数据时只导出表头。商品、订单标识按文本保留精度和前导零。
|
||||
- 明细已接入现有 SQL Server 报表副本的订单主表、商品明细、换货规则、PM 替换款关系、库存、云仓、仓库档案及清货库存,并关联产品全量档案;不读取 Excel 历史订单。已按用户确认的“逻辑总结”执行分类、建议与部门映射。明细与报表均已接入每日存档和定时任务;明细人工处理反馈保存、是否可替换配置及解决标记尚未接入。
|
||||
- 已实现可单独验证的件数汇总、全货号状态聚合、真实缺货计算、替换信息清理及六个月查询边界规则。明细视图在筛选前应用件数汇总;状态聚合与报表生成需在接入数据的 Service 中使用全量来源。
|
||||
|
||||
## 业务数据链
|
||||
|
||||
1. 聚水潭订单和明细:内部订单号、线上订单号、商品编码、数量、状态、付款时间、标签、退款等。仅保留最新版本 `status=Question` 且 `question_type IN (N'缺货', N'真实缺货', N'预售')` 的明细;剔除刷单标签及补发类型订单,已取消、Sent 等状态不进入。普通 `labels` 原样展示。
|
||||
2. 产品全量档案 SupplyChainProductArchive:按商品编码获取货号、商品名、分类、生产状态、供应商、单双包和标签。采购读取档案已同步的 `purchaseOwner`(来源为供应商采购关联),缺失时留空。
|
||||
3. 换货规则 `rpt.jst_sku_replace_rule`:原商品编码匹配 `sku_id`,换货编码读取 `data`;仅取最新 `snapshot_date` 中 `enabled = 1` 的规则。换货编码再关联产品档案的 `sku` 和 `productTag`。这组字段对应 AE–AH 中的 AF/AG/AH。
|
||||
4. 库存按公有可用数口径,从 `JSReportReplica.rpt.jst_inventoryInfo`、原云仓可用数与同库仓库档案计算,覆盖原编码、换货编码、货号、替换款及仓库维度。清货库存来自 plm_productDiscontinuation。
|
||||
5. 替换关系 pm_replacementManage:先按商品编码匹配,未命中时按货号匹配替换货号,再按限定仓库范围的公有可用库存选择目标货号下库存最多的编码;读取类型、是否换图、修改点,对应 AQ 及后续替换款字段。是否可替换来自人工配置。
|
||||
6. 分类结果匹配“逻辑总结”的处理建议与处理部门,保留人工反馈与解决标记。
|
||||
|
||||
## 用户已确认的修正
|
||||
|
||||
- 2026-11-11 从全部明细视图、列设置与导出中移除“状态”“退款状态”;旧浏览器偏好中的这两个字段在恢复时自动过滤。下方原文件映射保留来源说明。
|
||||
- 2026-11-12 优化订单读取,数据源地址及四个订单/明细视图保持不变。每个平台只按 `status=Question` 读取内部订单号和异常类型,在服务端保留缺货、真实缺货、预售候选;按每批100个 bigint 内部订单号读取候选订单的全部版本,按修改时间、源Id去重后再检查最终状态、异常类型、刷单标签和补发类型。之后分批读取商品明细并按来源、订单号、明细号及源Id去重;缺少明细号时使用源行Id。不再读取历史Id上下界和约69个历史分段,不在候选SQL中叠加异常类型IN、标签或类型条件,以避免当前源视图选择慢查询。两个平台共用两个读取工作槽,单次查询预算仍为30秒,明细超时可二分至单订单。无日期限制、候选数量上限或最终明细截断;失败不发布部分数据。
|
||||
- 2026-11-20 用户要求明细每天北京时间09:00全量生成,日内固定。`ShortageOrderDailySnapshot` 按日期保存所有明细字段和实际读取时间;任务每次重新读取订单、全量档案、换货/替换规则、库存、云仓、仓库、清货并重新计算全部派生字段。完整成功后一次发布,同日重跑不覆盖;失败保留上一份完整快照,首次尚未成功时明确显示未生成。
|
||||
- 明细接口 `GET /api/supply-chain/management/shortage-order-details` 只查询最新已保存快照,返回 `ready` 或 `empty`(HTTP 200);旧客户端的 `refresh=1` 兼容为只读操作。页面、筛选、49列及Excel导出使用同一份固定数据,文件名采用快照日期;重开页面、缓存过期和Web重启都不会自动重算。查看、下载权限沿用原节点。
|
||||
- 2026-11-24 修复“重新读取”只重读旧存档的问题。具备 `shortageOrderDetails.edit` 权限的账号点击按钮,通过无参数 `POST` 显式启动全量抓取;后台完整重读并重算订单、库存、档案、换货/替换及清货字段,再计算当日缺货报表。同日允许手动更新,明细与报表在同一事务发布,保留仍在当日报表中的人工填报,历史日期不改写。后台查询预算为120秒,HTTP请求立即返回;仅任务进行中每1.5秒通过GET查询进度,结束后停止轮询。页面重开可继续查看进行中的任务,PostgreSQL会话锁阻止Web/命令进程重复生成。失败显示重试提示、保留上次完整数据;跨北京时间午夜的任务不发布到旧日期。定时任务继续关闭。
|
||||
- 2026-11-20 用户要求测试完成前取消定时,Windows 任务 `FurnitureRuyi-ShortageReportDaily` 保持 Disabled。本次规则变更仅显式手动全量抓取并原子更新当日明细及报表;保留仍在报表中的三项人工填报,不改历史快照,不恢复定时。
|
||||
- 当前直接映射 N 异常类型=`question_type`、T 标签=`labels`。每日任务先冻结完整明细,再以当天冻结明细生成独立缺货报表;报表重建也不实时重抓明细。
|
||||
- 2026-11-11 AE 按原文件 AE10“表格内线上订单号&货号在此表内的计数”实现:在完整缺货明细内按“线上订单号 + 货号”统计明细行数,先计算再筛选、分页;与 Z 的 M 数量件数合计分别处理。线上订单号或货号缺失时留空,不把未知记录归为一组。
|
||||
- 2026-11-11 用户确认 AG 从 `rpt.jst_sku_replace_rule` 获取。原商品编码在去除首尾空格、统一大小写后精确匹配 `sku_id`,保留编码前导零;同编码多条有效规则取修改时间(缺失时取创建时间)较新者,时间相同时取较大源行 Id。`data` 中多个候选按源顺序去重展示,不按库存擅自挑选。档案读取同时包含原编码和全部换货候选;AG 用逗号连接编码,AF/AH 分别去重显示对应货号和标签。无有效规则时三项留空;有编码但目标档案缺失时保留 AG,缺失的 AF/AH 留空。换货规则读取失败会使整次读取失败,不发布缺失换货字段的部分快照。
|
||||
- 页面“商品编码”始终是本行原编码;“换货编码”直接展示该原编码在 `sku_id → data` 规则中的目标。Service 使用统一正向映射函数,对规则原编码、订单商品编码及目标档案编码统一去空格、忽略大小写;编码本身保持文本,目标缺档不影响换货编码返回。换货货号、标签与库存均沿此目标编码关联,不从目标反查原编码,也不套用同货号或 PM 替换款关系。
|
||||
|
||||
- Z 缺货总量:同货号的 M 数量按件数求和,先汇总再筛选、分页,不使用订单行数或订单数。
|
||||
- AA 货号生产状态:读取该货号在 SupplyChainProductArchive 中的全部编码;含销售优先为销售;只有退市/停产且含退市为退市;全部停产为停产。不能使用首条 VLOOKUP 或只看本次缺货订单涉及的编码。缺档或状态未知且无销售时保留未知。
|
||||
- 缺货报表 O 替换货号与 C 原货号一致时,仅清空 O/P/Q 替换信息,原缺货记录保留。
|
||||
- 2026-11-11 用户确认分类以“逻辑总结”为准,退款关闭、信誉/虚拟订单优先;仓库分组按需求说明,正常大货仓为属性精确等于“成品发货仓-真实库存”,前置仓仅“三方-南昌樵舍仓”,不含重庆西南仓。
|
||||
- 2026-11-11 用户确认清货 `state=3` 代表清货完成,库存按 0;`state=2` 读取 `remainingStock`,`state=0/1` 显示“未填报清货库存”。同编码按更新时间、源 Id 取最新状态;无记录和未定义状态仍未知。
|
||||
|
||||
## 2026-11-11 全字段排查与补齐
|
||||
|
||||
- 排查覆盖全部 52 个页面/导出字段。此前有 26 项未在 DTO 中返回;其中 18 项为库存和替换款字段,4 项为分类及其派生结果,4 项为没有业务记录来源的人工/辅助字段。服务现在显式返回全部字段;后四项保留空值,不默认“否”或“已解决”。
|
||||
- 2026-11-12 用户指定订单明细的仓库库存统一读取 `JSReportReplica.rpt.jst_inventoryInfo`,并确认沿用公有可用数公式。库存及仓库档案均使用显式数据库、Schema、表名,避免受连接默认数据库或其他来源的Schema配置影响。公有可用数 = `qty - order_lock - 运营云仓 order_able_qty`;原云仓仍通过 `JianSun_Old` 读取 `JianSun.dbo.jst_virtualstockStocksInfo`,只取 `qty > 0`,按“编码 + 实际仓库编号”归集,保留负数。原编码与全部换货候选在合计前去重,防止重复库存。换货编码、原编码、原编码+换货编码、货号总库存、正常大货仓、前置仓及替换款各库存字段共用此链路;清货剩余库存仍读取供应商清货进度。
|
||||
- 2026-11-12 用户要求库存最终计算结果为负数时显示为 0。订单明细及独立缺货报表的库存、分仓库存和清货库存列,在全部计算完成后统一用于表格、悬浮提示与 Excel 导出;原始数值保留用于汇总和分类,空值仍留空,未填报文字保留。
|
||||
- 全货号库存使用产品档案中该货号的全部编码。完整成功读取后,已请求编码没有范围内库存记录时按 SUMIFS 的空集合口径返回 0;未请求编码及范围内库存源字段空值仍保留未知。任何必需来源读取失败时整次快照失败,不返回伪造的零库存。
|
||||
- 2026-11-20 库存范围收敛为五类属性仓库:“成品发货仓-真实库存”“成品代发仓-虚拟库存”“模块化商品项目-半成品仓-真实库存”“渠道专用仓-真实库存”“临时仓-成品发货仓-真实库存”,外加名称为“三方-南昌樵舍仓”的库存,一起进入计算。两部分取并集合计,重叠只计一次;没有档案、属性不符且非南昌的仓库不进入计算,其未知数值也不污染范围内结果。总库存、货号库存、原编码与换货库存、替换款库存及选码使用同一范围;正常大货仓仍只取第一类属性,前置仓仍只取南昌。公有可用数公式和最终负数显示为0的规则保持不变;清货库存沿用清货进度来源。
|
||||
- PM 替换款从 `rpt.pm_replacementManage` 读取 `[delete]=0` 的有效关系,`sku/replaceSku` 均可能维护商品编码或货号,查询同时包含两种标识。匹配顺序为正向精确编码、反向精确编码、正向货号、反向货号,保留原反查能力,编码粒度优先于货号。重复关系按创建时间、源 Id 取最新。`replaceType=1/2` 分别为相似款/相同款;`isSwapping=1/2` 分别为换图/不换图,0 或未定义值留空。
|
||||
- 精确编码关系直接使用指定目标编码;按货号匹配时,加载目标货号下全部编码,按上述公有可用库存降序选一个。库存相同时按规范化编码字典序升序,负值仍按原始值排名;未知库存不当0参与排名,全部未知时保留目标货号、编码留空。标签读取最终选中编码;替换款库存、分仓库存及状态仍汇总目标货号全部编码。
|
||||
- 例如 `DNZ028907N866V01` 归属 `DNZ028907`,PM维护 `DNZ028907 → DNZ028915`;2026-11-20手动读取时目标编码 `DNZ028915N866V01` 公有可用库存25,`DNZ028915N887V01` 为0,因此替换款编码选择 `DNZ028915N866V01`。示例库存只记录此次验收值,不作为固定配置。
|
||||
- 分类在完整明细汇总后计算,不随页面筛选或分页改变。顺序为退款关闭 → 分类含信誉/虚拟 → 产品状态缺失的特殊或组合商品 → 原编码库存严格大于缺货总量的非真实缺货规则 → 原编码及换货编码无库存但货号有库存的待核实规则 → 停产/退市库存分支 → 销售库存、特殊发货标签及替换款分支;当前分支所需关键输入缺失时为“异常订单-待核实处理”。建议与部门按“逻辑总结”对应关系返回,不使用“操作步骤”的旧部门配置。
|
||||
- 2026-11-21 用户确认:当原编码库存 `originalStock > totalShortage`,统一标记“非真实缺货-原商品编码大货仓有库存且能补齐缺货”;处理建议为“核实有库存未锁定原因并处理异常”,部门为“如懿”,AY缺货数量为0。比较原编码在五类属性仓库加南昌樵舍仓的公有可用总库存,与该货号完整明细M件数合计,不比较单行数量、换货合计或其他编码的货号库存。严格大于才命中,等于沿原规则;库存和需求须为有限数值。
|
||||
- 新非真实缺货规则优先于特殊发货标签、换货/替换款、分仓及停产清货分支;原编码已足够时不再依赖无关的换货库存、替换款库存、货号生产状态或清货资料。退款关闭、信誉/虚拟及未拆特殊/组合商品仍先判断。旧“原+换货=0且货号库存非0”规则继续生效,但若因负数换货库存抵消导致合计为0且原编码自身已经足够,优先使用本次明确的非真实缺货规则。
|
||||
- 分类名称中的“大货仓”按用户指定保留;本条判断允许库存来自渠道、代发、半成品、临时及南昌等已纳入仓库,不表示18件等库存必然属于“正常大货仓”分组。分仓列与库存公式均保持原定义。
|
||||
- 2026-11-20 用户确认:原编码+换货编码总库存等于 0,且货号总库存不等于 0 时,统一标记“异常订单-待核实处理”,处理建议同名、处理部门为如懿、AY 缺货数量为 0。此规则覆盖全部编码、销售/停产/退市状态及替换款、特殊发货标签分支,保留退款关闭、信誉/虚拟及未拆特殊/组合商品的优先级。使用已知有限数值的原始计算结果精确比较,库存未知不当作零;负库存显示为 0 的既有显示规则不改变分类输入。
|
||||
- AY 按分类以“缺货-”开头时取本明细 M 件数,否则为 0;未确定的库存相等边界仍标待核实,不自行派单。人工“是否可替换”未确认时不进入依赖其为“是”的分支。
|
||||
- 部分已接入商品字段仍可为空:组合套装/特殊编码没有产品档案,或者档案中的分类、采购、单双包等本身为空。付款日期、店铺商品编码和普通标签的空值沿用订单源,不填默认值。
|
||||
- `Y feedback`、`BA canReplace`、`BC helper`、`BD resolved` 当前没有持久化来源;处理反馈与解决状态需要后续明确录入/保存业务流程,辅助字段需明确用途。
|
||||
|
||||
## 独立缺货报表(工作表“4.缺货报表”)
|
||||
|
||||
报表按“生成日期 + 商品编码”保存每日汇总结果;生成日期是快照日期,不是订单付款日期。J 缺货数量先按编码合计明细 AY 缺货数量,不能使用 Z 货号总量,也不能直接合计所有 M 数量。库存与替换信息应在编码汇总后关联一次,避免订单行导致库存重复。
|
||||
|
||||
| Excel 列 | 页面字段 | 来源与规则 |
|
||||
| --- | --- | --- |
|
||||
| B | 生成日期 | 每日快照生成日期,业务时区 Asia/Shanghai |
|
||||
| C | 货号 | 缺货订单明细货号,标识按文本保留 |
|
||||
| D | 商品编码 | 缺货订单明细商品编码,按编码汇总 |
|
||||
| E | 商品名称 | SupplyChainProductArchive 商品名称;原表映射和说明误写“供应商”,按标题及示例公式采用商品名称 |
|
||||
| F | 货号生产状态 | 使用上述 AA 全货号聚合规则 |
|
||||
| G | 条码生产状态 | 按商品编码取档案商品状态 |
|
||||
| H | 供应商 | 按商品编码取档案供应商 |
|
||||
| I | 采购 | 按供应商关联 js_supplier;示例公式默认人员未确认,不硬编码 |
|
||||
| J | 缺货数量 | 同商品编码的明细 AY 缺货数量件数合计 |
|
||||
| K | 现有库存 | JSReportReplica.rpt.jst_inventoryInfo,按货号汇总属性“成品发货仓-真实库存”的公有可用数 |
|
||||
| L | 真实缺货 | J - K;剔除小于等于 0 的记录;任一输入未知时仍显示未知,不伪造真实缺货数 |
|
||||
| M | 预计到货时间 | 用户确认由人员手工填报,持久化保存 |
|
||||
| N | 备注 | 用户确认由人员手工填报,持久化保存 |
|
||||
| O | 替换货号 | 与原货号相同则清空 O/P/Q,保留原缺货记录 |
|
||||
| P | 叫货在途-替换款 | 用户确认由人员手工填报,持久化保存 |
|
||||
| Q | 替换货号库存 | 按替换货号全部编码汇总限定范围内的公有可用数 |
|
||||
|
||||
- 筛选:生成日期起止范围、货号、商品编码、供应商、采购;四个业务字段均支持多值。同字段按或、字段间按且,点击查询应用;重置清空。
|
||||
- 全部 16 列默认展示;列设置支持显隐、顺序、恢复默认;支持列宽调整和分页,与明细页共用组件。浏览器偏好使用独立用户键,互不覆盖。
|
||||
- 导出当前筛选结果与当前显示列的顺序和列宽;空结果仅导出表头。
|
||||
- 存档策略:每日一次,最多保留六个自然月;月底取目标月最后一天。例如 2026-08-31 的最早保留日期为 2026-02-28。查询边界按当天业务日期计算,拒绝非法日期、倒置范围、过期和未来日期。
|
||||
- 每日快照在完整数据校验后整体保存,历史快照不随当前库存或产品档案变化而改写。明细使用独立日期快照表;报表已实现存档、每日任务及六个自然月以前的物理清理。页面读取持久化结果;没有明细快照时明确提示尚未生成。
|
||||
|
||||
## 接入前待确认
|
||||
|
||||
这些问题只记录,不在页面中擅自执行某一种口径:
|
||||
|
||||
- 缺货补齐比较原规则使用 > 或 <,库存恰好等于需求的边界仍需确认;当前保留待核实,不按不足或足够自动派单。
|
||||
- “逻辑总结”中部分条件重复、部分分支没有条件说明;无法确定的组合保留待核实。
|
||||
- 在售商品只有无需换图的替换款库存、但不能补齐缺货时,“逻辑总结”没有对应处理关系,暂列待核实,不沿用停产商品的劝退建议。
|
||||
- Y 处理反馈、BC 辅助、BD 是否已解决来源未完整定义;BA 是否可替换依赖的人工配置页面不属于本次设计。
|
||||
- E7 分类批注为“剔除配件带-”,需明确具体排除条件,不能直接推断为所有配件或所有带连字符的货号。
|
||||
- 独立报表 K 使用用户已确认的正常大货仓属性口径;M/N/P 为人工填报,Q为替换货号库存,采购按已接入的供应商关联读取。
|
||||
|
||||
## 明细字段映射
|
||||
|
||||
下表保留原文件用语;Z/AA/AG 按用户确认的口径修正,AE 按原文件计数说明实现,空白表示原文件未定义。
|
||||
|
||||
| Excel 列 | 展示字段 | 数据源 | 映射字段 | 取值说明 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| B | 订单类型 | jst_Orders. jst_orderitem--其他<br>jst_qmcust_orderlist_item--淘系 | 订单类型 | 直取 |
|
||||
| C | 内部订单号 | jst_Orders. jst_orderitem--其他<br>jst_qmcust_orderlist_item--淘系 | 内部订单ID | 直取 |
|
||||
| D | 线上订单号 | jst_Orders. jst_orderitem--其他<br>jst_qmcust_orderlist_item--淘系 | 订单号 | 直取 |
|
||||
| E | 分类 | SupplyChainProductArchive | 二级类目 | 直取 |
|
||||
| F | 货号 | SupplyChainProductArchive | SKU | 由商品编码获取对应SKU |
|
||||
| G | 商品编码 | jst_Orders. jst_orderitem--其他<br>jst_qmcust_orderlist_item--淘系 | 系统商品编码 | 直取 |
|
||||
| H | 商品名称 | SupplyChainProductArchive | 商品名称 | 由商品编码获取对应商品名称 |
|
||||
| I | 生产状态 | SupplyChainProductArchive | 商品状态 | 由商品编码获取对应商品状态 |
|
||||
| J | 供应商 | SupplyChainProductArchive | 供应商 | 由商品编码获取对应供应商 |
|
||||
| K | 采购 | select * from js_supplier --简尚主表 | 采购 | 由供应商获取对应采购 |
|
||||
| L | 单双包 | SupplyChainProductArchive | 单双包 | 由商品编码获取对应单双包 |
|
||||
| M | 数量 | jst_Orders. jst_orderitem--其他<br>jst_qmcust_orderlist_item--淘系 | 数量 | 直取 |
|
||||
| N | 异常类型 | | | 直取 |
|
||||
| O | 状态 | jst_Orders. jst_orderitem--其他<br>jst_qmcust_orderlist_item--淘系 | 订单状态 | 直取 |
|
||||
| P | 平台站点 | jst_Orders. jst_orderitem--其他<br>jst_qmcust_orderlist_item--淘系 | 平台 | 直取 |
|
||||
| Q | 店铺名称 | jst_Orders. jst_orderitem--其他<br>jst_qmcust_orderlist_item--淘系 | 店铺名称 | 直取 |
|
||||
| R | 付款日期 | jst_Orders. jst_orderitem--其他<br>jst_qmcust_orderlist_item--淘系 | 付款时间 | 直取 |
|
||||
| S | 店铺商品编码 | jst_Orders. jst_orderitem--其他<br>jst_qmcust_orderlist_item--淘系 | 平台商品编码 | 直取 |
|
||||
| T | 标签 | jst_Orders | labels | 直取 |
|
||||
| U | 退款状态 | jst_Orders. jst_orderitem--其他<br>jst_qmcust_orderlist_item--淘系 | 退款状态 | 直取 |
|
||||
| V | 缺货类型达标 | 逻辑总结 | 分类规则 | 退款关闭、信誉/虚拟优先;关键输入未知时待核实 |
|
||||
| W | 处理建议 | 逻辑总结 | 分类 → 处理意见 | 按分类匹配 |
|
||||
| X | 处理部门 | 逻辑总结 | 分类 → 处理部门 | 按分类匹配 |
|
||||
| Y | 处理进度反馈 | | | |
|
||||
| Z | 缺货总量 | / | M 数量 | 按同货号对 M 列件数求和,在筛选和分页前计算 |
|
||||
| AA | 货号生产状态 | SupplyChainProductArchive | 全货号所有编码的商品状态 | 含销售优先销售;只有退市/停产且含退市为退市;全部停产为停产;不取首条匹配 |
|
||||
| AB | 清货剩余库存 | plm_productDiscontinuation | remainingStock / state | 最新状态 2 取剩余库存;0/1 为未填报;3 清货完成为 0 |
|
||||
| AC | 交易单号&货号 | / | / | 表格内线上订单号&货号 |
|
||||
| AD | 商品标签-原商品编码 | SupplyChainProductArchive | 商品标签 | 直取 |
|
||||
| AE | 单交易单单号单货号销售数量 | 完整缺货明细 | 线上订单号 + 货号 | 同组合的明细行数,筛选和分页前计算;任一键缺失时留空 |
|
||||
| AF | 换货货号 | SupplyChainProductArchive | SKU | 以 AG 目标编码精确匹配 barcode,读取 sku;多个目标按规则顺序去重货号,档案缺失时留空 |
|
||||
| AG | 换货编码 | rpt.jst_sku_replace_rule | sku_id → data | 最新快照的启用规则;按原编码精确匹配,多候选按源顺序展示 |
|
||||
| AH | 商品标签-换货编码 | SupplyChainProductArchive | productTag | 以 AG 目标编码精确匹配 barcode,读取该编码标签;多个目标标签按规则顺序去重,不聚合同货号其他编码标签 |
|
||||
| AI | 换货编码库存 | jst_inventoryInfo_view | 公有可用数 | 换货编码共有可用数库存 |
|
||||
| AJ | 原编码库存 | jst_inventoryInfo_view | 公有可用数 | 商品编码共有可用数库存 |
|
||||
| AK | 原编码+换货编码总库存 | / | / | 换货编码共有可用数库存+商品编码共有可用数库存 |
|
||||
| AL | 货号总库存 | jst_inventoryInfo_view | 公有可用数 | 货号维度共有可用数库存 |
|
||||
| AM | 付款日期 | jst_Orders. jst_orderitem--其他<br>jst_qmcust_orderlist_item--淘系 | 付款时间 | 直取 |
|
||||
| AN | 原编码+换货编码正常大货仓库存 | jst_inventoryInfo_view | 公有可用数 | 仓库属性=成品发货仓-真实库存公有可用数合计(以换货编码维度) |
|
||||
| AO | 原编码+换货编码前置仓库存 | jst_inventoryInfo_view | 公有可用数 | 三方-南昌樵舍仓共有可用数 |
|
||||
| AP | 替换款货号 | pm_replacementManage / SupplyChainProductArchive | SKU | 精确编码目标取档案SKU;货号关系直接确定替换货号 |
|
||||
| AQ | 替换款条码 | pm_replacementManage / SupplyChainProductArchive / JSReportReplica.rpt.jst_inventoryInfo | replaceSku(反查时为 sku)及目标货号全部编码 | 编码匹配优先;货号匹配时选择目标货号下限定仓库公有可用库存最多的编码 |
|
||||
| AR | 替换类型 | pm_replacementManage | replaceType | 直取 |
|
||||
| AS | 是否换图 | pm_replacementManage | isSwapping | 直取 |
|
||||
| AT | 修改点 | pm_replacementManage | differentPoints | 直取 |
|
||||
| AU | 替换款库存 | jst_inventoryInfo_view 口径 | 公有可用数 | 按示例公式汇总目标货号全部编码;目标缺档时仅保留已知目标编码库存 |
|
||||
| AV | 正常大货仓 | jst_inventoryInfo_view 口径 | 公有可用数 | 目标货号全部编码,仓库属性=成品发货仓-真实库存公有可用数合计 |
|
||||
| AW | 前置仓 | jst_inventoryInfo_view 口径 | 公有可用数 | 目标货号全部编码,三方-南昌樵舍仓公有可用数合计 |
|
||||
| AX | 商品标签-替换款条码 | SupplyChainProductArchive | 商品标签 | 直取 |
|
||||
| AY | 缺货数量 | 本明细 | M 数量 | 分类以“缺货-”开头时取 M 数量,否则 0 |
|
||||
| AZ | 替换款状态 | SupplyChainProductArchive | 全目标货号商品状态 | 按 AA 口径聚合替换货号;无 PM 替换款时取换货货号 |
|
||||
| BA | 是否可替换 | / | / | 设置人工配置页面,依据人工配置的是否替换页面获取 |
|
||||
| BB | 替换款清货剩余库存 | plm_productDiscontinuation | remainingStock / state | 按替换目标货号汇总;无替换款时按换货货号;状态同 AB |
|
||||
| BC | 辅助 | | | |
|
||||
| BD | 是否已解决 | | | |
|
||||
|
||||
## 分类与处理关系(来自“逻辑总结”)
|
||||
|
||||
此表为用户确认的处理建议与部门来源。分类实现遵循“逻辑总结”的优先级;重复或未定义条件按上方待确认项保留核实。
|
||||
|
||||
| 缺货分类 | 处理建议 | 处理部门 |
|
||||
| --- | --- | --- |
|
||||
| 异常订单-退款关闭 | 核实并处理异常 | 如懿 |
|
||||
| 异常订单-信誉订单 | 核实并处理异常 | 如懿 |
|
||||
| 异常订单-特殊或组合商品,待拆解 | 核实并处理异常 | 如懿 |
|
||||
| 停产无库存-无相同款或相似款库存 | 跟进下架/转聚水潭异常订单,建议劝退 | 如懿/客服 |
|
||||
| 停产无库存-前置仓或有库存但不发特殊标签订单 | 转聚水潭异常订单,建议劝退 | 如懿/客服 |
|
||||
| 停产无库存-前置仓或有库存但不发特殊标签订单,有相似款或相同款但需换图或不确定是否换图 | 建议劝退或沟通买家换货 | 客服 |
|
||||
| 停产无库存-有相同款库存且不换图且能补齐缺货 | 维护自定义换货规则并重刷缺货订单 | 如懿 |
|
||||
| 停产无库存-有相同款库存且无需换图但不能补齐缺货 | 维护自定义换货规则并重刷缺货订单,其他转聚水潭异常订单,建议劝退 | 如懿 |
|
||||
| 停产无库存-有相似款库存或有相同款库存但需换图或不确定是否换图但能补齐缺货 | 沟通买家换货,或劝退 | 客服 |
|
||||
| 停产无库存-有相似款或相同款库存但需换图或不确定是否换图但不能补齐缺货 | 沟通买家换货,或劝退 | 客服 |
|
||||
| 停产无库存-原编码含前置仓库存可补齐缺货 | 核实有库存未锁定原因并处理异常 | 如懿 |
|
||||
| 停产无库存-含换货编码含前置仓库存可补齐缺货 | 核实有库存未锁定原因并处理异常 | 如懿 |
|
||||
| 缺货-无相同款或相似款库存 | 采购反馈交期/根据采购交期设置预售 | 采购/运营 |
|
||||
| 缺货-前置仓或有库存但不发特殊标签订单 | 采购反馈交期/根据采购交期设置预售 | 采购/运营 |
|
||||
| 缺货-有相同款库存且无需换图且能补齐缺货 | 维护自定义换货规则并重刷缺货订单 | 如懿 |
|
||||
| 缺货-有相似款或有相同款库存但需换图或不确定是否换图但能补齐缺货 | 采购反馈交期/根据采购交期设置预售/沟通买家换货或等待 | 采购/运营/客服 |
|
||||
| 非真实缺货-原商品编码大货仓有库存且能补齐缺货 | 核实有库存未锁定原因并处理异常 | 如懿 |
|
||||
| 缺货-含换货编码大货仓有库存且能补齐缺货 | 采购反馈交期/根据采购交期设置预售/核实有库存未锁定原因并处理异常 | 采购/运营/如懿 |
|
||||
| 缺货-原商品编码含前置仓库存能补齐缺货 | 核实有库存未锁定原因并处理异常 | 如懿 |
|
||||
| 缺货-含换货编码含前置仓库存能补齐缺货 | 核实有库存未锁定原因并处理异常 | 如懿 |
|
||||
| 缺货-含相同款且不换图库存能补齐缺货 | 维护自定义换货规则并重刷缺货订单 | 如懿 |
|
||||
| 缺货-含前置仓含相同款且不换图库存能补齐缺货 | 核实有库存未锁定原因并处理异常 | 如懿 |
|
||||
| 缺货-原商品编码大货仓有库存但无法补齐缺货 | 采购反馈交期/根据采购交期设置预售/核实有库存未锁定原因并处理异常 | 采购/运营/如懿 |
|
||||
| 缺货-原商品编码前置仓有库存但无法补齐缺货 | 采购反馈交期/根据采购交期设置预售/核实有库存未锁定原因并处理异常 | 采购/运营/如懿 |
|
||||
| 缺货-含换货编码大货仓有库存但无法补齐缺货 | 采购反馈交期/根据采购交期设置预售/核实有库存未锁定原因并处理异常 | 采购/运营/如懿 |
|
||||
| 缺货-含换货编码前置仓有库存但无法补齐缺货 | 采购反馈交期/根据采购交期设置预售/核实有库存未锁定原因并处理异常 | 采购/运营/如懿 |
|
||||
| 缺货-有相似款或有相同款库存但需换图或不确定是否换图但不能补齐缺货 | 采购反馈交期/根据采购交期设置预售/沟通买家换货或等待 | 采购/运营/客服 |
|
||||
| 缺货-京喜双仓缺货 | 采购反馈交期/根据采购交期设置预售 | 采购/运营 |
|
||||
| 异常订单-待核实处理 | 异常订单-待核实处理 | 如懿 |
|
||||
| 停产无库存-有替换款在售但暂无库存 | 维护自定义换货规则并重刷缺货订单 | 如懿 |
|
||||
@ -0,0 +1,36 @@
|
||||
CREATE TABLE "ShortageReportSnapshot" (
|
||||
"generatedOn" DATE NOT NULL,
|
||||
"generatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"sourceFetchedAt" TIMESTAMP(3) NOT NULL,
|
||||
CONSTRAINT "ShortageReportSnapshot_pkey" PRIMARY KEY ("generatedOn")
|
||||
);
|
||||
|
||||
CREATE TABLE "ShortageReportEntry" (
|
||||
"id" TEXT NOT NULL,
|
||||
"generatedOn" DATE NOT NULL,
|
||||
"sku" TEXT NOT NULL,
|
||||
"barcode" TEXT NOT NULL,
|
||||
"productName" TEXT,
|
||||
"skuProductionStatus" TEXT,
|
||||
"productionStatus" TEXT,
|
||||
"supplier" TEXT,
|
||||
"purchaser" TEXT,
|
||||
"shortageQuantity" DOUBLE PRECISION,
|
||||
"stock" DOUBLE PRECISION,
|
||||
"realShortage" DOUBLE PRECISION,
|
||||
"replacementSku" TEXT,
|
||||
"replacementStock" DOUBLE PRECISION,
|
||||
"expectedArrival" TEXT,
|
||||
"notes" TEXT,
|
||||
"replacementTransit" DOUBLE PRECISION,
|
||||
"version" INTEGER NOT NULL DEFAULT 0,
|
||||
"updatedById" TEXT,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "ShortageReportEntry_pkey" PRIMARY KEY ("id"),
|
||||
CONSTRAINT "ShortageReportEntry_version_check" CHECK ("version" >= 0),
|
||||
CONSTRAINT "ShortageReportEntry_transit_check" CHECK ("replacementTransit" IS NULL OR ("replacementTransit" >= 0 AND "replacementTransit" <= 1000000000 AND "replacementTransit" = floor("replacementTransit")))
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX "ShortageReportEntry_generatedOn_barcode_key" ON "ShortageReportEntry"("generatedOn", "barcode");
|
||||
CREATE INDEX "ShortageReportEntry_sku_idx" ON "ShortageReportEntry"("sku");
|
||||
ALTER TABLE "ShortageReportEntry" ADD CONSTRAINT "ShortageReportEntry_generatedOn_fkey" FOREIGN KEY ("generatedOn") REFERENCES "ShortageReportSnapshot"("generatedOn") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@ -0,0 +1,8 @@
|
||||
CREATE TABLE "ShortageOrderDailySnapshot" (
|
||||
"generatedOn" DATE NOT NULL,
|
||||
"generatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"sourceFetchedAt" TIMESTAMP(3) NOT NULL,
|
||||
"rows" JSONB NOT NULL,
|
||||
CONSTRAINT "ShortageOrderDailySnapshot_pkey" PRIMARY KEY ("generatedOn"),
|
||||
CONSTRAINT "ShortageOrderDailySnapshot_rows_check" CHECK (jsonb_typeof("rows") = 'array')
|
||||
);
|
||||
@ -9,6 +9,50 @@ datasource db {
|
||||
provider = "postgresql"
|
||||
}
|
||||
|
||||
/// 每日09:00全量计算的订单明细;日内固定,页面只读取最新成功快照。
|
||||
model ShortageOrderDailySnapshot {
|
||||
generatedOn DateTime @id @db.Date
|
||||
generatedAt DateTime @default(now())
|
||||
sourceFetchedAt DateTime
|
||||
rows Json
|
||||
}
|
||||
|
||||
/// 每日缺货报表:只在完整源读取成功后发布,当日生成结果固定不覆盖。
|
||||
model ShortageReportSnapshot {
|
||||
generatedOn DateTime @id @db.Date
|
||||
generatedAt DateTime @default(now())
|
||||
sourceFetchedAt DateTime
|
||||
rows ShortageReportEntry[]
|
||||
}
|
||||
|
||||
/// 按生成日期与商品编码唯一;人工反馈独立于冻结的计算字段。
|
||||
model ShortageReportEntry {
|
||||
id String @id
|
||||
generatedOn DateTime @db.Date
|
||||
snapshot ShortageReportSnapshot @relation(fields: [generatedOn], references: [generatedOn], onDelete: Cascade)
|
||||
sku String
|
||||
barcode String
|
||||
productName String?
|
||||
skuProductionStatus String?
|
||||
productionStatus String?
|
||||
supplier String?
|
||||
purchaser String?
|
||||
shortageQuantity Float?
|
||||
stock Float?
|
||||
realShortage Float?
|
||||
replacementSku String?
|
||||
replacementStock Float?
|
||||
expectedArrival String?
|
||||
notes String? @db.Text
|
||||
replacementTransit Float?
|
||||
version Int @default(0)
|
||||
updatedById String?
|
||||
updatedAt DateTime @default(now()) @updatedAt
|
||||
|
||||
@@unique([generatedOn, barcode])
|
||||
@@index([sku])
|
||||
}
|
||||
|
||||
model SampleProgressItem {
|
||||
id String @id @default(cuid())
|
||||
orderDate DateTime @db.Date
|
||||
|
||||
@ -0,0 +1,15 @@
|
||||
/** 每天北京时间08:50下载并校验聚水潭文件;09:00任务独立计算快照。 */
|
||||
import { loadEnvConfig } from '@next/env'
|
||||
loadEnvConfig(process.cwd())
|
||||
|
||||
async function main() {
|
||||
if (process.argv.length > 2) throw new Error('No arguments are supported')
|
||||
const { supplyChainShortageWebSourceService } = await import('@/server/services/supply-chain-shortage-web-source.service')
|
||||
try {
|
||||
console.log(JSON.stringify({ download: await supplyChainShortageWebSourceService.prepareDailyDownload() }))
|
||||
} finally { await supplyChainShortageWebSourceService.close() }
|
||||
}
|
||||
void main().catch(error => {
|
||||
console.error('[shortage-download]', error instanceof Error ? error.message : '下载失败;未发布完成标记')
|
||||
process.exitCode = 1
|
||||
})
|
||||
@ -0,0 +1,33 @@
|
||||
/** 每天北京时间09:00执行;读取08:50已下载文件,冻结明细,再生成报表。 */
|
||||
import { loadEnvConfig } from '@next/env'
|
||||
loadEnvConfig(process.cwd())
|
||||
|
||||
async function main() {
|
||||
const args = process.argv.slice(2)
|
||||
if (args.some(arg => arg !== '--rebuild-today')) throw new Error('Only --rebuild-today is supported')
|
||||
const { supplyChainShortageReportService } = await import('@/server/services/supply-chain-shortage-report.service')
|
||||
const { SupplyChainShortageOrderSnapshotService } = await import('@/server/services/supply-chain-shortage-order-snapshot.service')
|
||||
const { supplyChainShortageOrderRepository, SupplyChainShortageOrderRepository } = await import('@/server/repositories/supply-chain-shortage-order.repository')
|
||||
const { closeSupplyChainArchiveReadPool } = await import('@/server/repositories/supply-chain-archive-read-pool')
|
||||
const { prisma } = await import('@/lib/prisma')
|
||||
const { supplyChainShortageWebSourceService } = await import('@/server/services/supply-chain-shortage-web-source.service')
|
||||
// 后台任务不受页面响应时间约束,冷查询允许120秒;仍只发布完整结果。
|
||||
const dailySource = new SupplyChainShortageOrderRepository(120_000)
|
||||
const preparedSource = {
|
||||
getSnapshotForReport: () => supplyChainShortageWebSourceService.getSnapshotFromPreparedFile(),
|
||||
getProgress: () => supplyChainShortageWebSourceService.getProgress(),
|
||||
}
|
||||
const dailyDetails = new SupplyChainShortageOrderSnapshotService(undefined, preparedSource, undefined, undefined, dailySource)
|
||||
try {
|
||||
const details = await dailyDetails.generateDailySnapshot()
|
||||
console.log(JSON.stringify({ details }))
|
||||
if (details.status === 'not-due') return
|
||||
if (details.status === 'busy') throw new Error('Daily detail generation is already running')
|
||||
const result = await supplyChainShortageReportService.generateDailySnapshot(args.includes('--rebuild-today'))
|
||||
if (result.status === 'busy') throw new Error('Daily report generation is already running')
|
||||
console.log(JSON.stringify({ snapshot: result }))
|
||||
} finally {
|
||||
await Promise.allSettled([prisma.$disconnect(), dailySource.close(), supplyChainShortageOrderRepository.close(), supplyChainShortageWebSourceService.close(), closeSupplyChainArchiveReadPool()])
|
||||
}
|
||||
}
|
||||
void main().catch(() => { console.error('[shortage-daily] generation failed; existing complete snapshots were preserved.'); process.exitCode = 1 })
|
||||
@ -0,0 +1,26 @@
|
||||
param(
|
||||
[string]$TaskName = 'FurnitureRuyi-ShortageReportDaily',
|
||||
[string]$DownloadTaskName = 'FurnitureRuyi-ShortageOrdersDownloadDaily'
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$appDirectory = [System.IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..'))
|
||||
$nodePath = (Get-Command node -ErrorAction Stop).Source
|
||||
$tsxPath = Join-Path $appDirectory 'node_modules/tsx/dist/cli.mjs'
|
||||
$jobPath = Join-Path $appDirectory 'scripts/generate-shortage-report-daily-snapshot.ts'
|
||||
if (!(Test-Path -LiteralPath $tsxPath) -or !(Test-Path -LiteralPath $jobPath)) { throw 'Install application dependencies first.' }
|
||||
if ((Get-TimeZone).Id -ne 'China Standard Time') { throw 'This local task requires Windows China Standard Time (Asia/Shanghai).' }
|
||||
$runnerPath = Join-Path $appDirectory 'scripts/run-shortage-daily-snapshot.ps1'
|
||||
if (!(Test-Path -LiteralPath $runnerPath)) { throw 'Daily snapshot runner is missing.' }
|
||||
$downloadRunnerPath = Join-Path $appDirectory 'scripts/run-shortage-daily-download.ps1'
|
||||
$downloadJobPath = Join-Path $appDirectory 'scripts/download-shortage-orders-daily.ts'
|
||||
if (!(Test-Path -LiteralPath $downloadRunnerPath) -or !(Test-Path -LiteralPath $downloadJobPath)) { throw 'Daily download runner is missing.' }
|
||||
$powershellPath = Join-Path $PSHOME 'powershell.exe'
|
||||
$action = New-ScheduledTaskAction -Execute $powershellPath -Argument ('-NoProfile -NonInteractive -WindowStyle Hidden -ExecutionPolicy Bypass -File "{0}"' -f $runnerPath) -WorkingDirectory $appDirectory
|
||||
$trigger = New-ScheduledTaskTrigger -Daily -At '09:00'
|
||||
$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -MultipleInstances IgnoreNew -ExecutionTimeLimit (New-TimeSpan -Hours 1) -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 15) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
|
||||
$principal = New-ScheduledTaskPrincipal -UserId ([System.Security.Principal.WindowsIdentity]::GetCurrent().Name) -LogonType Interactive -RunLevel Limited
|
||||
Register-ScheduledTask -TaskName $TaskName -Action $action -Trigger $trigger -Settings $settings -Principal $principal -Description 'At 09:00 Asia/Shanghai read the completed same-day 08:50 JST export, freeze details, then generate the shortage report. No webpage download or previous-day file fallback.' -Force | Select-Object TaskName, State
|
||||
$downloadAction = New-ScheduledTaskAction -Execute $powershellPath -Argument ('-NoProfile -NonInteractive -WindowStyle Hidden -ExecutionPolicy Bypass -File "{0}"' -f $downloadRunnerPath) -WorkingDirectory $appDirectory
|
||||
$downloadTrigger = New-ScheduledTaskTrigger -Daily -At '08:50'
|
||||
$downloadSettings = New-ScheduledTaskSettingsSet -StartWhenAvailable -MultipleInstances IgnoreNew -ExecutionTimeLimit (New-TimeSpan -Minutes 10) -RestartCount 2 -RestartInterval (New-TimeSpan -Minutes 5) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
|
||||
Register-ScheduledTask -TaskName $DownloadTaskName -Action $downloadAction -Trigger $downloadTrigger -Settings $downloadSettings -Principal $principal -Description 'At 08:50 Asia/Shanghai download and validate the JST shortage order workbook for the 09:00 snapshot. Keep replenishment orders; exclude accessory and brush orders.' -Force | Select-Object TaskName, State
|
||||
126
furniture-3d-system/scripts/jst-shortage-orders-export.mjs
Normal file
126
furniture-3d-system/scripts/jst-shortage-orders-export.mjs
Normal file
@ -0,0 +1,126 @@
|
||||
import { createRequire } from 'node:module'
|
||||
import { dirname, resolve, basename, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const appDirectory = resolve(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const require = createRequire(join(appDirectory, 'package.json'))
|
||||
require('@next/env').loadEnvConfig(appDirectory)
|
||||
const SPACE_NAME = '聚水潭缺货订单导入与每日快照'
|
||||
|
||||
/** 由 ego-browser nodejs 运行;沿用浏览器登录会话,不在代码中保存账号密码。 */
|
||||
export async function exportShortageOrders() {
|
||||
const previous = (await listTaskSpaces()).find(space => space.name === SPACE_NAME)
|
||||
if (previous && previous.ownership !== 'agent') throw new Error('聚水潭浏览器当前由人员控制,请完成浏览器操作后重试')
|
||||
const task = await taskSpace(previous?.id ?? SPACE_NAME)
|
||||
const page = (await task.pages())[0] ?? task.page('p1')
|
||||
console.log(JSON.stringify({ stage: 'browser', taskSpaceId: task.spaceId }))
|
||||
try {
|
||||
await page.goto('https://www.erp321.com/epaas', { timeout: 60000 })
|
||||
await page.waitForFunction(() => Boolean(document.querySelector('#login_id') || document.querySelector('[role=tab]')), undefined, { timeout: 45000 })
|
||||
const loginRequired = await page.evaluate(() => Boolean(document.querySelector('#login_id')?.getBoundingClientRect().width))
|
||||
if (loginRequired) {
|
||||
const loginId = process.env.SHORTAGE_JST_LOGIN_ID
|
||||
const password = process.env.SHORTAGE_JST_LOGIN_PASSWORD
|
||||
if (!loginId || !password) throw new Error('聚水潭登录已失效,请配置本地私有登录凭据或重新登录')
|
||||
await page.fill('#login_id', loginId)
|
||||
await page.fill('#password', password)
|
||||
await page.evaluate(() => {
|
||||
const agreement = document.querySelector('[class*="agreement-wrap"] input[type=checkbox]')
|
||||
if (agreement && !agreement.checked) agreement.click()
|
||||
for (const input of document.querySelectorAll('input[type=checkbox]')) {
|
||||
if (/记住密码|保持登录/.test(input.parentElement?.innerText ?? '') && !input.checked) input.click()
|
||||
}
|
||||
})
|
||||
await page.click('text="立即登录"')
|
||||
try {
|
||||
await page.waitForFunction(() => Boolean(document.querySelector('[role=tab]')) || /验证码|安全验证|拖动滑块|短信验证/.test(document.body.innerText), undefined, { timeout: 45000 })
|
||||
} catch { throw new Error('聚水潭登录未完成,请在浏览器检查登录状态') }
|
||||
const humanVerification = await page.evaluate(() => !document.querySelector('[role=tab]') && /验证码|安全验证|拖动滑块|短信验证/.test(document.body.innerText))
|
||||
if (humanVerification) { await task.handOff(); throw new Error('聚水潭需要人工验证,请完成验证后重新读取') }
|
||||
}
|
||||
// 关闭欢迎页的订购提醒,不修改任何订单。
|
||||
await page.evaluate(() => {
|
||||
for (const frame of document.querySelectorAll('iframe')) {
|
||||
try {
|
||||
const d = frame.contentDocument
|
||||
for (const dialog of d?.querySelectorAll('[role=dialog]') ?? []) {
|
||||
if (dialog.innerText.includes('订购到期或即将到期')) dialog.querySelector('button[aria-label=Close]')?.click()
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
})
|
||||
const hasOrderTab = await page.evaluate(() => [...document.querySelectorAll('[role=tab]')].some(e => e.textContent.trim() === '订单'))
|
||||
if (hasOrderTab) await page.click('loc=role:tab[name="订单"]')
|
||||
else {
|
||||
// 菜单入口由真实页面语义定位;同名的“订单”二级菜单出现后再选择。
|
||||
await page.hover('loc=css:#menuContentWrap a:has-text("订单")')
|
||||
await page.waitForSelector('div[class^="groupItem___"]:text-is("订单") >> nth=0', { state: 'visible', timeout: 30000 })
|
||||
await page.click('div[class^="groupItem___"]:text-is("订单") >> nth=0')
|
||||
}
|
||||
await page.waitForSelector('input#q_13', { state: 'visible', timeout: 45000 })
|
||||
await page.click('span.btn_4:text-is("清空")')
|
||||
await page.click('input#q_13')
|
||||
await page.click('input#q_14')
|
||||
await page.click('input#q_15')
|
||||
const validFilters = await page.evaluate(() => {
|
||||
const documents = []
|
||||
const visit = d => { documents.push(d); for (const f of d.querySelectorAll('iframe')) { try { if (f.contentDocument) visit(f.contentDocument) } catch {} } }
|
||||
visit(document)
|
||||
return documents.some(d => {
|
||||
const chosen = [...d.querySelectorAll('input[name=question_type]:checked')].map(e => e.value).sort()
|
||||
return chosen.join(',') === ['真实缺货', '缺货', '预售'].sort().join(',')
|
||||
&& d.querySelector('#status_question')?.checked
|
||||
})
|
||||
})
|
||||
if (!validFilters) throw new Error('未能设置完整的缺货异常条件,本次未导出')
|
||||
await page.click('span.btn_search:text-is("组合查询")')
|
||||
await page.click('span#ExportOrder')
|
||||
await page.waitForSelector('span.ding_db_txt:text-is("导出所有符合条件的订单")', { state: 'visible', timeout: 45000 })
|
||||
const closeHelp = await page.evaluate(() => {
|
||||
const visit = d => {
|
||||
const close = d.querySelector('#pop_close')
|
||||
if (close?.getBoundingClientRect().width) { close.click(); return true }
|
||||
for (const f of d.querySelectorAll('iframe')) { try { if (f.contentDocument && visit(f.contentDocument)) return true } catch {} }
|
||||
return false
|
||||
}
|
||||
return visit(document)
|
||||
})
|
||||
if (closeHelp) console.log(JSON.stringify({ stage: 'export-help-closed' }))
|
||||
await page.click('span.ding_db_txt:text-is("导出所有符合条件的订单")')
|
||||
await page.waitForSelector('input[name=template_dom]', { state: 'visible', timeout: 30000 })
|
||||
const template = await page.evaluate(() => {
|
||||
const visit = d => {
|
||||
const input = d.querySelector('input[name=template_dom]')
|
||||
if (input?.getBoundingClientRect().width) return input.value
|
||||
for (const f of d.querySelectorAll('iframe')) { try { const value = f.contentDocument && visit(f.contentDocument); if (value) return value } catch {} }
|
||||
return null
|
||||
}
|
||||
return visit(document)
|
||||
})
|
||||
if (template !== '缺货报表看板') throw new Error('请选择聚水潭导出模板“缺货报表看板”后重试')
|
||||
const pending = page.waitForEvent('download', { timeout: 60000 })
|
||||
await page.click('text="确定"')
|
||||
const download = await pending.catch(async error => {
|
||||
const limited = await page.evaluate(() => {
|
||||
const visit = d => {
|
||||
if (/相同的条件不要频繁导出,请5分钟后再试/.test(d.body?.innerText ?? '')) return true
|
||||
for (const f of d.querySelectorAll('iframe')) { try { if (f.contentDocument && visit(f.contentDocument)) return true } catch {} }
|
||||
return false
|
||||
}
|
||||
return visit(document)
|
||||
})
|
||||
if (limited) throw new Error('聚水潭限制相同条件频繁导出,请5分钟后再试')
|
||||
throw error
|
||||
})
|
||||
const filename = download.suggestedFilename()
|
||||
if (!/^订单.*\.xlsx$/i.test(filename) || basename(filename) !== filename) throw new Error('聚水潭导出文件名不符合订单模板')
|
||||
const date = new Date().toLocaleDateString('sv-SE', { timeZone: 'Asia/Shanghai' })
|
||||
const output = join(appDirectory, '.codex-runtime', 'jst-shortage-exports', date, filename)
|
||||
await download.saveAs(output)
|
||||
console.log(`JST_SHORTAGE_EXPORT_RESULT=${JSON.stringify({ filename, path: output, exportedAt: new Date().toISOString(), ownsTaskSpace: !previous, taskSpaceId: task.spaceId })}`)
|
||||
} catch (error) {
|
||||
// 验证码或浏览器被人员接管时保留现场,由当前用户继续处理。
|
||||
console.error(JSON.stringify({ failed: true, message: error instanceof Error ? error.message : '聚水潭网页导出失败', taskSpaceId: task.spaceId }))
|
||||
throw error
|
||||
}
|
||||
}
|
||||
10
furniture-3d-system/scripts/run-shortage-daily-download.ps1
Normal file
10
furniture-3d-system/scripts/run-shortage-daily-download.ps1
Normal file
@ -0,0 +1,10 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$appDirectory = [System.IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..'))
|
||||
Set-Location -LiteralPath $appDirectory
|
||||
$logDirectory = Join-Path $appDirectory '.codex-logs'
|
||||
New-Item -ItemType Directory -Path $logDirectory -Force | Out-Null
|
||||
$logPrefix = Join-Path $logDirectory ('shortage-download-' + (Get-Date -Format 'yyyyMMdd-HHmmss-fff'))
|
||||
$nodePath = (Get-Command node -ErrorAction Stop).Source
|
||||
$arguments = '"{0}" "{1}"' -f (Join-Path $appDirectory 'node_modules/tsx/dist/cli.mjs'), (Join-Path $appDirectory 'scripts/download-shortage-orders-daily.ts')
|
||||
$job = Start-Process -FilePath $nodePath -ArgumentList $arguments -WorkingDirectory $appDirectory -WindowStyle Hidden -Wait -PassThru -RedirectStandardOutput ($logPrefix + '.out.log') -RedirectStandardError ($logPrefix + '.err.log')
|
||||
exit $job.ExitCode
|
||||
10
furniture-3d-system/scripts/run-shortage-daily-snapshot.ps1
Normal file
10
furniture-3d-system/scripts/run-shortage-daily-snapshot.ps1
Normal file
@ -0,0 +1,10 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$appDirectory = [System.IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..'))
|
||||
Set-Location -LiteralPath $appDirectory
|
||||
$logDirectory = Join-Path $appDirectory '.codex-logs'
|
||||
New-Item -ItemType Directory -Path $logDirectory -Force | Out-Null
|
||||
$logPrefix = Join-Path $logDirectory ('shortage-daily-' + (Get-Date -Format 'yyyyMMdd-HHmmss-fff'))
|
||||
$nodePath = (Get-Command node -ErrorAction Stop).Source
|
||||
$arguments = '"{0}" "{1}"' -f (Join-Path $appDirectory 'node_modules/tsx/dist/cli.mjs'), (Join-Path $appDirectory 'scripts/generate-shortage-report-daily-snapshot.ts')
|
||||
$job = Start-Process -FilePath $nodePath -ArgumentList $arguments -WorkingDirectory $appDirectory -WindowStyle Hidden -Wait -PassThru -RedirectStandardOutput ($logPrefix + '.out.log') -RedirectStandardError ($logPrefix + '.err.log')
|
||||
exit $job.ExitCode
|
||||
@ -0,0 +1,43 @@
|
||||
/** @jest-environment node */
|
||||
import type { NextRequest } from 'next/server'
|
||||
import { POST } from './route'
|
||||
import { supplyChainShortageOrderSnapshotService } from '@/server/services/supply-chain-shortage-order-snapshot.service'
|
||||
import { handleRequest } from '@/server/core/response'
|
||||
|
||||
jest.mock('@/server/services/supply-chain-shortage-order-snapshot.service', () => ({
|
||||
supplyChainShortageOrderSnapshotService: { requestImport: jest.fn() },
|
||||
}))
|
||||
jest.mock('@/server/core/response', () => ({
|
||||
handleRequest: jest.fn(async (_request, handler) => handler({ user: { id: 'user' }, requestId: 'test' })),
|
||||
jsonSuccess: (data: unknown, status: number) => ({ data, status, headers: new Headers() }),
|
||||
jsonError: (_code: string, message: string, status: number) => ({ message, status }),
|
||||
}))
|
||||
|
||||
const requestFor = (form: FormData, query = '') => ({
|
||||
nextUrl: new URL(`http://localhost/api/import${query}`), headers: new Headers(), formData: async () => form,
|
||||
}) as unknown as NextRequest
|
||||
|
||||
describe('缺货网页订单导入接口', () => {
|
||||
const start = jest.mocked(supplyChainShortageOrderSnapshotService.requestImport)
|
||||
beforeEach(() => { jest.clearAllMocks(); start.mockResolvedValue({ status: 'empty', message: '', refresh: { status: 'loading' } }) })
|
||||
|
||||
it('authenticates and forwards one complete file to the permission-checked service', async () => {
|
||||
const form = new FormData()
|
||||
form.append('file', new File(['content'], '订单_不同日期.xlsx'))
|
||||
const request = requestFor(form)
|
||||
const response = await POST(request)
|
||||
expect(response.status).toBe(202)
|
||||
expect(response.headers.get('Cache-Control')).toBe('private, no-store')
|
||||
expect(start).toHaveBeenCalledWith({ id: 'user' }, Buffer.from('content'), '订单_不同日期.xlsx')
|
||||
expect(handleRequest).toHaveBeenCalledWith(request, expect.any(Function), { requireAuth: true })
|
||||
})
|
||||
|
||||
it.each(['missing', 'wrong-name', 'empty', 'duplicate', 'extra-field', 'query'])('rejects %s before starting import', async kind => {
|
||||
const form = new FormData()
|
||||
if (kind !== 'missing') form.append('file', new File([kind === 'empty' ? '' : 'content'], kind === 'wrong-name' ? '其他.xlsx' : '订单.xlsx'))
|
||||
if (kind === 'duplicate') form.append('file', new File(['content'], '订单2.xlsx'))
|
||||
if (kind === 'extra-field') form.append('date', '2026-11-20')
|
||||
expect((await POST(requestFor(form, kind === 'query' ? '?date=2026-11-20' : ''))).status).toBe(400)
|
||||
expect(start).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@ -0,0 +1,23 @@
|
||||
import { NextRequest } from 'next/server'
|
||||
import { ErrorCode } from '@/server/core/errors'
|
||||
import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response'
|
||||
import { supplyChainShortageOrderSnapshotService } from '@/server/services/supply-chain-shortage-order-snapshot.service'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
export const runtime = 'nodejs'
|
||||
|
||||
/** 导入完整网页导出文件;后台计算成功后原子替换当日明细与报表。 */
|
||||
export async function POST(request: NextRequest) {
|
||||
return handleRequest(request, async ctx => {
|
||||
if (request.nextUrl.search || Number(request.headers.get('content-length') ?? 0) > 21 * 1024 * 1024) return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '导入请求不正确或文件过大', 400, ctx.requestId)
|
||||
const form = await request.formData().catch(() => null)
|
||||
const file = form?.get('file')
|
||||
if (!(file instanceof File) || !/^订单.*\.xlsx$/i.test(file.name) || !file.size || file.size > 20 * 1024 * 1024 || [...form!.keys()].some(key => key !== 'file') || form!.getAll('file').length !== 1) {
|
||||
return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '请选择小于20MB、文件名以“订单”开头的xlsx订单文件', 400, ctx.requestId)
|
||||
}
|
||||
const state = await supplyChainShortageOrderSnapshotService.requestImport(ctx.user, Buffer.from(await file.arrayBuffer()), file.name)
|
||||
const response = jsonSuccess(state, 202, ctx.requestId)
|
||||
response.headers.set('Cache-Control', 'private, no-store')
|
||||
return response
|
||||
}, { requireAuth: true })
|
||||
}
|
||||
@ -0,0 +1,31 @@
|
||||
import { NextRequest } from 'next/server'
|
||||
import { ErrorCode } from '@/server/core/errors'
|
||||
import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response'
|
||||
import { supplyChainShortageReportService } from '@/server/services/supply-chain-shortage-report.service'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
return handleRequest(request, async ctx => {
|
||||
const params = request.nextUrl.searchParams
|
||||
if ([...params.keys()].some(key => key !== 'retry') || (params.has('retry') && !['0', '1'].includes(params.get('retry')!))) {
|
||||
return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '读取参数不正确', 400, ctx.requestId)
|
||||
}
|
||||
const state = await supplyChainShortageReportService.getReadState(ctx.user, params.get('retry') === '1')
|
||||
const response = jsonSuccess(state, state.status === 'loading' ? 202 : 200, ctx.requestId)
|
||||
response.headers.set('Cache-Control', 'private, no-store')
|
||||
return response
|
||||
}, { requireAuth: true })
|
||||
}
|
||||
|
||||
export async function PATCH(request: NextRequest) {
|
||||
return handleRequest(request, async ctx => {
|
||||
let body: unknown
|
||||
try { body = await request.json() }
|
||||
catch { return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '填报内容必须为JSON', 400, ctx.requestId) }
|
||||
const row = await supplyChainShortageReportService.updateManual(ctx.user, body)
|
||||
const response = jsonSuccess(row, 200, ctx.requestId)
|
||||
response.headers.set('Cache-Control', 'private, no-store')
|
||||
return response
|
||||
}, { requireAuth: true })
|
||||
}
|
||||
@ -0,0 +1,60 @@
|
||||
/** @jest-environment node */
|
||||
import type { NextRequest } from 'next/server'
|
||||
import { GET, POST } from './route'
|
||||
import { supplyChainShortageOrderSnapshotService } from '@/server/services/supply-chain-shortage-order-snapshot.service'
|
||||
import { handleRequest } from '@/server/core/response'
|
||||
|
||||
jest.mock('@/server/services/supply-chain-shortage-order-snapshot.service', () => ({
|
||||
supplyChainShortageOrderSnapshotService: { getReadState: jest.fn(), requestRefresh: jest.fn() },
|
||||
}))
|
||||
jest.mock('@/server/core/response', () => ({
|
||||
handleRequest: jest.fn(async (_request, handler) => handler({ user: { id: 'user' }, requestId: 'test' })),
|
||||
jsonSuccess: (data: unknown, status: number) => ({ data, status, headers: new Headers() }),
|
||||
jsonError: (_code: string, message: string, status: number) => ({ message, status }),
|
||||
}))
|
||||
|
||||
describe('缺货明细快照只读接口', () => {
|
||||
const read = jest.mocked(supplyChainShortageOrderSnapshotService.getReadState)
|
||||
beforeEach(() => { jest.clearAllMocks(); read.mockResolvedValue({ status: 'empty', message: '09:00生成' }) })
|
||||
|
||||
it.each(['', '?refresh=0', '?refresh=1'])('only reads the saved snapshot for %s, including old force-refresh callers', async query => {
|
||||
const request = { nextUrl: new URL(`http://localhost/api/supply-chain/management/shortage-order-details${query}`) } as unknown as NextRequest
|
||||
const result = await GET(request)
|
||||
expect(read).toHaveBeenCalledWith({ id: 'user' })
|
||||
expect(read.mock.calls[0]).toHaveLength(1)
|
||||
expect(result.status).toBe(200)
|
||||
expect(result.headers.get('Cache-Control')).toBe('private, no-store')
|
||||
expect(handleRequest).toHaveBeenCalledWith(request, expect.any(Function), { requireAuth: true })
|
||||
})
|
||||
|
||||
it.each(['?refresh=bad', '?generate=1'])('rejects invalid generation-like input %s', async query => {
|
||||
const result = await GET({ nextUrl: new URL(`http://localhost/api${query}`) } as unknown as NextRequest)
|
||||
expect(result.status).toBe(400)
|
||||
expect(read).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('forwards an exact history date as a read and rejects duplicate dates', async () => {
|
||||
const request = (query: string) => ({ nextUrl: new URL(`http://localhost/api${query}`) }) as unknown as NextRequest
|
||||
expect((await GET(request('?date=2026-11-21'))).status).toBe(200)
|
||||
expect(read).toHaveBeenCalledWith({ id: 'user' }, '2026-11-21')
|
||||
read.mockClear()
|
||||
expect((await GET(request('?date=2026-11-21&date=2026-11-20'))).status).toBe(400)
|
||||
expect(read).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('starts an authenticated background refresh only through POST and returns 202 without caching', async () => {
|
||||
jest.mocked(supplyChainShortageOrderSnapshotService.requestRefresh).mockResolvedValue({ status: 'empty', message: '', refresh: { status: 'loading' } })
|
||||
const request = { nextUrl: new URL('http://localhost/api'), text: async () => '' } as unknown as NextRequest
|
||||
const result = await POST(request)
|
||||
expect(result.status).toBe(202)
|
||||
expect(result.headers.get('Cache-Control')).toBe('private, no-store')
|
||||
expect(supplyChainShortageOrderSnapshotService.requestRefresh).toHaveBeenCalledWith({ id: 'user' })
|
||||
expect(handleRequest).toHaveBeenCalledWith(request, expect.any(Function), { requireAuth: true })
|
||||
})
|
||||
|
||||
it.each([['?date=2026-11-21', ''], ['', '{"date":"2026-11-21"}']])('rejects arbitrary refresh input', async (query, body) => {
|
||||
const result = await POST({ nextUrl: new URL(`http://localhost/api${query}`), text: async () => body } as unknown as NextRequest)
|
||||
expect(result.status).toBe(400)
|
||||
expect(supplyChainShortageOrderSnapshotService.requestRefresh).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@ -0,0 +1,38 @@
|
||||
import { NextRequest } from 'next/server'
|
||||
import { ErrorCode } from '@/server/core/errors'
|
||||
import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response'
|
||||
import { supplyChainShortageOrderSnapshotService } from '@/server/services/supply-chain-shortage-order-snapshot.service'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
/** GET: 仅读取最新成功的每日快照;兼容旧 refresh 参数但不触发实时抓取。 */
|
||||
export async function GET(request: NextRequest) {
|
||||
return handleRequest(request, async ctx => {
|
||||
const params = request.nextUrl.searchParams
|
||||
if ([...params.keys()].some(key => !['refresh', 'date'].includes(key)) ||
|
||||
(params.has('date') && !/^\d{4}-\d{2}-\d{2}$/.test(params.get('date')!)) ||
|
||||
params.getAll('date').length > 1 ||
|
||||
(params.has('refresh') && !['0', '1'].includes(params.get('refresh')!))) {
|
||||
return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '读取参数不正确', 400, ctx.requestId)
|
||||
}
|
||||
const state = params.has('date')
|
||||
? await supplyChainShortageOrderSnapshotService.getReadState(ctx.user, params.get('date')!)
|
||||
: await supplyChainShortageOrderSnapshotService.getReadState(ctx.user)
|
||||
const response = jsonSuccess(state, 200, ctx.requestId)
|
||||
response.headers.set('Cache-Control', 'private, no-store')
|
||||
return response
|
||||
}, { requireAuth: true })
|
||||
}
|
||||
|
||||
/** POST: 显式手动全量更新,立即返回任务状态,由 GET 轮询完成结果。 */
|
||||
export async function POST(request: NextRequest) {
|
||||
return handleRequest(request, async ctx => {
|
||||
if (request.nextUrl.search || (await request.text()).trim()) {
|
||||
return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '更新请求无需参数或请求体', 400, ctx.requestId)
|
||||
}
|
||||
const state = await supplyChainShortageOrderSnapshotService.requestRefresh(ctx.user)
|
||||
const response = jsonSuccess(state, state.refresh?.status === 'loading' ? 202 : 200, ctx.requestId)
|
||||
response.headers.set('Cache-Control', 'private, no-store')
|
||||
return response
|
||||
}, { requireAuth: true })
|
||||
}
|
||||
@ -110,6 +110,8 @@ export const SUPPLY_CHAIN_ROUTE_TITLES: Record<string, string> = {
|
||||
'/supply-chain/purchase/daily-affairs': '日常事项',
|
||||
'/supply-chain/purchase/price-change': '产品变价',
|
||||
'/supply-chain/management/employee-hours': '员工工时统计',
|
||||
'/supply-chain/management/shortage-order-details': '缺货订单明细',
|
||||
'/supply-chain/management/shortage-order-details/report': '缺货报表',
|
||||
'/supply-chain/management/logistics-arrival-signing-duration': '物流到货签收时长看板',
|
||||
'/supply-chain/management/order-not-dispatched': '应发未发',
|
||||
'/supply-chain/management/production-stop-demands': '停产需求管理',
|
||||
|
||||
@ -1,6 +1,19 @@
|
||||
import { filterSupplyChainMenu, flattenSupplyChainMenu, SUPPLY_CHAIN_MENU } from './supply-chain-menu'
|
||||
import { getSupplyChainPermissionTargetForPath } from '@/lib/supply-chain-permission-paths'
|
||||
import { SUPPLY_CHAIN_PERMISSION_TARGET_ROUTES } from '@/lib/supply-chain-permission-targets'
|
||||
|
||||
describe('supply chain menu', () => {
|
||||
it('places shortage order details under management with a dedicated permission and route', () => {
|
||||
const route = '/supply-chain/management/shortage-order-details'
|
||||
expect(flattenSupplyChainMenu(filterSupplyChainMenu(['shortageOrderDetails']))).toEqual([
|
||||
expect.objectContaining({ label: '缺货订单明细', module: '经营管理', route }),
|
||||
])
|
||||
expect(flattenSupplyChainMenu(filterSupplyChainMenu(['managementBlankPage1', 'logisticsArrivalSigningDuration'])).some(item => item.route === route)).toBe(false)
|
||||
expect(getSupplyChainPermissionTargetForPath(route)).toBe('shortageOrderDetails')
|
||||
expect(getSupplyChainPermissionTargetForPath(`${route}/report`)).toBe('shortageOrderDetails')
|
||||
expect(getSupplyChainPermissionTargetForPath(`${route}-other`)).not.toBe('shortageOrderDetails')
|
||||
expect(SUPPLY_CHAIN_PERMISSION_TARGET_ROUTES.shortageOrderDetails).toBe(route)
|
||||
})
|
||||
it('keeps the top-level modules in the requested order', () => {
|
||||
expect(SUPPLY_CHAIN_MENU.map((module) => module.key)).toEqual([
|
||||
'dashboard',
|
||||
|
||||
@ -148,6 +148,11 @@ export const SUPPLY_CHAIN_MENU: SupplyChainMenuModule[] = [
|
||||
route: '/supply-chain/management/finished-product-strategy',
|
||||
targetKey: 'finishedProductStrategy',
|
||||
},
|
||||
{
|
||||
label: '缺货订单明细',
|
||||
route: '/supply-chain/management/shortage-order-details',
|
||||
targetKey: 'shortageOrderDetails',
|
||||
},
|
||||
{
|
||||
label: '停产下架管理',
|
||||
route: '/supply-chain/management/discontinuation',
|
||||
|
||||
@ -0,0 +1,141 @@
|
||||
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import { ShortageOrderDetailsLoader } from './ShortageOrderDetailsLoader'
|
||||
|
||||
jest.mock('./ShortageOrderDetailsView', () => ({
|
||||
ShortageOrderDetailsView: ({ rows, loading, loadError, emptyMessage, refreshMessage, generatedOn, onRefresh, onDateChange, onImport }: {
|
||||
rows: unknown[]; loading: boolean; loadError: string; emptyMessage: string; refreshMessage: string; generatedOn?: string; onRefresh?: () => void; onDateChange: (date: string) => void; onImport?: (file: File) => void
|
||||
}) => <div><span>{loading ? 'loading' : `rows:${rows.length}`}</span><span role="alert">{loadError}</span><span>{emptyMessage}</span><span>{refreshMessage}</span><span>{generatedOn}</span>{onRefresh && <button disabled={loading} onClick={onRefresh}>refresh</button>}<button onClick={() => onDateChange('2026-11-21')}>history</button>{onImport && <input aria-label="import" type="file" onChange={event => onImport(event.target.files![0])} />}</div>,
|
||||
}))
|
||||
|
||||
describe('缺货订单读取状态', () => {
|
||||
const originalFetch = global.fetch
|
||||
const fetchMock = jest.fn()
|
||||
beforeEach(() => { fetchMock.mockReset(); global.fetch = fetchMock })
|
||||
afterAll(() => { global.fetch = originalFetch })
|
||||
|
||||
it('switches to historical snapshots using GET only', async () => {
|
||||
const ready = (date: string) => ({ ok: true, json: async () => ({ success: true, data: { status: 'ready', dates: ['2026-11-24', '2026-11-21'], snapshot: { rows: [], generatedOn: date } } }) })
|
||||
fetchMock.mockResolvedValueOnce(ready('2026-11-24')).mockResolvedValueOnce(ready('2026-11-21'))
|
||||
render(<ShortageOrderDetailsLoader userId="u" canDownload canRefresh />)
|
||||
await screen.findByText('2026-11-24')
|
||||
fireEvent.click(screen.getByText('history'))
|
||||
await screen.findByText('2026-11-21')
|
||||
expect(fetchMock).toHaveBeenLastCalledWith('/api/supply-chain/management/shortage-order-details?date=2026-11-21', expect.objectContaining({ method: 'GET' }))
|
||||
expect(fetchMock.mock.calls.every(call => call[1].method === 'GET')).toBe(true)
|
||||
})
|
||||
|
||||
it('sends the selected file as multipart data and preserves the snapshot on an import error', async () => {
|
||||
fetchMock.mockResolvedValueOnce({ ok: true, json: async () => ({ success: true, data: { status: 'ready', snapshot: { rows: [{ id: 'one' }] } } }) })
|
||||
.mockResolvedValueOnce({ ok: false, json: async () => ({ success: false, error: { message: '文件格式不正确' } }) })
|
||||
render(<ShortageOrderDetailsLoader userId="u" canDownload canRefresh />)
|
||||
await screen.findByText('rows:1')
|
||||
const file = new File(['content'], '订单.xlsx')
|
||||
fireEvent.change(screen.getByLabelText('import'), { target: { files: [file] } })
|
||||
await screen.findByText('文件格式不正确')
|
||||
expect(screen.getByText('rows:1')).toBeInTheDocument()
|
||||
expect(fetchMock).toHaveBeenLastCalledWith('/api/supply-chain/management/shortage-order-details/import', expect.objectContaining({ method: 'POST', body: expect.any(FormData) }))
|
||||
expect(fetchMock.mock.calls[1][1].body.get('file')).toBe(file)
|
||||
})
|
||||
|
||||
it('reads the saved snapshot on mount and explicitly POSTs to refresh on click', async () => {
|
||||
fetchMock.mockResolvedValue({ ok: true, json: async () => ({ success: true, data: { status: 'ready', snapshot: { rows: [{ id: 'one' }], fetchedAt: '2026-11-11T01:00:00Z' } } }) })
|
||||
render(<ShortageOrderDetailsLoader userId="u" canDownload canRefresh />)
|
||||
expect(screen.getByText('loading')).toBeInTheDocument()
|
||||
await screen.findByText('rows:1')
|
||||
fireEvent.click(screen.getByText('refresh'))
|
||||
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2))
|
||||
expect(fetchMock.mock.calls[0][1].method).toBe('GET')
|
||||
expect(fetchMock).toHaveBeenLastCalledWith('/api/supply-chain/management/shortage-order-details', expect.objectContaining({ cache: 'no-store', method: 'POST' }))
|
||||
await screen.findByText('rows:1')
|
||||
})
|
||||
|
||||
it('preserves previously loaded rows when a refresh fails, then allows retry', async () => {
|
||||
fetchMock.mockResolvedValueOnce({ ok: true, json: async () => ({ success: true, data: { status: 'ready', snapshot: { rows: [{ id: 'one' }] } } }) })
|
||||
.mockResolvedValueOnce({ ok: false, json: async () => ({ success: false, error: { message: '读取失败' } }) })
|
||||
.mockResolvedValueOnce({ ok: true, json: async () => ({ success: true, data: { status: 'ready', snapshot: { rows: [{ id: 'two' }] } } }) })
|
||||
render(<ShortageOrderDetailsLoader userId="u" canDownload canRefresh />)
|
||||
await screen.findByText('rows:1')
|
||||
fireEvent.click(screen.getByText('refresh'))
|
||||
await screen.findByText('读取失败')
|
||||
expect(screen.getByText('rows:1')).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByText('refresh'))
|
||||
await screen.findByText('rows:1')
|
||||
expect(screen.getByRole('alert')).toBeEmptyDOMElement()
|
||||
})
|
||||
|
||||
it('polls only while a manual job is active, installs the new snapshot, and stops polling', async () => {
|
||||
jest.useFakeTimers()
|
||||
try {
|
||||
const ready = (date: string) => ({ ok: true, json: async () => ({ success: true, data: { status: 'ready', snapshot: { rows: [{ id: date }], generatedOn: date } } }) })
|
||||
fetchMock.mockResolvedValueOnce(ready('2026-11-21'))
|
||||
.mockResolvedValueOnce({ ok: true, json: async () => ({ success: true, data: { status: 'ready', snapshot: { rows: [], generatedOn: '2026-11-21' }, refresh: { status: 'loading', progress: { stage: 'items', completed: 2, total: 4 } } } }) })
|
||||
.mockResolvedValueOnce(ready('2026-11-24'))
|
||||
const { unmount } = render(<ShortageOrderDetailsLoader userId="u" canDownload canRefresh />)
|
||||
await act(async () => { await Promise.resolve() })
|
||||
fireEvent.click(screen.getByText('refresh'))
|
||||
await act(async () => { await Promise.resolve() })
|
||||
expect(screen.getByText('正在读取订单商品 · 50%')).toBeInTheDocument()
|
||||
expect(screen.getByText('refresh')).toBeDisabled()
|
||||
await act(async () => { await jest.advanceTimersByTimeAsync(1500) })
|
||||
expect(screen.getByText('2026-11-24')).toBeInTheDocument()
|
||||
expect(fetchMock.mock.calls.map(call => call[1].method)).toEqual(['GET', 'POST', 'GET'])
|
||||
await act(async () => { await jest.advanceTimersByTimeAsync(60_000) })
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3)
|
||||
unmount()
|
||||
} finally { jest.useRealTimers() }
|
||||
})
|
||||
|
||||
it('continues an already running job after a page reload without POSTing again', async () => {
|
||||
jest.useFakeTimers()
|
||||
try {
|
||||
fetchMock.mockResolvedValue({ ok: true, json: async () => ({ success: true, data: { status: 'empty', message: '', refresh: { status: 'loading' } } }) })
|
||||
const { unmount } = render(<ShortageOrderDetailsLoader userId="u" canDownload />)
|
||||
await act(async () => { await Promise.resolve() })
|
||||
await act(async () => { await jest.advanceTimersByTimeAsync(1500) })
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2)
|
||||
expect(fetchMock.mock.calls.every(call => call[1].method === 'GET')).toBe(true)
|
||||
unmount()
|
||||
await act(async () => { await jest.advanceTimersByTimeAsync(6000) })
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2)
|
||||
} finally { jest.useRealTimers() }
|
||||
})
|
||||
|
||||
it('hides the refresh action from accounts without edit access', async () => {
|
||||
fetchMock.mockResolvedValue({ ok: true, json: async () => ({ success: true, data: { status: 'empty', message: '请管理员生成快照' } }) })
|
||||
render(<ShortageOrderDetailsLoader userId="u" canDownload />)
|
||||
await screen.findByText('rows:0')
|
||||
expect(screen.queryByText('refresh')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('aborts an in-flight request when leaving the page', () => {
|
||||
fetchMock.mockReturnValue(new Promise(() => {}))
|
||||
const { unmount } = render(<ShortageOrderDetailsLoader userId="u" canDownload />)
|
||||
const signal = fetchMock.mock.calls[0][1].signal as AbortSignal
|
||||
expect(signal.aborted).toBe(false)
|
||||
unmount()
|
||||
expect(signal.aborted).toBe(true)
|
||||
})
|
||||
|
||||
it('keeps displayed data fixed without background polling, including across the next 09:00', async () => {
|
||||
jest.useFakeTimers()
|
||||
try {
|
||||
fetchMock.mockResolvedValue({ ok: true, json: async () => ({ success: true, data: { status: 'ready', snapshot: { rows: [{ id: 'one' }], generatedOn: '2026-11-20' } } }) })
|
||||
const { unmount } = render(<ShortageOrderDetailsLoader userId="u" canDownload />)
|
||||
await act(async () => { await Promise.resolve() })
|
||||
expect(screen.getByText('rows:1')).toBeInTheDocument()
|
||||
expect(screen.getByText('2026-11-20')).toBeInTheDocument()
|
||||
await act(async () => { await jest.advanceTimersByTimeAsync(86_400_000) })
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
unmount()
|
||||
} finally { jest.useRealTimers() }
|
||||
})
|
||||
|
||||
it('shows the ungenerated state without errors or polling', async () => {
|
||||
fetchMock.mockResolvedValueOnce({ ok: true, json: async () => ({ success: true, data: { status: 'empty', message: '尚未生成明细快照,每天北京时间09:00生成。' } }) })
|
||||
render(<ShortageOrderDetailsLoader userId="u" canDownload />)
|
||||
await screen.findByText('尚未生成明细快照,每天北京时间09:00生成。')
|
||||
expect(screen.getByText('rows:0')).toBeInTheDocument()
|
||||
expect(screen.getByRole('alert')).toBeEmptyDOMElement()
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@ -0,0 +1,68 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import type { ShortageOrderDailySnapshot, ShortageOrderDailyReadState } from '@/lib/supply-chain-shortage-orders'
|
||||
import { ShortageOrderDetailsView } from './ShortageOrderDetailsView'
|
||||
|
||||
export function ShortageOrderDetailsLoader({ userId, canDownload, canRefresh = false }: { userId: string; canDownload: boolean; canRefresh?: boolean }) {
|
||||
const [snapshot, setSnapshot] = useState<ShortageOrderDailySnapshot | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState('')
|
||||
const [action, setAction] = useState<{ kind: 'read' | 'refresh' | 'import'; sequence: number; file?: File }>({ kind: 'read', sequence: 0 })
|
||||
const [selectedDate, setSelectedDate] = useState('')
|
||||
const [dates, setDates] = useState<string[]>([])
|
||||
const [emptyMessage, setEmptyMessage] = useState('')
|
||||
const [refreshMessage, setRefreshMessage] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController()
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
setLoading(true)
|
||||
setError('')
|
||||
setRefreshMessage('')
|
||||
const read = async (startRefresh = false) => {
|
||||
try {
|
||||
const importing = startRefresh && action.kind === 'import'
|
||||
const form = importing ? new FormData() : undefined
|
||||
if (form && action.file) form.append('file', action.file)
|
||||
const response = await fetch(`/api/supply-chain/management/shortage-order-details${importing ? '/import' : !startRefresh && selectedDate ? `?date=${selectedDate}` : ''}`, {
|
||||
method: startRefresh ? 'POST' : 'GET', cache: 'no-store', signal: controller.signal,
|
||||
...(form ? { body: form } : {}),
|
||||
})
|
||||
const result = await response.json()
|
||||
if (!response.ok || !result.success) throw new Error(result.error?.message || '明细快照读取失败')
|
||||
if (controller.signal.aborted) return
|
||||
const state: ShortageOrderDailyReadState = result.data
|
||||
if (state.dates) setDates(state.dates)
|
||||
if (state.status === 'ready') { setSnapshot(state.snapshot); setEmptyMessage('') }
|
||||
else if (state.status === 'empty') { setSnapshot(null); setEmptyMessage(state.message) }
|
||||
else throw new Error('明细快照返回格式不正确,请重新读取。')
|
||||
if (state.refresh?.status === 'loading') {
|
||||
const progress = state.refresh.progress
|
||||
const stage = progress?.stage === 'download' ? '正在从聚水潭导出订单' : progress?.stage === 'import' ? '正在导入订单文件' : progress?.stage === 'orders' ? '正在读取订单' : progress?.stage === 'items' ? '正在读取订单商品' : progress ? '正在更新库存与替换信息' : '正在生成明细与报表'
|
||||
setRefreshMessage(`${stage}${progress && progress.total > 0 ? ` · ${Math.floor(progress.completed / progress.total * 100)}%` : '…'}`)
|
||||
timer = setTimeout(() => void read(), 1500)
|
||||
return
|
||||
}
|
||||
setRefreshMessage('')
|
||||
setError(state.refresh?.status === 'error' ? state.refresh.message : '')
|
||||
setLoading(false)
|
||||
} catch (cause) {
|
||||
if (!controller.signal.aborted) {
|
||||
setError(cause instanceof Error ? cause.message : '明细快照读取失败,请重试。')
|
||||
setRefreshMessage('')
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
void read(action.kind !== 'read')
|
||||
return () => { controller.abort(); clearTimeout(timer) }
|
||||
}, [action, selectedDate])
|
||||
|
||||
return <ShortageOrderDetailsView userId={userId} canDownload={canDownload}
|
||||
rows={snapshot?.rows ?? []} loading={loading} loadError={error} emptyMessage={emptyMessage} refreshMessage={refreshMessage}
|
||||
generatedOn={snapshot?.generatedOn} generatedAt={snapshot?.generatedAt} fetchedAt={snapshot?.fetchedAt}
|
||||
dates={dates} selectedDate={selectedDate} onDateChange={date => { setSelectedDate(date); setAction(value => ({ kind: 'read', sequence: value.sequence + 1 })) }}
|
||||
onRefresh={canRefresh ? () => { setSelectedDate(''); setAction(value => ({ kind: 'refresh', sequence: value.sequence + 1 })) } : undefined}
|
||||
onImport={canRefresh ? file => { setSelectedDate(''); setAction(value => ({ kind: 'import', sequence: value.sequence + 1, file })) } : undefined} />
|
||||
}
|
||||
@ -0,0 +1,100 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { Columns3, Download, RefreshCw, RotateCcw, Search, Upload } from 'lucide-react'
|
||||
import { PlatformSection } from '@/components/platform/PlatformSection'
|
||||
import { WorkbenchTabStrip } from '@/components/platform/WorkbenchTabStrip'
|
||||
import Button from '@/components/ui/Button'
|
||||
import { applySkuQuantityTotals } from '@/lib/supply-chain-shortage-rules'
|
||||
import { ShortageOrderFilter } from './ShortageOrderFilter'
|
||||
import { ShortageColumnSettings } from './ShortageColumnSettings'
|
||||
import { ShortageDataTable } from './ShortageDataTable'
|
||||
import { shortageCellValue } from './shortage-cell-value'
|
||||
import { createColumnSettings, filterShortageRows, restoreDetailColumns, SHORTAGE_FILTERS, SHORTAGE_ORDER_FIELDS, SHORTAGE_VIEWS, type ColumnSetting, type ShortageFilters, type ShortageRow } from './shortage-order-fields'
|
||||
import styles from './shortage-order-details.module.css'
|
||||
|
||||
export function ShortageOrderDetailsView({ userId, canDownload, rows, loading = false, loadError = '', emptyMessage = '', refreshMessage = '', generatedOn, generatedAt, fetchedAt, onRefresh, onImport, dates = [], selectedDate = '', onDateChange }: {
|
||||
userId: string; canDownload: boolean; rows: readonly ShortageRow[]
|
||||
loading?: boolean; loadError?: string; emptyMessage?: string; refreshMessage?: string; generatedOn?: string; generatedAt?: string; fetchedAt?: string; onRefresh?: () => void
|
||||
onImport?: (file: File) => void; dates?: string[]; selectedDate?: string; onDateChange?: (date: string) => void
|
||||
}) {
|
||||
const [draft, setDraft] = useState<ShortageFilters>({})
|
||||
const [filters, setFilters] = useState<ShortageFilters>({})
|
||||
const [viewKey, setViewKey] = useState('all')
|
||||
const [columns, setColumns] = useState<ColumnSetting[]>(createColumnSettings)
|
||||
const [settingsOpen, setSettingsOpen] = useState(false)
|
||||
const [storageReady, setStorageReady] = useState(false)
|
||||
const [notice, setNotice] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [exporting, setExporting] = useState(false)
|
||||
const fileInput = useRef<HTMLInputElement>(null)
|
||||
const storageKey = `supply-chain:shortage-orders:columns:v1:${userId}`
|
||||
|
||||
useEffect(() => {
|
||||
try {
|
||||
const raw = localStorage.getItem(storageKey)
|
||||
if (raw) {
|
||||
setColumns(restoreDetailColumns(JSON.parse(raw)))
|
||||
}
|
||||
} catch { setNotice('无法读取列设置,已使用默认视图。') }
|
||||
setStorageReady(true)
|
||||
}, [storageKey])
|
||||
|
||||
useEffect(() => {
|
||||
if (!storageReady) return
|
||||
try { localStorage.setItem(storageKey, JSON.stringify({ viewKey, columns })) }
|
||||
catch { setNotice('浏览器未允许保存列设置,本次调整仍然有效。') }
|
||||
}, [columns, storageKey, storageReady, viewKey])
|
||||
|
||||
const normalizedRows = useMemo(() => applySkuQuantityTotals(rows).map(row => ({ ...row,
|
||||
preparedAt: generatedAt ? new Date(generatedAt).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false }) : null,
|
||||
})), [rows, generatedAt])
|
||||
const filtered = useMemo(() => filterShortageRows(normalizedRows, filters), [normalizedRows, filters])
|
||||
const visibleColumns = columns.filter(column => column.visible)
|
||||
const filterCount = Object.values(filters).filter(values => values?.length).length
|
||||
const facets = useMemo(() => Object.fromEntries(SHORTAGE_FILTERS.map(({ key }) => [key, [...new Set(rows.flatMap(row => {
|
||||
const value = String(row[key] ?? '').trim()
|
||||
return value ? key === 'department' ? value.split(/[\/、]/) : [value] : []
|
||||
}))].sort((a, b) => a.localeCompare(b, 'zh-CN'))])), [rows])
|
||||
|
||||
function switchView(key: string) {
|
||||
setViewKey(key)
|
||||
setColumns(createColumnSettings(key))
|
||||
}
|
||||
function resetFilters() { setDraft({}); setFilters({}) }
|
||||
async function exportRows() {
|
||||
if (!canDownload || exporting || loading || loadError) return
|
||||
setExporting(true)
|
||||
setError('')
|
||||
try {
|
||||
const XLSX = await import('xlsx')
|
||||
const exportFields = visibleColumns.map(column => SHORTAGE_ORDER_FIELDS.find(field => field.key === column.key)!)
|
||||
const header = exportFields.map(field => field.label)
|
||||
const sheet = XLSX.utils.aoa_to_sheet([header, ...filtered.map(row => exportFields.map(field => shortageCellValue(field, row[field.key])))])
|
||||
sheet['!cols'] = visibleColumns.map(column => ({ wch: Math.round(column.width / 9) }))
|
||||
const workbook = XLSX.utils.book_new()
|
||||
XLSX.utils.book_append_sheet(workbook, sheet, '缺货订单明细')
|
||||
XLSX.writeFile(workbook, `缺货订单明细-${generatedOn ?? new Date().toLocaleDateString('sv-SE', { timeZone: 'Asia/Shanghai' })}.xlsx`)
|
||||
setNotice(filtered.length ? `已导出当前筛选结果 ${filtered.length} 条。` : '当前无明细数据,已导出所选字段表头。')
|
||||
} catch { setError('导出失败,请重试。') }
|
||||
finally { setExporting(false) }
|
||||
}
|
||||
|
||||
return <main className={styles.page}>
|
||||
<header className={styles.pageHeader}><div><h1>缺货订单明细</h1><span className={styles.subtitle}>每日09:00生成,支持按制表日期查看</span></div><div className={styles.headerActions}><span className={styles.sourceStatus} role="status" title="订单基础字段来自聚水潭网页导出文件;库存与规则在制表时统一计算"><i />{loading ? refreshMessage || '正在读取快照…' : loadError ? '更新失败,保留上次完整数据' : fetchedAt ? `数据快照 · ${new Date(fetchedAt).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false })}` : '尚未生成快照'}</span>{onRefresh && <Button variant="gray" className={styles.button} disabled={loading} title="从聚水潭网页下载最新订单文件,重新计算并更新当日快照" onClick={onRefresh}><RefreshCw size={14} />{loading && refreshMessage ? '更新中…' : '网页读取'}</Button>}{onImport && <><input ref={fileInput} type="file" accept=".xlsx" hidden aria-label="选择聚水潭订单文件" onChange={event => { const file = event.target.files?.[0]; event.target.value = ''; if (file) onImport(file) }} /><Button variant="gray" className={styles.button} disabled={loading} onClick={() => fileInput.current?.click()}><Upload size={14} />导入订单</Button></>}<Button variant="gray" className={styles.button} disabled={!canDownload || exporting || loading || Boolean(loadError) || Boolean(emptyMessage)} title={canDownload ? '按筛选结果和当前显示列导出;无数据时仅导出表头' : '需要下载权限'} onClick={() => void exportRows()}><Download size={14} />{exporting ? '导出中…' : '导出'}</Button></div></header>
|
||||
|
||||
<form className={styles.filterPanel} aria-label="缺货订单筛选" onSubmit={event => { event.preventDefault(); setFilters(draft) }}>
|
||||
<div className={styles.filterGrid}>{onDateChange && <label className={styles.filter}><span className={styles.fieldLabel}>制表日期</span><select className={styles.snapshotSelect} aria-label="制表日期" value={selectedDate} disabled={loading} onChange={event => onDateChange(event.target.value)}><option value="">最新快照</option>{dates.map(date => <option key={date} value={date}>{date}</option>)}</select></label>}{SHORTAGE_FILTERS.map(field => <ShortageOrderFilter key={field.key} label={field.label} caseInsensitive={field.key === 'barcode' || field.key === 'sku'} values={draft[field.key] ?? []} options={facets[field.key] ?? []} onChange={values => setDraft(current => ({ ...current, [field.key]: values }))} />)}</div>
|
||||
<div className={styles.filterActions}><span>同字段多选匹配,不同字段组合查询</span><div><Button type="button" variant="gray" className={styles.button} onClick={resetFilters}><RotateCcw size={14} />重置</Button><Button type="submit" className={styles.button}><Search size={14} />查询</Button></div></div>
|
||||
</form>
|
||||
|
||||
{(loadError || error) && <div className={styles.error} role="alert">{loadError || error}</div>}
|
||||
{notice && <div className={styles.notice} role="status">{notice}</div>}
|
||||
<PlatformSection title="订单明细" className={styles.tableSection} contentClassName={styles.tableContent} aside={<span className={styles.resultCount}>{loading ? '正在读取…' : loadError ? '读取失败' : `共 ${filtered.length.toLocaleString('zh-CN')} 条`}{filterCount > 0 && ` · 已应用 ${filterCount} 项筛选`}</span>}>
|
||||
<div className={styles.tableToolbar}><WorkbenchTabStrip activeTabKey={viewKey} tabCount={SHORTAGE_VIEWS.length} className={styles.viewTabs} aria-label="明细视图">{SHORTAGE_VIEWS.map(view => <button type="button" key={view.key} aria-pressed={viewKey === view.key} data-workbench-tab-active={viewKey === view.key} onClick={() => switchView(view.key)}>{view.label}</button>)}</WorkbenchTabStrip><button type="button" className={styles.columnButton} onClick={() => setSettingsOpen(true)}><Columns3 size={14} />列设置<span>{visibleColumns.length}</span></button></div>
|
||||
<ShortageDataTable label="缺货订单明细表" fields={SHORTAGE_ORDER_FIELDS} columns={columns} onResize={(key, width) => setColumns(previous => previous.map(column => column.key === key ? { ...column, width } : column))} rows={filtered} scrollResetKey={viewKey}
|
||||
emptyTitle={loading ? '正在读取明细快照' : loadError ? '明细快照读取失败' : rows.length ? '没有符合条件的订单' : emptyMessage ? '尚未生成每日快照' : '本次快照无缺货订单'} emptyDescription={loading ? refreshMessage || '正在读取已保存的明细,请稍候。' : loadError ? '请点击重新读取重试。' : rows.length ? '请调整筛选条件后重新查询。' : emptyMessage || '本次快照没有符合条件的缺货、真实缺货或预售订单。'} onClearFilters={filterCount ? resetFilters : undefined} />
|
||||
</PlatformSection>
|
||||
<ShortageColumnSettings open={settingsOpen} onClose={() => setSettingsOpen(false)} fields={SHORTAGE_ORDER_FIELDS} columns={columns} onChange={setColumns} onReset={() => setColumns(createColumnSettings(viewKey))} />
|
||||
</main>
|
||||
}
|
||||
@ -0,0 +1,18 @@
|
||||
'use client'
|
||||
|
||||
import Link from 'next/link'
|
||||
import { usePathname } from 'next/navigation'
|
||||
import { WorkbenchTabStrip } from '@/components/platform/WorkbenchTabStrip'
|
||||
import styles from './shortage-order-details.module.css'
|
||||
|
||||
const pages = [
|
||||
{ href: '/supply-chain/management/shortage-order-details', label: '订单明细' },
|
||||
{ href: '/supply-chain/management/shortage-order-details/report', label: '缺货报表' },
|
||||
]
|
||||
|
||||
export function ShortageOrderSubnav() {
|
||||
const pathname = usePathname()
|
||||
return <nav className={styles.subnav} aria-label="缺货订单明细子页面"><WorkbenchTabStrip activeTabKey={pathname} tabCount={pages.length} className={styles.subnavTabs}>
|
||||
{pages.map(page => <Link key={page.href} href={page.href} aria-current={pathname === page.href ? 'page' : undefined} data-workbench-tab-active={pathname === page.href}>{page.label}</Link>)}
|
||||
</WorkbenchTabStrip></nav>
|
||||
}
|
||||
@ -0,0 +1,7 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import { ShortageOrderSubnav } from './ShortageOrderSubnav'
|
||||
import styles from './shortage-order-details.module.css'
|
||||
|
||||
export default function ShortageOrderLayout({ children }: { children: ReactNode }) {
|
||||
return <div className={styles.module}><ShortageOrderSubnav />{children}</div>
|
||||
}
|
||||
@ -0,0 +1,15 @@
|
||||
import { redirect } from 'next/navigation'
|
||||
import { requireSession } from '@/lib/server-session'
|
||||
import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service'
|
||||
import { ShortageOrderDetailsLoader } from './ShortageOrderDetailsLoader'
|
||||
|
||||
export const metadata = { title: '缺货订单明细 · 供应链中心' }
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
export default async function ShortageOrderDetailsPage() {
|
||||
const { authUser } = await requireSession('/login')
|
||||
const access = await supplyChainPermissionSettingsService.getUserAccess(authUser, 'shortageOrderDetails')
|
||||
if (!access.view) redirect('/supply-chain')
|
||||
|
||||
return <ShortageOrderDetailsLoader userId={authUser.id} canDownload={access.download} canRefresh={access.edit} />
|
||||
}
|
||||
@ -0,0 +1,34 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import Modal from '@/components/ui/Modal'
|
||||
import Button from '@/components/ui/Button'
|
||||
import type { ShortageReportManualInput, ShortageReportRow } from '@/lib/supply-chain-shortage-report'
|
||||
import styles from '../shortage-order-details.module.css'
|
||||
|
||||
export function ShortageReportEditor({ row, onClose, onSave }: {
|
||||
row: ShortageReportRow; onClose: () => void; onSave: (input: ShortageReportManualInput) => Promise<void>
|
||||
}) {
|
||||
const [arrival, setArrival] = useState(row.expectedArrival ?? '')
|
||||
const [notes, setNotes] = useState(row.notes ?? '')
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
async function save() {
|
||||
if (saving) return
|
||||
setSaving(true); setError('')
|
||||
try {
|
||||
await onSave({ id: row.id, version: row.version ?? 0, expectedArrival: arrival.trim() || null, notes: notes.trim() || null, replacementTransit: row.replacementTransit ?? null })
|
||||
onClose()
|
||||
} catch (cause) { setError(cause instanceof Error ? cause.message : '保存失败,请重试。') }
|
||||
finally { setSaving(false) }
|
||||
}
|
||||
return <Modal isOpen onClose={() => { if (!saving) onClose() }} title="报表人工填报" size="small" variant="compact" bodyClassName={styles.settingsBody}
|
||||
footer={<div className={styles.settingsFooter}><Button variant="gray" className={styles.button} disabled={saving} onClick={onClose}>取消</Button><Button type="submit" form="shortage-report-edit" className={styles.button} disabled={saving}>{saving ? '保存中…' : '保存'}</Button></div>}>
|
||||
<form id="shortage-report-edit" className={styles.reportEditForm} onSubmit={event => { event.preventDefault(); void save() }}>
|
||||
<p>{row.generatedOn} · {row.barcode}</p>
|
||||
<label>预计到货时间<input aria-label="预计到货时间" value={arrival} maxLength={120} disabled={saving} onChange={event => setArrival(event.target.value)} /></label>
|
||||
<label>缺货原因<textarea value={notes} rows={4} maxLength={2000} disabled={saving} onChange={event => setNotes(event.target.value)} /></label>
|
||||
{error && <div className={styles.error} role="alert">{error}</div>}
|
||||
</form>
|
||||
</Modal>
|
||||
}
|
||||
@ -0,0 +1,142 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { Columns3, Download, RefreshCw, RotateCcw, Search } from 'lucide-react'
|
||||
import { PlatformSection } from '@/components/platform/PlatformSection'
|
||||
import Button from '@/components/ui/Button'
|
||||
import { filterShortageReportRows, getShortageReportDateBounds, prepareShortageReportRows, SHORTAGE_REPORT_ARCHIVE_POLICY, SHORTAGE_REPORT_FILTERS, sortShortageReportRows, validateShortageReportFilters, type ShortageReportFilters, type ShortageReportRow, type ShortageReportReadState, type ShortageReportManualInput } from '@/lib/supply-chain-shortage-report'
|
||||
import { ShortageColumnSettings } from '../ShortageColumnSettings'
|
||||
import { ShortageDataTable } from '../ShortageDataTable'
|
||||
import { shortageCellValue } from '../shortage-cell-value'
|
||||
import { ShortageOrderFilter } from '../ShortageOrderFilter'
|
||||
import { createReportColumnSettings, readReportColumnSettings, SHORTAGE_REPORT_FIELDS, type ReportColumnSetting } from './shortage-report-fields'
|
||||
import { ShortageReportEditor } from './ShortageReportEditor'
|
||||
import styles from '../shortage-order-details.module.css'
|
||||
|
||||
export function ShortageReportView({ userId, canDownload, canEdit, today: initialToday }: { userId: string; canDownload: boolean; canEdit: boolean; today: string }) {
|
||||
const [rows, setRows] = useState<ShortageReportRow[]>([])
|
||||
const [today, setToday] = useState(initialToday)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [loadError, setLoadError] = useState('')
|
||||
const [loadMessage, setLoadMessage] = useState('正在读取报表…')
|
||||
const [generatedAt, setGeneratedAt] = useState<string | null>(null)
|
||||
const [revision, setRevision] = useState(0)
|
||||
const [editingRow, setEditingRow] = useState<ShortageReportRow | null>(null)
|
||||
const [draft, setDraft] = useState<ShortageReportFilters>({})
|
||||
const [filters, setFilters] = useState<ShortageReportFilters>({})
|
||||
const [columns, setColumns] = useState<ReportColumnSetting[]>(createReportColumnSettings)
|
||||
const [settingsOpen, setSettingsOpen] = useState(false)
|
||||
const [storageReady, setStorageReady] = useState(false)
|
||||
const [notice, setNotice] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [exporting, setExporting] = useState(false)
|
||||
const storageKey = `supply-chain:shortage-report:columns:v1:${userId}`
|
||||
const bounds = getShortageReportDateBounds(today)
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController()
|
||||
setLoading(true); setLoadError('')
|
||||
void (async () => {
|
||||
try {
|
||||
let retry = revision > 0
|
||||
while (!controller.signal.aborted) {
|
||||
const response = await fetch(`/api/supply-chain/management/shortage-order-details/report${retry ? '?retry=1' : ''}`, { cache: 'no-store', signal: controller.signal })
|
||||
retry = false
|
||||
const result = await response.json()
|
||||
if (!response.ok || !result.success) throw new Error(result.error?.message || '报表读取失败')
|
||||
if (controller.signal.aborted) return
|
||||
const state: ShortageReportReadState = result.data
|
||||
if (state.status === 'error') throw new Error(state.message)
|
||||
if (state.status === 'ready') { setRows(state.rows); setToday(state.today); setGeneratedAt(state.generatedAt); break }
|
||||
setLoadMessage(state.message)
|
||||
await new Promise<void>(resolve => {
|
||||
const finish = () => { clearTimeout(timer); controller.signal.removeEventListener('abort', finish); resolve() }
|
||||
const timer = setTimeout(finish, 2000)
|
||||
controller.signal.addEventListener('abort', finish, { once: true })
|
||||
})
|
||||
}
|
||||
} catch (cause) { if (!controller.signal.aborted) setLoadError(cause instanceof Error ? cause.message : '报表读取失败,请重试。') }
|
||||
finally { if (!controller.signal.aborted) setLoading(false) }
|
||||
})()
|
||||
return () => controller.abort()
|
||||
}, [revision])
|
||||
|
||||
async function saveManual(input: ShortageReportManualInput) {
|
||||
const response = await fetch('/api/supply-chain/management/shortage-order-details/report', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(input) })
|
||||
const result = await response.json()
|
||||
if (!response.ok || !result.success) throw new Error(result.error?.message || '保存失败,请重试。')
|
||||
const row: ShortageReportRow = result.data
|
||||
setRows(current => current.map(item => item.id === row.id ? row : item))
|
||||
setNotice('填报已保存。')
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
try {
|
||||
const raw = localStorage.getItem(storageKey)
|
||||
if (raw) {
|
||||
const restored = readReportColumnSettings(JSON.parse(raw))
|
||||
if (restored) setColumns(restored)
|
||||
}
|
||||
} catch { setNotice('无法读取列设置,已使用默认字段。') }
|
||||
setStorageReady(true)
|
||||
}, [storageKey])
|
||||
useEffect(() => {
|
||||
if (!storageReady) return
|
||||
try { localStorage.setItem(storageKey, JSON.stringify(columns)) }
|
||||
catch { setNotice('浏览器未允许保存列设置,本次调整仍然有效。') }
|
||||
}, [columns, storageKey, storageReady])
|
||||
|
||||
const prepared = useMemo(() => sortShortageReportRows(prepareShortageReportRows(rows, today)), [rows, today])
|
||||
const filtered = useMemo(() => filterShortageReportRows(prepared, filters), [prepared, filters])
|
||||
const visibleColumns = columns.filter(column => column.visible)
|
||||
const filterCount = SHORTAGE_REPORT_FILTERS.filter(({ key }) => filters[key]?.length).length + (filters.generatedFrom || filters.generatedTo ? 1 : 0)
|
||||
const facets = useMemo(() => Object.fromEntries(SHORTAGE_REPORT_FILTERS.map(({ key }) => [key, [...new Set(prepared.map(row => String(row[key] ?? '').trim()).filter(Boolean))].sort((a, b) => a.localeCompare(b, 'zh-CN'))])), [prepared])
|
||||
function resetFilters() { setDraft({}); setFilters({}); setError('') }
|
||||
|
||||
async function exportRows() {
|
||||
if (!canDownload || exporting || loading || loadError) return
|
||||
setExporting(true)
|
||||
setError('')
|
||||
try {
|
||||
const XLSX = await import('xlsx')
|
||||
const exportFields = visibleColumns.map(column => SHORTAGE_REPORT_FIELDS.find(field => field.key === column.key)!)
|
||||
const header = exportFields.map(field => field.label)
|
||||
const sheet = XLSX.utils.aoa_to_sheet([header, ...filtered.map(row => exportFields.map(field => shortageCellValue(field, row[field.key])))])
|
||||
sheet['!cols'] = visibleColumns.map(column => ({ wch: Math.round(column.width / 9) }))
|
||||
const workbook = XLSX.utils.book_new()
|
||||
XLSX.utils.book_append_sheet(workbook, sheet, '缺货报表')
|
||||
XLSX.writeFile(workbook, `缺货报表-${today}.xlsx`)
|
||||
setNotice(filtered.length ? `已导出当前筛选结果 ${filtered.length} 条。` : '当前无报表数据,已导出所选字段表头。')
|
||||
} catch { setError('导出失败,请重试。') }
|
||||
finally { setExporting(false) }
|
||||
}
|
||||
|
||||
return <main className={styles.page}>
|
||||
<header className={styles.pageHeader}><div><h1>缺货报表</h1><span className={styles.subtitle}>按商品编码汇总 · 每日快照</span></div><div className={styles.headerActions}><span className={styles.sourceStatus} role="status"><i />{loading ? loadMessage : loadError ? '报表读取失败' : generatedAt ? `已存档 · ${today}` : '今日09:00生成'}</span><Button variant="gray" className={styles.button} disabled={loading} onClick={() => setRevision(value => value + 1)}><RefreshCw size={14} />刷新</Button><Button variant="gray" className={styles.button} disabled={!canDownload || exporting || loading || Boolean(loadError)} title={canDownload ? '按筛选结果和当前显示列导出;无数据时仅导出表头' : '需要下载权限'} onClick={() => void exportRows()}><Download size={14} />{exporting ? '导出中…' : '导出'}</Button></div></header>
|
||||
<form className={styles.filterPanel} aria-label="缺货报表筛选" onSubmit={event => {
|
||||
event.preventDefault()
|
||||
const validation = validateShortageReportFilters(draft, today)
|
||||
setError(validation ?? '')
|
||||
if (!validation) setFilters(draft)
|
||||
}}>
|
||||
<div className={`${styles.filterGrid} ${styles.reportFilterGrid}`}>
|
||||
<div className={styles.dateFilter}><span className={styles.fieldLabel}>生成日期</span><div className={styles.dateRange}>
|
||||
<input type="date" aria-label="生成日期开始" min={bounds.min} max={bounds.max} value={draft.generatedFrom ?? ''} onChange={event => setDraft(current => ({ ...current, generatedFrom: event.target.value }))} /><span>至</span>
|
||||
<input type="date" aria-label="生成日期结束" min={bounds.min} max={bounds.max} value={draft.generatedTo ?? ''} onChange={event => setDraft(current => ({ ...current, generatedTo: event.target.value }))} />
|
||||
</div></div>
|
||||
{SHORTAGE_REPORT_FILTERS.map(field => <ShortageOrderFilter key={field.key} label={field.label} caseInsensitive={field.key === 'barcode' || field.key === 'sku'} values={draft[field.key] ?? []} options={facets[field.key] ?? []} onChange={values => setDraft(current => ({ ...current, [field.key]: values }))} />)}
|
||||
</div>
|
||||
<div className={styles.filterActions}><span>可查询范围:{bounds.min} 至 {bounds.max}</span><div><Button type="button" variant="gray" className={styles.button} onClick={resetFilters}><RotateCcw size={14} />重置</Button><Button type="submit" className={styles.button}><Search size={14} />查询</Button></div></div>
|
||||
</form>
|
||||
{(loadError || error) && <div className={styles.error} role="alert">{loadError || error}</div>}
|
||||
{notice && <div className={styles.notice} role="status">{notice}</div>}
|
||||
<PlatformSection title="每日缺货汇总" className={styles.tableSection} contentClassName={styles.tableContent} aside={<span className={styles.resultCount}>共 {filtered.length.toLocaleString('zh-CN')} 条{filterCount > 0 && ` · 已应用 ${filterCount} 项筛选`}</span>}>
|
||||
<div className={styles.tableToolbar}><span className={styles.archivePolicy}>每日09:00存档 · 保留 {SHORTAGE_REPORT_ARCHIVE_POLICY.retentionMonths} 个月{canEdit && ' · 点击填报列编辑'}</span><button type="button" className={styles.columnButton} onClick={() => setSettingsOpen(true)}><Columns3 size={14} />列设置<span>{visibleColumns.length}</span></button></div>
|
||||
<ShortageDataTable label="缺货报表汇总表" fields={SHORTAGE_REPORT_FIELDS} columns={columns} onResize={(key, width) => setColumns(previous => previous.map(column => column.key === key ? { ...column, width } : column))} rows={filtered}
|
||||
editableFields={['expectedArrival', 'notes']} onEditRow={canEdit && !loading && !loadError ? id => setEditingRow(filtered.find(row => row.id === id) ?? null) : undefined}
|
||||
emptyTitle={loading ? '正在生成缺货报表' : loadError ? '报表读取失败' : prepared.length ? '没有符合条件的报表' : '暂无缺货报表'} emptyDescription={loading ? '正在读取完整明细、商品档案和库存,请稍候。' : loadError ? '请点击刷新重新读取。' : prepared.length ? '请调整生成日期或其他筛选条件后重新查询。' : generatedAt ? '当日报表已生成,没有真实缺货大于0的记录。' : '每天北京时间09:00生成当日报表。'} onClearFilters={filterCount ? resetFilters : undefined} />
|
||||
</PlatformSection>
|
||||
<ShortageColumnSettings open={settingsOpen} onClose={() => setSettingsOpen(false)} fields={SHORTAGE_REPORT_FIELDS} columns={columns} onChange={setColumns} onReset={() => setColumns(createReportColumnSettings())} resetLabel="恢复默认字段" />
|
||||
{editingRow && <ShortageReportEditor key={editingRow.id} row={editingRow} onClose={() => setEditingRow(null)} onSave={saveManual} />}
|
||||
</main>
|
||||
}
|
||||
@ -0,0 +1,16 @@
|
||||
import { redirect } from 'next/navigation'
|
||||
import { requireSession } from '@/lib/server-session'
|
||||
import { SHORTAGE_REPORT_ARCHIVE_POLICY } from '@/lib/supply-chain-shortage-report'
|
||||
import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service'
|
||||
import { ShortageReportView } from './ShortageReportView'
|
||||
|
||||
export const metadata = { title: '缺货报表 · 供应链中心' }
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
export default async function ShortageReportPage() {
|
||||
const { authUser } = await requireSession('/login')
|
||||
const access = await supplyChainPermissionSettingsService.getUserAccess(authUser, 'shortageOrderDetails')
|
||||
if (!access.view) redirect('/supply-chain')
|
||||
const today = new Date().toLocaleDateString('sv-SE', { timeZone: SHORTAGE_REPORT_ARCHIVE_POLICY.timeZone })
|
||||
return <ShortageReportView userId={authUser.id} canDownload={access.download} canEdit={access.edit} today={today} />
|
||||
}
|
||||
@ -0,0 +1,27 @@
|
||||
import type { ShortageReportRow } from '@/lib/supply-chain-shortage-report'
|
||||
import { normalizeColumnSettings, type ShortageColumnSetting, type ShortageTableField } from '../shortage-table-settings'
|
||||
|
||||
export const SHORTAGE_REPORT_FIELDS = [
|
||||
{ key: 'generatedOn', label: '生成日期', group: '报表信息', width: 130, hint: '每日快照的生成日期,不是订单付款日期。' },
|
||||
{ key: 'sku', label: '货号', group: '商品信息', width: 140 },
|
||||
{ key: 'barcode', label: '商品编码', group: '商品信息', width: 170 },
|
||||
{ key: 'productName', label: '商品名称', group: '商品信息', width: 240 },
|
||||
{ key: 'skuProductionStatus', label: '货号生产状态', group: '商品信息', width: 140, hint: '按产品档案中该货号全部编码聚合:含销售为销售;仅退市/停产且含退市为退市;全停产为停产。' },
|
||||
{ key: 'productionStatus', label: '条码生产状态', group: '商品信息', width: 140, hint: '按商品编码关联产品档案中的商品状态。' },
|
||||
{ key: 'supplier', label: '供应商', group: '责任信息', width: 180 },
|
||||
{ key: 'purchaser', label: '采购', group: '责任信息', width: 110 },
|
||||
{ key: 'shortageQuantity', label: '缺货数量', group: '缺货核算', width: 110, numeric: true, hint: '按商品编码合计缺货订单明细 AY 列的缺货数量。' },
|
||||
{ key: 'stock', label: '现有库存', group: '缺货核算', width: 110, numeric: true, nonNegative: true, hint: '同货号全部编码,按仓库属性“成品发货仓-真实库存”汇总公有可用数;最终合计为负数时显示及导出为0,未知库存留空。' },
|
||||
{ key: 'realShortage', label: '真实缺货', group: '缺货核算', width: 110, numeric: true, hint: '缺货数量减现有库存,剔除小于等于 0 的记录。' },
|
||||
{ key: 'expectedArrival', label: '预计到货时间', group: '交期反馈', width: 160, hint: '人工填报,按生成日期与商品编码保存。' },
|
||||
{ key: 'notes', label: '缺货原因', group: '交期反馈', width: 220, hint: '人工填报,按生成日期与商品编码保存。' },
|
||||
] as const satisfies readonly ShortageTableField<Exclude<keyof ShortageReportRow, 'id'>>[]
|
||||
|
||||
export type ShortageReportFieldKey = typeof SHORTAGE_REPORT_FIELDS[number]['key']
|
||||
export type ReportColumnSetting = ShortageColumnSetting<ShortageReportFieldKey>
|
||||
export function createReportColumnSettings(): ReportColumnSetting[] {
|
||||
return SHORTAGE_REPORT_FIELDS.map(field => ({ key: field.key, width: field.width, visible: true }))
|
||||
}
|
||||
export function readReportColumnSettings(value: unknown) {
|
||||
return normalizeColumnSettings(value, SHORTAGE_REPORT_FIELDS)
|
||||
}
|
||||
@ -0,0 +1,44 @@
|
||||
import { indexShortageInventory } from '@/lib/supply-chain-shortage-enrichment'
|
||||
import { shortageCellValue } from './shortage-cell-value'
|
||||
import { SHORTAGE_ORDER_FIELDS } from './shortage-order-fields'
|
||||
import { SHORTAGE_REPORT_FIELDS } from './report/shortage-report-fields'
|
||||
|
||||
describe('缺货库存最终显示值', () => {
|
||||
it('shows negative final stock as numeric zero across detail, warehouse, clearance and report stock columns', () => {
|
||||
const fields = [
|
||||
...SHORTAGE_ORDER_FIELDS.filter(field => field.group === '库存核对'),
|
||||
...SHORTAGE_REPORT_FIELDS.filter(field => field.label.includes('库存')),
|
||||
]
|
||||
for (const field of fields) {
|
||||
expect(shortageCellValue(field, -189)).toBe(0)
|
||||
expect(shortageCellValue(field, 0)).toBe(0)
|
||||
expect(shortageCellValue(field, 8.5)).toBe(8.5)
|
||||
expect(shortageCellValue(field, null)).toBe('')
|
||||
expect(shortageCellValue(field, undefined)).toBe('')
|
||||
expect(shortageCellValue(field, '未填报清货库存')).toBe('未填报清货库存')
|
||||
}
|
||||
})
|
||||
|
||||
it('sums signed stock before formatting without changing the quantities used for aggregation', () => {
|
||||
const inventory = { requestedBarcodes: ['A', 'B'], cloud: [],
|
||||
inventory: [
|
||||
{ barcode: 'A', warehouseId: 1, quantity: 0, orderLock: 20 },
|
||||
{ barcode: 'B', warehouseId: 1, quantity: 30, orderLock: 0 },
|
||||
], warehouses: [{ id: 1, name: '大货仓', attribute: '成品发货仓-真实库存' }] }
|
||||
const stockFor = indexShortageInventory(inventory)
|
||||
const field = SHORTAGE_ORDER_FIELDS.find(field => field.key === 'combinedStock')!
|
||||
expect(shortageCellValue(field, stockFor(['A']))).toBe(0)
|
||||
expect(shortageCellValue(field, stockFor(['A', 'B']))).toBe(10)
|
||||
expect(shortageCellValue(field, stockFor(['UNKNOWN']))).toBe('')
|
||||
expect(stockFor(['A'])).toBe(-20)
|
||||
expect(inventory.inventory[0].orderLock).toBe(20)
|
||||
})
|
||||
|
||||
it('preserves non-stock quantities and identifier text', () => {
|
||||
const quantity = SHORTAGE_ORDER_FIELDS.find(field => field.key === 'quantity')!
|
||||
const barcode = SHORTAGE_ORDER_FIELDS.find(field => field.key === 'barcode')!
|
||||
expect(shortageCellValue(quantity, -2)).toBe(-2)
|
||||
expect(shortageCellValue(barcode, '000123')).toBe('000123')
|
||||
expect(shortageCellValue(barcode, null)).toBe('')
|
||||
})
|
||||
})
|
||||
@ -23,17 +23,19 @@
|
||||
font-size: 13px;
|
||||
}
|
||||
.pageHeader, .headerActions, .filterActions, .filterActions > div, .tableToolbar, .pagination, .pagination > div, .settingsFooter, .settingsSummary { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
.pageHeader { flex-shrink: 0; min-height: 42px; padding-bottom: 12px; border-bottom: 1px solid var(--sc-border, #e4e4e7); }
|
||||
.pageHeader { flex-shrink: 0; flex-wrap: wrap; min-height: 42px; padding-bottom: 12px; border-bottom: 1px solid var(--sc-border, #e4e4e7); }
|
||||
.headerActions { max-width: 100%; flex-wrap: wrap; }
|
||||
.pageHeader > div:first-child { display: flex; align-items: baseline; gap: 12px; }
|
||||
.pageHeader h1 { margin: 0; font-size: 18px; font-weight: 600; letter-spacing: -.3px; }
|
||||
.subtitle, .sourceStatus, .resultCount { color: #71717a; font-size: 12px; }
|
||||
.sourceStatus { display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; }
|
||||
.sourceStatus { display: inline-flex; max-width: 100%; align-items: center; gap: 6px; white-space: normal; }
|
||||
.sourceStatus i { width: 6px; height: 6px; border-radius: 50%; background: #a1a1aa; }
|
||||
.button.button { min-height: 34px; height: 34px; min-width: 72px; gap: 6px; padding: 0 12px; border-radius: 6px; font-size: 13px; }
|
||||
.filterPanel { flex-shrink: 0; border: 1px solid var(--sc-border, #e4e4e7); border-radius: 8px; padding: 12px; background: #fafafb; }
|
||||
.filterGrid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px 16px; }
|
||||
.filter { position: relative; min-width: 0; }
|
||||
.fieldLabel { display: block; margin-bottom: 6px; color: #52525b; font-size: 12px; }
|
||||
.snapshotSelect { width: 100%; height: 34px; border: 1px solid #dcdce1; border-radius: 5px; padding: 0 10px; background: #fff; color: #52525b; font-size: 12px; }
|
||||
.filterTrigger { display: flex; width: 100%; height: 34px; align-items: center; justify-content: space-between; gap: 8px; border: 1px solid #dcdce1; border-radius: 5px; padding: 0 10px; background: #fff; color: #a1a1aa; cursor: pointer; text-align: left; }
|
||||
.filterTrigger > span { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.filterTrigger:hover, .filterTrigger[aria-expanded=true] { border-color: #71717a; }
|
||||
|
||||
@ -0,0 +1,67 @@
|
||||
import { createColumnSettings, filterShortageRows, parseFilterValues, readColumnSettings, restoreDetailColumns, SHORTAGE_VIEWS, SHORTAGE_ORDER_FIELDS, type ShortageRow } from './shortage-order-fields'
|
||||
|
||||
describe('缺货订单筛选与显示偏好', () => {
|
||||
const rows: ShortageRow[] = [
|
||||
{ id: 'one', sku: 'A', barcode: '0001234567890123456789', supplier: '甲', department: '采购/运营/如懿' },
|
||||
{ id: 'two', sku: 'B', barcode: '02', supplier: '乙', department: '客服' },
|
||||
{ id: 'three', sku: 'B', barcode: '03', supplier: '甲', department: '采购/运营' },
|
||||
]
|
||||
|
||||
it('matches multiple values within a field and intersects separate fields', () => {
|
||||
expect(filterShortageRows(rows, { sku: ['A', 'B'], supplier: ['甲'] }).map(row => row.id)).toEqual(['one', 'three'])
|
||||
expect(filterShortageRows(rows, { barcode: ['0001234567890123456789'] }).map(row => row.id)).toEqual(['one'])
|
||||
expect(filterShortageRows(rows, { sku: ['A'], supplier: ['乙'] })).toEqual([])
|
||||
})
|
||||
|
||||
it('matches each assigned department exactly without matching a partial name', () => {
|
||||
expect(filterShortageRows(rows, { department: ['采购'] }).map(row => row.id)).toEqual(['one', 'three'])
|
||||
expect(filterShortageRows(rows, { department: ['采'] })).toEqual([])
|
||||
expect(filterShortageRows(rows, {})).toEqual(rows)
|
||||
})
|
||||
|
||||
it('matches complete codes regardless of source or input case without changing other text filters', () => {
|
||||
const mixed: ShortageRow[] = [
|
||||
{ id: 'upper', barcode: 'DNZ004409N1222V01', sku: 'DNZ004409', supplier: 'Vendor A' },
|
||||
{ id: 'lower', barcode: 'dnz004409N1222V01', sku: 'dnz004409', supplier: 'Vendor A' },
|
||||
{ id: 'different', barcode: 'DNZ004409N1222V02', sku: 'DNZ004409', supplier: 'Vendor A' },
|
||||
]
|
||||
expect(filterShortageRows(mixed, { barcode: ['dnz004409n1222v01'], sku: ['dnz004409'] }).map(row => row.id)).toEqual(['upper', 'lower'])
|
||||
expect(filterShortageRows(mixed, { barcode: ['DNZ004409N1222V01'] }).map(row => row.id)).toEqual(['upper', 'lower'])
|
||||
expect(filterShortageRows(mixed, { barcode: ['dnz004409'] })).toEqual([])
|
||||
expect(filterShortageRows(mixed, { supplier: ['vendor a'] })).toEqual([])
|
||||
})
|
||||
|
||||
it('preserves identifier precision and spaces inside supplier names during batch input', () => {
|
||||
expect(parseFilterValues('0001234567890123456789,供应商 A\n供应商 A;02\t03、04;05')).toEqual(['0001234567890123456789', '供应商 A', '02', '03', '04', '05'])
|
||||
})
|
||||
|
||||
it('rejects unknown settings and repairs missing, duplicate or out-of-range columns', () => {
|
||||
expect(readColumnSettings(null)).toBeNull()
|
||||
expect(readColumnSettings([{ key: 'unknown', visible: true, width: 100 }])).toBeNull()
|
||||
const result = readColumnSettings([
|
||||
{ key: 'barcode', visible: false, width: 900 },
|
||||
{ key: 'barcode', visible: true, width: 100 },
|
||||
{ key: 'sku', visible: false, width: 2 },
|
||||
{ key: 'supplier', visible: true, width: Infinity },
|
||||
])!
|
||||
expect(result).toHaveLength(SHORTAGE_ORDER_FIELDS.length)
|
||||
expect(result[0]).toEqual({ key: 'barcode', visible: true, width: 560 })
|
||||
expect(result[1]).toEqual({ key: 'sku', visible: false, width: 80 })
|
||||
expect(result.some(column => column.key === 'supplier' && column.visible)).toBe(false)
|
||||
})
|
||||
|
||||
it('removes the three presets, migrates their saved preferences and preserves custom all-field preferences', () => {
|
||||
expect(SHORTAGE_VIEWS.map(view => view.key)).toEqual(['all'])
|
||||
for (const view of ['handling', 'inventory', 'replacement', 'all']) {
|
||||
const settings = createColumnSettings(view)
|
||||
expect(new Set(settings.map(column => column.key)).size).toBe(SHORTAGE_ORDER_FIELDS.length)
|
||||
expect(settings.every(column => column.visible)).toBe(true)
|
||||
if (view !== 'all') expect(restoreDetailColumns({ viewKey: view, columns: [{ key: 'barcode', visible: true, width: 100 }] })).toEqual(createColumnSettings())
|
||||
}
|
||||
const restored = restoreDetailColumns({ viewKey: 'all', columns: [{ key: 'barcode', visible: true, width: 111 }, { key: 'purchaser', visible: true, width: 110 }] })
|
||||
expect(restored[0]).toMatchObject({ key: 'preparedAt', visible: true })
|
||||
expect(restored.find(column => column.key === 'barcode')?.width).toBe(111)
|
||||
expect(restored.some(column => String(column.key) === 'purchaser')).toBe(false)
|
||||
expect(SHORTAGE_ORDER_FIELDS.filter(field => field.label === '付款日期')).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
@ -0,0 +1,119 @@
|
||||
import { normalizeColumnSettings, type ShortageColumnSetting } from './shortage-table-settings'
|
||||
|
||||
type Field = {
|
||||
key: string
|
||||
label: string
|
||||
group: '订单信息' | '商品信息' | '缺货处理' | '库存核对' | '替换款信息' | '辅助字段'
|
||||
width: number
|
||||
numeric?: boolean
|
||||
nonNegative?: boolean
|
||||
hint?: string
|
||||
}
|
||||
|
||||
/** 对应需求文件「2.缺货订单明细」B:BD;付款日期合并,仅保留用户需要的展示和导出列。 */
|
||||
export const SHORTAGE_ORDER_FIELDS = [
|
||||
{ key: 'preparedAt', label: '制表时间', group: '订单信息', width: 180 },
|
||||
{ key: 'orderType', label: '订单类型', group: '订单信息', width: 130 },
|
||||
{ key: 'internalOrderId', label: '内部订单号', group: '订单信息', width: 160 },
|
||||
{ key: 'onlineOrderId', label: '线上订单号', group: '订单信息', width: 200 },
|
||||
{ key: 'category', label: '分类', group: '商品信息', width: 140 },
|
||||
{ key: 'sku', label: '货号', group: '商品信息', width: 140 },
|
||||
{ key: 'barcode', label: '商品编码', group: '商品信息', width: 160, hint: '编码按文本展示和导出,保留前导零与完整精度。' },
|
||||
{ key: 'productName', label: '商品名称', group: '商品信息', width: 240 },
|
||||
{ key: 'productionStatus', label: '生产状态', group: '商品信息', width: 120 },
|
||||
{ key: 'supplier', label: '供应商', group: '商品信息', width: 150 },
|
||||
{ key: 'packageType', label: '单双包', group: '商品信息', width: 100 },
|
||||
{ key: 'quantity', label: '数量', group: '订单信息', width: 90, numeric: true },
|
||||
{ key: 'exceptionType', label: '异常类型', group: '订单信息', width: 140 },
|
||||
{ key: 'platform', label: '平台站点', group: '订单信息', width: 130 },
|
||||
{ key: 'shopName', label: '店铺名称', group: '订单信息', width: 180 },
|
||||
{ key: 'paidAt', label: '付款日期', group: '订单信息', width: 170, hint: '合并原表 R、AM 两列,均映射订单付款时间。' },
|
||||
{ key: 'shopProductCode', label: '店铺商品编码', group: '订单信息', width: 170 },
|
||||
{ key: 'labels', label: '标签', group: '订单信息', width: 220 },
|
||||
{ key: 'shortageCategory', label: '缺货类型打标', group: '缺货处理', width: 300, hint: '按“逻辑总结”识别,退款关闭及信誉/虚拟订单优先;关键库存未知或边界未定义时标为待核实处理。' },
|
||||
{ key: 'suggestion', label: '处理建议', group: '缺货处理', width: 320 },
|
||||
{ key: 'department', label: '处理部门', group: '缺货处理', width: 150 },
|
||||
{ key: 'totalShortage', label: '缺货总量', group: '缺货处理', width: 110, numeric: true, hint: '按同货号汇总 M 列数量的件数,不是订单行数;在筛选和分页之前计算。' },
|
||||
{ key: 'skuProductionStatus', label: '货号生产状态', group: '商品信息', width: 140, hint: '聚合货号下全部编码:含销售为销售;仅有退市、停产且含退市为退市;全部停产为停产。' },
|
||||
{ key: 'clearanceStock', label: '清货剩余库存', group: '库存核对', width: 140, nonNegative: true, hint: '需区分未填报清货库存与已填报的数值零;计算结果为负数时显示及导出为 0。' },
|
||||
{ key: 'orderSkuKey', label: '交易单号&货号', group: '辅助字段', width: 220 },
|
||||
{ key: 'originalProductLabels', label: '商品标签-原商品编码', group: '商品信息', width: 200 },
|
||||
{ key: 'orderSkuQuantity', label: '单交易单单号单货号销售数量', group: '辅助字段', width: 220, numeric: true, hint: '按需求表 AE 列说明,在完整明细中对相同线上订单号和货号计数(明细行数),不是数量件数合计。' },
|
||||
{ key: 'exchangeSku', label: '换货货号', group: '替换款信息', width: 140, hint: '按换货目标编码匹配产品档案 barcode,读取对应 SKU;多个目标货号去重展示。' },
|
||||
{ key: 'exchangeBarcode', label: '换货编码', group: '替换款信息', width: 160, hint: '以本行商品编码匹配自定义换货规则的原编码,显示换货目标编码;只取最新快照的启用规则,目标档案缺失时仍保留编码。' },
|
||||
{ key: 'exchangeLabels', label: '商品标签-换货编码', group: '替换款信息', width: 220, hint: '按换货目标编码匹配产品档案 barcode,读取该编码的商品标签;不取原编码或同货号其他编码的标签。' },
|
||||
{ key: 'exchangeStock', label: '换货编码库存', group: '库存核对', width: 140, numeric: true, nonNegative: true, hint: '公有可用数 = 实际库存 - 订单占有 - 运营云仓可用数,最终合计为负数时显示及导出为 0。' },
|
||||
{ key: 'originalStock', label: '原编码库存', group: '库存核对', width: 130, numeric: true, nonNegative: true, hint: '公有可用数 = 实际库存 - 订单占有 - 运营云仓可用数,最终合计为负数时显示及导出为 0。' },
|
||||
{ key: 'combinedStock', label: '原编码+换货编码总库存', group: '库存核对', width: 210, numeric: true, nonNegative: true },
|
||||
{ key: 'skuStock', label: '货号总库存', group: '库存核对', width: 130, numeric: true, nonNegative: true },
|
||||
{ key: 'combinedMainStock', label: '原编码+换货编码正常大货仓库存', group: '库存核对', width: 260, numeric: true, nonNegative: true },
|
||||
{ key: 'combinedFrontStock', label: '原编码+换货编码前置仓库存', group: '库存核对', width: 240, numeric: true, nonNegative: true, hint: '仅统计三方-南昌樵舍仓,不含重庆西南仓;原编码与换货编码去重后合计。' },
|
||||
{ key: 'replacementSku', label: '替换款货号', group: '替换款信息', width: 140 },
|
||||
{ key: 'replacementBarcode', label: '替换款条码', group: '替换款信息', width: 160 },
|
||||
{ key: 'replacementType', label: '替换类型', group: '替换款信息', width: 120 },
|
||||
{ key: 'imageChange', label: '是否换图', group: '替换款信息', width: 120 },
|
||||
{ key: 'differences', label: '修改点', group: '替换款信息', width: 220 },
|
||||
{ key: 'replacementStock', label: '替换款库存', group: '库存核对', width: 130, numeric: true, nonNegative: true },
|
||||
{ key: 'replacementMainStock', label: '正常大货仓', group: '库存核对', width: 130, numeric: true, nonNegative: true, hint: '替换款正常大货仓公有可用数。' },
|
||||
{ key: 'replacementFrontStock', label: '前置仓', group: '库存核对', width: 120, numeric: true, nonNegative: true, hint: '替换款前置仓公有可用数。' },
|
||||
{ key: 'replacementLabels', label: '商品标签-替换款条码', group: '替换款信息', width: 200 },
|
||||
{ key: 'shortageQuantity', label: '缺货数量', group: '缺货处理', width: 110, numeric: true, hint: '分类以“缺货-”开头时取该明细的 M 数量,其余为 0。' },
|
||||
{ key: 'replacementStatus', label: '替换款状态', group: '替换款信息', width: 130 },
|
||||
{ key: 'canReplace', label: '是否可替换', group: '替换款信息', width: 130, hint: '依赖人工确认;有替换关系不代表已获准替换,未确认时留空。' },
|
||||
{ key: 'replacementClearanceStock', label: '替换款清货剩余库存', group: '库存核对', width: 190, nonNegative: true },
|
||||
] as const satisfies readonly Field[]
|
||||
|
||||
export type ShortageFieldKey = typeof SHORTAGE_ORDER_FIELDS[number]['key']
|
||||
export type ShortageRow = { id: string } & Partial<Record<ShortageFieldKey, string | number | null>>
|
||||
export type ColumnSetting = ShortageColumnSetting<ShortageFieldKey>
|
||||
|
||||
export const SHORTAGE_FILTERS = [
|
||||
{ key: 'sku', label: '货号' },
|
||||
{ key: 'barcode', label: '商品编码' },
|
||||
{ key: 'supplier', label: '供应商' },
|
||||
{ key: 'internalOrderId', label: '内部订单号' },
|
||||
{ key: 'onlineOrderId', label: '线上订单号' },
|
||||
{ key: 'shopName', label: '店铺名称' },
|
||||
{ key: 'department', label: '处理部门' },
|
||||
] as const
|
||||
export type FilterKey = typeof SHORTAGE_FILTERS[number]['key']
|
||||
export type ShortageFilters = Partial<Record<FilterKey, string[]>>
|
||||
|
||||
export const SHORTAGE_VIEWS: { key: string; label: string; fields: readonly ShortageFieldKey[] }[] = [
|
||||
{ key: 'all', label: '全部字段', fields: SHORTAGE_ORDER_FIELDS.map(field => field.key) },
|
||||
]
|
||||
|
||||
export function createColumnSettings(viewKey = 'all'): ColumnSetting[] {
|
||||
const visible = SHORTAGE_VIEWS.find(view => view.key === viewKey)?.fields ?? SHORTAGE_VIEWS[0].fields
|
||||
const order = [...visible, ...SHORTAGE_ORDER_FIELDS.map(field => field.key).filter(key => !visible.includes(key))]
|
||||
return order.map(key => ({ key, visible: visible.includes(key), width: SHORTAGE_ORDER_FIELDS.find(field => field.key === key)!.width }))
|
||||
}
|
||||
|
||||
/** 已删除的预设迁移到全部字段,避免旧浏览器偏好继续隐藏大部分列。 */
|
||||
export function restoreDetailColumns(value: unknown): ColumnSetting[] {
|
||||
if (!value || typeof value !== 'object' || !('viewKey' in value) || value.viewKey !== 'all') return createColumnSettings()
|
||||
const settings = readColumnSettings('columns' in value ? value.columns : null) ?? createColumnSettings()
|
||||
// 历史偏好中没有制表时间时,将新列放在订单类型前并显示。
|
||||
const hadPreparedAt = 'columns' in value && Array.isArray(value.columns) && value.columns.some(item => item?.key === 'preparedAt')
|
||||
if (!hadPreparedAt) return [{ key: 'preparedAt', visible: true, width: 180 }, ...settings.filter(column => column.key !== 'preparedAt')]
|
||||
return settings
|
||||
}
|
||||
|
||||
export { parseFilterValues } from './shortage-filter-values'
|
||||
|
||||
/** 用户显示偏好只接受已知字段、布尔可见值和有限列宽,不信任浏览器存储中的任意内容。 */
|
||||
export function readColumnSettings(value: unknown): ColumnSetting[] | null {
|
||||
return normalizeColumnSettings(value, SHORTAGE_ORDER_FIELDS)
|
||||
}
|
||||
|
||||
export function filterShortageRows(rows: readonly ShortageRow[], filters: ShortageFilters) {
|
||||
// 同字段多个值为“或”,不同字段之间为“且”;部门允许匹配复合部门中的单个部门。
|
||||
return rows.filter(row => SHORTAGE_FILTERS.every(({ key }) => {
|
||||
const values = filters[key]
|
||||
if (!values?.length) return true
|
||||
const actual = String(row[key] ?? '').trim()
|
||||
return values.some(value => key === 'barcode' || key === 'sku'
|
||||
? actual.toUpperCase() === value.trim().toUpperCase()
|
||||
: actual === value || (key === 'department' && actual.split(/[\/、]/).includes(value)))
|
||||
}))
|
||||
}
|
||||
@ -6,6 +6,7 @@ export function getSupplyChainPermissionTargetForPath(pathname: string): SupplyC
|
||||
if (pathname === '/supply-chain/management/modular-product-processing-orders') return 'modularProductProcessingOrders' as const
|
||||
if (pathname === '/supply-chain/management/owner-config') return 'ownerConfig' as const
|
||||
if (pathname === '/supply-chain/management/custom-table') return 'limitManagement' as const
|
||||
if (pathname === '/supply-chain/management/shortage-order-details' || pathname.startsWith('/supply-chain/management/shortage-order-details/')) return 'shortageOrderDetails' as const
|
||||
if (pathname === '/supply-chain/management/freight-maintenance') return 'freightMaintenance' as const
|
||||
if (pathname === '/supply-chain/management/discontinuation') return 'discontinuationManagement' as const
|
||||
if (pathname === '/supply-chain/management/front-warehouse-inventory') return 'frontWarehouseInventory' as const
|
||||
@ -91,6 +92,9 @@ export function getSupplyChainApiPermissionRequirement(pathname: string, method:
|
||||
action: pathname.endsWith('/export') ? 'download' as const : action,
|
||||
}
|
||||
}
|
||||
if (pathname === '/api/supply-chain/management/shortage-order-details' || pathname.startsWith('/api/supply-chain/management/shortage-order-details/')) {
|
||||
return { targetKey: 'shortageOrderDetails' as const, action: pathname.endsWith('/export') ? 'download' as const : action }
|
||||
}
|
||||
if (pathname.startsWith('/api/supply-chain/management/modular-product-processing-orders')) {
|
||||
const modularBase = '/api/supply-chain/management/modular-product-processing-orders'
|
||||
if (pathname === modularBase || pathname.startsWith(`${modularBase}/components`) ||
|
||||
|
||||
@ -649,6 +649,13 @@ describe('supply chain permission settings', () => {
|
||||
).toEqual({ targetKey: 'logisticsArrivalSigningDuration', action: 'edit' })
|
||||
})
|
||||
|
||||
it('maps shortage detail reads and exports to the same permission target as the page', () => {
|
||||
const base = '/api/supply-chain/management/shortage-order-details'
|
||||
expect(getSupplyChainApiPermissionRequirement(base, 'GET')).toEqual({ targetKey: 'shortageOrderDetails', action: 'view' })
|
||||
expect(getSupplyChainApiPermissionRequirement(`${base}/export`, 'GET')).toEqual({ targetKey: 'shortageOrderDetails', action: 'download' })
|
||||
expect(getSupplyChainApiPermissionRequirement(base, 'POST')).toEqual({ targetKey: 'shortageOrderDetails', action: 'edit' })
|
||||
})
|
||||
|
||||
it('maps production stop demand routes and API exemptions', () => {
|
||||
expect(
|
||||
getSupplyChainPermissionTargetForPath('/supply-chain/management/production-stop-demands'),
|
||||
|
||||
@ -131,6 +131,7 @@ export type SupplyChainPermissionTargetKey =
|
||||
| 'productionStopFlowOwnerConfigDelete'
|
||||
| 'logisticsArrivalSigningDuration'
|
||||
| 'orderNotDispatched'
|
||||
| 'shortageOrderDetails'
|
||||
| 'managementBlankPage1'
|
||||
| 'managementBlankPage2'
|
||||
| 'managementBlankPage7'
|
||||
@ -273,6 +274,7 @@ export const SUPPLY_CHAIN_PERMISSION_TARGETS: SupplyChainPermissionTarget[] = [
|
||||
{ key: 'productStopWarehouseMappingExport', label: '仓库映射导出', description: '导出仓库映射' },
|
||||
{ key: 'logisticsArrivalSigningDuration', label: '物流到货签收时长看板', description: '物流签收查询与明细导出' },
|
||||
{ key: 'orderNotDispatched', label: '应发未发', description: '查看应发未发订单、超时原因、处理人与原始订单明细' },
|
||||
{ key: 'shortageOrderDetails', label: '缺货订单明细', description: '缺货订单、库存与替换款核对及明细导出' },
|
||||
{ key: 'managementBlankPage1', label: '空白页 1', description: '经营管理空白页 1' },
|
||||
{ key: 'managementBlankPage2', label: '空白页 2', description: '经营管理空白页 2' },
|
||||
{ key: 'managementBlankPage7', label: '外贸销量', description: '外贸销量查看、下载与维护' },
|
||||
@ -415,6 +417,7 @@ export const SUPPLY_CHAIN_PERMISSION_TARGET_ROUTES: Partial<
|
||||
productInventoryStop: '/supply-chain/management/product-inventory-stop',
|
||||
logisticsArrivalSigningDuration: '/supply-chain/management/logistics-arrival-signing-duration',
|
||||
orderNotDispatched: '/supply-chain/management/order-not-dispatched',
|
||||
shortageOrderDetails: '/supply-chain/management/shortage-order-details',
|
||||
managementBlankPage1: '/supply-chain/management/blank-pages/blank-page-1',
|
||||
managementBlankPage2: '/supply-chain/management/blank-pages/blank-page-2',
|
||||
managementBlankPage7: '/supply-chain/management/blank-pages/blank-page-7',
|
||||
|
||||
@ -0,0 +1,133 @@
|
||||
import { applyShortageClassification, classifyShortageOrder } from './supply-chain-shortage-classification'
|
||||
|
||||
const row = {
|
||||
category: '柜', productionStatus: '销售', skuProductionStatus: '销售', refundStatus: null, labels: null, exceptionType: '缺货',
|
||||
quantity: 2, totalShortage: 5, clearanceStock: null, originalStock: 0, combinedStock: 0, skuStock: 0, combinedMainStock: 0, combinedFrontStock: 0,
|
||||
exchangeBarcode: null, replacementBarcode: null, replacementStock: 0, replacementMainStock: 0, replacementFrontStock: 0,
|
||||
imageChange: null, replacementStatus: null, replacementClearanceStock: null, canReplace: null,
|
||||
}
|
||||
|
||||
describe('缺货明细分类按逻辑总结执行', () => {
|
||||
it('prioritizes refund closed before virtual/credit and missing product data', () => {
|
||||
expect(classifyShortageOrder({ ...row, refundStatus: '退款关闭', category: '虚拟', productionStatus: null })).toBe('异常订单-退款关闭')
|
||||
expect(classifyShortageOrder({ ...row, refundStatus: 'closed', category: '虚拟', productionStatus: null })).toBe('异常订单-退款关闭')
|
||||
expect(classifyShortageOrder({ ...row, category: '虚拟商品', productionStatus: null })).toBe('异常订单-信誉订单')
|
||||
expect(classifyShortageOrder({ ...row, productionStatus: null })).toBe('异常订单-特殊或组合商品,待拆解')
|
||||
})
|
||||
|
||||
it('does not convert missing inventory or discontinued clearance into zero stock', () => {
|
||||
expect(classifyShortageOrder({ ...row, combinedStock: null })).toBe('异常订单-待核实处理')
|
||||
expect(classifyShortageOrder({ ...row, skuProductionStatus: '停产', clearanceStock: null })).toBe('异常订单-待核实处理')
|
||||
expect(classifyShortageOrder({ ...row, skuProductionStatus: '停产', clearanceStock: '未知状态' })).toBe('异常订单-待核实处理')
|
||||
expect(classifyShortageOrder({ ...row, skuProductionStatus: '停产', clearanceStock: 0 })).toBe('停产无库存-无相同款或相似款库存')
|
||||
})
|
||||
|
||||
it.each(['退市', '停产'])('continues stock classification for %s with explicitly unreported clearance', skuProductionStatus => {
|
||||
const unreported = { ...row, skuProductionStatus, clearanceStock: '未填报清货库存' }
|
||||
expect(applyShortageClassification([unreported])[0]).toMatchObject({ shortageCategory: '缺货-无相同款或相似款库存', shortageQuantity: 2 })
|
||||
expect(classifyShortageOrder({ ...unreported, combinedStock: 6, skuStock: 6, combinedMainStock: 6 })).toBe('非真实缺货-原商品编码大货仓有库存且能补齐缺货')
|
||||
expect(classifyShortageOrder({ ...unreported, combinedStock: null })).toBe('异常订单-待核实处理')
|
||||
expect(applyShortageClassification([{ ...unreported, refundStatus: '退款关闭' }])[0].shortageQuantity).toBe(0)
|
||||
expect(applyShortageClassification([{ ...unreported, category: '虚拟商品' }])[0].shortageQuantity).toBe(0)
|
||||
})
|
||||
|
||||
it('calculates AY from detail pieces only for 缺货- classifications and maps actions', () => {
|
||||
const [result] = applyShortageClassification([row])
|
||||
expect(result).toMatchObject({ shortageCategory: '缺货-无相同款或相似款库存', suggestion: '采购反馈交期/根据采购交期设置预售', department: '采购/运营', shortageQuantity: 2 })
|
||||
expect(applyShortageClassification([{ ...row, refundStatus: '退款关闭' }])[0].shortageQuantity).toBe(0)
|
||||
})
|
||||
|
||||
it.each([
|
||||
{},
|
||||
{ labels: '京东供销订单,京喜' },
|
||||
{ exchangeBarcode: 'EXCHANGE', replacementBarcode: 'REPLACEMENT', replacementMainStock: 30, imageChange: '不换图' },
|
||||
{ skuProductionStatus: '停产', clearanceStock: 0 },
|
||||
{ skuProductionStatus: '退市', clearanceStock: null },
|
||||
{ combinedStock: null, skuStock: null, replacementStock: null, combinedMainStock: null, combinedFrontStock: null, replacementMainStock: null, skuProductionStatus: null },
|
||||
])('prioritizes sufficient original barcode stock over warehouse, replacement and clearance branches: %j', overrides => {
|
||||
expect(applyShortageClassification([{ ...row, originalStock: 18, totalShortage: 2, combinedStock: 18, skuStock: 18, ...overrides }])[0]).toMatchObject({
|
||||
shortageCategory: '非真实缺货-原商品编码大货仓有库存且能补齐缺货',
|
||||
suggestion: '核实有库存未锁定原因并处理异常', department: '如懿', shortageQuantity: 0,
|
||||
})
|
||||
})
|
||||
|
||||
it('preserves refund, credit and unresolved product exceptions even with sufficient original stock', () => {
|
||||
const covered = { ...row, originalStock: 18, totalShortage: 2 }
|
||||
expect(classifyShortageOrder({ ...covered, refundStatus: 'closed' })).toBe('异常订单-退款关闭')
|
||||
expect(classifyShortageOrder({ ...covered, category: '信誉商品' })).toBe('异常订单-信誉订单')
|
||||
expect(classifyShortageOrder({ ...covered, category: '虚拟商品' })).toBe('异常订单-信誉订单')
|
||||
expect(classifyShortageOrder({ ...covered, productionStatus: null })).toBe('异常订单-特殊或组合商品,待拆解')
|
||||
})
|
||||
|
||||
it('requires strictly greater, finite original stock and total shortage, without using exchange or SKU stock as original stock', () => {
|
||||
for (const originalStock of [null, NaN, Infinity, -1, 2, 5]) {
|
||||
expect(classifyShortageOrder({ ...row, originalStock, combinedStock: 2, skuStock: 2, combinedMainStock: 2 })).toBe('缺货-原商品编码大货仓有库存但无法补齐缺货')
|
||||
}
|
||||
for (const totalShortage of [null, NaN, Infinity]) {
|
||||
expect(classifyShortageOrder({ ...row, originalStock: 18, totalShortage })).toBe('异常订单-待核实处理')
|
||||
}
|
||||
expect(classifyShortageOrder({ ...row, originalStock: 1, combinedStock: 10, skuStock: 100, combinedMainStock: 10, exchangeBarcode: 'EXCHANGE' })).toBe('缺货-含换货编码大货仓有库存且能补齐缺货')
|
||||
})
|
||||
|
||||
it('keeps equality for further classification and overrides negative exchange offsets only when original stock is sufficient', () => {
|
||||
expect(classifyShortageOrder({ ...row, originalStock: 5, combinedStock: 5, skuStock: 5, combinedMainStock: 5 })).toBe('异常订单-待核实处理')
|
||||
expect(classifyShortageOrder({ ...row, originalStock: 6, combinedStock: 0, skuStock: 8, exchangeBarcode: 'NEGATIVE-EXCHANGE' })).toBe('非真实缺货-原商品编码大货仓有库存且能补齐缺货')
|
||||
expect(classifyShortageOrder({ ...row, originalStock: 4, combinedStock: 0, skuStock: 8, exchangeBarcode: 'NEGATIVE-EXCHANGE' })).toBe('异常订单-待核实处理')
|
||||
})
|
||||
|
||||
it('uses the whole SKU quantity total rather than this order line when deciding sufficient original stock', () => {
|
||||
expect(classifyShortageOrder({ ...row, quantity: 1, totalShortage: 20, originalStock: 18, combinedStock: 18, skuStock: 18, combinedMainStock: 18 })).toBe('缺货-原商品编码大货仓有库存但无法补齐缺货')
|
||||
})
|
||||
|
||||
it.each([
|
||||
{ skuStock: 8 },
|
||||
{ skuStock: -3 },
|
||||
{ skuStock: 8, exchangeBarcode: 'EXCHANGE' },
|
||||
{ skuStock: 8, labels: '淘宝分销订单' },
|
||||
{ skuStock: 8, replacementBarcode: 'REPLACEMENT', replacementStock: 6, replacementMainStock: 6, imageChange: '不换图' },
|
||||
{ skuStock: 8, skuProductionStatus: '停产', clearanceStock: 0, labels: '淘宝分销订单' },
|
||||
{ skuStock: 8, skuProductionStatus: '退市', clearanceStock: '未填报清货库存' },
|
||||
])('requires verification for zero combined stock and nonzero style stock: %j', inventory => {
|
||||
expect(applyShortageClassification([{ ...row, ...inventory }])[0]).toMatchObject({
|
||||
shortageCategory: '异常订单-待核实处理', suggestion: '异常订单-待核实处理', department: '如懿', shortageQuantity: 0,
|
||||
})
|
||||
})
|
||||
|
||||
it('preserves higher priority exceptions when zero combined stock conflicts with style stock', () => {
|
||||
const mismatch = { ...row, skuStock: 8 }
|
||||
expect(classifyShortageOrder({ ...mismatch, refundStatus: '退款关闭', category: '虚拟商品' })).toBe('异常订单-退款关闭')
|
||||
expect(classifyShortageOrder({ ...mismatch, category: '信誉商品' })).toBe('异常订单-信誉订单')
|
||||
expect(classifyShortageOrder({ ...mismatch, productionStatus: null })).toBe('异常订单-特殊或组合商品,待拆解')
|
||||
})
|
||||
|
||||
it('only applies the inventory mismatch rule to exact known zero and known nonzero stock', () => {
|
||||
expect(classifyShortageOrder({ ...row, combinedStock: 1, skuStock: 8 })).toBe('缺货-原商品编码大货仓有库存但无法补齐缺货')
|
||||
expect(classifyShortageOrder({ ...row, combinedStock: -1, skuStock: 8 })).toBe('缺货-原商品编码大货仓有库存但无法补齐缺货')
|
||||
expect(classifyShortageOrder(row)).toBe('缺货-无相同款或相似款库存')
|
||||
for (const skuStock of [null, NaN, Infinity]) {
|
||||
expect(classifyShortageOrder({ ...row, skuStock })).toBe('异常订单-待核实处理')
|
||||
}
|
||||
})
|
||||
|
||||
it('distinguishes main stock with no exchange, main stock with exchange and front stock', () => {
|
||||
expect(classifyShortageOrder({ ...row, combinedStock: 6, skuStock: 6, combinedMainStock: 6 })).toBe('非真实缺货-原商品编码大货仓有库存且能补齐缺货')
|
||||
expect(classifyShortageOrder({ ...row, combinedStock: 6, skuStock: 6, combinedMainStock: 6, exchangeBarcode: 'NEW' })).toBe('缺货-含换货编码大货仓有库存且能补齐缺货')
|
||||
expect(classifyShortageOrder({ ...row, combinedStock: 6, skuStock: 6, combinedFrontStock: 6 })).toBe('缺货-原商品编码含前置仓库存能补齐缺货')
|
||||
})
|
||||
|
||||
it('applies special shipping labels before standard replacement decisions', () => {
|
||||
expect(classifyShortageOrder({ ...row, combinedStock: 6, skuStock: 6, combinedFrontStock: 6, labels: '普通,淘宝分销订单' })).toBe('缺货-前置仓或有库存但不发特殊标签订单')
|
||||
})
|
||||
|
||||
it('distinguishes replacement coverage, image requirements and undefined equality', () => {
|
||||
expect(classifyShortageOrder({ ...row, replacementBarcode: 'NEW', replacementStock: 6, imageChange: '不换图' })).toBe('缺货-有相同款库存且无需换图且能补齐缺货')
|
||||
expect(classifyShortageOrder({ ...row, replacementBarcode: 'NEW', replacementStock: 6, imageChange: '换图' })).toBe('缺货-有相似款或有相同款库存但需换图或不确定是否换图但能补齐缺货')
|
||||
expect(classifyShortageOrder({ ...row, replacementBarcode: 'NEW', replacementStock: 4, imageChange: '不换图' })).toBe('异常订单-待核实处理')
|
||||
expect(classifyShortageOrder({ ...row, replacementBarcode: 'NEW', replacementStock: 5, imageChange: '不换图' })).toBe('异常订单-待核实处理')
|
||||
})
|
||||
|
||||
it('does not infer manual replacement approval from the presence of a rule', () => {
|
||||
expect(classifyShortageOrder({ ...row, skuProductionStatus: '停产', clearanceStock: 0, replacementBarcode: 'NEW', replacementStatus: '销售' })).toBe('停产无库存-无相同款或相似款库存')
|
||||
expect(classifyShortageOrder({ ...row, skuProductionStatus: '停产', clearanceStock: 0, replacementBarcode: 'NEW', replacementStatus: '销售', canReplace: '是' })).toBe('停产无库存-有替换款在售但暂无库存')
|
||||
})
|
||||
})
|
||||
@ -0,0 +1,155 @@
|
||||
type ClassificationInput = {
|
||||
category: string | null
|
||||
productionStatus: string | null
|
||||
skuProductionStatus: string | null
|
||||
refundStatus: string | null
|
||||
labels: string | null
|
||||
exceptionType: string
|
||||
quantity: number | null
|
||||
totalShortage: number | null
|
||||
clearanceStock: number | string | null
|
||||
originalStock: number | null
|
||||
combinedStock: number | null
|
||||
skuStock: number | null
|
||||
combinedMainStock: number | null
|
||||
combinedFrontStock: number | null
|
||||
exchangeBarcode: string | null
|
||||
replacementBarcode: string | null
|
||||
replacementStock: number | null
|
||||
replacementMainStock: number | null
|
||||
replacementFrontStock: number | null
|
||||
imageChange: string | null
|
||||
replacementStatus: string | null
|
||||
replacementClearanceStock: number | string | null
|
||||
canReplace: string | null
|
||||
}
|
||||
|
||||
const verify = ['核实并处理异常', '如懿'] as const
|
||||
const restock = ['采购反馈交期/根据采购交期设置预售', '采购/运营'] as const
|
||||
const maintain = ['维护自定义换货规则并重刷缺货订单', '如懿'] as const
|
||||
const investigate = ['核实有库存未锁定原因并处理异常', '如懿'] as const
|
||||
const investigateRestock = ['采购反馈交期/根据采购交期设置预售/核实有库存未锁定原因并处理异常', '采购/运营/如懿'] as const
|
||||
const discussRestock = ['采购反馈交期/根据采购交期设置预售/沟通买家换货或等待', '采购/运营/客服'] as const
|
||||
const actions: Record<string, readonly [string, string]> = {
|
||||
'异常订单-退款关闭': verify,
|
||||
'异常订单-信誉订单': verify,
|
||||
'异常订单-特殊或组合商品,待拆解': verify,
|
||||
'异常订单-待核实处理': ['异常订单-待核实处理', '如懿'],
|
||||
'停产无库存-无相同款或相似款库存': ['跟进下架/转聚水潭异常订单,建议劝退', '如懿/客服'],
|
||||
'停产无库存-前置仓或有库存但不发特殊标签订单': ['转聚水潭异常订单,建议劝退', '如懿/客服'],
|
||||
'停产无库存-前置仓或有库存但不发特殊标签订单,有相似款或相同款但需换图或不确定是否换图': ['建议劝退或沟通买家换货', '客服'],
|
||||
'停产无库存-有相同款库存且不换图且能补齐缺货': maintain,
|
||||
'停产无库存-有相同款库存且无需换图但不能补齐缺货': ['维护自定义换货规则并重刷缺货订单,其他转聚水潭异常订单,建议劝退', '如懿'],
|
||||
'停产无库存-有相似款库存或有相同款库存但需换图或不确定是否换图但能补齐缺货': ['沟通买家换货,或劝退', '客服'],
|
||||
'停产无库存-有相似款或相同款库存但需换图或不确定是否换图但不能补齐缺货': ['沟通买家换货,或劝退', '客服'],
|
||||
'停产无库存-原编码含前置仓库存可补齐缺货': investigate,
|
||||
'停产无库存-含换货编码含前置仓库存可补齐缺货': investigate,
|
||||
'停产无库存-有替换款在售但暂无库存': maintain,
|
||||
'缺货-无相同款或相似款库存': restock,
|
||||
'缺货-前置仓或有库存但不发特殊标签订单': restock,
|
||||
'缺货-有相同款库存且无需换图且能补齐缺货': maintain,
|
||||
'缺货-有相似款或有相同款库存但需换图或不确定是否换图但能补齐缺货': discussRestock,
|
||||
'缺货-有相似款或有相同款库存但需换图或不确定是否换图但不能补齐缺货': discussRestock,
|
||||
'非真实缺货-原商品编码大货仓有库存且能补齐缺货': investigate,
|
||||
'缺货-含换货编码大货仓有库存且能补齐缺货': investigateRestock,
|
||||
'缺货-原商品编码含前置仓库存能补齐缺货': investigate,
|
||||
'缺货-含换货编码含前置仓库存能补齐缺货': investigate,
|
||||
'缺货-含相同款且不换图库存能补齐缺货': maintain,
|
||||
'缺货-含前置仓含相同款且不换图库存能补齐缺货': investigate,
|
||||
'缺货-原商品编码大货仓有库存但无法补齐缺货': investigateRestock,
|
||||
'缺货-原商品编码前置仓有库存但无法补齐缺货': investigateRestock,
|
||||
'缺货-含换货编码大货仓有库存但无法补齐缺货': investigateRestock,
|
||||
'缺货-含换货编码前置仓有库存但无法补齐缺货': investigateRestock,
|
||||
'缺货-京喜双仓缺货': restock,
|
||||
}
|
||||
|
||||
const specialLabels = ['淘宝分销订单', '抖音订单', '拼多多订单', '京东供销订单', '唯品会JITX', '京东厂家直送']
|
||||
const known = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value)
|
||||
|
||||
/** 用户确认采用“逻辑总结”的优先级;缺失关键输入不转换成库存零。 */
|
||||
export function classifyShortageOrder(row: ClassificationInput): string {
|
||||
if (['退款关闭', 'closed'].includes(row.refundStatus?.trim().toLowerCase() ?? '')) return '异常订单-退款关闭'
|
||||
if (/信誉|虚拟/.test(row.category ?? '')) return '异常订单-信誉订单'
|
||||
if (!row.productionStatus?.trim()) return '异常订单-特殊或组合商品,待拆解'
|
||||
if (!known(row.totalShortage)) return '异常订单-待核实处理'
|
||||
// 用户确认:限定范围内原编码总库存 > 全货号需求时优先判为非真实缺货;
|
||||
// 沿用指定分类名称“大货仓”,不再要求库存仅位于正常大货仓。
|
||||
if (known(row.originalStock) && row.originalStock > row.totalShortage) return '非真实缺货-原商品编码大货仓有库存且能补齐缺货'
|
||||
if (!row.skuProductionStatus) return '异常订单-待核实处理'
|
||||
const { combinedStock, skuStock, replacementStock, combinedMainStock, combinedFrontStock, replacementMainStock } = row
|
||||
if (![combinedStock, skuStock, replacementStock, combinedMainStock, combinedFrontStock, replacementMainStock].every(known)) return '异常订单-待核实处理'
|
||||
// 原编码及换货编码无库存,但同货号其他编码仍有库存时,先核实订单。
|
||||
if (combinedStock === 0 && skuStock !== 0) return '异常订单-待核实处理'
|
||||
const primary = Math.max(combinedStock!, skuStock!)
|
||||
const replacement = replacementStock!
|
||||
const main = combinedMainStock!
|
||||
const front = combinedFrontStock!
|
||||
const replacementMain = replacementMainStock!
|
||||
const demand = row.totalShortage
|
||||
const noImageChange = /可替换|不换图/.test(row.imageChange ?? '')
|
||||
const special = specialLabels.some(label => row.labels?.includes(label))
|
||||
const hasExchange = Boolean(row.exchangeBarcode)
|
||||
const discontinued = row.skuProductionStatus !== '销售'
|
||||
|
||||
if (discontinued) {
|
||||
// 状态 0/1 是需求明确的文字标记,不满足清货库存 <=0;继续后续库存分类。
|
||||
// 真正缺失或无效的清货数据仍待核实,不能当作已清货或库存零。
|
||||
if (!known(row.clearanceStock) && row.clearanceStock !== '未填报清货库存') return '异常订单-待核实处理'
|
||||
if (known(row.clearanceStock) && row.clearanceStock <= 0) {
|
||||
if (primary <= 0 && replacement <= 0) {
|
||||
const retiredReplacementHasClearance = row.replacementStatus === '退市' &&
|
||||
(known(row.replacementClearanceStock) && row.replacementClearanceStock > 0)
|
||||
if (row.canReplace === '是' && (row.replacementStatus === '销售' || retiredReplacementHasClearance)) return '停产无库存-有替换款在售但暂无库存'
|
||||
return '停产无库存-无相同款或相似款库存'
|
||||
}
|
||||
if (main + replacementMain <= 0 && special) return '停产无库存-前置仓或有库存但不发特殊标签订单'
|
||||
if (primary <= 0 && replacement > 0) {
|
||||
if (replacement === demand) return '异常订单-待核实处理' // 原规则未定义恰好相等的边界。
|
||||
if (noImageChange) return replacement > demand
|
||||
? '停产无库存-有相同款库存且不换图且能补齐缺货'
|
||||
: '停产无库存-有相同款库存且无需换图但不能补齐缺货'
|
||||
return replacement > demand
|
||||
? '停产无库存-有相似款库存或有相同款库存但需换图或不确定是否换图但能补齐缺货'
|
||||
: '停产无库存-有相似款或相同款库存但需换图或不确定是否换图但不能补齐缺货'
|
||||
}
|
||||
if (combinedStock! > demand) return hasExchange
|
||||
? '停产无库存-含换货编码含前置仓库存可补齐缺货'
|
||||
: '停产无库存-原编码含前置仓库存可补齐缺货'
|
||||
}
|
||||
}
|
||||
if (primary <= 0 && replacement <= 0) return '缺货-无相同款或相似款库存'
|
||||
if (main + replacementMain <= 0 && special) return '缺货-前置仓或有库存但不发特殊标签订单'
|
||||
if ((primary <= 0 && replacement > demand) || (main <= 0 && replacementMain > demand)) return noImageChange
|
||||
? '缺货-有相同款库存且无需换图且能补齐缺货'
|
||||
: '缺货-有相似款或有相同款库存但需换图或不确定是否换图但能补齐缺货'
|
||||
if (primary <= 0 && replacement > 0 && replacement < demand) return noImageChange
|
||||
? '异常订单-待核实处理' // “逻辑总结”未给出此组合的处理关系,不能套用停产劝退建议。
|
||||
: '缺货-有相似款或有相同款库存但需换图或不确定是否换图但不能补齐缺货'
|
||||
if (main > demand) return hasExchange
|
||||
? '缺货-含换货编码大货仓有库存且能补齐缺货'
|
||||
: '非真实缺货-原商品编码大货仓有库存且能补齐缺货'
|
||||
if (main + front > demand) return hasExchange
|
||||
? '缺货-含换货编码含前置仓库存能补齐缺货'
|
||||
: '缺货-原商品编码含前置仓库存能补齐缺货'
|
||||
if (!hasExchange && noImageChange && main + replacementMain > demand) return '缺货-含相同款且不换图库存能补齐缺货'
|
||||
if (!hasExchange && noImageChange && primary + replacement > demand) return '缺货-含前置仓含相同款且不换图库存能补齐缺货'
|
||||
// 相等边界没有在原规则中定义,不自行按“足够”或“不足”派单。
|
||||
if ([primary, replacement, main, main + front, main + replacementMain].includes(demand)) return '异常订单-待核实处理'
|
||||
if (replacement === 0 && front === 0 && main < demand) return hasExchange
|
||||
? '缺货-含换货编码大货仓有库存但无法补齐缺货'
|
||||
: '缺货-原商品编码大货仓有库存但无法补齐缺货'
|
||||
if (replacement === 0 && main === 0 && front < demand) return hasExchange
|
||||
? '缺货-含换货编码前置仓有库存但无法补齐缺货'
|
||||
: '缺货-原商品编码前置仓有库存但无法补齐缺货'
|
||||
if (row.exceptionType === '真实缺货') return '缺货-京喜双仓缺货'
|
||||
return '异常订单-待核实处理'
|
||||
}
|
||||
|
||||
export function applyShortageClassification<T extends ClassificationInput>(rows: readonly T[]) {
|
||||
return rows.map(row => {
|
||||
const shortageCategory = classifyShortageOrder(row)
|
||||
const [suggestion, department] = actions[shortageCategory]
|
||||
return { ...row, shortageCategory, suggestion, department,
|
||||
shortageQuantity: shortageCategory.startsWith('缺货-') ? row.quantity : 0 }
|
||||
})
|
||||
}
|
||||
114
furniture-3d-system/src/lib/supply-chain-shortage-combo.test.ts
Normal file
114
furniture-3d-system/src/lib/supply-chain-shortage-combo.test.ts
Normal file
@ -0,0 +1,114 @@
|
||||
import { expandShortageOrderCombos, removeSupersededShortageOrderItems } from './supply-chain-shortage-combo'
|
||||
|
||||
describe('源系统已拆套装原行', () => {
|
||||
const parent = { id: 'OTHER:10249473:13434599', source: 'OTHER', internalOrderId: '10249473',
|
||||
outerItemId: 'platform-line', skuType: 'combine', comboParentBarcode: null, barcode: '运营组合套装12182', quantity: 0, itemStatus: null as string | null }
|
||||
const children = ['SJ038043N1410V01', 'SJ038044N1410V01', 'SJ038045N1410V01', 'SJ038020N1410V02'].map((barcode, index) => ({
|
||||
...parent, id: `OTHER:10249473:${13434600 + index}`, skuType: 'normal', comboParentBarcode: parent.barcode, barcode, quantity: 1,
|
||||
}))
|
||||
|
||||
it('retains the four component rows and removes the associated source parent regardless of row order or parent quantity', () => {
|
||||
for (const quantity of [0, 1, null]) {
|
||||
const rows = [...children.slice(0, 2), { ...parent, quantity }, ...children.slice(2)]
|
||||
expect(removeSupersededShortageOrderItems(rows)).toEqual(children)
|
||||
expect(rows).toHaveLength(5)
|
||||
}
|
||||
})
|
||||
|
||||
it.each([{ source: 'TAOBAO' }, { internalOrderId: 'other-order' }, { outerItemId: 'other-line' }, { comboParentBarcode: 'other-combo' }])(
|
||||
'does not link unrelated source, order, platform line or combo: %j', change => {
|
||||
const rows = [parent, { ...children[0], ...change }]
|
||||
expect(removeSupersededShortageOrderItems(rows)).toEqual(rows)
|
||||
},
|
||||
)
|
||||
|
||||
it('keeps an unexpanded parent, an ordinary zero-quantity item and an invalid self-reference', () => {
|
||||
expect(removeSupersededShortageOrderItems([parent])).toEqual([parent])
|
||||
const ordinary = { ...parent, skuType: 'normal' }
|
||||
expect(removeSupersededShortageOrderItems([ordinary, children[0]])).toEqual([ordinary, children[0]])
|
||||
const self = { ...children[0], barcode: parent.barcode }
|
||||
expect(removeSupersededShortageOrderItems([parent, self])).toEqual([parent, self])
|
||||
})
|
||||
|
||||
it('normalizes source codes and preserves child multiplicity when platform line IDs are absent', () => {
|
||||
const rows = [{ ...parent, barcode: ' zh-sj009523n430v01-2 ', outerItemId: null },
|
||||
{ ...children[0], barcode: 'SJ009523N430V01', outerItemId: null, comboParentBarcode: 'ZH-SJ009523N430V01-2' },
|
||||
{ ...children[0], id: 'OTHER:10249473:second', barcode: 'SJ009523N430V01', outerItemId: null, comboParentBarcode: 'ZH-SJ009523N430V01-2' }]
|
||||
const retained = removeSupersededShortageOrderItems(rows)
|
||||
expect(retained).toEqual(rows.slice(1))
|
||||
expect(expandShortageOrderCombos(retained)).toEqual(retained)
|
||||
expect(removeSupersededShortageOrderItems(retained)).toEqual(retained)
|
||||
})
|
||||
|
||||
it.each(['OTHER', 'TAOBAO'])('removes a normal Replaced line without combo links on source %s', source => {
|
||||
const original = { ...parent, source, barcode: 'MKHDNZ0409260601079+MKHSJ0425080100105', skuType: 'normal', itemStatus: 'Replaced' }
|
||||
const split = ['MKHDNZ0409260601079', 'MKHSJ0425080100105'].map((barcode, index) => ({
|
||||
...original, id: `split-${index}`, barcode, quantity: 1, itemStatus: null,
|
||||
}))
|
||||
const rows = [split[0], original, split[1]]
|
||||
expect(removeSupersededShortageOrderItems(rows)).toEqual(split)
|
||||
expect(rows).toHaveLength(3)
|
||||
})
|
||||
|
||||
it('removes every Replaced detail before ZH expansion even without visible successors or a platform line ID', () => {
|
||||
const original = { ...parent, barcode: 'ZH-SJ009523N430V01-2', quantity: 3, skuType: 'normal', outerItemId: null, itemStatus: ' replaced ' }
|
||||
expect(expandShortageOrderCombos(removeSupersededShortageOrderItems([original]))).toEqual([])
|
||||
})
|
||||
|
||||
it('retains active normal details including zero or unknown quantities and plus-sign codes', () => {
|
||||
const rows = [0, 1, null].map((quantity, index) => ({
|
||||
...parent, id: `normal-${index}`, barcode: 'A+B', quantity, skuType: 'normal', itemStatus: null,
|
||||
}))
|
||||
expect(removeSupersededShortageOrderItems(rows)).toEqual(rows)
|
||||
})
|
||||
|
||||
it('does not use replaced child details to remove an active combo parent', () => {
|
||||
const replacedChild = { ...children[0], itemStatus: 'Replaced' }
|
||||
expect(removeSupersededShortageOrderItems([parent, replacedChild])).toEqual([parent])
|
||||
})
|
||||
})
|
||||
|
||||
describe('缺货订单组合装拆行', () => {
|
||||
const row = { id: 'TAOBAO:1:2', barcode: 'ZH-SJ009523N430V01-2', quantity: 3, onlineOrderId: '000123', labels: '普通', refundStatus: null }
|
||||
|
||||
it('expands a two-piece combo into two component rows and preserves the purchased quantity on each', () => {
|
||||
const rows = expandShortageOrderCombos([row])
|
||||
expect(rows).toEqual([
|
||||
{ ...row, id: 'TAOBAO:1:2:combo:1:1', barcode: 'SJ009523N430V01' },
|
||||
{ ...row, id: 'TAOBAO:1:2:combo:1:2', barcode: 'SJ009523N430V01' },
|
||||
])
|
||||
expect(rows.reduce((sum, item) => sum + item.quantity, 0)).toBe(6)
|
||||
expect(row.barcode).toBe('ZH-SJ009523N430V01-2')
|
||||
expect(expandShortageOrderCombos(rows)).toEqual(rows)
|
||||
})
|
||||
|
||||
it('expands each component count and preserves prefixes and hyphens within component codes', () => {
|
||||
const rows = expandShortageOrderCombos([{ ...row, barcode: 'ZH-GBGJ-SJ038020N1410V02-2-PJ002801N799V01-1-GL001-SZ-1' }])
|
||||
expect(rows.map(item => item.barcode)).toEqual(['GBGJ-SJ038020N1410V02', 'GBGJ-SJ038020N1410V02', 'PJ002801N799V01', 'GL001-SZ'])
|
||||
expect(new Set(rows.map(item => item.id)).size).toBe(4)
|
||||
})
|
||||
|
||||
it('keeps repeated components and separate source lines distinct with stable identifiers', () => {
|
||||
const source = [{ ...row, barcode: 'ZH-SJ009523N430V01-1-SJ009523N430V01-2' }, { ...row, id: 'OTHER:1:2' }]
|
||||
const rows = expandShortageOrderCombos(source)
|
||||
expect(rows).toHaveLength(5)
|
||||
expect(new Set(rows.map(item => item.id)).size).toBe(5)
|
||||
expect(expandShortageOrderCombos(source)).toEqual(rows)
|
||||
})
|
||||
|
||||
it.each([0, null])('preserves zero or unknown order quantities: %s', quantity => {
|
||||
expect(expandShortageOrderCombos([{ ...row, quantity }]).map(item => item.quantity)).toEqual([quantity, quantity])
|
||||
})
|
||||
|
||||
it('matches the combo prefix without case sensitivity and normalizes component codes', () => {
|
||||
const rows = expandShortageOrderCombos([{ ...row, barcode: ' zh-cy000904N965V01-1-DNZ015467N68V01-1 ' }])
|
||||
expect(rows.map(item => item.barcode)).toEqual(['CY000904N965V01', 'DNZ015467N68V01'])
|
||||
})
|
||||
|
||||
it.each([null, '', 'SJ009523N430V01', 'SJ009523N430V01-2', 'GBGJ-SJ038020N1410V02', 'ZH-SJ009523N430V01', 'ZH-SJ009523N430V01-0', 'ZH-SJ009523N430V01--2', 'ZH-SJ009523N430V01-1-UNFINISHED', 'ZH-SJ009523N430V01-9007199254740992'])(
|
||||
'preserves ordinary or incomplete codes without partial expansion: %s', barcode => {
|
||||
const original = { ...row, barcode }
|
||||
expect(expandShortageOrderCombos([original])).toEqual([original])
|
||||
},
|
||||
)
|
||||
})
|
||||
53
furniture-3d-system/src/lib/supply-chain-shortage-combo.ts
Normal file
53
furniture-3d-system/src/lib/supply-chain-shortage-combo.ts
Normal file
@ -0,0 +1,53 @@
|
||||
type ComboOrder = { id: string; barcode: string | null }
|
||||
type SourceComboOrder = ComboOrder & {
|
||||
source: string
|
||||
internalOrderId: string
|
||||
outerItemId: string | null
|
||||
skuType: string | null
|
||||
comboParentBarcode: string | null
|
||||
itemStatus: string | null
|
||||
}
|
||||
|
||||
/** 已替换明细统一剔除;其余已拆套装按源组合关系移除原行,避免重复计数。 */
|
||||
export function removeSupersededShortageOrderItems<T extends SourceComboOrder>(rows: readonly T[]): T[] {
|
||||
const active = rows.filter(row => row.itemStatus?.trim().toLowerCase() !== 'replaced')
|
||||
const normalizeCode = (value: string | null) => value?.trim().toUpperCase() || ''
|
||||
const key = (row: T, barcode: string) => JSON.stringify([row.source, row.internalOrderId, row.outerItemId?.trim() || null, barcode])
|
||||
const expanded = new Set(active.flatMap(row => {
|
||||
const parent = normalizeCode(row.comboParentBarcode)
|
||||
const barcode = normalizeCode(row.barcode)
|
||||
return parent && barcode && parent !== barcode ? [key(row, parent)] : []
|
||||
}))
|
||||
return active.filter(row => row.skuType?.trim().toLowerCase() !== 'combine' || !expanded.has(key(row, normalizeCode(row.barcode))))
|
||||
}
|
||||
|
||||
/** ZH-编码-件数,可连续包含多个子编码;编码自身允许带字母前缀和连字符。 */
|
||||
function comboComponents(barcode: string | null) {
|
||||
const code = barcode?.trim()
|
||||
if (!code || !/^ZH-/i.test(code)) return null
|
||||
const components: { barcode: string; quantity: number }[] = []
|
||||
let parts: string[] = []
|
||||
for (const token of code.slice(3).split('-')) {
|
||||
if (!/^[a-z0-9]+$/i.test(token)) return null
|
||||
if (/^[0-9]+$/.test(token) && parts.length) {
|
||||
const quantity = Number(token)
|
||||
if (!Number.isSafeInteger(quantity) || quantity <= 0) return null
|
||||
components.push({ barcode: parts.join('-').toUpperCase(), quantity })
|
||||
parts = []
|
||||
} else parts.push(token)
|
||||
}
|
||||
return components.length && !parts.length ? components : null
|
||||
}
|
||||
|
||||
/** 在资料匹配和所有汇总前拆行;每行保留原订单购买套数,不再重复乘子件数。 */
|
||||
export function expandShortageOrderCombos<T extends ComboOrder>(rows: readonly T[]): T[] {
|
||||
return rows.flatMap(row => {
|
||||
const components = comboComponents(row.barcode)
|
||||
if (!components) return [row]
|
||||
return components.flatMap((component, componentIndex) => Array.from({ length: component.quantity }, (_, copyIndex) => ({
|
||||
...row,
|
||||
id: `${row.id}:combo:${componentIndex + 1}:${copyIndex + 1}`,
|
||||
barcode: component.barcode,
|
||||
})))
|
||||
})
|
||||
}
|
||||
@ -0,0 +1,150 @@
|
||||
import { buildShortageSupportingFields, indexShortageClearance, indexShortageInventory, indexShortageReplacements, type ShortageInventorySnapshot, type ShortageReplacementRule } from './supply-chain-shortage-enrichment'
|
||||
|
||||
const products = [
|
||||
{ barcode: '0001', sku: 'A', productStatus: '停产', productTag: '原标签' },
|
||||
{ barcode: '0002', sku: 'B', productStatus: '销售', productTag: '新标签' },
|
||||
{ barcode: '0003', sku: 'B', productStatus: '停产', productTag: '新标签二' },
|
||||
]
|
||||
const rule: ShortageReplacementRule = { id: 1, barcode: '0001', replacementBarcode: '0002', replacementType: 2, imageChange: 2, differences: '新颜色', createdAt: '2026-11-11 08:00:00' }
|
||||
const inventory: ShortageInventorySnapshot = {
|
||||
requestedBarcodes: ['0001', '0002', '0003', 'EMPTY'],
|
||||
inventory: [
|
||||
{ barcode: '0001', warehouseId: 1, quantity: 10, orderLock: 3 },
|
||||
{ barcode: '0001', warehouseId: 2, quantity: 5, orderLock: 0 },
|
||||
{ barcode: '0001', warehouseId: 3, quantity: 100, orderLock: 0 },
|
||||
{ barcode: '0002', warehouseId: 1, quantity: 8, orderLock: 1 },
|
||||
{ barcode: '0003', warehouseId: 2, quantity: 3, orderLock: 5 },
|
||||
],
|
||||
cloud: [{ barcode: '0001', warehouseId: 1, available: 2 }, { barcode: '0001', warehouseId: 1, available: 1 }],
|
||||
warehouses: [
|
||||
{ id: 1, name: '简尚仓', attribute: '成品发货仓-真实库存' },
|
||||
{ id: 2, name: '三方-南昌樵舍仓', attribute: '成品专用仓-真实库存' },
|
||||
{ id: 3, name: '三方-重庆西南仓', attribute: '成品专用仓-真实库存' },
|
||||
],
|
||||
}
|
||||
|
||||
describe('缺货明细库存与替换款', () => {
|
||||
it('deducts cloud reservations, keeps negative stock and uses the confirmed warehouse scope', () => {
|
||||
const stock = indexShortageInventory(inventory)
|
||||
expect(stock(['0001'])).toBe(9)
|
||||
expect(stock(['0001'], 'main')).toBe(4)
|
||||
expect(stock(['0001'], 'front')).toBe(5)
|
||||
expect(stock(['0003'])).toBe(-2)
|
||||
expect(stock(['0001', '0001', '0002'])).toBe(16)
|
||||
})
|
||||
|
||||
it('includes only the five exact attributes or the named front warehouse, counting overlaps once', () => {
|
||||
const warehouses = [
|
||||
{ id: 1, name: '大货', attribute: '成品发货仓-真实库存' },
|
||||
{ id: 2, name: '代发', attribute: ' 成品代发仓-虚拟库存 ' },
|
||||
{ id: 3, name: '半成品', attribute: '模块化商品项目-半成品仓-真实库存' },
|
||||
{ id: 4, name: '渠道', attribute: '渠道专用仓-真实库存' },
|
||||
{ id: 5, name: '临时', attribute: '临时仓-成品发货仓-真实库存' },
|
||||
{ id: 6, name: ' 三方-南昌樵舍仓 ', attribute: null },
|
||||
{ id: 7, name: '信誉仓', attribute: '信誉代发仓-虚拟库存' },
|
||||
{ id: 8, name: '三方-重庆西南仓', attribute: '成品专用仓-真实库存' },
|
||||
{ id: 9, name: '相似属性', attribute: '成品发货仓-真实库存(不可释放)' },
|
||||
{ id: 10, name: '未知属性', attribute: null },
|
||||
{ id: 11, name: '三方-南昌樵舍仓', attribute: '成品发货仓-真实库存' },
|
||||
]
|
||||
const stock = indexShortageInventory({ requestedBarcodes: ['A'], warehouses,
|
||||
inventory: [...warehouses.map(warehouse => ({ barcode: 'A', warehouseId: warehouse.id, quantity: warehouse.id <= 6 || warehouse.id === 11 ? 10 : null, orderLock: 1 })),
|
||||
{ barcode: 'A', warehouseId: 999, quantity: 100000, orderLock: 0 }],
|
||||
cloud: [{ barcode: 'A', warehouseId: 2, available: 2 }, { barcode: 'A', warehouseId: 8, available: null }],
|
||||
})
|
||||
expect(stock(['A'])).toBe(61) // 7个参与仓各9件,减代发仓云仓2件;其余仓完全排除。
|
||||
expect(stock(['A'], 'main')).toBe(18)
|
||||
expect(stock(['A'], 'front')).toBe(18)
|
||||
})
|
||||
|
||||
it('distinguishes a completed zero-row lookup from an unrequested or unknown stock value', () => {
|
||||
const stock = indexShortageInventory(inventory)
|
||||
expect(stock(['EMPTY'])).toBe(0)
|
||||
expect(stock(['NOT-REQUESTED'])).toBeNull()
|
||||
expect(stock([])).toBe(0)
|
||||
const unknown = indexShortageInventory({ ...inventory, inventory: [{ barcode: '0001', warehouseId: 1, quantity: null, orderLock: 1 }] })
|
||||
expect(unknown(['0001'])).toBeNull()
|
||||
expect(unknown(['0001'], 'main')).toBeNull()
|
||||
const zero = indexShortageInventory({ ...inventory, inventory: [{ barcode: '0001', warehouseId: 999, quantity: 0, orderLock: 0 }], cloud: [] })
|
||||
expect(zero(['0001'], 'main')).toBe(0)
|
||||
expect(zero(['0001'], 'front')).toBe(0)
|
||||
})
|
||||
|
||||
it('deduplicates original and exchange barcodes before adding stock', () => {
|
||||
const [row] = buildShortageSupportingFields([{ id: '1', barcode: '0001', sku: 'A', exchangeBarcode: '0001,0002' }], products, [rule], inventory, [])
|
||||
expect(row.combinedStock).toBe(16)
|
||||
expect(row.replacementStock).toBe(5) // 目标 B 货号下全部编码,含负库存。
|
||||
expect(row).toMatchObject({ replacementSku: 'B', replacementBarcode: '0002', replacementType: '相同款', imageChange: '不换图', differences: '新颜色', replacementLabels: '新标签', replacementStatus: '销售' })
|
||||
expect(row.feedback).toBeNull()
|
||||
expect(row.canReplace).toBeNull()
|
||||
expect(row.resolved).toBeNull()
|
||||
})
|
||||
|
||||
it('uses a forward rule before reverse matches and preserves precise barcode text', () => {
|
||||
const pick = indexShortageReplacements([rule, { ...rule, id: 2, barcode: '0004', replacementBarcode: '0001' }], products, indexShortageInventory(inventory))
|
||||
expect(pick(' 0001 ', 'A')?.target).toBe('0002')
|
||||
expect(pick('0002', 'B')?.target).toBe('0001')
|
||||
})
|
||||
|
||||
it('resolves same-style rules deterministically by latest creation and Id', () => {
|
||||
const pick = indexShortageReplacements([rule, { ...rule, id: 2, barcode: '0003', replacementBarcode: 'OTHER' }], products, indexShortageInventory(inventory))
|
||||
expect(pick('0005', 'B')?.target).toBe('OTHER')
|
||||
expect(pick('0002', 'B')?.target).toBe('0001') // 编码反向命中也优先于货号匹配。
|
||||
})
|
||||
|
||||
it('reads a SKU-only rule and selects the target variant with the most scoped public stock', () => {
|
||||
const profiles = [
|
||||
{ ...products[0], barcode: 'DNZ028907N866V01', sku: 'DNZ028907' },
|
||||
{ ...products[1], barcode: 'DNZ028915N866V01', sku: 'DNZ028915' },
|
||||
{ ...products[2], barcode: 'DNZ028915N887V01', sku: 'DNZ028915' },
|
||||
]
|
||||
const input: ShortageInventorySnapshot = { requestedBarcodes: profiles.map(product => product.barcode), cloud: [], warehouses: inventory.warehouses,
|
||||
inventory: [
|
||||
{ barcode: profiles[1].barcode, warehouseId: 1, quantity: 21, orderLock: 1 },
|
||||
{ barcode: profiles[2].barcode, warehouseId: 1, quantity: 10, orderLock: 1 },
|
||||
{ barcode: profiles[2].barcode, warehouseId: 3, quantity: 99999, orderLock: 0 },
|
||||
] }
|
||||
const rules = [{ ...rule, barcode: 'dnz028907', replacementBarcode: 'dnz028915' }]
|
||||
const [row] = buildShortageSupportingFields([{ id: '1', barcode: profiles[0].barcode, sku: profiles[0].sku, exchangeBarcode: null }], profiles, rules, input, [])
|
||||
expect(row).toMatchObject({ replacementSku: 'DNZ028915', replacementBarcode: 'DNZ028915N866V01', replacementStock: 29, replacementMainStock: 29, replacementFrontStock: 0, replacementLabels: '新标签' })
|
||||
})
|
||||
|
||||
it('keeps an exact barcode target even when a SKU rule or another target variant has more stock', () => {
|
||||
const rules = [rule, { ...rule, id: 9, barcode: 'A', replacementBarcode: 'B' }]
|
||||
const pick = indexShortageReplacements(rules, products, codes => codes[0] === '0003' ? 999 : 0)
|
||||
expect(pick('0001', 'A')).toMatchObject({ target: '0002', targetSku: 'B', rule })
|
||||
const stylePick = indexShortageReplacements([rule], products, codes => codes[0] === '0003' ? 999 : 0)
|
||||
expect(stylePick('ANOTHER-A', 'A')).toMatchObject({ target: '0003', targetSku: 'B' })
|
||||
})
|
||||
|
||||
it('resolves mixed code/SKU rules, reverse style matches, zero/tied/negative stock and unknown inventory', () => {
|
||||
const skuRule = { ...rule, barcode: 'A', replacementBarcode: 'B' }
|
||||
const allZero = indexShortageReplacements([skuRule], [...products].reverse(), () => 0)
|
||||
expect(allZero('0001', 'A')?.target).toBe('0002')
|
||||
expect(allZero('0003', 'B')).toMatchObject({ target: '0001', targetSku: 'A' })
|
||||
const negative = indexShortageReplacements([skuRule], products, codes => codes[0] === '0002' ? -4 : -2)
|
||||
expect(negative('0001', 'A')?.target).toBe('0003')
|
||||
const unknown = indexShortageReplacements([skuRule], products, () => null)
|
||||
expect(unknown('0001', 'A')).toMatchObject({ target: null, targetSku: 'B' })
|
||||
const mixed = indexShortageReplacements([{ ...rule, replacementBarcode: 'B' }], products, codes => codes[0] === '0003' ? 5 : null)
|
||||
expect(mixed('0001', 'A')?.target).toBe('0003')
|
||||
})
|
||||
|
||||
it('keeps replacement codes when the target archive is missing, with unknown metadata', () => {
|
||||
const [row] = buildShortageSupportingFields([{ id: '1', barcode: '0001', sku: 'A', exchangeBarcode: null }], products, [{ ...rule, replacementBarcode: 'MISSING' }], inventory, [])
|
||||
expect(row).toMatchObject({ replacementBarcode: 'MISSING', replacementSku: null, replacementLabels: null, replacementStock: null })
|
||||
})
|
||||
|
||||
it('uses the latest clearance state, preserving unknown and unreported values', () => {
|
||||
const clearance = indexShortageClearance([
|
||||
{ id: 1, barcode: '0001', state: 2, remainingStock: 7, updatedAt: '2026-11-10' },
|
||||
{ id: 2, barcode: '0001', state: 0, remainingStock: 0, updatedAt: '2026-11-11' },
|
||||
{ id: 3, barcode: '0002', state: 2, remainingStock: 0, updatedAt: '2026-11-11' },
|
||||
{ id: 4, barcode: '0003', state: 3, remainingStock: 99, updatedAt: '2026-11-11' },
|
||||
])
|
||||
expect(clearance(['0001'])).toBe('未填报清货库存')
|
||||
expect(clearance(['0002'])).toBe(0)
|
||||
expect(clearance(['0003'])).toBe(0)
|
||||
expect(clearance(['unknown'])).toBeNull()
|
||||
})
|
||||
})
|
||||
234
furniture-3d-system/src/lib/supply-chain-shortage-enrichment.ts
Normal file
234
furniture-3d-system/src/lib/supply-chain-shortage-enrichment.ts
Normal file
@ -0,0 +1,234 @@
|
||||
import { aggregateSkuProductionStatus } from './supply-chain-shortage-rules'
|
||||
|
||||
export type ShortageReplacementRule = {
|
||||
id: number
|
||||
barcode: string
|
||||
replacementBarcode: string
|
||||
replacementType: number | null
|
||||
imageChange: number | null
|
||||
differences: string | null
|
||||
createdAt: string | null
|
||||
}
|
||||
export type ShortageClearanceRecord = {
|
||||
id: number
|
||||
barcode: string
|
||||
state: number
|
||||
remainingStock: number | null
|
||||
updatedAt: string | null
|
||||
}
|
||||
export type ShortageInventorySnapshot = {
|
||||
requestedBarcodes: string[]
|
||||
inventory: { barcode: string; warehouseId: number; quantity: number | null; orderLock: number | null }[]
|
||||
cloud: { barcode: string; warehouseId: number; available: number | null }[]
|
||||
warehouses: { id: number; name: string; attribute: string | null }[]
|
||||
}
|
||||
export type ShortageProductProfile = {
|
||||
barcode: string
|
||||
sku: string
|
||||
productStatus: string | null
|
||||
productTag: string | null
|
||||
}
|
||||
|
||||
export const shortageCode = (value: string | null | undefined) => value?.trim().toUpperCase() ?? ''
|
||||
|
||||
/** 商品编码匹配优先;未命中编码时按货号匹配,并选目标货号公有可用库存最多的编码。 */
|
||||
export function indexShortageReplacements(
|
||||
rules: readonly ShortageReplacementRule[],
|
||||
products: readonly ShortageProductProfile[],
|
||||
stockFor: (codes: readonly string[]) => number | null,
|
||||
) {
|
||||
const byBarcode = new Map(products.map(product => [shortageCode(product.barcode), product]))
|
||||
const productsBySku = new Map<string, ShortageProductProfile[]>()
|
||||
for (const product of products) {
|
||||
const sku = shortageCode(product.sku)
|
||||
if (!sku) continue
|
||||
const group = productsBySku.get(sku) ?? []
|
||||
group.push(product)
|
||||
productsBySku.set(sku, group)
|
||||
}
|
||||
const skuOf = (token: string) => shortageCode(byBarcode.get(token)?.sku) || (productsBySku.has(token) ? token : '')
|
||||
const byCode = new Map<string, ShortageReplacementRule>()
|
||||
const bySku = new Map<string, ShortageReplacementRule>()
|
||||
const reverseByCode = new Map<string, ShortageReplacementRule>()
|
||||
const reverseBySku = new Map<string, ShortageReplacementRule>()
|
||||
const latest = (map: Map<string, ShortageReplacementRule>, key: string, rule: ShortageReplacementRule) => {
|
||||
if (!key) return
|
||||
const previous = map.get(key)
|
||||
if (!previous || (rule.createdAt ?? '') > (previous.createdAt ?? '') ||
|
||||
((rule.createdAt ?? '') === (previous.createdAt ?? '') && rule.id > previous.id)) map.set(key, rule)
|
||||
}
|
||||
for (const rule of rules) {
|
||||
const original = shortageCode(rule.barcode)
|
||||
const replacement = shortageCode(rule.replacementBarcode)
|
||||
if (!original || !replacement || original === replacement) continue
|
||||
if (byBarcode.has(original) || !productsBySku.has(original)) latest(byCode, original, rule)
|
||||
latest(bySku, skuOf(original), rule)
|
||||
if (byBarcode.has(replacement) || !productsBySku.has(replacement)) latest(reverseByCode, replacement, rule)
|
||||
latest(reverseBySku, skuOf(replacement), rule)
|
||||
}
|
||||
const bestBySku = new Map<string, string | null>()
|
||||
const bestBarcode = (sku: string) => {
|
||||
if (bestBySku.has(sku)) return bestBySku.get(sku)!
|
||||
let best: { code: string; stock: number } | null = null
|
||||
for (const product of productsBySku.get(sku) ?? []) {
|
||||
const code = shortageCode(product.barcode)
|
||||
const stock = stockFor([code])
|
||||
if (stock === null) continue // 未读取到的库存不能冒充零参与排名。
|
||||
if (!best || stock > best.stock || (stock === best.stock && code < best.code)) best = { code, stock }
|
||||
}
|
||||
const code = best?.code ?? null
|
||||
bestBySku.set(sku, code)
|
||||
return code
|
||||
}
|
||||
return (barcode: string | null, sku: string | null) => {
|
||||
const code = shortageCode(barcode)
|
||||
const style = shortageCode(sku)
|
||||
const exactForward = byCode.get(code)
|
||||
const exactReverse = reverseByCode.get(code)
|
||||
const styleForward = bySku.get(style)
|
||||
const rule = exactForward ?? exactReverse ?? styleForward ?? reverseBySku.get(style)
|
||||
if (!rule) return null
|
||||
const forward = exactForward || (!exactReverse && styleForward)
|
||||
const token = shortageCode(forward ? rule.replacementBarcode : rule.barcode)
|
||||
const targetSku = skuOf(token) || null
|
||||
const exactTarget = Boolean(exactForward || exactReverse) && byBarcode.has(token)
|
||||
const target = exactTarget || !targetSku ? token : bestBarcode(targetSku)
|
||||
return { rule, target, targetSku }
|
||||
}
|
||||
}
|
||||
|
||||
type Stock = { total: number | null; main: number | null; front: number | null }
|
||||
const replacementTypeLabels: Record<number, string> = { 1: '相似款', 2: '相同款' }
|
||||
const imageChangeLabels: Record<number, string> = { 1: '换图', 2: '不换图' }
|
||||
|
||||
export const SHORTAGE_INVENTORY_WAREHOUSE_ATTRIBUTES = [
|
||||
'成品发货仓-真实库存',
|
||||
'成品代发仓-虚拟库存',
|
||||
'模块化商品项目-半成品仓-真实库存',
|
||||
'渠道专用仓-真实库存',
|
||||
'临时仓-成品发货仓-真实库存',
|
||||
] as const
|
||||
const inventoryAttributes = new Set<string>(SHORTAGE_INVENTORY_WAREHOUSE_ATTRIBUTES)
|
||||
|
||||
/** 限定五类仓库属性或南昌樵舍仓;公有可用数 = 实际库存 - 订单占有 - 原云仓可用数。 */
|
||||
export function indexShortageInventory(snapshot: ShortageInventorySnapshot) {
|
||||
const requested = new Set(snapshot.requestedBarcodes.map(shortageCode))
|
||||
const warehouses = new Map(snapshot.warehouses.map(warehouse => [warehouse.id, warehouse]))
|
||||
const cloud = new Map<string, number | null>()
|
||||
for (const row of snapshot.cloud) {
|
||||
const key = JSON.stringify([shortageCode(row.barcode), row.warehouseId])
|
||||
const previous = cloud.get(key)
|
||||
cloud.set(key, row.available === null || previous === null ? null : (previous ?? 0) + row.available)
|
||||
}
|
||||
const byBarcode = new Map<string, Stock>()
|
||||
const add = (left: number | null, right: number | null) => left === null || right === null ? null : left + right
|
||||
for (const row of snapshot.inventory) {
|
||||
const code = shortageCode(row.barcode)
|
||||
if (!code) continue
|
||||
const warehouse = warehouses.get(row.warehouseId)
|
||||
if (!warehouse || (!inventoryAttributes.has(warehouse.attribute?.trim() ?? '') && warehouse.name.trim() !== '三方-南昌樵舍仓')) continue
|
||||
const reserved = cloud.get(JSON.stringify([code, row.warehouseId])) ?? 0
|
||||
const cloudKnown = cloud.get(JSON.stringify([code, row.warehouseId])) !== null
|
||||
const available = row.quantity === null || row.orderLock === null || !cloudKnown ? null : row.quantity - row.orderLock - reserved
|
||||
const stock = byBarcode.get(code) ?? { total: 0, main: 0, front: 0 }
|
||||
stock.total = add(stock.total, available)
|
||||
if (warehouse.attribute?.trim() === '成品发货仓-真实库存') stock.main = add(stock.main, available)
|
||||
if (warehouse.name.trim() === '三方-南昌樵舍仓') stock.front = add(stock.front, available)
|
||||
byBarcode.set(code, stock)
|
||||
}
|
||||
return (codes: readonly string[], field: keyof Stock = 'total'): number | null => {
|
||||
const unique = [...new Set(codes.map(shortageCode).filter(Boolean))]
|
||||
if (!unique.length) return 0 // 没有换货/替换关系是明确的空集合,与读取不到库存区分。
|
||||
let sum = 0
|
||||
for (const code of unique) {
|
||||
const stock = byBarcode.has(code) ? byBarcode.get(code)![field] : requested.has(code) ? 0 : null
|
||||
if (stock == null) return null
|
||||
sum += stock
|
||||
}
|
||||
return sum
|
||||
}
|
||||
}
|
||||
|
||||
export function indexShortageClearance(records: readonly ShortageClearanceRecord[]) {
|
||||
const latest = new Map<string, ShortageClearanceRecord>()
|
||||
for (const row of records) {
|
||||
const code = shortageCode(row.barcode)
|
||||
const previous = latest.get(code)
|
||||
if (!previous || (row.updatedAt ?? '') > (previous.updatedAt ?? '') ||
|
||||
((row.updatedAt ?? '') === (previous.updatedAt ?? '') && row.id > previous.id)) latest.set(code, row)
|
||||
}
|
||||
return (codes: readonly string[]): number | '未填报清货库存' | null => {
|
||||
const matched = [...new Set(codes.map(shortageCode).filter(Boolean))].flatMap(code => {
|
||||
const row = latest.get(code)
|
||||
return row ? [row] : []
|
||||
})
|
||||
if (!matched.length) return null
|
||||
if (matched.some(row => row.state === 0 || row.state === 1)) return '未填报清货库存'
|
||||
// 用户确认状态 3 为清货完成,按零;状态 2 数量缺失仍保持未知。
|
||||
if (matched.some(row => ![2, 3].includes(row.state) || (row.state === 2 && row.remainingStock === null))) return null
|
||||
return matched.reduce((sum, row) => sum + (row.state === 3 ? 0 : row.remainingStock!), 0)
|
||||
}
|
||||
}
|
||||
|
||||
export function buildShortageSupportingFields<T extends { id: string; barcode: string | null; sku: string | null; exchangeBarcode: string | null }>(
|
||||
rows: readonly T[],
|
||||
products: readonly ShortageProductProfile[],
|
||||
rules: readonly ShortageReplacementRule[],
|
||||
inventory: ShortageInventorySnapshot,
|
||||
clearance: readonly ShortageClearanceRecord[],
|
||||
) {
|
||||
const byBarcode = new Map(products.map(product => [shortageCode(product.barcode), product]))
|
||||
const bySku = new Map<string, ShortageProductProfile[]>()
|
||||
for (const product of products) {
|
||||
const key = shortageCode(product.sku)
|
||||
if (!key) continue
|
||||
const group = bySku.get(key) ?? []
|
||||
group.push(product)
|
||||
bySku.set(key, group)
|
||||
}
|
||||
const stockFor = indexShortageInventory(inventory)
|
||||
const replacementFor = indexShortageReplacements(rules, products, stockFor)
|
||||
const clearanceFor = indexShortageClearance(clearance)
|
||||
return rows.map(row => {
|
||||
const originalCodes = row.barcode ? [row.barcode] : []
|
||||
const exchangeCodes = row.exchangeBarcode?.split(',').filter(Boolean) ?? []
|
||||
const combined = [...originalCodes, ...exchangeCodes]
|
||||
const originalProducts = bySku.get(shortageCode(row.sku)) ?? []
|
||||
const matched = replacementFor(row.barcode, row.sku)
|
||||
const replacementProduct = matched?.target ? byBarcode.get(matched.target) : undefined
|
||||
const replacementSku = replacementProduct?.sku || matched?.targetSku || null
|
||||
const replacementProducts = replacementSku ? bySku.get(shortageCode(replacementSku)) ?? [] : []
|
||||
const replacementCodes = replacementProducts.length ? replacementProducts.map(product => product.barcode) : matched?.target ? [matched.target] : []
|
||||
const exchangeProducts = [...new Set(exchangeCodes.flatMap(code => {
|
||||
const sku = byBarcode.get(shortageCode(code))?.sku
|
||||
return sku ? bySku.get(shortageCode(sku)) ?? [] : []
|
||||
}))]
|
||||
const statusProducts = matched ? replacementProducts : exchangeProducts
|
||||
return {
|
||||
...row,
|
||||
clearanceStock: clearanceFor(originalProducts.map(product => product.barcode)),
|
||||
exchangeStock: stockFor(exchangeCodes),
|
||||
originalStock: originalCodes.length ? stockFor(originalCodes) : null,
|
||||
combinedStock: combined.length ? stockFor(combined) : null,
|
||||
skuStock: originalProducts.length ? stockFor(originalProducts.map(product => product.barcode)) : null,
|
||||
combinedMainStock: combined.length ? stockFor(combined, 'main') : null,
|
||||
combinedFrontStock: combined.length ? stockFor(combined, 'front') : null,
|
||||
replacementSku,
|
||||
replacementBarcode: matched?.target ?? null,
|
||||
replacementType: matched ? replacementTypeLabels[matched.rule.replacementType ?? 0] ?? null : null,
|
||||
imageChange: matched ? imageChangeLabels[matched.rule.imageChange ?? 0] ?? null : null,
|
||||
differences: matched?.rule.differences?.trim() || null,
|
||||
replacementStock: stockFor(replacementCodes),
|
||||
replacementMainStock: stockFor(replacementCodes, 'main'),
|
||||
replacementFrontStock: stockFor(replacementCodes, 'front'),
|
||||
replacementLabels: replacementProduct?.productTag || null,
|
||||
replacementStatus: statusProducts.length ? aggregateSkuProductionStatus(statusProducts.map(product => product.productStatus)) : null,
|
||||
replacementClearanceStock: clearanceFor(matched ? replacementCodes : exchangeProducts.map(product => product.barcode)),
|
||||
// 这些人工字段没有来源或持久化记录;保持显式空值,不默认“否”或“已解决”。
|
||||
feedback: null,
|
||||
canReplace: null,
|
||||
helper: null,
|
||||
resolved: null,
|
||||
}
|
||||
})
|
||||
}
|
||||
@ -0,0 +1,36 @@
|
||||
import { applyShortageExchangeRules } from './supply-chain-shortage-exchange'
|
||||
|
||||
describe('换货编码按原商品编码匹配换货目标', () => {
|
||||
const rule = { barcode: ' 000original ', exchangeBarcodes: ['000target'] }
|
||||
const products = [
|
||||
{ barcode: '000ORIGINAL', sku: '原货号', productTag: '原标签' },
|
||||
{ barcode: ' 000target ', sku: '目标货号', productTag: '目标标签' },
|
||||
]
|
||||
|
||||
it('normalizes both original keys and target lookups and preserves the order barcode', () => {
|
||||
const [row] = applyShortageExchangeRules([{ barcode: ' 000Original ', exchangeBarcode: null }], [rule], products)
|
||||
expect(row).toEqual({ barcode: ' 000Original ', exchangeBarcode: '000TARGET', exchangeSku: '目标货号', exchangeLabels: '目标标签' })
|
||||
})
|
||||
|
||||
it('does not infer reverse or same-style rules for other original barcodes', () => {
|
||||
const rows = applyShortageExchangeRules([{ barcode: '000TARGET' }, { barcode: 'OTHER', sku: '原货号' }], [rule], products)
|
||||
expect(rows.every(row => row.exchangeBarcode === null && row.exchangeSku === null && row.exchangeLabels === null)).toBe(true)
|
||||
})
|
||||
|
||||
it('returns the target barcode when its product archive is missing', () => {
|
||||
expect(applyShortageExchangeRules([{ barcode: '000ORIGINAL' }], [rule], [products[0]])[0])
|
||||
.toEqual({ barcode: '000ORIGINAL', exchangeBarcode: '000TARGET', exchangeSku: null, exchangeLabels: null })
|
||||
})
|
||||
|
||||
it('preserves all distinct targets in rule order and derives metadata from those targets', () => {
|
||||
const rules = [{ barcode: '000ORIGINAL', exchangeBarcodes: ['000target', '000SECOND', ' 000TARGET ', ''] }]
|
||||
const [row] = applyShortageExchangeRules([{ barcode: '000ORIGINAL' }], rules,
|
||||
[...products, { barcode: '000SECOND', sku: '目标货号', productTag: '第二标签' }])
|
||||
expect(row).toMatchObject({ exchangeBarcode: '000TARGET,000SECOND', exchangeSku: '目标货号', exchangeLabels: '目标标签;第二标签' })
|
||||
})
|
||||
|
||||
it('keeps rows without an original code or matching rule empty', () => {
|
||||
const rows = applyShortageExchangeRules([{ barcode: null }, { barcode: 'UNMATCHED' }], [rule], products)
|
||||
expect(rows.every(row => row.exchangeBarcode === null)).toBe(true)
|
||||
})
|
||||
})
|
||||
@ -0,0 +1,35 @@
|
||||
export type ShortageExchangeRule = {
|
||||
/** rpt.jst_sku_replace_rule.sku_id:原商品编码。 */
|
||||
barcode: string
|
||||
/** rpt.jst_sku_replace_rule.data:换货目标编码。 */
|
||||
exchangeBarcodes: string[]
|
||||
}
|
||||
|
||||
type ExchangeProduct = { barcode: string; sku: string | null; productTag: string | null }
|
||||
const codeKey = (code: string | null | undefined) => code?.trim().toUpperCase() ?? ''
|
||||
|
||||
/** 本行商品编码只匹配规则原编码;目标编码独立于产品档案返回。 */
|
||||
export function applyShortageExchangeRules<T extends { barcode: string | null }>(
|
||||
rows: readonly T[],
|
||||
rules: readonly ShortageExchangeRule[],
|
||||
products: readonly ExchangeProduct[],
|
||||
) {
|
||||
const targetsByOriginal = new Map(rules.map(rule => [
|
||||
codeKey(rule.barcode),
|
||||
[...new Set(rule.exchangeBarcodes.map(codeKey).filter(Boolean))],
|
||||
]))
|
||||
const productsByBarcode = new Map(products.map(product => [codeKey(product.barcode), product]))
|
||||
return rows.map(row => {
|
||||
const targets = targetsByOriginal.get(codeKey(row.barcode)) ?? []
|
||||
const targetProducts = targets.flatMap(target => {
|
||||
const product = productsByBarcode.get(target)
|
||||
return product ? [product] : []
|
||||
})
|
||||
return {
|
||||
...row,
|
||||
exchangeBarcode: targets.join(',') || null,
|
||||
exchangeSku: [...new Set(targetProducts.map(product => product.sku?.trim()).filter(Boolean))].join('、') || null,
|
||||
exchangeLabels: [...new Set(targetProducts.map(product => product.productTag?.trim()).filter(Boolean))].join(';') || null,
|
||||
}
|
||||
})
|
||||
}
|
||||
@ -0,0 +1,56 @@
|
||||
/** @jest-environment node */
|
||||
import JSZip from 'jszip'
|
||||
import * as XLSX from 'xlsx'
|
||||
import { parseShortageOrderImport, SHORTAGE_IMPORT_COLUMNS } from './supply-chain-shortage-order-import'
|
||||
|
||||
const columns = Object.keys(SHORTAGE_IMPORT_COLUMNS) as (keyof typeof SHORTAGE_IMPORT_COLUMNS)[]
|
||||
const sample = {
|
||||
orderType: '普通订单', internalOrderId: '10354383', onlineOrderId: '3692498019828213',
|
||||
category: '住宅家具 - 书架', sku: 'MKHSJ0425080100326', barcode: '00001234567890123456789',
|
||||
productName: '书架', productionStatus: '销售', supplier: '甲', packageType: '', quantity: '1',
|
||||
exceptionType: '缺货', platform: '京东商城', shopName: '店铺甲', paidAt: '2026-11-24 06:27:39',
|
||||
shopProductCode: '0000000001', labels: '晚发赔',
|
||||
}
|
||||
function file(rows: Partial<typeof sample>[], header = Object.values(SHORTAGE_IMPORT_COLUMNS) as string[]) {
|
||||
const workbook = XLSX.utils.book_new()
|
||||
XLSX.utils.book_append_sheet(workbook, XLSX.utils.aoa_to_sheet([header, ...rows.map(row => columns.map(key => ({ ...sample, ...row })[key]))]), '订单')
|
||||
return XLSX.write(workbook, { type: 'buffer', bookType: 'xlsx' }) as Buffer
|
||||
}
|
||||
|
||||
describe('聚水潭网页导出订单导入', () => {
|
||||
it('preserves all 17 file fields, identifier precision, leading zeroes, and explicit blanks', async () => {
|
||||
const result = await parseShortageOrderImport(file([{}]), '订单_20261124173004_1.xlsx')
|
||||
expect(result.rows[0]).toMatchObject({ ...sample, quantity: 1, packageType: null, orderStatus: 'Question' })
|
||||
expect(result.importedRows).toBe(1)
|
||||
})
|
||||
|
||||
it('keeps replenishment orders and excludes entire accessory or brush orders and other exception types', async () => {
|
||||
const result = await parseShortageOrderImport(file([
|
||||
{ internalOrderId: '1', labels: '刷单' }, { internalOrderId: '1' },
|
||||
{ internalOrderId: '2', orderType: '补发订单' }, { internalOrderId: '3', exceptionType: '暂停发货' },
|
||||
{ internalOrderId: '4', exceptionType: '真实缺货' }, { internalOrderId: '5', exceptionType: '预售' },
|
||||
{ internalOrderId: '6', orderType: '配件订单' }, { internalOrderId: '6' },
|
||||
{ internalOrderId: '7', orderType: '售后补发', labels: '刷单' },
|
||||
{ internalOrderId: '8', productName: '含配件的书架', category: '配件收纳' },
|
||||
]), '订单_任意日期.xlsx')
|
||||
expect(result.rows.map(row => row.internalOrderId)).toEqual(['2', '4', '5', '8'])
|
||||
expect(result.excludedRows).toBe(6)
|
||||
})
|
||||
|
||||
it('accepts a valid empty export but rejects missing columns, unsafe identifiers and invalid quantities', async () => {
|
||||
expect((await parseShortageOrderImport(file([]), '订单.xlsx')).rows).toEqual([])
|
||||
await expect(parseShortageOrderImport(file([{}], ['错误模板']), '订单.xlsx')).rejects.toThrow('17列')
|
||||
await expect(parseShortageOrderImport(file([{ onlineOrderId: '3.69249801982821E+15' }]), '订单.xlsx')).rejects.toThrow('科学计数法')
|
||||
await expect(parseShortageOrderImport(file([{ quantity: '' }]), '订单.xlsx')).rejects.toThrow('数量')
|
||||
await expect(parseShortageOrderImport(file([{}]), '旧数据.xlsx')).rejects.toThrow('订单')
|
||||
})
|
||||
|
||||
it('reads the CDATA inline strings used by the real web export after ZIP normalization', async () => {
|
||||
const zip = await JSZip.loadAsync(file([{}]))
|
||||
const name = 'xl/worksheets/sheet1.xml'
|
||||
const xml = await zip.file(name)!.async('string')
|
||||
zip.file(name, xml.replace(/<t>([^<]*)<\/t>/g, '<t><![CDATA[$1]]></t>'))
|
||||
const result = await parseShortageOrderImport(await zip.generateAsync({ type: 'nodebuffer' }), '订单.xlsx')
|
||||
expect(result.rows[0].onlineOrderId).toBe(sample.onlineOrderId)
|
||||
})
|
||||
})
|
||||
@ -0,0 +1,92 @@
|
||||
import JSZip from 'jszip'
|
||||
import * as XLSX from 'xlsx'
|
||||
import type { ShortageSourceRow } from '@/server/repositories/supply-chain-shortage-order.repository'
|
||||
|
||||
export const SHORTAGE_IMPORT_COLUMNS = {
|
||||
orderType: '订单类型', internalOrderId: '内部订单号', onlineOrderId: '线上订单号',
|
||||
category: '分类', sku: '货号', barcode: '商品编码', productName: '商品名称',
|
||||
productionStatus: '生产状态', supplier: '供应商', packageType: '单双包', quantity: '数量',
|
||||
exceptionType: '异常类型', platform: '平台站点', shopName: '店铺名称', paidAt: '付款日期',
|
||||
shopProductCode: '店铺商品编码', labels: '标签',
|
||||
} as const
|
||||
export type ShortageImportedOrder = ShortageSourceRow & {
|
||||
category: string | null; sku: string | null; productName: string | null
|
||||
productionStatus: string | null; supplier: string | null; packageType: string | null
|
||||
}
|
||||
|
||||
const MAX_FILE_BYTES = 20 * 1024 * 1024
|
||||
const MAX_EXPANDED_BYTES = 80 * 1024 * 1024
|
||||
const exceptionTypes = new Set(['缺货', '真实缺货', '预售'])
|
||||
const text = (value: unknown) => String(value ?? '').trim() || null
|
||||
|
||||
/** 聚水潭使用 ZIP64 导出;先由 JSZip 解包并重新封装,再交给现有表格解析器。 */
|
||||
async function readableWorkbook(content: Buffer) {
|
||||
if (!content.length || content.length > MAX_FILE_BYTES) throw new Error('订单文件需小于20MB且不能为空')
|
||||
if (content[0] !== 0x50 || content[1] !== 0x4b) throw new Error('请选择聚水潭导出的xlsx订单文件')
|
||||
const zip = await JSZip.loadAsync(content)
|
||||
let expanded = 0
|
||||
const normalized = new JSZip()
|
||||
for (const entry of Object.values(zip.files)) {
|
||||
if (entry.dir) continue
|
||||
// ZIP 元数据中的展开尺寸先校验,避免解析异常文件时分配超大内存。
|
||||
const size = (entry as unknown as { _data?: { uncompressedSize?: number } })._data?.uncompressedSize
|
||||
if (size !== undefined && (!Number.isSafeInteger(size) || size < 0 || size > MAX_EXPANDED_BYTES - expanded)) throw new Error('订单文件展开后过大')
|
||||
const data = await entry.async('nodebuffer')
|
||||
expanded += data.length
|
||||
if (expanded > MAX_EXPANDED_BYTES) throw new Error('订单文件展开后过大')
|
||||
normalized.file(entry.name, data)
|
||||
}
|
||||
return XLSX.read(await normalized.generateAsync({ type: 'nodebuffer', compression: 'STORE' }), { type: 'buffer', cellDates: false })
|
||||
}
|
||||
|
||||
/** 只接收模板中的订单数据;不根据缺失值向旧订单数据库回填基础字段。 */
|
||||
export async function parseShortageOrderImport(content: Buffer, filename: string) {
|
||||
if (!/^订单.*\.xlsx$/i.test(filename)) throw new Error('请选择文件名以“订单”开头的xlsx导出文件')
|
||||
const workbook = await readableWorkbook(content)
|
||||
const required = Object.values(SHORTAGE_IMPORT_COLUMNS)
|
||||
const candidates = workbook.SheetNames.map(name => {
|
||||
const matrix = XLSX.utils.sheet_to_json<unknown[]>(workbook.Sheets[name], { header: 1, raw: false, defval: '', blankrows: false })
|
||||
const headerIndex = matrix.slice(0, 10).findIndex(row => required.every(label => row.some(cell => text(cell) === label)))
|
||||
return { matrix, headerIndex }
|
||||
}).filter(candidate => candidate.headerIndex >= 0)
|
||||
if (candidates.length !== 1) throw new Error('订单文件应包含唯一的“缺货报表看板”明细表,且完整包含订单类型至标签的17列')
|
||||
const { matrix, headerIndex } = candidates[0]
|
||||
const headers = matrix[headerIndex].map(value => text(value) ?? '')
|
||||
if (required.some(label => headers.filter(header => header === label).length !== 1)) throw new Error('订单文件存在重复字段,请重新导出')
|
||||
const column = Object.fromEntries(Object.entries(SHORTAGE_IMPORT_COLUMNS).map(([key, label]) => [key, headers.indexOf(label)])) as Record<keyof typeof SHORTAGE_IMPORT_COLUMNS, number>
|
||||
const rows: ShortageImportedOrder[] = []
|
||||
const excludedOrders = new Set<string>()
|
||||
let excludedRows = 0
|
||||
for (let offset = headerIndex + 1; offset < matrix.length; offset++) {
|
||||
const values = matrix[offset]
|
||||
if (values.every(value => text(value) === null)) continue
|
||||
const get = (key: keyof typeof column) => text(values[column[key]])
|
||||
const internalOrderId = get('internalOrderId')
|
||||
if (!internalOrderId || !/^\d+$/.test(internalOrderId)) throw new Error(`第${offset + 1}行内部订单号为空或格式不正确`)
|
||||
const onlineOrderId = get('onlineOrderId')
|
||||
if (onlineOrderId && /[eE][+-]?\d+$/.test(onlineOrderId)) throw new Error(`第${offset + 1}行线上订单号为科学计数法,请重新导出文本订单号`)
|
||||
const statusIndex = headers.indexOf('状态')
|
||||
const status = statusIndex < 0 ? null : text(values[statusIndex])
|
||||
const orderType = get('orderType')
|
||||
const labels = get('labels')
|
||||
const exceptionType = get('exceptionType')
|
||||
if (labels?.includes('刷单') || orderType?.includes('配件')) excludedOrders.add(internalOrderId)
|
||||
if (!exceptionTypes.has(exceptionType ?? '') || (status && !['Question', '异常'].includes(status))) { excludedRows++; continue }
|
||||
const rawQuantity = get('quantity')
|
||||
const quantity = rawQuantity === null ? null : Number(rawQuantity.replace(/,/g, ''))
|
||||
if (quantity === null || !Number.isFinite(quantity) || quantity < 0) throw new Error(`第${offset + 1}行数量为空或无效`)
|
||||
const barcode = get('barcode')
|
||||
if (!barcode) throw new Error(`第${offset + 1}行商品编码为空`)
|
||||
const id = `IMPORT:${internalOrderId}:${offset + 1}`
|
||||
rows.push({ id, source: 'OTHER', itemId: `sheet-${offset + 1}`, internalOrderId, onlineOrderId, orderType,
|
||||
category: get('category'), sku: get('sku'), barcode, productName: get('productName'),
|
||||
productionStatus: get('productionStatus'), supplier: get('supplier'), packageType: get('packageType'),
|
||||
quantity, exceptionType: exceptionType!, orderStatus: 'Question', platform: get('platform'), shopName: get('shopName'),
|
||||
paidAt: get('paidAt'), shopProductCode: get('shopProductCode'), labels,
|
||||
refundStatus: headers.includes('退款状态') ? text(values[headers.indexOf('退款状态')]) : null,
|
||||
skuType: null, comboParentBarcode: null, outerItemId: null, itemStatus: null,
|
||||
})
|
||||
}
|
||||
const included = rows.filter(row => !excludedOrders.has(row.internalOrderId))
|
||||
return { rows: included, importedRows: included.length, excludedRows: excludedRows + rows.length - included.length }
|
||||
}
|
||||
@ -0,0 +1,23 @@
|
||||
import { z } from 'zod'
|
||||
import type { ShortageOrderDataRow } from './supply-chain-shortage-orders'
|
||||
|
||||
const text = z.string().nullable()
|
||||
const number = z.number().nullable()
|
||||
const clearance = z.union([z.number(), z.literal('未填报清货库存')]).nullable()
|
||||
|
||||
/** 保存与读取同一份完整 DTO;未知、零、负值及编码文本均按原值冻结。 */
|
||||
export const shortageOrderSnapshotRowsSchema: z.ZodType<ShortageOrderDataRow[]> = z.array(z.object({
|
||||
id: z.string(), internalOrderId: z.string(), onlineOrderId: text, orderType: text,
|
||||
barcode: text, quantity: number, exceptionType: z.string(), orderStatus: text,
|
||||
platform: text, shopName: text, paidAt: text, shopProductCode: text, labels: text, refundStatus: text,
|
||||
sku: text, category: text, productName: text, productionStatus: text, supplier: text, purchaser: text,
|
||||
packageType: text, originalProductLabels: text, orderSkuKey: text, orderSkuQuantity: number,
|
||||
exchangeSku: text, exchangeBarcode: text, exchangeLabels: text, skuProductionStatus: text,
|
||||
totalShortage: number, clearanceStock: clearance, exchangeStock: number, originalStock: number,
|
||||
combinedStock: number, skuStock: number, combinedMainStock: number, combinedFrontStock: number,
|
||||
replacementSku: text, replacementBarcode: text, replacementType: text, imageChange: text, differences: text,
|
||||
replacementStock: number, replacementMainStock: number, replacementFrontStock: number, replacementLabels: text,
|
||||
replacementStatus: text, replacementClearanceStock: clearance, feedback: text, canReplace: text,
|
||||
helper: text, resolved: text, shortageCategory: z.string(), suggestion: z.string(), department: z.string(),
|
||||
shortageQuantity: number,
|
||||
}))
|
||||
88
furniture-3d-system/src/lib/supply-chain-shortage-orders.ts
Normal file
88
furniture-3d-system/src/lib/supply-chain-shortage-orders.ts
Normal file
@ -0,0 +1,88 @@
|
||||
/** 订单明细读取接口 DTO。订单号和编码始终以文本传输。 */
|
||||
export type ShortageOrderDataRow = {
|
||||
id: string
|
||||
internalOrderId: string
|
||||
onlineOrderId: string | null
|
||||
orderType: string | null
|
||||
barcode: string | null
|
||||
quantity: number | null
|
||||
exceptionType: string
|
||||
orderStatus: string | null
|
||||
platform: string | null
|
||||
shopName: string | null
|
||||
paidAt: string | null
|
||||
shopProductCode: string | null
|
||||
labels: string | null
|
||||
refundStatus: string | null
|
||||
sku: string | null
|
||||
category: string | null
|
||||
productName: string | null
|
||||
productionStatus: string | null
|
||||
supplier: string | null
|
||||
purchaser: string | null
|
||||
packageType: string | null
|
||||
originalProductLabels: string | null
|
||||
orderSkuKey: string | null
|
||||
orderSkuQuantity: number | null
|
||||
exchangeSku: string | null
|
||||
exchangeBarcode: string | null
|
||||
exchangeLabels: string | null
|
||||
skuProductionStatus: string | null
|
||||
totalShortage: number | null
|
||||
clearanceStock: number | '未填报清货库存' | null
|
||||
exchangeStock: number | null
|
||||
originalStock: number | null
|
||||
combinedStock: number | null
|
||||
skuStock: number | null
|
||||
combinedMainStock: number | null
|
||||
combinedFrontStock: number | null
|
||||
replacementSku: string | null
|
||||
replacementBarcode: string | null
|
||||
replacementType: string | null
|
||||
imageChange: string | null
|
||||
differences: string | null
|
||||
replacementStock: number | null
|
||||
replacementMainStock: number | null
|
||||
replacementFrontStock: number | null
|
||||
replacementLabels: string | null
|
||||
replacementStatus: string | null
|
||||
replacementClearanceStock: number | '未填报清货库存' | null
|
||||
feedback: string | null
|
||||
canReplace: string | null
|
||||
helper: string | null
|
||||
resolved: string | null
|
||||
shortageCategory: string
|
||||
suggestion: string
|
||||
department: string
|
||||
shortageQuantity: number | null
|
||||
}
|
||||
|
||||
export type ShortageOrderSnapshot = {
|
||||
rows: ShortageOrderDataRow[]
|
||||
fetchedAt: string
|
||||
}
|
||||
|
||||
export type ShortageOrderDailySnapshot = ShortageOrderSnapshot & {
|
||||
generatedOn: string
|
||||
generatedAt: string
|
||||
}
|
||||
|
||||
export type ShortageSnapshotRefreshState =
|
||||
| { status: 'loading'; progress?: ShortageReadProgress }
|
||||
| { status: 'error'; message: string }
|
||||
|
||||
export type ShortageOrderDailyReadState = (
|
||||
| { status: 'ready'; snapshot: ShortageOrderDailySnapshot }
|
||||
| { status: 'empty'; message: string }
|
||||
) & { refresh?: ShortageSnapshotRefreshState; dates?: string[] }
|
||||
|
||||
export type ShortageReadProgress = {
|
||||
stage: 'orders' | 'items' | 'archive' | 'download' | 'import'
|
||||
completed: number
|
||||
total: number
|
||||
}
|
||||
|
||||
export type ShortageOrderReadState =
|
||||
| { status: 'loading'; progress: ShortageReadProgress }
|
||||
| { status: 'ready'; snapshot: ShortageOrderSnapshot }
|
||||
| { status: 'error'; message: string }
|
||||
@ -0,0 +1,76 @@
|
||||
import { aggregateShortageReport, type ShortageReportProduct } from './supply-chain-shortage-report-aggregation'
|
||||
import type { ShortageOrderDataRow } from './supply-chain-shortage-orders'
|
||||
import { buildShortageSupportingFields, type ShortageInventorySnapshot } from './supply-chain-shortage-enrichment'
|
||||
import { applyShortageClassification } from './supply-chain-shortage-classification'
|
||||
|
||||
const order = { id: 'one', barcode: '0001234567890123456789', sku: 'A', quantity: 100, totalShortage: 900, shortageQuantity: 4, replacementSku: 'B' } as ShortageOrderDataRow
|
||||
const product: ShortageReportProduct = { barcode: order.barcode!, sku: 'A', productName: '柜', productStatus: '停产', supplierName: '甲' }
|
||||
const products = [product, { ...product, barcode: 'a2', productStatus: '销售' }, { ...product, barcode: 'b1', sku: 'B' }]
|
||||
const inventory: ShortageInventorySnapshot = {
|
||||
requestedBarcodes: products.map(row => row.barcode), cloud: [],
|
||||
warehouses: [{ id: 1, name: '大货仓', attribute: '成品发货仓-真实库存' }, { id: 2, name: '前置', attribute: '前置仓' }],
|
||||
inventory: [
|
||||
{ barcode: product.barcode, warehouseId: 1, quantity: 3, orderLock: 1 },
|
||||
{ barcode: 'a2', warehouseId: 1, quantity: 1, orderLock: 0 },
|
||||
{ barcode: product.barcode, warehouseId: 2, quantity: 100, orderLock: 0 },
|
||||
{ barcode: 'b1', warehouseId: 1, quantity: 10, orderLock: 0 },
|
||||
],
|
||||
}
|
||||
const buyers = [{ supplier: '甲', purchaser: '乙' }]
|
||||
const date = '2026-11-12'
|
||||
|
||||
it('sums AY by barcode, keeps text precision, deduplicates full-SKU stock and reads purchaser from supplier', () => {
|
||||
const rows = aggregateShortageReport([order, { ...order, id: 'two', shortageQuantity: 5 }], products, inventory, buyers, date)
|
||||
expect(rows).toHaveLength(1)
|
||||
expect(rows[0]).toMatchObject({ barcode: '0001234567890123456789', shortageQuantity: 9, stock: 3, realShortage: 6, skuProductionStatus: '销售', productionStatus: '停产', purchaser: '乙', productName: '柜', replacementStock: 10 })
|
||||
})
|
||||
|
||||
it('subtracts cloud reservations and signed warehouses before the final stock display', () => {
|
||||
const input = { ...inventory, cloud: [{ barcode: product.barcode, warehouseId: 1, available: 1 }], inventory: [...inventory.inventory, { barcode: 'a2', warehouseId: 1, quantity: -4, orderLock: 0 }] }
|
||||
expect(aggregateShortageReport([order], products, input, buyers, date)[0]).toMatchObject({ stock: -2, realShortage: 6 })
|
||||
})
|
||||
|
||||
it('removes non-shortage rows only after aggregating AY', () => {
|
||||
expect(aggregateShortageReport([{ ...order, shortageQuantity: 3 }], products, inventory, buyers, date)).toEqual([])
|
||||
expect(aggregateShortageReport([{ ...order, shortageQuantity: 0 }], products, inventory, buyers, date)).toEqual([])
|
||||
expect(aggregateShortageReport([{ ...order, shortageQuantity: 0 }], [], inventory, buyers, date)).toEqual([])
|
||||
const negative = { ...inventory, inventory: [{ barcode: product.barcode, warehouseId: 1, quantity: -5, orderLock: 0 }] }
|
||||
expect(aggregateShortageReport([{ ...order, shortageQuantity: 0 }], products, negative, buyers, date)).toEqual([])
|
||||
})
|
||||
|
||||
it('clears same-SKU replacement fields while keeping the original shortage', () => {
|
||||
expect(aggregateShortageReport([{ ...order, replacementSku: ' A ' }], products, inventory, buyers, date)[0]).toMatchObject({ replacementSku: null, replacementStock: null, replacementTransit: null, realShortage: 1 })
|
||||
})
|
||||
|
||||
it('uses the explicit Excel purchaser default only for an unmatched supplier, keeping matched blank values blank', () => {
|
||||
expect(aggregateShortageReport([order], products, inventory, [], date)[0].purchaser).toBe('宁珂')
|
||||
expect(aggregateShortageReport([order], products, inventory, [{ supplier: '甲', purchaser: null }], date)[0].purchaser).toBeNull()
|
||||
})
|
||||
|
||||
it('preserves unknown source quantities and missing archive inventory rather than inventing zero', () => {
|
||||
const rows = aggregateShortageReport([{ ...order, shortageQuantity: null }], [], inventory, [], date)
|
||||
expect(rows[0]).toMatchObject({ shortageQuantity: null, stock: null, realShortage: null, replacementStock: null })
|
||||
})
|
||||
|
||||
it.each([
|
||||
{ state: 0, remainingStock: null, included: true },
|
||||
{ state: 1, remainingStock: null, included: true },
|
||||
{ state: 2, remainingStock: null, included: false },
|
||||
{ state: 2, remainingStock: 0, included: false },
|
||||
{ state: 3, remainingStock: 99, included: false },
|
||||
])('carries clearance state $state ($remainingStock) through detail classification into the report', ({ state, remainingStock, included }) => {
|
||||
const retired = { ...product, productStatus: '退市', productTag: null }
|
||||
const source = { ...order, quantity: 2, totalShortage: 2, skuProductionStatus: '退市', productionStatus: '退市', category: '电脑桌', refundStatus: null, labels: null, exceptionType: '缺货', exchangeBarcode: null }
|
||||
const stock: ShortageInventorySnapshot = { requestedBarcodes: [retired.barcode], inventory: [], cloud: [], warehouses: [] }
|
||||
const enriched = buildShortageSupportingFields([source], [retired], [], stock, [{ id: 1, barcode: retired.barcode, state, remainingStock, updatedAt: '2026-11-12' }])
|
||||
const details = applyShortageClassification(enriched)
|
||||
const report = aggregateShortageReport(details, [retired], stock, buyers, date)
|
||||
if (included) {
|
||||
expect(details[0]).toMatchObject({ clearanceStock: '未填报清货库存', shortageCategory: '缺货-无相同款或相似款库存', shortageQuantity: 2 })
|
||||
expect(report).toHaveLength(1)
|
||||
expect(report[0]).toMatchObject({ barcode: retired.barcode, productionStatus: '退市', shortageQuantity: 2, stock: 0, realShortage: 2 })
|
||||
} else {
|
||||
expect(details[0].shortageQuantity).toBe(0)
|
||||
expect(report).toEqual([])
|
||||
}
|
||||
})
|
||||
@ -0,0 +1,60 @@
|
||||
import type { ShortageOrderDataRow } from './supply-chain-shortage-orders'
|
||||
import { aggregateSkuProductionStatus } from './supply-chain-shortage-rules'
|
||||
import { indexShortageInventory, shortageCode, type ShortageInventorySnapshot } from './supply-chain-shortage-enrichment'
|
||||
import { prepareShortageReportRows, type ShortageReportRow } from './supply-chain-shortage-report'
|
||||
|
||||
export type ShortageReportProduct = {
|
||||
barcode: string; sku: string; productName: string | null; productStatus: string | null; supplierName: string | null
|
||||
}
|
||||
|
||||
/** AY 按编码相加;库存按全货号去重汇总一次,不因订单条数重复累加。 */
|
||||
export function aggregateShortageReport(
|
||||
details: readonly ShortageOrderDataRow[], products: readonly ShortageReportProduct[],
|
||||
inventory: ShortageInventorySnapshot, purchasers: readonly { supplier: string; purchaser: string | null }[], generatedOn: string,
|
||||
): ShortageReportRow[] {
|
||||
const byBarcode = new Map(products.map(product => [shortageCode(product.barcode), product]))
|
||||
const bySku = new Map<string, ShortageReportProduct[]>()
|
||||
for (const product of products) {
|
||||
const key = shortageCode(product.sku)
|
||||
if (!key) continue
|
||||
const group = bySku.get(key) ?? []
|
||||
group.push(product)
|
||||
bySku.set(key, group)
|
||||
}
|
||||
const buyerBySupplier = new Map(purchasers.map(row => [row.supplier.trim(), row.purchaser]))
|
||||
const stockFor = indexShortageInventory(inventory)
|
||||
const groups = new Map<string, ShortageOrderDataRow[]>()
|
||||
for (const row of details) {
|
||||
const code = shortageCode(row.barcode)
|
||||
if (!code) continue
|
||||
const group = groups.get(code) ?? []
|
||||
group.push(row)
|
||||
groups.set(code, group)
|
||||
}
|
||||
const rows: ShortageReportRow[] = [...groups].map(([barcode, group]) => {
|
||||
const first = group[0]
|
||||
const product = byBarcode.get(barcode)
|
||||
const sku = product?.sku?.trim() || first.sku?.trim() || ''
|
||||
const skuProducts = bySku.get(shortageCode(sku)) ?? []
|
||||
const supplier = product?.supplierName?.trim() || first.supplier?.trim() || null
|
||||
const replacements = [...new Set(group.map(row => row.replacementSku?.trim()).filter((value): value is string => Boolean(value)))]
|
||||
// 明细的 PM 替换货号保持原意;自定义换货编码不冒充 PM 替换款。
|
||||
const replacementSku = replacements.join(';') || null
|
||||
const replacementCodes = replacements.flatMap(target => (bySku.get(shortageCode(target)) ?? []).map(item => item.barcode))
|
||||
const replacementKnown = replacements.length > 0 && replacements.every(target => bySku.has(shortageCode(target)))
|
||||
const shortageQuantity = group.some(row => row.shortageQuantity === null) ? null : group.reduce((sum, row) => sum + row.shortageQuantity!, 0)
|
||||
return {
|
||||
id: `${generatedOn}:${barcode}`, generatedOn, sku, barcode,
|
||||
productName: product?.productName ?? first.productName,
|
||||
productionStatus: product?.productStatus ?? first.productionStatus,
|
||||
skuProductionStatus: skuProducts.length ? aggregateSkuProductionStatus(skuProducts.map(item => item.productStatus)) : first.skuProductionStatus,
|
||||
supplier,
|
||||
// Excel I10 明确指定未匹配供应商的采购为宁珂,匹配到空采购则保持为空。
|
||||
purchaser: supplier && buyerBySupplier.has(supplier) ? buyerBySupplier.get(supplier) ?? null : '宁珂',
|
||||
shortageQuantity, stock: skuProducts.length ? stockFor(skuProducts.map(item => item.barcode), 'main') : null,
|
||||
replacementSku, replacementStock: replacementKnown ? stockFor(replacementCodes) : null,
|
||||
expectedArrival: null, notes: null, replacementTransit: null, version: 0,
|
||||
}
|
||||
})
|
||||
return prepareShortageReportRows(rows, generatedOn).sort((a, b) => a.sku.localeCompare(b.sku, 'zh-CN') || a.barcode.localeCompare(b.barcode))
|
||||
}
|
||||
@ -0,0 +1,9 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
export const shortageReportManualSchema = z.object({
|
||||
id: z.string().min(1).max(300),
|
||||
version: z.number().int().nonnegative(),
|
||||
expectedArrival: z.string().trim().max(120).nullable().transform(value => value || null),
|
||||
notes: z.string().trim().max(2000).nullable().transform(value => value || null),
|
||||
replacementTransit: z.number().finite().int().min(0).max(1_000_000_000).nullable(),
|
||||
}).strict()
|
||||
@ -0,0 +1,93 @@
|
||||
import { filterShortageReportRows, getShortageReportDateBounds, prepareShortageReportRows, sortShortageReportRows, validateShortageReportFilters, type ShortageReportRow } from './supply-chain-shortage-report'
|
||||
|
||||
const row: ShortageReportRow = { id: 'one', generatedOn: '2026-11-11', sku: '001', barcode: '0001234567890123456789', shortageQuantity: 12, stock: 3 }
|
||||
|
||||
describe('独立缺货报表', () => {
|
||||
it('subtracts stock from barcode shortage and removes zero and negative results', () => {
|
||||
const result = prepareShortageReportRows([
|
||||
row,
|
||||
{ ...row, id: 'equal', stock: 12 },
|
||||
{ ...row, id: 'surplus', stock: 20 },
|
||||
{ ...row, id: 'negative-stock', stock: -2 },
|
||||
], '2026-11-11')
|
||||
expect(result.map(item => [item.id, item.realShortage])).toEqual([['one', 9], ['negative-stock', 14]])
|
||||
})
|
||||
|
||||
it('keeps unknown quantities and inventory unknown instead of treating them as zero', () => {
|
||||
const result = prepareShortageReportRows([{ ...row, stock: null }, { ...row, id: 'missing', shortageQuantity: null }], '2026-11-11')
|
||||
expect(result.map(item => item.realShortage)).toEqual([null, null])
|
||||
})
|
||||
|
||||
it('clears all same-SKU replacement information and keeps the original shortage row', () => {
|
||||
const input = { ...row, replacementSku: ' 001 ', replacementTransit: 8, replacementStock: 9 }
|
||||
expect(prepareShortageReportRows([input], '2026-11-11')).toEqual([
|
||||
{ ...row, realShortage: 9, replacementSku: null, replacementTransit: null, replacementStock: null },
|
||||
])
|
||||
expect(input.replacementSku).toBe(' 001 ')
|
||||
})
|
||||
|
||||
it('preserves replacement information for a different SKU including reported zero stock', () => {
|
||||
const input = { ...row, replacementSku: '002', replacementTransit: 0, replacementStock: 4 }
|
||||
expect(prepareShortageReportRows([input], '2026-11-11')[0]).toEqual({ ...input, realShortage: 9 })
|
||||
})
|
||||
|
||||
it.each([
|
||||
['2026-11-11', '2026-05-11'],
|
||||
['2026-08-31', '2026-02-28'],
|
||||
['2024-08-31', '2024-02-29'],
|
||||
['2026-03-31', '2025-09-30'],
|
||||
])('retains six calendar months from %s, bounded by %s', (today, min) => {
|
||||
expect(getShortageReportDateBounds(today)).toEqual({ min, max: today })
|
||||
})
|
||||
|
||||
it('rejects invalid, expired, future and reversed date ranges', () => {
|
||||
for (const filters of [
|
||||
{ generatedFrom: '2026-02-30' }, { generatedFrom: '2026-05-10' },
|
||||
{ generatedTo: '2026-11-12' }, { generatedFrom: '2026-11-11', generatedTo: '2026-11-10' },
|
||||
]) expect(validateShortageReportFilters(filters, '2026-11-11')).toBeTruthy()
|
||||
expect(validateShortageReportFilters({ generatedFrom: '2026-05-11', generatedTo: '2026-11-11' }, '2026-11-11')).toBeNull()
|
||||
expect(validateShortageReportFilters({}, '2026-11-11')).toBeNull()
|
||||
})
|
||||
|
||||
it('excludes expired and future snapshots while retaining the boundary date', () => {
|
||||
const result = prepareShortageReportRows(['2026-05-10', '2026-05-11', '2026-11-11', '2026-11-12', 'bad-date'].map(generatedOn => ({ ...row, id: generatedOn, generatedOn })), '2026-11-11')
|
||||
expect(result.map(item => item.generatedOn)).toEqual(['2026-05-11', '2026-11-11'])
|
||||
})
|
||||
|
||||
it('filters snapshot generation dates and combines multivalue filters without changing totals', () => {
|
||||
const rows = prepareShortageReportRows([
|
||||
{ ...row, supplier: '甲', purchaser: '采购 A' },
|
||||
{ ...row, id: 'two', generatedOn: '2026-11-10', sku: '002', supplier: '乙', purchaser: '采购 B' },
|
||||
{ ...row, id: 'three', generatedOn: '2026-11-09', supplier: '乙', purchaser: '采购 A' },
|
||||
], '2026-11-11')
|
||||
const result = filterShortageReportRows(rows, { generatedFrom: '2026-11-10', generatedTo: '2026-11-11', sku: ['001', '002'], supplier: ['甲', '乙'], purchaser: ['采购 A'], barcode: ['0001234567890123456789'] })
|
||||
expect(result.map(item => [item.id, item.realShortage])).toEqual([['one', 9]])
|
||||
})
|
||||
|
||||
it('keeps each supplier together across snapshot dates and sorts purchasers within that supplier', () => {
|
||||
const source = [
|
||||
{ ...row, id: 'a-b-new', supplier: 'Supplier A', purchaser: 'Buyer B' },
|
||||
{ ...row, id: 'b-a', supplier: 'Supplier B', purchaser: 'Buyer A' },
|
||||
{ ...row, id: 'no-supplier', supplier: null, purchaser: 'Buyer A' },
|
||||
{ ...row, id: 'a-no-buyer', supplier: 'Supplier A', purchaser: ' ' },
|
||||
{ ...row, id: 'a-b-old', supplier: ' Supplier A ', purchaser: ' Buyer B ', generatedOn: '2026-11-10' },
|
||||
{ ...row, id: 'a-a', supplier: 'Supplier A', purchaser: 'Buyer A', generatedOn: '2026-11-10' },
|
||||
]
|
||||
const originalIds = source.map(item => item.id)
|
||||
|
||||
const sorted = sortShortageReportRows(source)
|
||||
|
||||
expect(sorted.map(item => item.id)).toEqual(['a-a', 'a-b-new', 'a-b-old', 'a-no-buyer', 'b-a', 'no-supplier'])
|
||||
expect(filterShortageReportRows(sorted, { purchaser: ['Buyer A'] }).map(item => item.id)).toEqual(['a-a', 'b-a', 'no-supplier'])
|
||||
expect(source.map(item => item.id)).toEqual(originalIds)
|
||||
})
|
||||
|
||||
it('finds the same archived code with uppercase, lowercase or mixed-case code filters', () => {
|
||||
const source = [{ ...row, barcode: 'DNZ004409N1222V01', sku: 'DNZ004409', supplier: 'Vendor A', shortageQuantity: 26, stock: 0 }]
|
||||
for (const barcode of ['dnz004409N1222V01', 'DNZ004409N1222V01', 'dnz004409n1222v01']) {
|
||||
expect(filterShortageReportRows(source, { barcode: [barcode], sku: ['dnz004409'] })).toEqual(source)
|
||||
}
|
||||
expect(filterShortageReportRows(source, { barcode: ['dnz004409'] })).toEqual([])
|
||||
expect(filterShortageReportRows(source, { supplier: ['vendor a'] })).toEqual([])
|
||||
})
|
||||
})
|
||||
129
furniture-3d-system/src/lib/supply-chain-shortage-report.ts
Normal file
129
furniture-3d-system/src/lib/supply-chain-shortage-report.ts
Normal file
@ -0,0 +1,129 @@
|
||||
import { shortageQuantityNumber } from './supply-chain-shortage-rules'
|
||||
|
||||
export const SHORTAGE_REPORT_ARCHIVE_POLICY = { frequency: 'daily', retentionMonths: 6, timeZone: 'Asia/Shanghai' } as const
|
||||
|
||||
export type ShortageReportRow = {
|
||||
id: string
|
||||
generatedOn: string
|
||||
sku: string
|
||||
barcode: string
|
||||
productName?: string | null
|
||||
skuProductionStatus?: string | null
|
||||
productionStatus?: string | null
|
||||
supplier?: string | null
|
||||
purchaser?: string | null
|
||||
shortageQuantity: number | null
|
||||
stock: number | null
|
||||
realShortage?: number | null
|
||||
expectedArrival?: string | null
|
||||
notes?: string | null
|
||||
replacementSku?: string | null
|
||||
replacementTransit?: number | null
|
||||
replacementStock?: number | null
|
||||
version?: number
|
||||
}
|
||||
|
||||
export type ShortageReportManualInput = {
|
||||
id: string
|
||||
version: number
|
||||
expectedArrival: string | null
|
||||
notes: string | null
|
||||
replacementTransit: number | null
|
||||
}
|
||||
|
||||
export type ShortageReportReadState =
|
||||
| { status: 'loading'; message: string }
|
||||
| { status: 'error'; message: string }
|
||||
| { status: 'ready'; rows: ShortageReportRow[]; today: string; generatedAt: string | null }
|
||||
|
||||
export function shortageReportToday(now = new Date()) {
|
||||
return now.toLocaleDateString('sv-SE', { timeZone: SHORTAGE_REPORT_ARCHIVE_POLICY.timeZone })
|
||||
}
|
||||
|
||||
export const SHORTAGE_REPORT_FILTERS = [
|
||||
{ key: 'sku', label: '货号' },
|
||||
{ key: 'barcode', label: '商品编码' },
|
||||
{ key: 'supplier', label: '供应商' },
|
||||
{ key: 'purchaser', label: '采购' },
|
||||
] as const
|
||||
export type ShortageReportFilters = {
|
||||
generatedFrom?: string
|
||||
generatedTo?: string
|
||||
} & Partial<Record<typeof SHORTAGE_REPORT_FILTERS[number]['key'], string[]>>
|
||||
|
||||
export function isShortageReportDate(value: string): boolean {
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return false
|
||||
const date = new Date(`${value}T00:00:00.000Z`)
|
||||
return Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === value
|
||||
}
|
||||
|
||||
/** 六个自然月,月底截到目标月最后一天;不用固定 180 天代替。 */
|
||||
export function getShortageReportDateBounds(today: string) {
|
||||
if (!isShortageReportDate(today)) throw new Error('无效的报表基准日期')
|
||||
const date = new Date(`${today}T00:00:00.000Z`)
|
||||
const day = date.getUTCDate()
|
||||
date.setUTCDate(1)
|
||||
date.setUTCMonth(date.getUTCMonth() - SHORTAGE_REPORT_ARCHIVE_POLICY.retentionMonths)
|
||||
const monthEnd = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 0)).getUTCDate()
|
||||
date.setUTCDate(Math.min(day, monthEnd))
|
||||
return { min: date.toISOString().slice(0, 10), max: today }
|
||||
}
|
||||
|
||||
export function validateShortageReportFilters(filters: ShortageReportFilters, today: string): string | null {
|
||||
const bounds = getShortageReportDateBounds(today)
|
||||
for (const value of [filters.generatedFrom, filters.generatedTo]) {
|
||||
if (!value) continue
|
||||
if (!isShortageReportDate(value)) return '请输入有效的生成日期。'
|
||||
if (value < bounds.min || value > bounds.max) return `生成日期须在 ${bounds.min} 至 ${bounds.max} 之间。`
|
||||
}
|
||||
if (filters.generatedFrom && filters.generatedTo && filters.generatedFrom > filters.generatedTo) return '生成日期的开始时间不能晚于结束时间。'
|
||||
return null
|
||||
}
|
||||
|
||||
export function prepareShortageReportRows(rows: readonly ShortageReportRow[], today: string): ShortageReportRow[] {
|
||||
const { min, max } = getShortageReportDateBounds(today)
|
||||
return rows.flatMap(row => {
|
||||
if (!isShortageReportDate(row.generatedOn) || row.generatedOn < min || row.generatedOn > max) return []
|
||||
const quantity = shortageQuantityNumber(row.shortageQuantity)
|
||||
// 报表只汇总实际缺货:AY明确为零的订单不能因负库存或缺失档案进入报表。
|
||||
if (quantity !== null && quantity <= 0) return []
|
||||
const stock = shortageQuantityNumber(row.stock)
|
||||
const realShortage = quantity === null || stock === null ? null : quantity - stock
|
||||
if (realShortage !== null && realShortage <= 0) return []
|
||||
const sameReplacement = Boolean(row.sku.trim()) && row.replacementSku?.trim() === row.sku.trim()
|
||||
return [{
|
||||
...row,
|
||||
realShortage,
|
||||
...(sameReplacement ? { replacementSku: null, replacementTransit: null, replacementStock: null } : {}),
|
||||
}]
|
||||
})
|
||||
}
|
||||
|
||||
const responsibilityCollator = new Intl.Collator('zh-CN')
|
||||
|
||||
function compareResponsibility(left?: string | null, right?: string | null) {
|
||||
const a = left?.trim() ?? ''
|
||||
const b = right?.trim() ?? ''
|
||||
if (!a || !b) return Number(!a) - Number(!b)
|
||||
return responsibilityCollator.compare(a, b) || (a < b ? -1 : a > b ? 1 : 0)
|
||||
}
|
||||
|
||||
/** 先排供应商,再排采购;组内保留原有快照和商品顺序。 */
|
||||
export function sortShortageReportRows(rows: readonly ShortageReportRow[]) {
|
||||
return [...rows].sort((a, b) => compareResponsibility(a.supplier, b.supplier)
|
||||
|| compareResponsibility(a.purchaser, b.purchaser))
|
||||
}
|
||||
|
||||
export function filterShortageReportRows(rows: readonly ShortageReportRow[], filters: ShortageReportFilters) {
|
||||
return rows.filter(row => {
|
||||
if (filters.generatedFrom && row.generatedOn < filters.generatedFrom) return false
|
||||
if (filters.generatedTo && row.generatedOn > filters.generatedTo) return false
|
||||
return SHORTAGE_REPORT_FILTERS.every(({ key }) => {
|
||||
const values = filters[key]
|
||||
const actual = String(row[key] ?? '').trim()
|
||||
return !values?.length || values.some(value => key === 'barcode' || key === 'sku'
|
||||
? actual.toUpperCase() === value.trim().toUpperCase()
|
||||
: actual === value)
|
||||
})
|
||||
})
|
||||
}
|
||||
@ -0,0 +1,68 @@
|
||||
import { aggregateSkuProductionStatus, applyOrderSkuLineCounts, applySkuProductionStatuses, applySkuQuantityTotals, sumShortageQuantitiesByBarcode } from './supply-chain-shortage-rules'
|
||||
import { filterShortageRows, type ShortageRow } from '@/app/supply-chain/management/shortage-order-details/shortage-order-fields'
|
||||
|
||||
describe('缺货订单确认口径', () => {
|
||||
it('counts AE detail lines by online order and SKU before filters, without summing pieces', () => {
|
||||
const rows: ShortageRow[] = [
|
||||
{ id: '1', onlineOrderId: '0001234567890123456789', sku: '001', quantity: 7, supplier: '甲' },
|
||||
{ id: '2', onlineOrderId: '0001234567890123456789', sku: '001', quantity: 4, supplier: '乙' },
|
||||
{ id: '3', onlineOrderId: '0001234567890123456789', sku: '002', quantity: 9 },
|
||||
{ id: '4', onlineOrderId: '1234567890123456789', sku: '001', quantity: 3 },
|
||||
{ id: '5', onlineOrderId: '', sku: '001', quantity: 2 },
|
||||
{ id: '6', onlineOrderId: '0001234567890123456789', sku: null },
|
||||
]
|
||||
const result = applyOrderSkuLineCounts(rows)
|
||||
expect(result.map(row => row.orderSkuQuantity)).toEqual([2, 2, 1, 1, null, null])
|
||||
expect(filterShortageRows(result, { supplier: ['甲'] })[0].orderSkuQuantity).toBe(2)
|
||||
expect(rows[0].orderSkuQuantity).toBeUndefined()
|
||||
})
|
||||
|
||||
it('sums M pieces for each SKU across all detail lines before display filters', () => {
|
||||
const rows: ShortageRow[] = [
|
||||
{ id: '1', sku: '001', barcode: '00001', quantity: 7, department: '采购' },
|
||||
{ id: '2', sku: '001', barcode: '00002', quantity: '4', department: '客服' },
|
||||
{ id: '3', sku: '002', barcode: '00003', quantity: 9, department: '采购' },
|
||||
]
|
||||
const result = applySkuQuantityTotals(rows)
|
||||
expect(result.map(row => row.totalShortage)).toEqual([11, 11, 9])
|
||||
expect(filterShortageRows(result, { department: ['采购'] }).map(row => row.totalShortage)).toEqual([11, 9])
|
||||
expect(rows[0].totalShortage).toBeUndefined()
|
||||
})
|
||||
|
||||
it('does not invent zero quantities or group missing SKUs together', () => {
|
||||
expect(applySkuQuantityTotals([
|
||||
{ sku: 'A', quantity: 3 }, { sku: 'A', quantity: null },
|
||||
{ sku: 'B', quantity: 0 }, { sku: '', quantity: 7 }, { quantity: 4 },
|
||||
]).map(row => row.totalShortage)).toEqual([null, null, 0, null, null])
|
||||
})
|
||||
|
||||
it.each([
|
||||
[['销售'], '销售'], [['停产', '销售', '退市'], '销售'],
|
||||
[['退市', '停产'], '退市'], [['退市'], '退市'],
|
||||
[['停产', '停产'], '停产'], [[' 停产 ', '退市'], '退市'],
|
||||
[[], null], [[null, '停产'], null], [['未知', '退市'], null], [['未知', '销售'], '销售'],
|
||||
])('aggregates all archive statuses %j to %s', (statuses, expected) => {
|
||||
expect(aggregateSkuProductionStatus(statuses)).toBe(expected)
|
||||
})
|
||||
|
||||
it('includes archive barcodes absent from the shortage orders when determining AA', () => {
|
||||
const result = applySkuProductionStatuses([{ sku: 'A', barcode: '01' }, { sku: 'B' }], [
|
||||
{ sku: 'A', productStatus: '停产' },
|
||||
{ sku: 'A', productStatus: '销售' }, // 该编码未出现在缺货订单中,仍须参与聚合。
|
||||
{ sku: 'B', productStatus: '退市' },
|
||||
{ sku: 'B', productStatus: '停产' },
|
||||
])
|
||||
expect(result.map(row => row.skuProductionStatus)).toEqual(['销售', '退市'])
|
||||
})
|
||||
|
||||
it('sums report J by barcode from AY and keeps identifiers intact', () => {
|
||||
const totals = sumShortageQuantitiesByBarcode([
|
||||
{ barcode: '0001234567890123456789', shortageQuantity: 6 },
|
||||
{ barcode: '0001234567890123456789', shortageQuantity: 3 },
|
||||
{ barcode: '00002', shortageQuantity: 0 },
|
||||
{ barcode: '00003', shortageQuantity: null },
|
||||
{ barcode: '', shortageQuantity: 20 },
|
||||
])
|
||||
expect([...totals]).toEqual([['0001234567890123456789', 9], ['00002', 0], ['00003', null]])
|
||||
})
|
||||
})
|
||||
88
furniture-3d-system/src/lib/supply-chain-shortage-rules.ts
Normal file
88
furniture-3d-system/src/lib/supply-chain-shortage-rules.ts
Normal file
@ -0,0 +1,88 @@
|
||||
export type SkuProductionStatus = '销售' | '退市' | '停产'
|
||||
|
||||
/** 必须传入货号下全部档案编码的状态,不能只传缺货订单涉及的编码。 */
|
||||
export function aggregateSkuProductionStatus(
|
||||
statuses: readonly (string | null | undefined)[],
|
||||
): SkuProductionStatus | null {
|
||||
const normalized = statuses.map(status => status?.trim() ?? '')
|
||||
if (normalized.includes('销售')) return '销售'
|
||||
if (!normalized.length || normalized.some(status => status !== '停产' && status !== '退市')) return null
|
||||
return normalized.includes('退市') ? '退市' : '停产'
|
||||
}
|
||||
|
||||
/** archive 必须是这些货号在产品档案下的全部编码,不能只传本次缺货订单命中的编码。 */
|
||||
export function applySkuProductionStatuses<T extends { sku?: string | number | null }>(
|
||||
rows: readonly T[],
|
||||
archive: readonly { sku: string | null; productStatus: string | null }[],
|
||||
) {
|
||||
const statuses = new Map<string, (string | null)[]>()
|
||||
for (const product of archive) {
|
||||
const sku = product.sku?.trim()
|
||||
if (!sku) continue
|
||||
const group = statuses.get(sku) ?? []
|
||||
group.push(product.productStatus)
|
||||
statuses.set(sku, group)
|
||||
}
|
||||
return rows.map(row => ({
|
||||
...row,
|
||||
skuProductionStatus: aggregateSkuProductionStatus(statuses.get(String(row.sku ?? '').trim()) ?? []),
|
||||
}))
|
||||
}
|
||||
|
||||
/** 缺货报表 J 列按商品编码合计明细 AY 缺货数量,不能用 Z 货号总量替代。 */
|
||||
export function sumShortageQuantitiesByBarcode(rows: readonly { barcode?: string | number | null; shortageQuantity?: string | number | null }[]) {
|
||||
const totals = new Map<string, number | null>()
|
||||
for (const row of rows) {
|
||||
const barcode = String(row.barcode ?? '').trim()
|
||||
if (!barcode) continue
|
||||
const quantity = shortageQuantityNumber(row.shortageQuantity)
|
||||
const previous = totals.get(barcode)
|
||||
totals.set(barcode, quantity === null || previous === null ? null : (previous ?? 0) + quantity)
|
||||
}
|
||||
return totals
|
||||
}
|
||||
|
||||
export function shortageQuantityNumber(value: string | number | null | undefined): number | null {
|
||||
if (value == null || (typeof value === 'string' && !value.trim())) return null
|
||||
const numeric = typeof value === 'number' ? value : Number(value)
|
||||
return Number.isFinite(numeric) ? numeric : null
|
||||
}
|
||||
|
||||
type OrderQuantity = {
|
||||
sku?: string | number | null
|
||||
quantity?: string | number | null
|
||||
}
|
||||
|
||||
/** AE 列按需求表计数:同线上订单号、同货号的明细行数,先计数、后筛选分页。 */
|
||||
export function applyOrderSkuLineCounts<T extends {
|
||||
onlineOrderId?: string | number | null
|
||||
sku?: string | number | null
|
||||
}>(rows: readonly T[]) {
|
||||
const keyOf = (row: T) => {
|
||||
const order = String(row.onlineOrderId ?? '').trim()
|
||||
const sku = String(row.sku ?? '').trim()
|
||||
return order && sku ? JSON.stringify([order, sku]) : null
|
||||
}
|
||||
const counts = new Map<string, number>()
|
||||
for (const row of rows) {
|
||||
const key = keyOf(row)
|
||||
if (key) counts.set(key, (counts.get(key) ?? 0) + 1)
|
||||
}
|
||||
return rows.map(row => ({ ...row, orderSkuQuantity: counts.get(keyOf(row) ?? '') ?? null }))
|
||||
}
|
||||
|
||||
/** Z 列:在完整明细范围按货号汇总 M 列件数,先汇总、后筛选分页。 */
|
||||
export function applySkuQuantityTotals<T extends OrderQuantity>(rows: readonly T[]) {
|
||||
const totals = new Map<string, number | null>()
|
||||
for (const row of rows) {
|
||||
const sku = String(row.sku ?? '').trim()
|
||||
if (!sku) continue
|
||||
const quantity = shortageQuantityNumber(row.quantity)
|
||||
const previous = totals.get(sku)
|
||||
totals.set(sku, quantity === null || previous === null ? null : (previous ?? 0) + quantity)
|
||||
}
|
||||
return rows.map(row => ({
|
||||
...row,
|
||||
totalShortage: totals.get(String(row.sku ?? '').trim()) ?? null,
|
||||
}))
|
||||
}
|
||||
@ -0,0 +1,77 @@
|
||||
import { Client } from 'pg'
|
||||
import type { Prisma, ShortageOrderDailySnapshot as StoredSnapshot } from '@prisma/client'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import type { ShortageOrderDailySnapshot, ShortageOrderSnapshot } from '@/lib/supply-chain-shortage-orders'
|
||||
import { shortageOrderSnapshotRowsSchema } from '@/lib/supply-chain-shortage-order-snapshot'
|
||||
import type { ShortageReportRow } from '@/lib/supply-chain-shortage-report'
|
||||
import { supplyChainShortageReportRepository } from './supply-chain-shortage-report.repository'
|
||||
|
||||
const dateValue = (date: string) => new Date(`${date}T00:00:00.000Z`)
|
||||
function dto(row: StoredSnapshot): ShortageOrderDailySnapshot {
|
||||
return { generatedOn: row.generatedOn.toISOString().slice(0, 10), generatedAt: row.generatedAt.toISOString(),
|
||||
fetchedAt: row.sourceFetchedAt.toISOString(), rows: shortageOrderSnapshotRowsSchema.parse(row.rows) }
|
||||
}
|
||||
|
||||
export class SupplyChainShortageOrderSnapshotRepository {
|
||||
async acquireGenerationLock(includeReport = false): Promise<(() => Promise<void>) | null> {
|
||||
const client = new Client({ connectionString: process.env.DATABASE_URL, connectionTimeoutMillis: 10_000 })
|
||||
try {
|
||||
await client.connect()
|
||||
const result = await client.query<{ locked: boolean }>('SELECT pg_try_advisory_lock(913712, 10) AS locked')
|
||||
if (!result.rows[0].locked) { await client.end(); return null }
|
||||
if (includeReport) {
|
||||
const report = await client.query<{ locked: boolean }>('SELECT pg_try_advisory_lock(913712, 9) AS locked')
|
||||
if (!report.rows[0].locked) { await client.end(); return null }
|
||||
}
|
||||
return async () => { await client.end() }
|
||||
} catch (error) { await client.end().catch(() => {}); throw error }
|
||||
}
|
||||
|
||||
async isGenerationRunning(): Promise<boolean> {
|
||||
const rows = await prisma.$queryRaw<{ running: boolean }[]>`SELECT EXISTS (
|
||||
SELECT 1 FROM pg_locks WHERE locktype = 'advisory' AND classid = 913712 AND objid = 10
|
||||
AND objsubid = 2 AND granted AND database = (SELECT oid FROM pg_database WHERE datname = current_database())
|
||||
) AS running`
|
||||
return rows[0].running
|
||||
}
|
||||
|
||||
/** 手动全量更新:同一事务发布明细与报表,报表沿用人工填报保留规则。 */
|
||||
async publishRefresh(date: string, snapshot: ShortageOrderSnapshot, reportRows: readonly ShortageReportRow[], min: string) {
|
||||
const rows = shortageOrderSnapshotRowsSchema.parse(snapshot.rows)
|
||||
return prisma.$transaction(async tx => {
|
||||
const data = { sourceFetchedAt: new Date(snapshot.fetchedAt), rows: rows as unknown as Prisma.InputJsonValue, generatedAt: new Date() }
|
||||
await tx.shortageOrderDailySnapshot.upsert({ where: { generatedOn: dateValue(date) },
|
||||
create: { generatedOn: dateValue(date), ...data }, update: data })
|
||||
await supplyChainShortageReportRepository.publish(date, snapshot.fetchedAt, reportRows, min, true, tx)
|
||||
}, { timeout: 30_000 })
|
||||
}
|
||||
|
||||
async findSnapshot(date: string): Promise<ShortageOrderDailySnapshot | null> {
|
||||
const row = await prisma.shortageOrderDailySnapshot.findUnique({ where: { generatedOn: dateValue(date) } })
|
||||
return row ? dto(row) : null
|
||||
}
|
||||
|
||||
async listDates(today: string): Promise<string[]> {
|
||||
const rows = await prisma.shortageOrderDailySnapshot.findMany({ where: { generatedOn: { lte: dateValue(today) } },
|
||||
orderBy: { generatedOn: 'desc' }, select: { generatedOn: true } })
|
||||
return rows.map(row => row.generatedOn.toISOString().slice(0, 10))
|
||||
}
|
||||
|
||||
async findLatest(today: string): Promise<ShortageOrderDailySnapshot | null> {
|
||||
const row = await prisma.shortageOrderDailySnapshot.findFirst({
|
||||
where: { generatedOn: { lte: dateValue(today) } }, orderBy: { generatedOn: 'desc' },
|
||||
})
|
||||
return row ? dto(row) : null
|
||||
}
|
||||
|
||||
/** 一次事务保存全部字段;日期唯一,同日重跑不覆盖已发布的结果。 */
|
||||
async publish(date: string, snapshot: ShortageOrderSnapshot) {
|
||||
const rows = shortageOrderSnapshotRowsSchema.parse(snapshot.rows)
|
||||
const result = await prisma.shortageOrderDailySnapshot.createMany({ data: [{
|
||||
generatedOn: dateValue(date), sourceFetchedAt: new Date(snapshot.fetchedAt), rows: rows as unknown as Prisma.InputJsonValue,
|
||||
}], skipDuplicates: true })
|
||||
return result.count === 1
|
||||
}
|
||||
}
|
||||
|
||||
export const supplyChainShortageOrderSnapshotRepository = new SupplyChainShortageOrderSnapshotRepository()
|
||||
@ -0,0 +1,391 @@
|
||||
/** @jest-environment node */
|
||||
|
||||
import sql from 'mssql'
|
||||
import { getSupplyChainArchiveReadPool } from './supply-chain-archive-read-pool'
|
||||
import { SHORTAGE_QUESTION_TYPES, shortageHeaderSql, SupplyChainShortageOrderRepository } from './supply-chain-shortage-order.repository'
|
||||
|
||||
jest.mock('mssql', () => ({
|
||||
__esModule: true,
|
||||
default: { ConnectionPool: jest.fn(), NVarChar: jest.fn(size => `nvarchar(${size})`), BigInt: 'bigint', Int: 'int', MAX: 'max' },
|
||||
}))
|
||||
jest.mock('./supply-chain-archive-read-pool', () => ({ getSupplyChainArchiveReadPool: jest.fn() }))
|
||||
|
||||
describe('缺货订单只读来源', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
jest.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
Object.assign(process.env, {
|
||||
JST_REPORT_DB_HOST: 'localhost', JST_REPORT_DB_NAME: 'test',
|
||||
JST_REPORT_DB_USER: 'reader', JST_REPORT_DB_PASSWORD: 'test', JST_REPORT_DB_SCHEMA: 'rpt',
|
||||
})
|
||||
})
|
||||
afterEach(() => jest.restoreAllMocks())
|
||||
|
||||
function mockPool(options: { failSource?: string; failLatest?: boolean; empty?: boolean; timeoutItems?: boolean; headers?: Record<string, unknown>[]; items?: Record<string, unknown>[]; beforeQuery?: (query: string, inputs: Record<string, unknown>) => void } = {}) {
|
||||
const calls: Array<{ query: string; inputs: Record<string, unknown> }> = []
|
||||
const headers = options.headers ?? [{ internalOrderId: '9007199254740993', exceptionType: '缺货', orderStatus: 'Question', sourceRowId: 1, sourceModifiedAt: null },
|
||||
...(options.timeoutItems ? [{ internalOrderId: '9007199254740994', exceptionType: '预售', orderStatus: 'Question', sourceRowId: 1, sourceModifiedAt: null }] : [])]
|
||||
const pool = { connect: jest.fn(), close: jest.fn().mockResolvedValue(undefined), request: () => {
|
||||
const inputs: Record<string, unknown> = {}
|
||||
const request = {
|
||||
input: (key: string, _type: unknown, value: unknown) => { inputs[key] = value; return request },
|
||||
query: jest.fn(async (query: string) => {
|
||||
calls.push({ query, inputs })
|
||||
options.beforeQuery?.(query, inputs)
|
||||
if (options.failSource && query.includes(options.failSource)) throw new Error('source unavailable')
|
||||
if (query.includes('@orderStatus')) return { recordset: options.empty ? [] : headers.map(row => ({ internalOrderId: row.internalOrderId, exceptionType: row.exceptionType })) }
|
||||
if (query.includes('WHERE o.o_id IN')) {
|
||||
if (options.failLatest) throw new Error('latest unavailable')
|
||||
return { recordset: headers.filter(row => Object.values(inputs).includes(row.internalOrderId)) }
|
||||
}
|
||||
if (options.timeoutItems && Object.keys(inputs).length > 1) throw Object.assign(new Error('item query timeout'), { code: 'ETIMEOUT' })
|
||||
if (options.items) return { recordset: options.items.filter(row => Object.values(inputs).includes(row.internalOrderId)) }
|
||||
return { recordset: Object.values(inputs).flatMap(internalOrderId => [
|
||||
{ internalOrderId, itemId: '001', barcode: '0001', quantity: 1, sourceRowId: 1, skuType: 'combine', comboParentBarcode: null, outerItemId: 'old-line' },
|
||||
{ internalOrderId, itemId: '001', barcode: '0001', quantity: 2, sourceRowId: 2, skuType: 'normal', comboParentBarcode: 'SET', outerItemId: 'current-line' },
|
||||
]) }
|
||||
}),
|
||||
}
|
||||
return request
|
||||
} }
|
||||
pool.connect.mockResolvedValue(pool)
|
||||
jest.mocked(sql.ConnectionPool).mockImplementation(() => pool as unknown as sql.ConnectionPool)
|
||||
return { pool, calls }
|
||||
}
|
||||
|
||||
it('supports a longer source query budget for unattended daily jobs without changing source filtering', async () => {
|
||||
const { calls } = mockPool({ empty: true })
|
||||
const repository = new SupplyChainShortageOrderRepository(120_000)
|
||||
expect(await repository.listOrderItems()).toEqual([])
|
||||
expect(jest.mocked(sql.ConnectionPool).mock.calls[0][0]).toMatchObject({ requestTimeout: 120_000, options: { readOnlyIntent: true } })
|
||||
expect(calls).toHaveLength(2)
|
||||
expect(calls.every(call => call.inputs.orderStatus === 'Question')).toBe(true)
|
||||
await repository.close()
|
||||
})
|
||||
|
||||
it('reads each complete candidate set once and preserves bigint IDs through latest-version and item lookups', async () => {
|
||||
const { calls } = mockPool()
|
||||
const repository = new SupplyChainShortageOrderRepository()
|
||||
const progress = jest.fn()
|
||||
const rows = await repository.listOrderItems(progress)
|
||||
expect(SHORTAGE_QUESTION_TYPES).toEqual(['缺货', '真实缺货', '预售'])
|
||||
const candidates = calls.filter(call => call.query.includes('@orderStatus'))
|
||||
expect(candidates).toHaveLength(2)
|
||||
expect(candidates.map(call => call.query)).toEqual(expect.arrayContaining([expect.stringContaining('[jst_Orders]'), expect.stringContaining('[jst_qmcust_orderlist]')]))
|
||||
for (const call of candidates) {
|
||||
expect(call.inputs).toEqual({ orderStatus: 'Question' })
|
||||
expect(call.query).toContain('o.question_type AS exceptionType')
|
||||
expect(call.query).toContain('o.status = @orderStatus')
|
||||
expect(call.query).not.toMatch(/DISTINCT|o.labels|o.type/)
|
||||
expect(call.query).not.toMatch(/TOP\s*\(|pay_date\s*[><=]|@fromId|@throughId|ROW_NUMBER/i)
|
||||
}
|
||||
for (const call of calls.filter(call => call.query.includes('WHERE o.o_id IN'))) {
|
||||
expect(call.inputs).toEqual({ order0: '9007199254740993' })
|
||||
expect(call.query.split('WHERE')[1]).not.toMatch(/status|question_type|labels|\.type/)
|
||||
}
|
||||
expect(calls.filter(call => call.query.includes('WHERE i.o_id IN'))[0].inputs).toEqual({ order0: '9007199254740993' })
|
||||
expect(rows.map(row => row.id)).toEqual(['OTHER:9007199254740993:001', 'TAOBAO:9007199254740993:001'])
|
||||
expect(rows[0]).toMatchObject({ barcode: '0001', quantity: 2, source: 'OTHER', skuType: 'normal', comboParentBarcode: 'SET', outerItemId: 'current-line' })
|
||||
for (const call of calls.filter(call => call.query.includes('WHERE i.o_id IN'))) {
|
||||
expect(call.query).toContain('i.sku_type AS skuType')
|
||||
expect(call.query).toContain('i.src_combine_sku_id AS comboParentBarcode')
|
||||
expect(call.query).toContain('i.outer_oi_id AS outerItemId')
|
||||
expect(call.query).toContain('i.item_status AS itemStatus')
|
||||
}
|
||||
expect(rows[0]).not.toHaveProperty('sourceRowId')
|
||||
expect(rows[0]).not.toHaveProperty('sourceModifiedAt')
|
||||
expect(jest.mocked(sql.ConnectionPool).mock.calls[0][0]).toMatchObject({ options: { readOnlyIntent: true } })
|
||||
expect(progress).toHaveBeenLastCalledWith({ stage: 'items', completed: 2, total: 2 })
|
||||
expect(calls).toHaveLength(6)
|
||||
await repository.close()
|
||||
})
|
||||
|
||||
it('retains the latest item status before service filtering without restoring an older active or replaced version', async () => {
|
||||
const item = { internalOrderId: '9007199254740993', barcode: 'A', quantity: 1 }
|
||||
mockPool({ items: [
|
||||
{ ...item, itemId: 'replaced', itemStatus: null, sourceRowId: 1 },
|
||||
{ ...item, itemId: 'active', itemStatus: null, sourceRowId: 4 },
|
||||
{ ...item, itemId: 'replaced', itemStatus: 'Replaced', sourceRowId: 2 },
|
||||
{ ...item, itemId: 'active', itemStatus: 'Replaced', sourceRowId: 3 },
|
||||
] })
|
||||
const repository = new SupplyChainShortageOrderRepository()
|
||||
const rows = await repository.listOrderItems()
|
||||
expect(rows).toHaveLength(4)
|
||||
expect(rows.filter(row => row.itemId === 'replaced').every(row => row.itemStatus === 'Replaced')).toBe(true)
|
||||
expect(rows.filter(row => row.itemId === 'active').every(row => row.itemStatus === null)).toBe(true)
|
||||
await repository.close()
|
||||
})
|
||||
|
||||
it.each([
|
||||
{ orderStatus: 'Sent' }, { orderStatus: 'Cancelled' }, { orderStatus: 'WaitConfirm' }, { orderStatus: null },
|
||||
{ labels: '普通,刷单待处理,其他' }, { labels: '已完成刷单' }, { exceptionType: '其他' }, { exceptionType: null }, { orderType: '配件订单' },
|
||||
])('never restores an older eligible order when its latest record is excluded on either source: %j', async excluded => {
|
||||
const base = { internalOrderId: '9007199254740993', orderStatus: 'Question', exceptionType: '缺货' }
|
||||
const { calls } = mockPool({ headers: [
|
||||
{ ...base, sourceRowId: 2, sourceModifiedAt: '2026-11-12 10:00:00', ...excluded },
|
||||
{ ...base, sourceRowId: 1, sourceModifiedAt: '2026-11-11 10:00:00' },
|
||||
] })
|
||||
const repository = new SupplyChainShortageOrderRepository()
|
||||
expect(await repository.listOrderItems()).toEqual([])
|
||||
expect(calls.filter(call => call.query.includes('WHERE i.o_id IN'))).toHaveLength(0)
|
||||
await repository.close()
|
||||
})
|
||||
|
||||
it('keeps replenishment orders on both sources', async () => {
|
||||
mockPool({ headers: [{ internalOrderId: '1', exceptionType: '缺货', orderStatus: 'Question', orderType: '售后补发', sourceRowId: 1 }] })
|
||||
const repository = new SupplyChainShortageOrderRepository()
|
||||
const rows = await repository.listOrderItems()
|
||||
expect(rows).toHaveLength(2)
|
||||
expect(rows.every(row => row.orderType === '售后补发')).toBe(true)
|
||||
await repository.close()
|
||||
})
|
||||
|
||||
it('deduplicates by modification time and then source ID regardless of row order, retaining eligible labels', async () => {
|
||||
const base = { internalOrderId: '1', exceptionType: '缺货', orderStatus: 'Question', labels: '普通订单' }
|
||||
mockPool({ headers: [
|
||||
{ ...base, sourceRowId: 20, sourceModifiedAt: '2026-11-11 00:00:00', shopName: 'older' },
|
||||
{ ...base, sourceRowId: 3, sourceModifiedAt: '2026-11-12 00:00:00', shopName: 'newest' },
|
||||
{ ...base, sourceRowId: 2, sourceModifiedAt: '2026-11-12 00:00:00', shopName: 'tie-loser' },
|
||||
{ ...base, sourceRowId: 30, sourceModifiedAt: null, shopName: 'undated' },
|
||||
] })
|
||||
const repository = new SupplyChainShortageOrderRepository()
|
||||
const rows = await repository.listOrderItems()
|
||||
expect(rows).toHaveLength(2)
|
||||
expect(rows.every(row => row.shopName === 'newest' && row.quantity === 2)).toBe(true)
|
||||
await repository.close()
|
||||
})
|
||||
|
||||
it('retains all candidates and final rows across item batches without a date or order cap', async () => {
|
||||
const { calls } = mockPool({ headers: Array.from({ length: 1201 }, (_, index) => ({
|
||||
internalOrderId: String(index + 1), exceptionType: '缺货', orderStatus: 'Question', sourceRowId: index + 1, sourceModifiedAt: null,
|
||||
})) })
|
||||
const repository = new SupplyChainShortageOrderRepository()
|
||||
const rows = await repository.listOrderItems()
|
||||
expect(rows).toHaveLength(2402)
|
||||
expect(new Set(rows.map(row => row.id)).size).toBe(2402)
|
||||
const latestCalls = calls.filter(call => call.query.includes('WHERE o.o_id IN'))
|
||||
expect(latestCalls).toHaveLength(26)
|
||||
expect(latestCalls.every(call => Object.keys(call.inputs).length <= 100)).toBe(true)
|
||||
const itemCalls = calls.filter(call => call.query.includes('WHERE i.o_id IN'))
|
||||
expect(itemCalls).toHaveLength(26)
|
||||
expect(itemCalls.every(call => Object.keys(call.inputs).length <= 100)).toBe(true)
|
||||
await repository.close()
|
||||
})
|
||||
|
||||
it.each([{ failSource: '[jst_qmcust_orderlist]' }, { failLatest: true }])('rejects incomplete source or latest-version reads: %j', async options => {
|
||||
mockPool(options)
|
||||
const repository = new SupplyChainShortageOrderRepository()
|
||||
await expect(repository.listOrderItems()).rejects.toThrow('unavailable')
|
||||
await repository.close()
|
||||
})
|
||||
|
||||
it('skips latest-version and item reads for empty candidate sets', async () => {
|
||||
const { calls } = mockPool({ empty: true })
|
||||
const repository = new SupplyChainShortageOrderRepository()
|
||||
await expect(repository.listOrderItems()).resolves.toEqual([])
|
||||
expect(calls).toHaveLength(2)
|
||||
await repository.close()
|
||||
})
|
||||
|
||||
it('subdivides timed-out item batches without losing orders or retaining duplicate item versions', async () => {
|
||||
const { calls } = mockPool({ timeoutItems: true })
|
||||
const repository = new SupplyChainShortageOrderRepository()
|
||||
const rows = await repository.listOrderItems()
|
||||
const batches = calls.filter(call => call.query.includes('[jst_OrderItem] i')).map(call => Object.values(call.inputs))
|
||||
expect(batches).toEqual([['9007199254740993', '9007199254740994'], ['9007199254740993'], ['9007199254740994']])
|
||||
expect(rows).toHaveLength(4)
|
||||
expect(new Set(rows.map(row => row.id)).size).toBe(4)
|
||||
expect(rows.every(row => row.quantity === 2)).toBe(true)
|
||||
await repository.close()
|
||||
})
|
||||
|
||||
it('retries a transient candidate timeout with a fresh request and retains both complete sources', async () => {
|
||||
const failed = new Set<string>()
|
||||
const { calls } = mockPool({ beforeQuery: query => {
|
||||
if (query.includes('@orderStatus') && !failed.has(query)) {
|
||||
failed.add(query)
|
||||
throw Object.assign(new Error('candidate timeout'), { code: 'ETIMEOUT' })
|
||||
}
|
||||
} })
|
||||
const repository = new SupplyChainShortageOrderRepository()
|
||||
const rows = await repository.listOrderItems()
|
||||
expect(rows.map(row => row.id)).toEqual(['OTHER:9007199254740993:001', 'TAOBAO:9007199254740993:001'])
|
||||
const attempts = calls.filter(call => call.query.includes('@orderStatus') && call.query.includes('[jst_Orders]'))
|
||||
expect(attempts).toHaveLength(2)
|
||||
expect(attempts[0].inputs).not.toBe(attempts[1].inputs)
|
||||
expect(attempts[1].inputs).toEqual({ orderStatus: 'Question' })
|
||||
await repository.close()
|
||||
})
|
||||
|
||||
it('stops after two candidate timeouts instead of looping or publishing a partial source', async () => {
|
||||
const { calls } = mockPool({ beforeQuery: query => {
|
||||
if (query.includes('@orderStatus') && query.includes('[jst_Orders]')) throw Object.assign(new Error('candidate timeout'), { code: 'ETIMEOUT' })
|
||||
} })
|
||||
const repository = new SupplyChainShortageOrderRepository()
|
||||
await expect(repository.listOrderItems()).rejects.toMatchObject({ code: 'ETIMEOUT' })
|
||||
expect(calls.filter(call => call.query.includes('@orderStatus') && call.query.includes('[jst_Orders]'))).toHaveLength(2)
|
||||
expect(calls.some(call => call.query.includes('WHERE i.o_id IN'))).toBe(false)
|
||||
await repository.close()
|
||||
})
|
||||
|
||||
it('subdivides timed-out header batches and still excludes an order with a newer cancelled version', async () => {
|
||||
const { calls } = mockPool({ headers: [
|
||||
{ internalOrderId: '1', exceptionType: '缺货', orderStatus: 'Question', sourceRowId: 1 },
|
||||
{ internalOrderId: '2', exceptionType: '预售', orderStatus: 'Question', sourceRowId: 2 },
|
||||
{ internalOrderId: '2', exceptionType: '预售', orderStatus: 'Cancelled', sourceRowId: 3 },
|
||||
], beforeQuery: (query, inputs) => {
|
||||
if (query.includes('WHERE o.o_id IN') && Object.keys(inputs).length > 1) throw Object.assign(new Error('header timeout'), { code: 'ETIMEOUT' })
|
||||
} })
|
||||
const repository = new SupplyChainShortageOrderRepository()
|
||||
const rows = await repository.listOrderItems()
|
||||
expect(rows.map(row => row.id)).toEqual(['OTHER:1:001', 'TAOBAO:1:001'])
|
||||
const batches = calls.filter(call => call.query.includes('[jst_Orders]') && call.query.includes('WHERE o.o_id IN')).map(call => Object.values(call.inputs))
|
||||
expect(batches).toEqual([['1', '2'], ['1'], ['2']])
|
||||
await repository.close()
|
||||
})
|
||||
|
||||
it.each(['headers', 'items'])('retries a timed-out single-order %s query only once', async operation => {
|
||||
const failures = new Set<string>()
|
||||
const marker = operation === 'headers' ? 'WHERE o.o_id IN' : 'WHERE i.o_id IN'
|
||||
const { calls } = mockPool({ beforeQuery: query => {
|
||||
if (query.includes(marker) && !failures.has(query)) {
|
||||
failures.add(query)
|
||||
throw Object.assign(new Error('single-order timeout'), { code: 'ETIMEOUT' })
|
||||
}
|
||||
} })
|
||||
const repository = new SupplyChainShortageOrderRepository()
|
||||
await expect(repository.listOrderItems()).resolves.toHaveLength(2)
|
||||
expect(calls.filter(call => call.query.includes(marker))).toHaveLength(4)
|
||||
await repository.close()
|
||||
})
|
||||
|
||||
it.each(['headers', 'items'])('rejects a permanently timed-out %s sub-batch after another sub-batch succeeds', async operation => {
|
||||
const marker = operation === 'headers' ? 'WHERE o.o_id IN' : 'WHERE i.o_id IN'
|
||||
const { calls } = mockPool({ headers: ['1', '2'].map(internalOrderId => ({
|
||||
internalOrderId, exceptionType: '缺货', orderStatus: 'Question', sourceRowId: 1,
|
||||
})), beforeQuery: (query, inputs) => {
|
||||
if (query.includes(marker) && Object.values(inputs).includes('2')) throw Object.assign(new Error('permanent timeout'), { code: 'ETIMEOUT' })
|
||||
} })
|
||||
const repository = new SupplyChainShortageOrderRepository()
|
||||
await expect(repository.listOrderItems()).rejects.toMatchObject({ code: 'ETIMEOUT' })
|
||||
const batches = calls.filter(call => call.query.includes(marker) && call.query.includes(operation === 'headers' ? '[jst_Orders]' : '[jst_OrderItem]')).map(call => Object.values(call.inputs))
|
||||
expect(batches).toEqual([['1', '2'], ['1'], ['2'], ['2']])
|
||||
await repository.close()
|
||||
})
|
||||
|
||||
|
||||
it('rejects invalid SQL identifiers before connecting', () => {
|
||||
expect(() => shortageHeaderSql('rpt]; DROP VIEW x;--', 'OTHER')).toThrow('Invalid report schema')
|
||||
})
|
||||
|
||||
it('reads all archive barcodes under matched styles, including barcodes absent from orders', async () => {
|
||||
const product = { barcode: '0001', sku: 'STYLE', productStatus: '停产' }
|
||||
const extra = { barcode: '0002', sku: 'STYLE', productStatus: '销售' }
|
||||
const query = jest.fn().mockResolvedValueOnce({ rows: [product] }).mockResolvedValueOnce({ rows: [product, extra] })
|
||||
jest.mocked(getSupplyChainArchiveReadPool).mockReturnValue({ query } as never)
|
||||
const result = await new SupplyChainShortageOrderRepository().listArchive(['0001'])
|
||||
expect(result).toEqual([product, extra])
|
||||
expect(query.mock.calls[1][0]).toContain('WHERE "sku" = ANY($1::text[])')
|
||||
expect(query.mock.calls[1][1]).toEqual([['STYLE']])
|
||||
})
|
||||
|
||||
it('reads enabled exchange rules from the latest snapshot and keeps the newest exact barcode mapping', async () => {
|
||||
const request = { input: jest.fn(), query: jest.fn().mockResolvedValue({ recordset: [
|
||||
{ barcode: ' 0001 ', targets: 'OLD', sourceId: 1, modifiedAt: '2026-11-10 08:00:00' },
|
||||
{ barcode: '0001', targets: '0002, 0003;0002', sourceId: 2, modifiedAt: '2026-11-11 08:00:00' },
|
||||
{ barcode: '0004', targets: null, sourceId: 3, modifiedAt: null },
|
||||
] }) }
|
||||
request.input.mockReturnValue(request)
|
||||
const pool = { connect: jest.fn(), request: () => request, close: jest.fn().mockResolvedValue(undefined) }
|
||||
pool.connect.mockResolvedValue(pool)
|
||||
jest.mocked(sql.ConnectionPool).mockImplementation(() => pool as unknown as sql.ConnectionPool)
|
||||
const repository = new SupplyChainShortageOrderRepository()
|
||||
const rules = await repository.listExchangeRules([' 0001 ', '0001', '0004'])
|
||||
expect(rules).toEqual([{ barcode: '0001', exchangeBarcodes: ['0002', '0003'] }, { barcode: '0004', exchangeBarcodes: [] }])
|
||||
expect(request.input).toHaveBeenCalledWith('barcodes', 'nvarchar(max)', '["0001","0004"]')
|
||||
expect(request.query.mock.calls[0][0]).toContain('MAX(snapshot_date)')
|
||||
expect(request.query.mock.calls[0][0]).toContain('r.enabled = 1')
|
||||
expect(request.query.mock.calls[0][0]).toContain('OPENJSON(@barcodes)')
|
||||
expect(request.query.mock.calls[0][0]).not.toContain('pm_replacementManage')
|
||||
await repository.close()
|
||||
})
|
||||
|
||||
it('skips exchange access when there are no original barcodes', async () => {
|
||||
const repository = new SupplyChainShortageOrderRepository()
|
||||
await expect(repository.listExchangeRules([])).resolves.toEqual([])
|
||||
expect(sql.ConnectionPool).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('tracks completed inventory lookups even when no rows exist and retains cloud/warehouse inputs', async () => {
|
||||
const request = { input: jest.fn(), query: jest.fn().mockResolvedValue({ recordsets: [[],
|
||||
[{ barcode: '0001', warehouseId: 1, available: 3 }], [{ id: 1, name: '仓', attribute: '成品发货仓-真实库存' }],
|
||||
] }) }
|
||||
request.input.mockReturnValue(request)
|
||||
const pool = { connect: jest.fn(), request: () => request, close: jest.fn().mockResolvedValue(undefined) }
|
||||
pool.connect.mockResolvedValue(pool)
|
||||
jest.mocked(sql.ConnectionPool).mockImplementation(() => pool as unknown as sql.ConnectionPool)
|
||||
const repository = new SupplyChainShortageOrderRepository()
|
||||
const snapshot = await repository.listInventory([' 0001 ', '0001'])
|
||||
expect(snapshot).toEqual({ requestedBarcodes: ['0001'], inventory: [], cloud: [{ barcode: '0001', warehouseId: 1, available: 3 }],
|
||||
warehouses: [{ id: 1, name: '仓', attribute: '成品发货仓-真实库存' }] })
|
||||
expect(request.input).toHaveBeenCalledWith('codes', 'nvarchar(max)', '["0001"]')
|
||||
await repository.close()
|
||||
})
|
||||
|
||||
it('pins all warehouse inventory to JSReportReplica.rpt while retaining the confirmed cloud deduction source', async () => {
|
||||
process.env.JST_REPORT_DB_SCHEMA = 'another_schema'
|
||||
const inventory = [{ barcode: '0001', warehouseId: 1, quantity: 10, orderLock: 4 }]
|
||||
const cloud = [{ barcode: '0001', warehouseId: 1, available: 3 }]
|
||||
const warehouses = [{ id: 1, name: '仓', attribute: '成品发货仓-真实库存' }]
|
||||
const request = { input: jest.fn(), query: jest.fn().mockResolvedValue({ recordsets: [inventory, cloud, warehouses] }) }
|
||||
request.input.mockReturnValue(request)
|
||||
const pool = { connect: jest.fn(), request: () => request, close: jest.fn().mockResolvedValue(undefined) }
|
||||
pool.connect.mockResolvedValue(pool)
|
||||
jest.mocked(sql.ConnectionPool).mockImplementation(() => pool as unknown as sql.ConnectionPool)
|
||||
const repository = new SupplyChainShortageOrderRepository()
|
||||
try {
|
||||
await expect(repository.listInventory([' 0001 ', '0001'])).resolves.toEqual({ requestedBarcodes: ['0001'], inventory, cloud, warehouses })
|
||||
const query = request.query.mock.calls[0][0]
|
||||
expect(query).toContain('FROM [JSReportReplica].[rpt].[jst_inventoryInfo] i')
|
||||
expect(query).toContain('FROM [JSReportReplica].[rpt].[jst_warehouseInfo]')
|
||||
expect(query).toContain('i.qty AS quantity, i.order_lock AS orderLock')
|
||||
expect(query).toContain('OPENJSON(@codes)')
|
||||
expect(query).toContain('OPENQUERY([JianSun_Old]')
|
||||
expect(query).toContain('FROM JianSun.dbo.jst_virtualstockStocksInfo WHERE qty > 0')
|
||||
expect(query).not.toContain('[another_schema]')
|
||||
expect(request.input).toHaveBeenCalledWith('codes', 'nvarchar(max)', '["0001"]')
|
||||
} finally { await repository.close() }
|
||||
})
|
||||
|
||||
it('skips all supporting-source connections for an empty barcode set', async () => {
|
||||
const repository = new SupplyChainShortageOrderRepository()
|
||||
await expect(repository.listInventory([])).resolves.toEqual({ requestedBarcodes: [], inventory: [], cloud: [], warehouses: [] })
|
||||
await expect(repository.listReplacementRules([])).resolves.toEqual([])
|
||||
await expect(repository.listClearance([])).resolves.toEqual([])
|
||||
expect(sql.ConnectionPool).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('finds SKU-only replacement rules without requiring a matching original barcode', async () => {
|
||||
const rule = { id: 889, barcode: 'DNZ028907', replacementBarcode: 'DNZ028915' }
|
||||
const request = { input: jest.fn(), query: jest.fn().mockResolvedValue({ recordset: [rule] }) }
|
||||
request.input.mockReturnValue(request)
|
||||
const pool = { connect: jest.fn(), request: () => request, close: jest.fn().mockResolvedValue(undefined) }
|
||||
pool.connect.mockResolvedValue(pool)
|
||||
jest.mocked(sql.ConnectionPool).mockImplementation(() => pool as unknown as sql.ConnectionPool)
|
||||
const repository = new SupplyChainShortageOrderRepository()
|
||||
try {
|
||||
await expect(repository.listReplacementRules([], [' dnz028907 ', 'DNZ028907'])).resolves.toEqual([rule])
|
||||
expect(request.input).toHaveBeenCalledWith('codes', 'nvarchar(max)', '["DNZ028907"]')
|
||||
} finally { await repository.close() }
|
||||
})
|
||||
|
||||
it('loads all target archive variants when the replacement token is a SKU', async () => {
|
||||
const variants = [{ barcode: 'DNZ028915N866V01', sku: 'DNZ028915' }, { barcode: 'DNZ028915N887V01', sku: 'DNZ028915' }]
|
||||
const query = jest.fn().mockResolvedValue({ rows: variants })
|
||||
jest.mocked(getSupplyChainArchiveReadPool).mockReturnValue({ query } as never)
|
||||
const result = await new SupplyChainShortageOrderRepository().listArchive([], [' dnz028915 '])
|
||||
expect(result).toEqual(variants)
|
||||
expect(query.mock.calls[0][1]).toEqual([[], ['DNZ028915']])
|
||||
expect(query.mock.calls[0][0]).toContain('UPPER(BTRIM("sku")) = ANY($2::text[])')
|
||||
})
|
||||
})
|
||||
@ -0,0 +1,367 @@
|
||||
import sql from 'mssql'
|
||||
import type { ShortageReadProgress } from '@/lib/supply-chain-shortage-orders'
|
||||
import type { ShortageClearanceRecord, ShortageInventorySnapshot, ShortageReplacementRule } from '@/lib/supply-chain-shortage-enrichment'
|
||||
import type { ShortageExchangeRule } from '@/lib/supply-chain-shortage-exchange'
|
||||
import { getSupplyChainArchiveReadPool } from './supply-chain-archive-read-pool'
|
||||
|
||||
export const SHORTAGE_QUESTION_TYPES = ['缺货', '真实缺货', '预售'] as const
|
||||
type Source = 'OTHER' | 'TAOBAO'
|
||||
type Header = {
|
||||
internalOrderId: string
|
||||
onlineOrderId: string | null
|
||||
orderType: string | null
|
||||
exceptionType: string
|
||||
orderStatus: string | null
|
||||
platform: string | null
|
||||
shopName: string | null
|
||||
paidAt: string | null
|
||||
labels: string | null
|
||||
}
|
||||
type HeaderRecord = Header & { sourceRowId: number; sourceModifiedAt: string | null }
|
||||
type Item = {
|
||||
internalOrderId: string
|
||||
itemId: string
|
||||
barcode: string | null
|
||||
quantity: number | null
|
||||
shopProductCode: string | null
|
||||
refundStatus: string | null
|
||||
skuType: string | null
|
||||
comboParentBarcode: string | null
|
||||
outerItemId: string | null
|
||||
itemStatus: string | null
|
||||
}
|
||||
type ItemRecord = Item & { sourceRowId: number }
|
||||
export type ShortageSourceRow = Header & Item & { id: string; source: Source }
|
||||
export type { ShortageExchangeRule } from '@/lib/supply-chain-shortage-exchange'
|
||||
type ExchangeRuleRecord = { barcode: string; targets: string | null; sourceId: number; modifiedAt: string | null }
|
||||
export type ShortageArchiveRow = {
|
||||
barcode: string
|
||||
sku: string
|
||||
categoryL2: string | null
|
||||
productName: string | null
|
||||
productStatus: string | null
|
||||
supplierName: string | null
|
||||
purchaseOwner: string | null
|
||||
packType: string | null
|
||||
productTag: string | null
|
||||
}
|
||||
|
||||
function requiredEnv(name: string) {
|
||||
const value = process.env[name]?.trim()
|
||||
if (!value) throw new Error(`Missing required environment variable: ${name}`)
|
||||
return value
|
||||
}
|
||||
|
||||
/** 所有批量读取共用两个工作槽,任一失败后停止分配新任务并等在途请求结束。 */
|
||||
async function readBatches<T>(batches: readonly T[], read: (batch: T) => Promise<void>) {
|
||||
let next = 0
|
||||
let failed = false
|
||||
const worker = async () => {
|
||||
try {
|
||||
while (!failed && next < batches.length) await read(batches[next++])
|
||||
} catch (error) { failed = true; throw error }
|
||||
}
|
||||
const results = await Promise.allSettled([worker(), worker()])
|
||||
for (const result of results) if (result.status === 'rejected') throw result.reason
|
||||
}
|
||||
|
||||
function timedOut(error: unknown) {
|
||||
return typeof error === 'object' && error !== null && 'code' in error && error.code === 'ETIMEOUT'
|
||||
}
|
||||
|
||||
type OrderReadContext = { source: Source; operation: 'candidates' | 'headers' | 'items'; batchSize?: number }
|
||||
|
||||
/** 不可再拆的读取最多重试一次;每次由调用方创建新 Request,不复用已取消的请求。 */
|
||||
async function readWithTimeoutRetry<T>(context: OrderReadContext, read: () => Promise<T>): Promise<T> {
|
||||
try { return await read() } catch (error) {
|
||||
if (!timedOut(error)) throw error
|
||||
console.warn('[shortage-orders] retrying timed-out source query', context)
|
||||
return read()
|
||||
}
|
||||
}
|
||||
|
||||
/** 大批次超时后缩小查询范围;只有完整读完所有子批次才返回。 */
|
||||
async function readOrderBatch<T>(context: OrderReadContext, ids: readonly string[], read: (ids: readonly string[]) => Promise<T[]>): Promise<T[]> {
|
||||
if (ids.length === 1) return readWithTimeoutRetry({ ...context, batchSize: 1 }, () => read(ids))
|
||||
try { return await read(ids) } catch (error) {
|
||||
if (!timedOut(error)) throw error
|
||||
console.warn('[shortage-orders] subdividing timed-out source query', { ...context, batchSize: ids.length })
|
||||
const middle = Math.floor(ids.length / 2)
|
||||
return [
|
||||
...await readOrderBatch(context, ids.slice(0, middle), read),
|
||||
...await readOrderBatch(context, ids.slice(middle), read),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
/** 标识符只能来自经过校验的本地配置;业务条件全部绑定参数。 */
|
||||
export function shortageHeaderSql(schema: string, source: Source, orderCount = 1) {
|
||||
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(schema)) throw new Error('Invalid report schema')
|
||||
if (!Number.isInteger(orderCount) || orderCount < 1 || orderCount > 100) throw new Error('Invalid order batch size')
|
||||
const table = source === 'OTHER' ? 'jst_Orders' : 'jst_qmcust_orderlist'
|
||||
return `SELECT CAST(o.o_id AS varchar(50)) AS internalOrderId,
|
||||
o.so_id AS onlineOrderId, o.type AS orderType,
|
||||
o.question_type AS exceptionType, o.status AS orderStatus,
|
||||
o.shop_site AS platform, o.shop_name AS shopName, o.labels,
|
||||
CONVERT(varchar(19), o.pay_date, 120) AS paidAt,
|
||||
o.Id AS sourceRowId, CONVERT(varchar(23), o.modified, 121) AS sourceModifiedAt
|
||||
FROM [${schema}].[${table}] o
|
||||
WHERE o.o_id IN (${Array.from({ length: orderCount }, (_, index) => `@order${index}`).join(',')})
|
||||
OPTION (RECOMPILE)`
|
||||
}
|
||||
|
||||
/** 只扫一次候选集合;之后读取候选订单的所有版本,再决定最新版本是否仍符合条件。 */
|
||||
export function shortageCandidateSql(schema: string, source: Source) {
|
||||
shortageHeaderSql(schema, source)
|
||||
const table = source === 'OTHER' ? 'jst_Orders' : 'jst_qmcust_orderlist'
|
||||
return `SELECT CAST(o.o_id AS varchar(50)) AS internalOrderId, o.question_type AS exceptionType
|
||||
FROM [${schema}].[${table}] o
|
||||
WHERE o.status = @orderStatus
|
||||
OPTION (RECOMPILE)`
|
||||
}
|
||||
|
||||
export class SupplyChainShortageOrderRepository {
|
||||
private poolPromise?: Promise<sql.ConnectionPool>
|
||||
|
||||
constructor(private readonly requestTimeout = 30_000) {}
|
||||
|
||||
private getPool() {
|
||||
if (!this.poolPromise) {
|
||||
const booleanEnv = (key: string) => !['false', '0'].includes(process.env[key]?.trim().toLowerCase() ?? '')
|
||||
this.poolPromise = new sql.ConnectionPool({
|
||||
server: requiredEnv('JST_REPORT_DB_HOST'),
|
||||
port: Number(process.env.JST_REPORT_DB_PORT || 1433),
|
||||
database: requiredEnv('JST_REPORT_DB_NAME'),
|
||||
user: requiredEnv('JST_REPORT_DB_USER'),
|
||||
password: requiredEnv('JST_REPORT_DB_PASSWORD'),
|
||||
options: {
|
||||
encrypt: booleanEnv('JST_REPORT_DB_ENCRYPT'),
|
||||
trustServerCertificate: booleanEnv('JST_REPORT_DB_TRUST_SERVER_CERTIFICATE'),
|
||||
readOnlyIntent: true,
|
||||
appName: 'supply-chain-shortage-orders',
|
||||
},
|
||||
pool: { min: 0, max: 2, idleTimeoutMillis: 30_000 },
|
||||
connectionTimeout: 20_000,
|
||||
requestTimeout: this.requestTimeout,
|
||||
}).connect().catch(error => {
|
||||
this.poolPromise = undefined
|
||||
throw error
|
||||
})
|
||||
}
|
||||
return this.poolPromise
|
||||
}
|
||||
|
||||
async listOrderItems(onProgress?: (progress: ShortageReadProgress) => void): Promise<ShortageSourceRow[]> {
|
||||
const schema = process.env.JST_REPORT_DB_SCHEMA?.trim() || 'rpt'
|
||||
// Validate before opening a connection.
|
||||
shortageHeaderSql(schema, 'OTHER')
|
||||
const pool = await this.getPool()
|
||||
const sources: Source[] = ['OTHER', 'TAOBAO']
|
||||
const headers = { OTHER: new Map<string, HeaderRecord>(), TAOBAO: new Map<string, HeaderRecord>() }
|
||||
const items = { OTHER: new Map<string, ItemRecord>(), TAOBAO: new Map<string, ItemRecord>() }
|
||||
let completed = 0
|
||||
onProgress?.({ stage: 'orders', completed, total: sources.length })
|
||||
await readBatches(sources, async source => {
|
||||
// 仅按状态读取小集合,避免异常类型 IN 组合在源视图上触发历史表扫描。
|
||||
const candidates = await readWithTimeoutRetry<{ recordset: Pick<Header, 'internalOrderId' | 'exceptionType'>[] }>({ source, operation: 'candidates' }, () =>
|
||||
pool.request().input('orderStatus', sql.NVarChar(255), 'Question')
|
||||
.query<{ internalOrderId: string; exceptionType: string }>(shortageCandidateSql(schema, source)))
|
||||
const ids = [...new Set(candidates
|
||||
.recordset.filter(row => SHORTAGE_QUESTION_TYPES.includes(row.exceptionType as typeof SHORTAGE_QUESTION_TYPES[number]))
|
||||
.map(row => row.internalOrderId))]
|
||||
for (let offset = 0; offset < ids.length; offset += 100) {
|
||||
const orderIds = ids.slice(offset, offset + 100)
|
||||
const batch = await readOrderBatch<HeaderRecord>({ source, operation: 'headers' }, orderIds, async batchIds => {
|
||||
const request = pool.request()
|
||||
batchIds.forEach((id, index) => request.input(`order${index}`, sql.BigInt, id))
|
||||
return (await request.query<HeaderRecord>(shortageHeaderSql(schema, source, batchIds.length))).recordset
|
||||
})
|
||||
for (const header of batch) {
|
||||
const previous = headers[source].get(header.internalOrderId)
|
||||
if (!previous || (header.sourceModifiedAt ?? '') > (previous.sourceModifiedAt ?? '') ||
|
||||
((header.sourceModifiedAt ?? '') === (previous.sourceModifiedAt ?? '') && header.sourceRowId > previous.sourceRowId)) {
|
||||
headers[source].set(header.internalOrderId, header)
|
||||
}
|
||||
}
|
||||
}
|
||||
onProgress?.({ stage: 'orders', completed: ++completed, total: sources.length })
|
||||
})
|
||||
|
||||
const itemBatches: Array<{ source: Source; orders: HeaderRecord[] }> = []
|
||||
for (const source of sources) {
|
||||
// 先取候选订单的所有版本并去重,避免排除最新状态后退回旧的异常订单。
|
||||
// 两个平台共用此条件,且在明细读取、货号需求汇总和缺货分类之前执行。
|
||||
const orders = [...headers[source].values()].filter(order =>
|
||||
order.orderStatus?.trim() === 'Question' && !order.labels?.includes('刷单') &&
|
||||
SHORTAGE_QUESTION_TYPES.includes(order.exceptionType as typeof SHORTAGE_QUESTION_TYPES[number]) &&
|
||||
!order.orderType?.includes('配件'))
|
||||
for (let offset = 0; offset < orders.length; offset += 100) {
|
||||
itemBatches.push({ source, orders: orders.slice(offset, offset + 100) })
|
||||
}
|
||||
}
|
||||
const readItems = async ({ source, orders }: typeof itemBatches[number]): Promise<void> => {
|
||||
const table = source === 'OTHER' ? 'jst_OrderItem' : 'jst_qmcust_orderlist_item'
|
||||
const batch = await readOrderBatch<ItemRecord>({ source, operation: 'items' }, orders.map(order => order.internalOrderId), async ids => {
|
||||
const itemRequest = pool.request()
|
||||
ids.forEach((id, index) => itemRequest.input(`order${index}`, sql.BigInt, id))
|
||||
const batch = await itemRequest.query<ItemRecord>(`SELECT CAST(i.o_id AS varchar(50)) AS internalOrderId,
|
||||
COALESCE(CAST(i.oi_id AS varchar(50)), CONCAT('row-', i.Id)) AS itemId,
|
||||
i.sku_id AS barcode, i.qty AS quantity, i.shop_sku_id AS shopProductCode,
|
||||
i.refund_status AS refundStatus, i.Id AS sourceRowId,
|
||||
i.sku_type AS skuType, i.src_combine_sku_id AS comboParentBarcode, i.outer_oi_id AS outerItemId,
|
||||
i.item_status AS itemStatus
|
||||
FROM [${schema}].[${table}] i
|
||||
WHERE i.o_id IN (${ids.map((_, index) => `@order${index}`).join(',')})
|
||||
OPTION (RECOMPILE)`)
|
||||
return batch.recordset
|
||||
})
|
||||
for (const item of batch) {
|
||||
const key = `${item.internalOrderId}:${item.itemId}`
|
||||
const previous = items[source].get(key)
|
||||
if (!previous || item.sourceRowId > previous.sourceRowId) items[source].set(key, item)
|
||||
}
|
||||
}
|
||||
completed = 0
|
||||
onProgress?.({ stage: 'items', completed, total: itemBatches.length })
|
||||
await readBatches(itemBatches, async batch => {
|
||||
await readItems(batch)
|
||||
onProgress?.({ stage: 'items', completed: ++completed, total: itemBatches.length })
|
||||
})
|
||||
return sources.flatMap(source => [...items[source].values()].flatMap(({ sourceRowId: _itemSourceId, ...item }) => {
|
||||
const header = headers[source].get(item.internalOrderId)
|
||||
if (!header) return []
|
||||
const { sourceRowId: _orderSourceId, sourceModifiedAt: _modified, ...order } = header
|
||||
return [{ ...order, ...item, source, id: `${source}:${item.internalOrderId}:${item.itemId}` }]
|
||||
}))
|
||||
}
|
||||
|
||||
async listExchangeRules(barcodes: readonly string[]): Promise<ShortageExchangeRule[]> {
|
||||
const codes = [...new Set(barcodes.map(code => code.trim().toUpperCase()).filter(Boolean))]
|
||||
if (!codes.length) return []
|
||||
const schema = process.env.JST_REPORT_DB_SCHEMA?.trim() || 'rpt'
|
||||
shortageHeaderSql(schema, 'OTHER')
|
||||
const pool = await this.getPool()
|
||||
const result = await pool.request()
|
||||
.input('barcodes', sql.NVarChar(sql.MAX), JSON.stringify(codes))
|
||||
.query<ExchangeRuleRecord>(`
|
||||
SELECT r.sku_id AS barcode, r.data AS targets, r.id AS sourceId,
|
||||
CONVERT(varchar(23), COALESCE(r.modified, r.created), 121) AS modifiedAt
|
||||
FROM [${schema}].[jst_sku_replace_rule] r
|
||||
WHERE r.snapshot_date = (SELECT MAX(snapshot_date) FROM [${schema}].[jst_sku_replace_rule])
|
||||
AND r.enabled = 1
|
||||
AND UPPER(LTRIM(RTRIM(r.sku_id))) IN (SELECT [value] FROM OPENJSON(@barcodes))
|
||||
`)
|
||||
const latest = new Map<string, ExchangeRuleRecord>()
|
||||
for (const row of result.recordset) {
|
||||
const barcode = row.barcode.trim().toUpperCase()
|
||||
const previous = latest.get(barcode)
|
||||
if (!previous || (row.modifiedAt ?? '') > (previous.modifiedAt ?? '') ||
|
||||
((row.modifiedAt ?? '') === (previous.modifiedAt ?? '') && row.sourceId > previous.sourceId)) latest.set(barcode, row)
|
||||
}
|
||||
return [...latest].map(([barcode, row]) => ({
|
||||
barcode,
|
||||
// 多个候选按源规则顺序展示;不擅自按库存选一个,也不使用 PM 替换款规则代替换货规则。
|
||||
exchangeBarcodes: [...new Set((row.targets ?? '').split(/[,,;;\r\n]+/).map(code => code.trim().toUpperCase()).filter(Boolean))],
|
||||
}))
|
||||
}
|
||||
|
||||
async listArchive(barcodes: readonly string[], skus: readonly string[] = []): Promise<ShortageArchiveRow[]> {
|
||||
if (!barcodes.length && !skus.length) return []
|
||||
const pool = getSupplyChainArchiveReadPool()
|
||||
const matched = await pool.query<ShortageArchiveRow>(`
|
||||
SELECT "barcode", "sku", "categoryL2", "productName", "productStatus", "supplierName",
|
||||
"purchaseOwner", "packType", "productTag"
|
||||
FROM public."SupplyChainProductArchive"
|
||||
WHERE UPPER(BTRIM("barcode")) = ANY($1::text[])
|
||||
OR UPPER(BTRIM("sku")) = ANY($2::text[])
|
||||
`, [[...new Set(barcodes.map(code => code.trim().toUpperCase()).filter(Boolean))], [...new Set(skus.map(code => code.trim().toUpperCase()).filter(Boolean))]])
|
||||
const matchedSkus = [...new Set(matched.rows.map(row => row.sku).filter(Boolean))]
|
||||
if (!matchedSkus.length) return matched.rows
|
||||
// AA 状态必须包含这些货号下的全部编码,不能仅聚合本次订单编码。
|
||||
const all = await pool.query<ShortageArchiveRow>(`
|
||||
SELECT "barcode", "sku", "categoryL2", "productName", "productStatus", "supplierName",
|
||||
"purchaseOwner", "packType", "productTag"
|
||||
FROM public."SupplyChainProductArchive" WHERE "sku" = ANY($1::text[])
|
||||
`, [matchedSkus])
|
||||
return [...new Map([...matched.rows, ...all.rows].map(row => [row.barcode, row])).values()]
|
||||
}
|
||||
|
||||
async listReplacementRules(barcodes: readonly string[], skus: readonly string[] = []): Promise<ShortageReplacementRule[]> {
|
||||
// 上游 sku / replaceSku 可维护商品编码,也可维护货号,两个粒度均须读取。
|
||||
const codes = [...new Set([...barcodes, ...skus].map(code => code.trim().toUpperCase()).filter(Boolean))]
|
||||
if (!codes.length) return []
|
||||
const schema = process.env.JST_REPORT_DB_SCHEMA?.trim() || 'rpt'
|
||||
shortageHeaderSql(schema, 'OTHER')
|
||||
const pool = await this.getPool()
|
||||
const result = await pool.request().input('codes', sql.NVarChar(sql.MAX), JSON.stringify(codes))
|
||||
.query<ShortageReplacementRule>(`SELECT r.id, r.sku AS barcode, r.replaceSku AS replacementBarcode,
|
||||
r.replaceType AS replacementType, r.isSwapping AS imageChange, r.differentPoints AS differences,
|
||||
CONVERT(varchar(23), r.createTime, 121) AS createdAt
|
||||
FROM [${schema}].[pm_replacementManage] r
|
||||
WHERE r.[delete] = 0 AND LTRIM(RTRIM(r.sku)) <> '' AND LTRIM(RTRIM(r.replaceSku)) <> ''
|
||||
AND (UPPER(LTRIM(RTRIM(r.sku))) IN (SELECT [value] FROM OPENJSON(@codes))
|
||||
OR UPPER(LTRIM(RTRIM(r.replaceSku))) IN (SELECT [value] FROM OPENJSON(@codes)))`)
|
||||
return result.recordset
|
||||
}
|
||||
|
||||
async listInventory(barcodes: readonly string[]): Promise<ShortageInventorySnapshot> {
|
||||
const codes = [...new Set(barcodes.map(code => code.trim().toUpperCase()).filter(Boolean))]
|
||||
if (!codes.length) return { requestedBarcodes: [], inventory: [], cloud: [], warehouses: [] }
|
||||
const pool = await this.getPool()
|
||||
// 用户指定所有仓库库存统一读取此副本;不依赖连接默认库或其他来源的 schema 配置。
|
||||
// 公有可用数继续扣减订单占用与原云仓可用数,仓库分组读取同库档案。
|
||||
const result = await pool.request().input('codes', sql.NVarChar(sql.MAX), JSON.stringify(codes)).query(`
|
||||
SELECT i.sku_id AS barcode, i.wms_co_id AS warehouseId, i.qty AS quantity, i.order_lock AS orderLock
|
||||
FROM [JSReportReplica].[rpt].[jst_inventoryInfo] i
|
||||
WHERE UPPER(LTRIM(RTRIM(i.sku_id))) IN (SELECT [value] FROM OPENJSON(@codes));
|
||||
SELECT sku_id AS barcode, wms_co_id AS warehouseId, order_able_qty AS available
|
||||
FROM OPENQUERY([JianSun_Old], N'SELECT sku_id, wms_co_id, order_able_qty
|
||||
FROM JianSun.dbo.jst_virtualstockStocksInfo WHERE qty > 0');
|
||||
SELECT wms_co_id AS id, name, remark2 AS attribute FROM [JSReportReplica].[rpt].[jst_warehouseInfo];
|
||||
`)
|
||||
const [inventory, cloud, warehouses] = result.recordsets as [
|
||||
ShortageInventorySnapshot['inventory'], ShortageInventorySnapshot['cloud'], ShortageInventorySnapshot['warehouses'],
|
||||
]
|
||||
return { requestedBarcodes: codes, inventory, cloud, warehouses }
|
||||
}
|
||||
|
||||
async listClearance(barcodes: readonly string[]): Promise<ShortageClearanceRecord[]> {
|
||||
const codes = [...new Set(barcodes.map(code => code.trim().toUpperCase()).filter(Boolean))]
|
||||
if (!codes.length) return []
|
||||
const schema = process.env.JST_REPORT_DB_SCHEMA?.trim() || 'rpt'
|
||||
shortageHeaderSql(schema, 'OTHER')
|
||||
const pool = await this.getPool()
|
||||
const result = await pool.request().input('codes', sql.NVarChar(sql.MAX), JSON.stringify(codes))
|
||||
.query<ShortageClearanceRecord>(`SELECT Id AS id, skucode AS barcode, state, remainingStock,
|
||||
CONVERT(varchar(23), COALESCE(updateTime, createTime), 121) AS updatedAt
|
||||
FROM [${schema}].[plm_productDiscontinuation]
|
||||
WHERE UPPER(LTRIM(RTRIM(skucode))) IN (SELECT [value] FROM OPENJSON(@codes))`)
|
||||
return result.recordset
|
||||
}
|
||||
|
||||
async listReportPurchasers(suppliers: readonly string[]): Promise<{ supplier: string; purchaser: string | null }[]> {
|
||||
const names = [...new Set(suppliers.map(name => name.trim()).filter(Boolean))]
|
||||
if (!names.length) return []
|
||||
const schema = process.env.JST_REPORT_DB_SCHEMA?.trim() || 'rpt'
|
||||
shortageHeaderSql(schema, 'OTHER')
|
||||
const pool = await this.getPool()
|
||||
const result = await pool.request().input('names', sql.NVarChar(sql.MAX), JSON.stringify(names))
|
||||
.query<{ supplier: string; purchaser: string | null }>(`
|
||||
WITH ranked AS (
|
||||
SELECT LTRIM(RTRIM(scmname)) AS supplier, NULLIF(LTRIM(RTRIM(buyer)), '') AS purchaser,
|
||||
ROW_NUMBER() OVER (PARTITION BY LTRIM(RTRIM(scmname)) ORDER BY local_updated DESC, Id DESC) AS rn
|
||||
FROM [${schema}].[js_supplier]
|
||||
WHERE LTRIM(RTRIM(scmname)) IN (SELECT [value] FROM OPENJSON(@names))
|
||||
) SELECT supplier, purchaser FROM ranked WHERE rn = 1
|
||||
`)
|
||||
return result.recordset
|
||||
}
|
||||
|
||||
async close() {
|
||||
const pool = await this.poolPromise
|
||||
this.poolPromise = undefined
|
||||
await pool?.close()
|
||||
}
|
||||
}
|
||||
|
||||
export const supplyChainShortageOrderRepository = new SupplyChainShortageOrderRepository()
|
||||
@ -0,0 +1,48 @@
|
||||
/** @jest-environment node */
|
||||
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { SupplyChainShortagePreparedFileRepository } from './supply-chain-shortage-prepared-file.repository'
|
||||
|
||||
describe('每日订单下载文件交接', () => {
|
||||
let directory: string
|
||||
let now: Date
|
||||
let repository: SupplyChainShortagePreparedFileRepository
|
||||
const file = { filename: '订单_日期不固定.xlsx', content: Buffer.from('completed workbook') }
|
||||
beforeEach(async () => {
|
||||
directory = await mkdtemp(path.join(tmpdir(), 'shortage-prepared-'))
|
||||
now = new Date('2026-11-24T00:50:00Z')
|
||||
repository = new SupplyChainShortagePreparedFileRepository(directory, () => now)
|
||||
})
|
||||
afterEach(async () => { await rm(directory, { recursive: true, force: true }) })
|
||||
|
||||
it('persists completed downloads across processes and atomically replaces the current-day marker', async () => {
|
||||
await repository.save(file, '2026-11-24')
|
||||
const reader = new SupplyChainShortagePreparedFileRepository(directory, () => now)
|
||||
expect(await reader.readToday()).toEqual(file)
|
||||
const replacement = { ...file, content: Buffer.from('second completed workbook') }
|
||||
await repository.save(replacement, '2026-11-24')
|
||||
expect(await reader.readToday()).toEqual(replacement)
|
||||
})
|
||||
|
||||
it('rejects missing downloads and never substitutes yesterday or accepts yesterday as a requested date', async () => {
|
||||
await expect(repository.readToday()).rejects.toThrow('08:50')
|
||||
await repository.save(file, '2026-11-24')
|
||||
now = new Date('2026-11-24T16:00:00Z')
|
||||
await expect(repository.readToday()).rejects.toThrow('2026-11-25')
|
||||
await expect(repository.readToday('2026-11-24')).rejects.toThrow('当日')
|
||||
await expect(repository.save(file, '2026-11-24')).rejects.toThrow('当日')
|
||||
})
|
||||
|
||||
it('rejects modified content, incorrect dates and unsafe manifest paths', async () => {
|
||||
const manifest = await repository.save(file, '2026-11-24')
|
||||
await writeFile(path.join(directory, '2026-11-24', `${manifest.sha256}.xlsx`), 'partial download')
|
||||
await expect(repository.readToday()).rejects.toThrow('校验失败')
|
||||
const markerPath = path.join(directory, '2026-11-24', 'completed.json')
|
||||
const original = JSON.parse(await readFile(markerPath, 'utf8'))
|
||||
for (const changed of [{ preparedOn: '2026-11-23' }, { preparedAt: '2026-11-23T00:50:00Z' }, { sha256: '../other' }, { filename: '订单/other.xlsx' }]) {
|
||||
await writeFile(markerPath, JSON.stringify({ ...original, ...changed }))
|
||||
await expect(repository.readToday()).rejects.toThrow('完成标记不正确')
|
||||
}
|
||||
})
|
||||
})
|
||||
@ -0,0 +1,53 @@
|
||||
import { createHash, randomUUID } from 'node:crypto'
|
||||
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
import { shortageReportToday } from '@/lib/supply-chain-shortage-report'
|
||||
|
||||
const digest = (content: Buffer) => createHash('sha256').update(content).digest('hex')
|
||||
|
||||
/** 08:50下载与09:00计算之间的本地持久交接;只有完整文件才发布完成标记。 */
|
||||
export class SupplyChainShortagePreparedFileRepository {
|
||||
constructor(
|
||||
private readonly directory = path.resolve(process.cwd(), '.codex-runtime', 'jst-shortage-prepared'),
|
||||
private readonly now: () => Date = () => new Date(),
|
||||
) {}
|
||||
|
||||
private todayDirectory(date: string) {
|
||||
if (date !== shortageReportToday(this.now())) throw new Error('仅允许使用当日下载的订单文件')
|
||||
return path.join(this.directory, date)
|
||||
}
|
||||
|
||||
async save(file: { content: Buffer; filename: string }, date: string) {
|
||||
const directory = this.todayDirectory(date)
|
||||
const sha256 = digest(file.content)
|
||||
const preparedAt = this.now().toISOString()
|
||||
await mkdir(directory, { recursive: true })
|
||||
const temporary = path.join(directory, `${randomUUID()}.tmp`)
|
||||
await writeFile(temporary, file.content, { flag: 'wx' })
|
||||
await rename(temporary, path.join(directory, `${sha256}.xlsx`))
|
||||
const manifest = { version: 1, preparedOn: date, preparedAt, filename: file.filename, sha256 }
|
||||
const marker = path.join(directory, `${randomUUID()}.json.tmp`)
|
||||
await writeFile(marker, JSON.stringify(manifest), { flag: 'wx' })
|
||||
this.todayDirectory(date)
|
||||
await rename(marker, path.join(directory, 'completed.json'))
|
||||
return manifest
|
||||
}
|
||||
|
||||
async readToday(date = shortageReportToday(this.now())) {
|
||||
const directory = this.todayDirectory(date)
|
||||
const manifest: unknown = await readFile(path.join(directory, 'completed.json'), 'utf8').then(JSON.parse).catch(() => {
|
||||
throw new Error(`${date}尚无完整订单下载文件,请检查08:50下载任务`)
|
||||
})
|
||||
if (!manifest || typeof manifest !== 'object' || !('version' in manifest) || manifest.version !== 1 ||
|
||||
!('preparedOn' in manifest) || manifest.preparedOn !== date ||
|
||||
!('preparedAt' in manifest) || typeof manifest.preparedAt !== 'string' || !Number.isFinite(Date.parse(manifest.preparedAt)) || shortageReportToday(new Date(manifest.preparedAt)) !== date ||
|
||||
!('filename' in manifest) || typeof manifest.filename !== 'string' || !/^订单[^/\\]*\.xlsx$/i.test(manifest.filename) ||
|
||||
!('sha256' in manifest) || typeof manifest.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(manifest.sha256)) throw new Error('当日订单下载完成标记不正确,请重新下载')
|
||||
const content = await readFile(path.join(directory, `${manifest.sha256}.xlsx`))
|
||||
if (digest(content) !== manifest.sha256) throw new Error('当日订单下载文件校验失败,请重新下载')
|
||||
this.todayDirectory(date)
|
||||
return { filename: manifest.filename, content }
|
||||
}
|
||||
}
|
||||
|
||||
export const supplyChainShortagePreparedFileRepository = new SupplyChainShortagePreparedFileRepository()
|
||||
@ -0,0 +1,78 @@
|
||||
import { Client } from 'pg'
|
||||
import type { Prisma, ShortageReportEntry } from '@prisma/client'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import type { ShortageReportManualInput, ShortageReportRow } from '@/lib/supply-chain-shortage-report'
|
||||
|
||||
const dateValue = (date: string) => new Date(`${date}T00:00:00.000Z`)
|
||||
function dto(row: ShortageReportEntry): ShortageReportRow {
|
||||
const { updatedById: _user, updatedAt: _updatedAt, ...values } = row
|
||||
return { ...values, generatedOn: row.generatedOn.toISOString().slice(0, 10) }
|
||||
}
|
||||
|
||||
export class SupplyChainShortageReportRepository {
|
||||
/** 会话锁跨 Web/定时进程共用;进程退出时由 PostgreSQL 自动释放。 */
|
||||
async acquireGenerationLock(): Promise<(() => Promise<void>) | null> {
|
||||
const client = new Client({ connectionString: process.env.DATABASE_URL, connectionTimeoutMillis: 10_000 })
|
||||
try {
|
||||
await client.connect()
|
||||
const result = await client.query<{ locked: boolean }>('SELECT pg_try_advisory_lock(913712, 9) AS locked')
|
||||
if (!result.rows[0].locked) { await client.end(); return null }
|
||||
return async () => { await client.end() }
|
||||
} catch (error) { await client.end().catch(() => {}); throw error }
|
||||
}
|
||||
|
||||
async findSnapshot(date: string) {
|
||||
return prisma.shortageReportSnapshot.findUnique({ where: { generatedOn: dateValue(date) } })
|
||||
}
|
||||
|
||||
async listRetained(min: string, max: string): Promise<ShortageReportRow[]> {
|
||||
const rows = await prisma.shortageReportEntry.findMany({
|
||||
where: { generatedOn: { gte: dateValue(min), lte: dateValue(max) } },
|
||||
orderBy: [{ generatedOn: 'desc' }, { sku: 'asc' }, { barcode: 'asc' }],
|
||||
})
|
||||
return rows.map(dto)
|
||||
}
|
||||
|
||||
async publish(date: string, sourceFetchedAt: string, rows: readonly ShortageReportRow[], min: string, rebuildToday = false, transaction?: Prisma.TransactionClient) {
|
||||
const persist = async (tx: Prisma.TransactionClient) => {
|
||||
const existing = await tx.shortageReportSnapshot.findUnique({ where: { generatedOn: dateValue(date) } })
|
||||
// 日常任务不覆盖;手动更新或规则修正显式重建当日,保留仍在报表中的人工填报。
|
||||
if (existing && !rebuildToday) return false
|
||||
if (existing) {
|
||||
await tx.shortageReportSnapshot.update({ where: { generatedOn: dateValue(date) }, data: { sourceFetchedAt: new Date(sourceFetchedAt), generatedAt: new Date() } })
|
||||
for (const row of rows) {
|
||||
const { id, generatedOn: _generatedOn, expectedArrival: _arrival, notes: _notes, replacementTransit: _transit, version: _version, ...computed } = row
|
||||
await tx.shortageReportEntry.upsert({
|
||||
where: { id },
|
||||
create: { ...row, generatedOn: dateValue(date) },
|
||||
update: { ...computed, version: { increment: 1 } },
|
||||
})
|
||||
}
|
||||
await tx.shortageReportEntry.deleteMany({ where: { generatedOn: dateValue(date), id: { notIn: rows.map(row => row.id) } } })
|
||||
} else {
|
||||
await tx.shortageReportSnapshot.create({ data: { generatedOn: dateValue(date), sourceFetchedAt: new Date(sourceFetchedAt) } })
|
||||
if (rows.length) await tx.shortageReportEntry.createMany({ data: rows.map(row => ({ ...row, generatedOn: dateValue(date) })) })
|
||||
}
|
||||
await tx.shortageReportSnapshot.deleteMany({ where: { generatedOn: { lt: dateValue(min) } } })
|
||||
return true
|
||||
}
|
||||
return transaction ? persist(transaction) : prisma.$transaction(persist, { timeout: 30_000 })
|
||||
}
|
||||
|
||||
async pruneBefore(min: string) {
|
||||
await prisma.shortageReportSnapshot.deleteMany({ where: { generatedOn: { lt: dateValue(min) } } })
|
||||
}
|
||||
|
||||
async updateManual(input: ShortageReportManualInput, userId: string, min: string, max: string): Promise<ShortageReportRow | null> {
|
||||
return prisma.$transaction(async tx => {
|
||||
const updated = await tx.shortageReportEntry.updateMany({
|
||||
where: { id: input.id, version: input.version, generatedOn: { gte: dateValue(min), lte: dateValue(max) } },
|
||||
data: { expectedArrival: input.expectedArrival, notes: input.notes, replacementTransit: input.replacementTransit, version: { increment: 1 }, updatedById: userId },
|
||||
})
|
||||
if (!updated.count) return null
|
||||
return dto((await tx.shortageReportEntry.findUniqueOrThrow({ where: { id: input.id } })))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export const supplyChainShortageReportRepository = new SupplyChainShortageReportRepository()
|
||||
@ -0,0 +1,49 @@
|
||||
/** @jest-environment node */
|
||||
import path from 'node:path'
|
||||
import { readFile } from 'node:fs/promises'
|
||||
|
||||
jest.mock('node:util', () => ({ promisify: () => (...args: unknown[]) => mockExecute(...args) }))
|
||||
jest.mock('node:fs/promises', () => ({ readFile: jest.fn() }))
|
||||
const mockExecute = jest.fn()
|
||||
import { SupplyChainShortageWebExportRepository } from './supply-chain-shortage-web-export.repository'
|
||||
|
||||
describe('聚水潭浏览器导出进程', () => {
|
||||
const repository = new SupplyChainShortageWebExportRepository()
|
||||
const filename = '订单_日期不固定.xlsx'
|
||||
const filePath = path.resolve('.codex-runtime/jst-shortage-exports/2026-11-24', filename)
|
||||
const marker = `JST_SHORTAGE_EXPORT_RESULT=${JSON.stringify({ filename, path: filePath })}`
|
||||
beforeEach(() => { jest.clearAllMocks(); jest.mocked(readFile).mockResolvedValue(Buffer.from('workbook')) })
|
||||
|
||||
it.each(['stdout', 'stderr'])('accepts the completed download marker from %s', async stream => {
|
||||
mockExecute.mockResolvedValue({ stdout: '', stderr: '', [stream]: `progress\r\n${marker}\r\n` })
|
||||
await expect(repository.downloadOrders()).resolves.toEqual({ filename, content: Buffer.from('workbook') })
|
||||
expect(readFile).toHaveBeenCalledWith(filePath)
|
||||
expect(mockExecute).toHaveBeenCalledWith(expect.any(String), ['nodejs', '-e', expect.stringContaining('exportShortageOrders()')], expect.objectContaining({ windowsHide: true, timeout: 480000 }))
|
||||
})
|
||||
|
||||
it('rejects a failed process even if it printed a result marker', async () => {
|
||||
mockExecute.mockRejectedValue({ stdout: marker, code: 1 })
|
||||
await expect(repository.downloadOrders()).rejects.toThrow('聚水潭网页导出未完成')
|
||||
expect(readFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns the observed ERP export frequency limit without misreporting a login failure', async () => {
|
||||
mockExecute.mockRejectedValue({ stderr: '聚水潭限制相同条件频繁导出,请5分钟后再试', code: 1 })
|
||||
await expect(repository.downloadOrders()).rejects.toThrow('聚水潭限制相同条件频繁导出,请5分钟后再试')
|
||||
expect(readFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not read an artifact outside the export directory', async () => {
|
||||
mockExecute.mockResolvedValue({ stdout: `JST_SHORTAGE_EXPORT_RESULT=${JSON.stringify({ filename, path: path.resolve('.env.local') })}`, stderr: '' })
|
||||
await expect(repository.downloadOrders()).rejects.toThrow('网页导出文件位置不正确')
|
||||
expect(readFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('finishes only its newly created browser space in a separate invocation after reading the artifact', async () => {
|
||||
mockExecute.mockResolvedValueOnce({ stdout: '', stderr: `JST_SHORTAGE_EXPORT_RESULT=${JSON.stringify({ filename, path: filePath, ownsTaskSpace: true, taskSpaceId: 17 })}` })
|
||||
.mockResolvedValueOnce({ stdout: '', stderr: '' })
|
||||
await expect(repository.downloadOrders()).resolves.toHaveProperty('filename', filename)
|
||||
expect(mockExecute).toHaveBeenNthCalledWith(2, expect.any(String), ['nodejs', '-e', 'const task = await taskSpace(17); await task.finish({ keep: [] })'], expect.objectContaining({ windowsHide: true, timeout: 30000 }))
|
||||
expect(jest.mocked(readFile).mock.invocationCallOrder[0]).toBeLessThan(mockExecute.mock.invocationCallOrder[1])
|
||||
})
|
||||
})
|
||||
@ -0,0 +1,37 @@
|
||||
import { execFile } from 'node:child_process'
|
||||
import { promisify } from 'node:util'
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
|
||||
const execute = promisify(execFile)
|
||||
|
||||
export class SupplyChainShortageWebExportRepository {
|
||||
async downloadOrders() {
|
||||
const script = pathToFileURL(path.resolve(process.cwd(), 'scripts/jst-shortage-orders-export.mjs')).href
|
||||
const executable = process.env.SHORTAGE_EGO_BROWSER_EXECUTABLE?.trim() || 'ego-browser'
|
||||
const { stdout, stderr } = await execute(executable, ['nodejs', '-e', `const m = await import(${JSON.stringify(script)}); await m.exportShortageOrders()`], {
|
||||
cwd: process.cwd(), windowsHide: true, timeout: 8 * 60_000, maxBuffer: 1024 * 1024,
|
||||
}).catch((error: { stdout?: string; stderr?: string }) => {
|
||||
if (`${error.stdout ?? ''}\n${error.stderr ?? ''}`.includes('聚水潭限制相同条件频繁导出,请5分钟后再试')) throw new Error('聚水潭限制相同条件频繁导出,请5分钟后再试')
|
||||
throw new Error('聚水潭网页导出未完成,请检查浏览器登录、验证及“缺货报表看板”模板后重试')
|
||||
})
|
||||
// Windows版ego-browser将nodejs控制台输出写入stderr;仅在进程成功退出时读取结果标记。
|
||||
const line = `${stdout}\n${stderr}`.split(/\r?\n/).find(value => value.startsWith('JST_SHORTAGE_EXPORT_RESULT='))
|
||||
if (!line) throw new Error('网页导出未返回完整订单文件')
|
||||
const result: unknown = JSON.parse(line.slice('JST_SHORTAGE_EXPORT_RESULT='.length))
|
||||
if (!result || typeof result !== 'object' || !('path' in result) || typeof result.path !== 'string' || !('filename' in result) || typeof result.filename !== 'string') throw new Error('网页导出结果格式不正确')
|
||||
const allowedDirectory = path.resolve(process.cwd(), '.codex-runtime', 'jst-shortage-exports') + path.sep
|
||||
if (!path.resolve(result.path).startsWith(allowedDirectory)) throw new Error('网页导出文件位置不正确')
|
||||
const content = await readFile(result.path)
|
||||
// 文件落盘并读取成功后,用独立的最后一轮关闭本进程新建的浏览器空间。
|
||||
if ('ownsTaskSpace' in result && result.ownsTaskSpace === true && 'taskSpaceId' in result && Number.isSafeInteger(result.taskSpaceId) && Number(result.taskSpaceId) > 0) {
|
||||
await execute(executable, ['nodejs', '-e', `const task = await taskSpace(${Number(result.taskSpaceId)}); await task.finish({ keep: [] })`], {
|
||||
cwd: process.cwd(), windowsHide: true, timeout: 30_000, maxBuffer: 1024 * 1024,
|
||||
})
|
||||
}
|
||||
return { filename: result.filename, content }
|
||||
}
|
||||
}
|
||||
|
||||
export const supplyChainShortageWebExportRepository = new SupplyChainShortageWebExportRepository()
|
||||
@ -0,0 +1,255 @@
|
||||
/** @jest-environment node */
|
||||
import type { AuthUser } from '@/server/core/types'
|
||||
import { AppError, ErrorCode } from '@/server/core/errors'
|
||||
import { SupplyChainShortageOrderSnapshotService } from './supply-chain-shortage-order-snapshot.service'
|
||||
|
||||
jest.mock('@/server/repositories/supply-chain-shortage-order-snapshot.repository', () => ({ supplyChainShortageOrderSnapshotRepository: {} }))
|
||||
jest.mock('./supply-chain-shortage-order.service', () => ({ SupplyChainShortageOrderService: jest.fn() }))
|
||||
jest.mock('@/server/repositories/supply-chain-shortage-order.repository', () => ({ SupplyChainShortageOrderRepository: jest.fn() }))
|
||||
jest.mock('./supply-chain-permission-settings.service', () => ({ supplyChainPermissionSettingsService: {} }))
|
||||
|
||||
const user = { id: 'user' } as AuthUser
|
||||
const stored = { rows: [], fetchedAt: '2026-11-19T01:01:00Z', generatedOn: '2026-11-19', generatedAt: '2026-11-19T01:01:01Z' }
|
||||
function setup(time = '2026-11-20T01:00:00Z') {
|
||||
let now = new Date(time)
|
||||
const release = jest.fn().mockResolvedValue(undefined)
|
||||
const repository = { findLatest: jest.fn().mockResolvedValue(stored), findSnapshot: jest.fn().mockResolvedValue(null),
|
||||
publish: jest.fn().mockResolvedValue(true), acquireGenerationLock: jest.fn().mockResolvedValue(release),
|
||||
isGenerationRunning: jest.fn().mockResolvedValue(false), publishRefresh: jest.fn().mockResolvedValue(undefined) }
|
||||
const source = { getSnapshotForReport: jest.fn().mockResolvedValue({ rows: [], fetchedAt: time }),
|
||||
getSnapshotFromFile: jest.fn().mockResolvedValue({ rows: [], fetchedAt: time }),
|
||||
getProgress: jest.fn().mockReturnValue({ stage: 'orders', completed: 0, total: 2 }) }
|
||||
const reportSource = { listArchive: jest.fn().mockResolvedValue([]), listInventory: jest.fn().mockResolvedValue({ requestedBarcodes: [], inventory: [], cloud: [], warehouses: [] }), listReportPurchasers: jest.fn().mockResolvedValue([]) }
|
||||
const permissions = { getUserAccess: jest.fn().mockResolvedValue({ view: true, edit: true }) }
|
||||
const service = new SupplyChainShortageOrderSnapshotService(repository, source, permissions, () => now, reportSource)
|
||||
return { service, repository, source, reportSource, permissions, release, setNow: (value: string) => { now = new Date(value) } }
|
||||
}
|
||||
|
||||
const settle = () => new Promise(resolve => setImmediate(resolve))
|
||||
|
||||
describe('手动全量更新快照', () => {
|
||||
it('publishes an imported file and its report without reading the order database', async () => {
|
||||
const { service, source, repository } = setup()
|
||||
const content = Buffer.from('test')
|
||||
await service.requestImport(user, content, '订单.xlsx')
|
||||
await settle()
|
||||
expect(source.getSnapshotFromFile).toHaveBeenCalledWith(content, '订单.xlsx')
|
||||
expect(source.getSnapshotForReport).not.toHaveBeenCalled()
|
||||
expect(repository.publishRefresh).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('keeps saved data when file validation fails and permits a valid retry', async () => {
|
||||
const { service, source, repository } = setup()
|
||||
source.getSnapshotFromFile.mockRejectedValueOnce(new AppError(ErrorCode.VALIDATION_FAILED, '缺少订单字段'))
|
||||
const log = jest.spyOn(console, 'error').mockImplementation(() => {})
|
||||
try {
|
||||
await service.requestImport(user, Buffer.from('bad'), '订单.xlsx')
|
||||
await settle()
|
||||
expect(await service.getReadState(user)).toMatchObject({ snapshot: stored, refresh: { status: 'error', message: '缺少订单字段;已保留上次完整数据。' } })
|
||||
expect(repository.publishRefresh).not.toHaveBeenCalled()
|
||||
await service.requestImport(user, Buffer.from('good'), '订单.xlsx')
|
||||
await settle()
|
||||
expect(repository.publishRefresh).toHaveBeenCalledTimes(1)
|
||||
} finally { log.mockRestore() }
|
||||
})
|
||||
|
||||
it('does not silently drop an uploaded file while another job is running', async () => {
|
||||
const { service, source } = setup()
|
||||
let finish!: (snapshot: { rows: []; fetchedAt: string }) => void
|
||||
source.getSnapshotFromFile.mockReturnValue(new Promise(resolve => { finish = resolve }))
|
||||
await service.requestImport(user, Buffer.from('one'), '订单.xlsx')
|
||||
await expect(service.requestImport(user, Buffer.from('two'), '订单.xlsx')).rejects.toThrow('已有明细任务正在更新')
|
||||
expect(source.getSnapshotFromFile).toHaveBeenCalledTimes(1)
|
||||
finish({ rows: [], fetchedAt: stored.fetchedAt })
|
||||
await settle()
|
||||
})
|
||||
|
||||
it('requires edit permission before locking, reading, or writing data', async () => {
|
||||
const { service, permissions, repository, source } = setup()
|
||||
permissions.getUserAccess.mockResolvedValue({ view: true, edit: false })
|
||||
await expect(service.requestRefresh(user)).rejects.toMatchObject({ code: 'AUTH_004' })
|
||||
expect(repository.acquireGenerationLock).not.toHaveBeenCalled()
|
||||
expect(source.getSnapshotForReport).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refreshes before 09:00, bypasses cache, and publishes today with its report in one call', async () => {
|
||||
const { service, source, repository, release } = setup('2026-11-24T00:30:00Z')
|
||||
await service.requestRefresh(user)
|
||||
await settle()
|
||||
expect(source.getSnapshotForReport).toHaveBeenCalledWith(true)
|
||||
expect(repository.acquireGenerationLock).toHaveBeenCalledWith(true)
|
||||
expect(repository.publishRefresh).toHaveBeenCalledWith('2026-11-24', { rows: [], fetchedAt: '2026-11-24T00:30:00Z' }, [], expect.any(String))
|
||||
expect(repository.publish).not.toHaveBeenCalled()
|
||||
expect(release).toHaveBeenCalledTimes(1)
|
||||
await service.requestRefresh(user)
|
||||
await settle()
|
||||
expect(repository.publishRefresh).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('keeps the previous snapshot and reports progress while deduplicating concurrent clicks', async () => {
|
||||
const { service, source, repository } = setup()
|
||||
let resolve!: (snapshot: typeof stored) => void
|
||||
source.getSnapshotForReport.mockReturnValue(new Promise(done => { resolve = done }))
|
||||
expect(await service.requestRefresh(user)).toMatchObject({ status: 'ready', snapshot: stored, refresh: { status: 'loading', progress: { stage: 'orders' } } })
|
||||
await service.requestRefresh(user)
|
||||
expect(source.getSnapshotForReport).toHaveBeenCalledTimes(1)
|
||||
expect(repository.acquireGenerationLock).toHaveBeenCalledTimes(1)
|
||||
resolve(stored)
|
||||
await settle()
|
||||
expect((await service.getReadState(user)).refresh).toBeUndefined()
|
||||
})
|
||||
|
||||
it('recognizes a job owned by another process without starting a new scan', async () => {
|
||||
const { service, repository, source } = setup()
|
||||
repository.isGenerationRunning.mockResolvedValue(true)
|
||||
expect(await service.getReadState(user)).toMatchObject({ snapshot: stored, refresh: { status: 'loading' } })
|
||||
repository.acquireGenerationLock.mockResolvedValue(null)
|
||||
await expect(service.requestRefresh(user)).rejects.toThrow('已有明细或报表任务')
|
||||
expect(source.getSnapshotForReport).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each(['source', 'report', 'publish'])('keeps saved data on %s failure and allows an explicit retry', async failure => {
|
||||
const { service, source, reportSource, repository, release } = setup()
|
||||
const failed = failure === 'source' ? source.getSnapshotForReport : failure === 'report' ? reportSource.listArchive : repository.publishRefresh
|
||||
failed.mockRejectedValueOnce(new Error('read failed'))
|
||||
const log = jest.spyOn(console, 'error').mockImplementation(() => {})
|
||||
try {
|
||||
await service.requestRefresh(user)
|
||||
await settle()
|
||||
expect(await service.getReadState(user)).toMatchObject({ status: 'ready', snapshot: stored, refresh: { status: 'error' } })
|
||||
if (failure !== 'publish') expect(repository.publishRefresh).not.toHaveBeenCalled()
|
||||
expect(release).toHaveBeenCalledTimes(1)
|
||||
await service.requestRefresh(user)
|
||||
await settle()
|
||||
expect((await service.getReadState(user)).refresh).toBeUndefined()
|
||||
expect(repository.publishRefresh).toHaveBeenCalled()
|
||||
} finally { log.mockRestore() }
|
||||
})
|
||||
|
||||
it('does not publish source data into the previous date after crossing Shanghai midnight', async () => {
|
||||
const { service, source, repository, setNow, release } = setup('2026-11-24T15:59:59Z')
|
||||
source.getSnapshotForReport.mockImplementation(async () => { setNow('2026-11-24T16:00:00Z'); return { rows: [], fetchedAt: '2026-11-24T16:00:00Z' } })
|
||||
const log = jest.spyOn(console, 'error').mockImplementation(() => {})
|
||||
try {
|
||||
await service.requestRefresh(user)
|
||||
await settle()
|
||||
expect(repository.publishRefresh).not.toHaveBeenCalled()
|
||||
expect(release).toHaveBeenCalled()
|
||||
expect((await service.getReadState(user)).refresh?.status).toBe('error')
|
||||
} finally { log.mockRestore() }
|
||||
})
|
||||
})
|
||||
|
||||
describe('每日缺货明细快照', () => {
|
||||
it('reads an exact historical date without attaching today’s job or fetching upstream data', async () => {
|
||||
const { service, repository, source } = setup()
|
||||
repository.findSnapshot.mockResolvedValue(stored)
|
||||
repository.isGenerationRunning.mockResolvedValue(true)
|
||||
expect(await service.getReadState(user, '2026-11-19')).toEqual({ status: 'ready', snapshot: stored })
|
||||
expect(repository.findSnapshot).toHaveBeenCalledWith('2026-11-19')
|
||||
expect(repository.findLatest).not.toHaveBeenCalled()
|
||||
expect(repository.isGenerationRunning).not.toHaveBeenCalled()
|
||||
expect(source.getSnapshotForReport).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each(['2026-02-30', '2026-13-01', '2026-11-21', '2026-1-01', 'not-a-date'])('rejects invalid or future history date %s before reading', async date => {
|
||||
const { service, repository } = setup()
|
||||
await expect(service.getReadState(user, date)).rejects.toMatchObject({ code: ErrorCode.VALIDATION_INVALID_FORMAT })
|
||||
expect(repository.findSnapshot).not.toHaveBeenCalled()
|
||||
expect(repository.findLatest).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns an empty exact date instead of silently substituting an older snapshot', async () => {
|
||||
const { service, repository } = setup()
|
||||
expect(await service.getReadState(user, '2026-11-18')).toMatchObject({ status: 'empty', message: '2026-11-18尚未生成明细快照' })
|
||||
expect(repository.findLatest).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('authorizes before reading any saved or upstream data', async () => {
|
||||
const { service, permissions, repository, source } = setup()
|
||||
permissions.getUserAccess.mockResolvedValue({ view: false })
|
||||
await expect(service.getReadState(user)).rejects.toMatchObject({ code: 'AUTH_004' })
|
||||
expect(repository.findLatest).not.toHaveBeenCalled()
|
||||
expect(source.getSnapshotForReport).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps the last complete snapshot across reloads and date changes without fetching live data', async () => {
|
||||
const { service, repository, source, setNow } = setup()
|
||||
expect(await service.getReadState(user)).toEqual({ status: 'ready', snapshot: stored })
|
||||
setNow('2026-11-21T02:00:00Z')
|
||||
expect(await service.getReadState(user)).toEqual({ status: 'ready', snapshot: stored })
|
||||
expect(repository.findLatest).toHaveBeenLastCalledWith('2026-11-21')
|
||||
expect(source.getSnapshotForReport).not.toHaveBeenCalled()
|
||||
expect(repository.publish).not.toHaveBeenCalled()
|
||||
expect(repository.acquireGenerationLock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns an explicit ungenerated state without starting a job from a page request', async () => {
|
||||
const { service, repository, source } = setup()
|
||||
repository.findLatest.mockResolvedValue(null)
|
||||
expect(await service.getReadState(user)).toMatchObject({ status: 'empty' })
|
||||
expect(await service.getReadState(user)).toMatchObject({ status: 'empty' })
|
||||
expect(source.getSnapshotForReport).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('runs at 09:00 Shanghai and always bypasses the old live cache when creating a new day', async () => {
|
||||
const { service, repository, source, setNow, release } = setup('2026-11-20T00:59:59.999Z')
|
||||
expect(await service.generateDailySnapshot()).toMatchObject({ status: 'not-due' })
|
||||
expect(repository.acquireGenerationLock).not.toHaveBeenCalled()
|
||||
setNow('2026-11-20T01:00:00Z')
|
||||
expect(await service.generateDailySnapshot()).toMatchObject({ status: 'published', generatedOn: '2026-11-20', rowCount: 0 })
|
||||
expect(source.getSnapshotForReport).toHaveBeenCalledWith(true)
|
||||
expect(repository.publish).toHaveBeenCalledWith('2026-11-20', { rows: [], fetchedAt: '2026-11-20T00:59:59.999Z' })
|
||||
expect(release).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('does not overwrite or rescan an already published day', async () => {
|
||||
const { service, repository, source, release } = setup()
|
||||
repository.findSnapshot.mockResolvedValue({ ...stored, generatedOn: '2026-11-20' })
|
||||
expect(await service.generateDailySnapshot()).toMatchObject({ status: 'exists' })
|
||||
expect(source.getSnapshotForReport).not.toHaveBeenCalled()
|
||||
expect(repository.publish).not.toHaveBeenCalled()
|
||||
expect(release).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not issue concurrent source scans when another scheduled worker owns the lock', async () => {
|
||||
const { service, repository, source } = setup()
|
||||
repository.acquireGenerationLock.mockResolvedValue(null)
|
||||
expect(await service.generateDailySnapshot()).toMatchObject({ status: 'busy' })
|
||||
expect(source.getSnapshotForReport).not.toHaveBeenCalled()
|
||||
expect(repository.publish).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('leaves the previous snapshot readable on upstream failure and releases the lock for retry', async () => {
|
||||
const { service, repository, source, release } = setup()
|
||||
source.getSnapshotForReport.mockRejectedValue(new Error('inventory source timeout'))
|
||||
await expect(service.generateDailySnapshot()).rejects.toThrow('inventory source timeout')
|
||||
expect(repository.publish).not.toHaveBeenCalled()
|
||||
expect(release).toHaveBeenCalledTimes(1)
|
||||
expect(await service.getReadState(user)).toEqual({ status: 'ready', snapshot: stored })
|
||||
})
|
||||
|
||||
it('releases the lock and leaves existing data alone when publication fails', async () => {
|
||||
const { service, repository, release } = setup()
|
||||
repository.publish.mockRejectedValue(new Error('database unavailable'))
|
||||
await expect(service.generateDailySnapshot()).rejects.toThrow('database unavailable')
|
||||
expect(release).toHaveBeenCalled()
|
||||
expect(await service.getReadState(user)).toEqual({ status: 'ready', snapshot: stored })
|
||||
})
|
||||
|
||||
it('never backfills a missed day with source data fetched after midnight', async () => {
|
||||
const { service, source, repository, setNow, release } = setup('2026-11-20T15:59:59Z')
|
||||
source.getSnapshotForReport.mockImplementation(async () => { setNow('2026-11-20T16:00:00Z'); return { rows: [], fetchedAt: '2026-11-20T16:00:00Z' } })
|
||||
await expect(service.generateDailySnapshot()).rejects.toThrow('date changed')
|
||||
expect(repository.publish).not.toHaveBeenCalled()
|
||||
expect(release).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('requires the frozen current day for reports and never silently reads live or uses yesterday', async () => {
|
||||
const { service, source, repository } = setup()
|
||||
await expect(service.getSnapshotForReport()).rejects.toThrow('今日订单明细快照尚未生成')
|
||||
repository.findSnapshot.mockResolvedValue({ ...stored, generatedOn: '2026-11-20' })
|
||||
expect(await service.getSnapshotForReport()).toMatchObject({ generatedOn: '2026-11-20' })
|
||||
expect(source.getSnapshotForReport).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@ -0,0 +1,129 @@
|
||||
import type { AuthUser } from '@/server/core/types'
|
||||
import { AppError, ErrorCode } from '@/server/core/errors'
|
||||
import type { ShortageOrderDailyReadState, ShortageOrderDailySnapshot } from '@/lib/supply-chain-shortage-orders'
|
||||
import { getShortageReportDateBounds, shortageReportToday } from '@/lib/supply-chain-shortage-report'
|
||||
import { aggregateShortageReport } from '@/lib/supply-chain-shortage-report-aggregation'
|
||||
import { SupplyChainShortageOrderRepository } from '@/server/repositories/supply-chain-shortage-order.repository'
|
||||
import { supplyChainShortageOrderSnapshotRepository } from '@/server/repositories/supply-chain-shortage-order-snapshot.repository'
|
||||
import type { SupplyChainShortageOrderService } from './supply-chain-shortage-order.service'
|
||||
import { supplyChainPermissionSettingsService } from './supply-chain-permission-settings.service'
|
||||
import { supplyChainShortageWebSourceService } from './supply-chain-shortage-web-source.service'
|
||||
|
||||
type Repository = Pick<typeof supplyChainShortageOrderSnapshotRepository, 'findLatest' | 'findSnapshot' | 'publish' | 'acquireGenerationLock' | 'isGenerationRunning' | 'publishRefresh'> & Partial<Pick<typeof supplyChainShortageOrderSnapshotRepository, 'listDates'>>
|
||||
type Source = Pick<SupplyChainShortageOrderService, 'getSnapshotForReport' | 'getProgress'> & {
|
||||
getSnapshotFromFile?: (content: Buffer, filename: string) => ReturnType<SupplyChainShortageOrderService['getSnapshotForReport']>
|
||||
}
|
||||
type ReportSource = Pick<SupplyChainShortageOrderRepository, 'listArchive' | 'listInventory' | 'listReportPurchasers'>
|
||||
type Permissions = Pick<typeof supplyChainPermissionSettingsService, 'getUserAccess'>
|
||||
|
||||
// 全量读取不占用 HTTP 请求;冷库查询使用与每日命令相同的超时预算。
|
||||
const fullReadRepository = new SupplyChainShortageOrderRepository(120_000)
|
||||
|
||||
export class SupplyChainShortageOrderSnapshotService {
|
||||
private pending?: Promise<void>
|
||||
private refreshError?: string
|
||||
private preparingReport = false
|
||||
constructor(
|
||||
private readonly repository: Repository = supplyChainShortageOrderSnapshotRepository,
|
||||
private readonly source: Source = supplyChainShortageWebSourceService,
|
||||
private readonly permissions: Permissions = supplyChainPermissionSettingsService,
|
||||
private readonly now: () => Date = () => new Date(),
|
||||
private readonly reportSource: ReportSource = fullReadRepository,
|
||||
) {}
|
||||
|
||||
/** GET 只读持久化快照和任务进度;首次访问与跨天不触发源查询。 */
|
||||
async getReadState(user: AuthUser, date?: string): Promise<ShortageOrderDailyReadState> {
|
||||
const access = await this.permissions.getUserAccess(user, 'shortageOrderDetails')
|
||||
if (!access.view) throw new AppError(ErrorCode.AUTH_PERMISSION_DENIED, '当前账号没有缺货订单明细查看权限')
|
||||
const today = shortageReportToday(this.now())
|
||||
if (date && (date > today || !/^\d{4}-\d{2}-\d{2}$/.test(date) || Number.isNaN(Date.parse(`${date}T00:00:00Z`)) || new Date(`${date}T00:00:00Z`).toISOString().slice(0, 10) !== date)) throw new AppError(ErrorCode.VALIDATION_INVALID_FORMAT, '制表日期不正确')
|
||||
const [snapshot, dates] = await Promise.all([
|
||||
date ? this.repository.findSnapshot(date) : this.repository.findLatest(today),
|
||||
this.repository.listDates?.(today),
|
||||
])
|
||||
const state: ShortageOrderDailyReadState = snapshot ? { status: 'ready', snapshot } : { status: 'empty', message: date ? `${date}尚未生成明细快照` : '尚未生成明细快照,请点击网页读取或导入订单文件。' }
|
||||
if (dates) state.dates = dates
|
||||
if (date && date !== today) return state
|
||||
if (this.pending) state.refresh = { status: 'loading', progress: this.preparingReport ? undefined : this.source.getProgress() }
|
||||
else if (await this.repository.isGenerationRunning()) state.refresh = { status: 'loading' }
|
||||
else if (this.refreshError) state.refresh = { status: 'error', message: this.refreshError }
|
||||
return state
|
||||
}
|
||||
|
||||
/** 仅显式 POST 启动全量抓取,允许当天覆盖;定时任务是否启用不受影响。 */
|
||||
async requestRefresh(user: AuthUser): Promise<ShortageOrderDailyReadState> {
|
||||
return this.requestUpdate(user, () => this.source.getSnapshotForReport(true))
|
||||
}
|
||||
|
||||
async requestImport(user: AuthUser, content: Buffer, filename: string): Promise<ShortageOrderDailyReadState> {
|
||||
return this.requestUpdate(user, () => {
|
||||
if (!this.source.getSnapshotFromFile) throw new Error('当前订单源不支持文件导入')
|
||||
return this.source.getSnapshotFromFile(content, filename)
|
||||
}, true)
|
||||
}
|
||||
|
||||
private async requestUpdate(user: AuthUser, read: () => ReturnType<Source['getSnapshotForReport']>, rejectBusy = false): Promise<ShortageOrderDailyReadState> {
|
||||
const access = await this.permissions.getUserAccess(user, 'shortageOrderDetails')
|
||||
if (!access.view || !access.edit) throw new AppError(ErrorCode.AUTH_PERMISSION_DENIED, '当前账号没有缺货订单明细更新权限')
|
||||
if (this.pending) {
|
||||
if (rejectBusy) throw new AppError(ErrorCode.VALIDATION_FAILED, '已有明细任务正在更新,请完成后再提交。')
|
||||
return this.getReadState(user)
|
||||
}
|
||||
const release = await this.repository.acquireGenerationLock(true)
|
||||
if (!release) throw new AppError(ErrorCode.VALIDATION_FAILED, '已有明细或报表任务正在生成,请完成后重新读取。')
|
||||
this.refreshError = undefined
|
||||
this.preparingReport = false
|
||||
const today = shortageReportToday(this.now())
|
||||
this.pending = this.refreshToday(today, read).catch(error => {
|
||||
this.refreshError = error instanceof AppError && error.code === ErrorCode.VALIDATION_FAILED
|
||||
? `${error.message};已保留上次完整数据。`
|
||||
: '本次全量更新失败,已保留上次完整数据,请检查聚水潭登录状态后重试。'
|
||||
console.error('[shortage-snapshot] manual refresh failed', { code: typeof error === 'object' && error !== null && 'code' in error ? error.code : 'REFRESH_FAILED' })
|
||||
}).finally(async () => {
|
||||
try { await release() } finally { this.pending = undefined }
|
||||
})
|
||||
void this.pending.catch(() => {})
|
||||
return this.getReadState(user)
|
||||
}
|
||||
|
||||
private async refreshToday(today: string, read: () => ReturnType<Source['getSnapshotForReport']>) {
|
||||
const snapshot = await read()
|
||||
this.preparingReport = true
|
||||
const codes = snapshot.rows.flatMap(row => [row.barcode, row.replacementBarcode].filter((code): code is string => Boolean(code)))
|
||||
const products = await this.reportSource.listArchive(codes)
|
||||
const [inventory, purchasers] = await Promise.all([
|
||||
this.reportSource.listInventory(products.map(product => product.barcode)),
|
||||
this.reportSource.listReportPurchasers(products.flatMap(product => product.supplierName ? [product.supplierName] : [])),
|
||||
])
|
||||
const rows = aggregateShortageReport(snapshot.rows, products, inventory, purchasers, today)
|
||||
if (shortageReportToday(this.now()) !== today) throw new Error('Snapshot date changed during source read')
|
||||
await this.repository.publishRefresh(today, snapshot, rows, getShortageReportDateBounds(today).min)
|
||||
}
|
||||
|
||||
/** 报表始终使用当日已冻结的明细,包括显式重建报表时。 */
|
||||
async getSnapshotForReport(): Promise<ShortageOrderDailySnapshot> {
|
||||
const snapshot = await this.repository.findSnapshot(shortageReportToday(this.now()))
|
||||
if (!snapshot) throw new Error('今日订单明细快照尚未生成,请先在明细页点击网页读取或导入文件。')
|
||||
return snapshot
|
||||
}
|
||||
|
||||
/** 仅由服务器定时任务调用;每日一次完整读取成功后原子发布。 */
|
||||
async generateDailySnapshot() {
|
||||
const started = this.now()
|
||||
const today = shortageReportToday(started)
|
||||
if (Number(started.toLocaleTimeString('en-GB', { timeZone: 'Asia/Shanghai', hour: '2-digit', hour12: false })) < 9) {
|
||||
return { status: 'not-due', generatedOn: today } as const
|
||||
}
|
||||
const release = await this.repository.acquireGenerationLock()
|
||||
if (!release) return { status: 'busy', generatedOn: today } as const
|
||||
try {
|
||||
if (await this.repository.findSnapshot(today)) return { status: 'exists', generatedOn: today } as const
|
||||
const snapshot = await this.source.getSnapshotForReport(true)
|
||||
if (shortageReportToday(this.now()) !== today) throw new Error('Snapshot date changed during source read')
|
||||
const published = await this.repository.publish(today, snapshot)
|
||||
return { status: published ? 'published' : 'exists', generatedOn: today, rowCount: snapshot.rows.length } as const
|
||||
} finally { await release() }
|
||||
}
|
||||
}
|
||||
|
||||
export const supplyChainShortageOrderSnapshotService = new SupplyChainShortageOrderSnapshotService()
|
||||
@ -0,0 +1,362 @@
|
||||
/** @jest-environment node */
|
||||
|
||||
import type { AuthUser } from '@/server/core/types'
|
||||
import type { ShortageSourceRow, ShortageArchiveRow } from '@/server/repositories/supply-chain-shortage-order.repository'
|
||||
import { SupplyChainShortageOrderService } from './supply-chain-shortage-order.service'
|
||||
import type { ShortageImportedOrder } from '@/lib/supply-chain-shortage-order-import'
|
||||
import { aggregateShortageReport } from '@/lib/supply-chain-shortage-report-aggregation'
|
||||
|
||||
jest.mock('@/server/repositories/supply-chain-shortage-order.repository', () => ({ supplyChainShortageOrderRepository: {} }))
|
||||
jest.mock('./supply-chain-permission-settings.service', () => ({ supplyChainPermissionSettingsService: {} }))
|
||||
|
||||
const user = { id: 'user', role: 'ADMIN' } as AuthUser
|
||||
const order = {
|
||||
id: 'OTHER:1:1', internalOrderId: '9007199254740993', itemId: '1', onlineOrderId: '0001234567890123456789',
|
||||
barcode: '0001', quantity: 2, exceptionType: '预售', paidAt: '2026-11-11 08:00:00', labels: '普通标签',
|
||||
} as ShortageSourceRow
|
||||
const product = {
|
||||
barcode: '0001', sku: 'A', productName: '柜', productStatus: '停产', supplierName: '供应商',
|
||||
categoryL2: '柜', purchaseOwner: '采购', packType: '双包', productTag: '标签',
|
||||
} as ShortageArchiveRow
|
||||
|
||||
function setup(view = true) {
|
||||
const repository = { listOrderItems: jest.fn().mockResolvedValue([order, { ...order, id: 'OTHER:2:2', quantity: 3 }]),
|
||||
listExchangeRules: jest.fn().mockResolvedValue([]),
|
||||
listReplacementRules: jest.fn().mockResolvedValue([]),
|
||||
listInventory: jest.fn().mockResolvedValue({ requestedBarcodes: [], inventory: [], cloud: [], warehouses: [] }),
|
||||
listClearance: jest.fn().mockResolvedValue([]),
|
||||
listArchive: jest.fn().mockResolvedValue([product, { ...product, barcode: '0002', productStatus: '销售' }]) }
|
||||
const permissions = { getUserAccess: jest.fn().mockResolvedValue({ view }) }
|
||||
return { repository, permissions, service: new SupplyChainShortageOrderService(repository, permissions) }
|
||||
}
|
||||
|
||||
describe('缺货订单数据服务', () => {
|
||||
it('uses imported basic fields including blanks and never queries database orders', async () => {
|
||||
const { service, repository } = setup()
|
||||
const imported = { ...order, category: '文件分类', sku: 'FILE-SKU', productName: '文件名称',
|
||||
productionStatus: '退市', supplier: null, packageType: null } as ShortageImportedOrder
|
||||
const snapshot = await service.getSnapshotFromImportedOrders([imported])
|
||||
expect(repository.listOrderItems).not.toHaveBeenCalled()
|
||||
expect(snapshot.rows[0]).toMatchObject({ category: '文件分类', sku: 'FILE-SKU', productName: '文件名称',
|
||||
productionStatus: '退市', supplier: null, packageType: null, purchaser: null })
|
||||
expect(repository.listArchive).toHaveBeenCalledWith(expect.any(Array), ['FILE-SKU'])
|
||||
})
|
||||
beforeEach(() => { jest.spyOn(console, 'error').mockImplementation(() => {}) })
|
||||
afterEach(() => { jest.restoreAllMocks() })
|
||||
it('checks permissions before any source/cache access', async () => {
|
||||
const { repository, permissions, service } = setup(false)
|
||||
await expect(service.getDetails(user)).rejects.toMatchObject({ code: 'AUTH_004' })
|
||||
expect(repository.listOrderItems).not.toHaveBeenCalled()
|
||||
permissions.getUserAccess.mockResolvedValue({ view: true })
|
||||
await service.getDetails(user)
|
||||
permissions.getUserAccess.mockResolvedValue({ view: false })
|
||||
await expect(service.getDetails(user)).rejects.toMatchObject({ code: 'AUTH_004' })
|
||||
})
|
||||
|
||||
it('enriches direct fields, aggregates all style statuses and full piece quantities, preserving identifier text', async () => {
|
||||
const { service } = setup()
|
||||
const result = await service.getDetails(user)
|
||||
expect(result.rows[0]).toMatchObject({
|
||||
internalOrderId: '9007199254740993', onlineOrderId: '0001234567890123456789', barcode: '0001',
|
||||
exceptionType: '预售', labels: '普通标签', sku: 'A', productName: '柜', purchaser: '采购',
|
||||
productionStatus: '停产', skuProductionStatus: '销售', totalShortage: 5, orderSkuQuantity: 2,
|
||||
exchangeBarcode: null, exchangeSku: null, exchangeLabels: null,
|
||||
})
|
||||
expect(result.rows[0]).toMatchObject({ shortageQuantity: 0, shortageCategory: '异常订单-待核实处理', department: '如懿' })
|
||||
expect(result.rows[0]).not.toHaveProperty('itemId')
|
||||
expect(Number.isNaN(Date.parse(result.fetchedAt))).toBe(false)
|
||||
})
|
||||
|
||||
it('leaves missing product data and style totals unknown', async () => {
|
||||
const { service, repository } = setup()
|
||||
repository.listArchive.mockResolvedValue([])
|
||||
const { rows } = await service.getDetails(user)
|
||||
expect(rows[0]).toMatchObject({ sku: null, productName: null, totalShortage: null, skuProductionStatus: null, orderSkuQuantity: null })
|
||||
})
|
||||
|
||||
it('classifies zero barcode stock with stock on other style variants as abnormal and excludes its pieces from the report', async () => {
|
||||
const { service, repository } = setup()
|
||||
const products = [product, { ...product, barcode: '0002', productStatus: '销售' }]
|
||||
const inventory = { requestedBarcodes: ['0001', '0002'],
|
||||
inventory: [{ barcode: '0002', warehouseId: 1, quantity: 9, orderLock: 1 }], cloud: [],
|
||||
warehouses: [{ id: 1, name: '简尚仓', attribute: '成品发货仓-真实库存' }] }
|
||||
repository.listArchive.mockResolvedValue(products)
|
||||
repository.listInventory.mockResolvedValue(inventory)
|
||||
const snapshot = await service.getDetails(user)
|
||||
expect(snapshot.rows).toHaveLength(2)
|
||||
for (const row of snapshot.rows) expect(row).toMatchObject({
|
||||
barcode: '0001', combinedStock: 0, skuStock: 8, totalShortage: 5,
|
||||
shortageCategory: '异常订单-待核实处理', suggestion: '异常订单-待核实处理', department: '如懿', shortageQuantity: 0,
|
||||
})
|
||||
expect(await service.getSnapshotForReport()).toBe(snapshot)
|
||||
expect(aggregateShortageReport(snapshot.rows, products, inventory, [], '2026-11-20')).toEqual([])
|
||||
})
|
||||
|
||||
it('expands combos before all product lookups, line counts, piece totals, classification and report aggregation', async () => {
|
||||
const { service, repository } = setup()
|
||||
const barcode = 'SJ009523N430V01'
|
||||
const combo = `ZH-${barcode}-2`
|
||||
const component = { ...product, barcode, sku: 'SJ009523', productStatus: '销售' }
|
||||
repository.listOrderItems.mockResolvedValue([
|
||||
{ ...order, barcode: combo, quantity: 3 },
|
||||
{ ...order, id: 'OTHER:1:2', itemId: '2', barcode, quantity: 1 },
|
||||
])
|
||||
repository.listArchive.mockResolvedValue([component])
|
||||
const inventory = { requestedBarcodes: [barcode], inventory: [], cloud: [], warehouses: [] }
|
||||
repository.listInventory.mockResolvedValue(inventory)
|
||||
const snapshot = await service.getDetails(user)
|
||||
expect(snapshot.rows).toHaveLength(3)
|
||||
expect(new Set(snapshot.rows.map(row => row.id)).size).toBe(3)
|
||||
expect(snapshot.rows.map(row => row.quantity)).toEqual([3, 3, 1])
|
||||
for (const row of snapshot.rows) expect(row).toMatchObject({
|
||||
barcode, sku: 'SJ009523', totalShortage: 7, orderSkuQuantity: 3,
|
||||
productName: '柜', shortageCategory: '缺货-无相同款或相似款库存', shortageQuantity: row.quantity,
|
||||
onlineOrderId: order.onlineOrderId, labels: order.labels,
|
||||
})
|
||||
for (const method of ['listExchangeRules', 'listArchive', 'listReplacementRules', 'listInventory', 'listClearance'] as const) {
|
||||
expect(repository[method].mock.calls[0][0]).toContain(barcode)
|
||||
expect(repository[method].mock.calls[0][0]).not.toContain(combo)
|
||||
}
|
||||
expect(await service.getSnapshotForReport()).toBe(snapshot)
|
||||
const report = aggregateShortageReport(snapshot.rows, [component], inventory, [], '2026-11-12')
|
||||
expect(report).toHaveLength(1)
|
||||
expect(report[0]).toMatchObject({ barcode, shortageQuantity: 7, stock: 0, realShortage: 7 })
|
||||
})
|
||||
|
||||
it('looks up every exchange candidate in the archive and preserves unmatched codes without inventing product metadata', async () => {
|
||||
const { service, repository } = setup()
|
||||
repository.listExchangeRules.mockResolvedValue([{ barcode: '0001', exchangeBarcodes: ['0002', '0003', '0004'] }])
|
||||
repository.listArchive.mockResolvedValue([
|
||||
product, { ...product, barcode: '0002', sku: 'B', productTag: '标签二' },
|
||||
{ ...product, barcode: '0003', sku: 'B', productTag: '标签三' },
|
||||
])
|
||||
const { rows } = await service.getDetails(user)
|
||||
expect(repository.listArchive.mock.calls[0][0]).toEqual(expect.arrayContaining(['0001', '0002', '0003', '0004']))
|
||||
expect(rows[0]).toMatchObject({ exchangeBarcode: '0002,0003,0004', exchangeSku: 'B', exchangeLabels: '标签二;标签三' })
|
||||
})
|
||||
|
||||
it('removes a source-expanded combo parent before enrichment, totals and report aggregation', async () => {
|
||||
const { service, repository } = setup()
|
||||
const parent = { ...order, source: 'OTHER', barcode: '运营组合套装12182', skuType: 'combine', quantity: 1,
|
||||
comboParentBarcode: null, outerItemId: 'platform-line' }
|
||||
const child = { ...parent, id: 'OTHER:1:child', itemId: 'child', barcode: 'SJ038043N1410V01', quantity: 2,
|
||||
skuType: 'normal', comboParentBarcode: parent.barcode }
|
||||
repository.listOrderItems.mockResolvedValue([parent, child])
|
||||
const childProduct = { ...product, barcode: child.barcode, sku: 'SJ038043', productStatus: '销售' }
|
||||
repository.listArchive.mockResolvedValue([childProduct,
|
||||
{ ...product, barcode: parent.barcode, productStatus: '销售' }])
|
||||
const inventory = { requestedBarcodes: [child.barcode], inventory: [], cloud: [], warehouses: [] }
|
||||
repository.listInventory.mockResolvedValue(inventory)
|
||||
const snapshot = await service.getDetails(user)
|
||||
expect(snapshot.rows).toHaveLength(1)
|
||||
expect(snapshot.rows[0]).toMatchObject({ id: child.id, barcode: child.barcode, totalShortage: 2, orderSkuQuantity: 1, shortageQuantity: 2 })
|
||||
for (const field of ['itemId', 'source', 'skuType', 'comboParentBarcode', 'outerItemId']) expect(snapshot.rows[0]).not.toHaveProperty(field)
|
||||
for (const method of ['listExchangeRules', 'listArchive'] as const) {
|
||||
expect(repository[method].mock.calls[0][0]).toEqual([child.barcode])
|
||||
}
|
||||
expect(await service.getSnapshotForReport()).toBe(snapshot)
|
||||
const report = aggregateShortageReport(snapshot.rows, [childProduct], inventory, [], '2026-11-16')
|
||||
expect(report).toHaveLength(1)
|
||||
expect(report[0]).toMatchObject({ barcode: child.barcode, shortageQuantity: 2 })
|
||||
})
|
||||
|
||||
it('excludes normal Replaced originals from lookups, counts, piece totals and report snapshots for every order', async () => {
|
||||
const { service, repository } = setup()
|
||||
const barcode = 'SJ038043N1410V01'
|
||||
const active = { ...order, barcode, quantity: 2, source: 'OTHER', skuType: 'normal', itemStatus: null, comboParentBarcode: null, outerItemId: null }
|
||||
const original = { ...active, id: 'OTHER:1:original', itemId: 'original', barcode: `ZH-${barcode}-2`, quantity: 4, itemStatus: 'Replaced' }
|
||||
repository.listOrderItems.mockResolvedValue([active, original, { ...original, id: 'TAOBAO:2:original', source: 'TAOBAO', internalOrderId: '2' }])
|
||||
const component = { ...product, barcode, sku: 'SJ038043', productStatus: '销售' }
|
||||
repository.listArchive.mockResolvedValue([component])
|
||||
const inventory = { requestedBarcodes: [barcode], inventory: [], cloud: [], warehouses: [] }
|
||||
repository.listInventory.mockResolvedValue(inventory)
|
||||
const snapshot = await service.getDetails(user)
|
||||
expect(snapshot.rows).toHaveLength(1)
|
||||
expect(snapshot.rows[0]).toMatchObject({ id: active.id, barcode, quantity: 2, totalShortage: 2, orderSkuQuantity: 1, shortageQuantity: 2 })
|
||||
expect(snapshot.rows[0]).not.toHaveProperty('itemStatus')
|
||||
for (const method of ['listExchangeRules', 'listArchive', 'listReplacementRules', 'listInventory', 'listClearance'] as const) {
|
||||
expect(repository[method].mock.calls[0][0]).not.toContain(original.barcode)
|
||||
}
|
||||
expect(await service.getSnapshotForReport()).toBe(snapshot)
|
||||
expect(aggregateShortageReport(snapshot.rows, [component], inventory, [], '2026-11-16')[0]).toMatchObject({ barcode, shortageQuantity: 2 })
|
||||
})
|
||||
|
||||
it('fails the whole read when exchange rules are unavailable instead of showing every exchange as absent', async () => {
|
||||
const { service, repository } = setup()
|
||||
repository.listExchangeRules.mockRejectedValue(new Error('exchange source unavailable'))
|
||||
await expect(service.getDetails(user)).rejects.toThrow('exchange source unavailable')
|
||||
expect(repository.listArchive).not.toHaveBeenCalled()
|
||||
expect(await service.getReadState(user)).toMatchObject({ status: 'error' })
|
||||
})
|
||||
|
||||
it('assigns exchange targets by the original order barcode and passes them into inventory enrichment', async () => {
|
||||
const { service, repository } = setup()
|
||||
repository.listOrderItems.mockResolvedValue([
|
||||
{ ...order, barcode: ' 000Original ' },
|
||||
{ ...order, id: 'OTHER:2:2', barcode: '000TARGET' },
|
||||
])
|
||||
repository.listExchangeRules.mockResolvedValue([{ barcode: ' 000original ', exchangeBarcodes: ['000target'] }])
|
||||
repository.listArchive.mockResolvedValue([
|
||||
{ ...product, barcode: '000ORIGINAL', sku: 'ORIGINAL', productTag: '原标签' },
|
||||
{ ...product, barcode: '000TARGET', sku: 'TARGET', productTag: '目标标签' },
|
||||
])
|
||||
repository.listInventory.mockResolvedValue({ requestedBarcodes: ['000ORIGINAL', '000TARGET'],
|
||||
inventory: [{ barcode: '000TARGET', warehouseId: 1, quantity: 9, orderLock: 1 }], cloud: [],
|
||||
warehouses: [{ id: 1, name: '简尚仓', attribute: '成品发货仓-真实库存' }] })
|
||||
const { rows } = await service.getDetails(user)
|
||||
expect(rows[0]).toMatchObject({ barcode: ' 000Original ', exchangeBarcode: '000TARGET', exchangeSku: 'TARGET',
|
||||
exchangeLabels: '目标标签', exchangeStock: 8, combinedStock: 8 })
|
||||
expect(rows[1]).toMatchObject({ barcode: '000TARGET', exchangeBarcode: null, exchangeSku: null, exchangeLabels: null })
|
||||
})
|
||||
|
||||
it('coalesces concurrent loads, caches complete results, and refreshes explicitly', async () => {
|
||||
const { service, repository } = setup()
|
||||
const [first, concurrent] = await Promise.all([service.getDetails(user), service.getDetails(user)])
|
||||
expect(concurrent).toBe(first)
|
||||
expect(await service.getDetails(user)).toBe(first)
|
||||
expect(repository.listOrderItems).toHaveBeenCalledTimes(1)
|
||||
await service.getDetails(user, true)
|
||||
expect(repository.listOrderItems).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('refreshes the exchange style and exact target tags together when a custom target changes', async () => {
|
||||
const { service, repository } = setup()
|
||||
repository.listExchangeRules.mockResolvedValueOnce([{ barcode: '0001', exchangeBarcodes: ['0002'] }])
|
||||
.mockResolvedValueOnce([{ barcode: '0001', exchangeBarcodes: ['0003'] }])
|
||||
.mockResolvedValueOnce([{ barcode: '0001', exchangeBarcodes: ['MISSING'] }])
|
||||
repository.listArchive.mockResolvedValue([
|
||||
product,
|
||||
{ ...product, barcode: '0002', sku: 'B', productTag: '旧目标标签' },
|
||||
{ ...product, barcode: '0003', sku: 'C', productTag: '新目标标签' },
|
||||
{ ...product, barcode: '0004', sku: 'C', productTag: '同货号其他编码标签' },
|
||||
])
|
||||
|
||||
const first = await service.getDetails(user)
|
||||
expect(first.rows[0]).toMatchObject({ exchangeBarcode: '0002', exchangeSku: 'B', exchangeLabels: '旧目标标签' })
|
||||
const changed = await service.getDetails(user, true)
|
||||
expect(changed.rows[0]).toMatchObject({ exchangeBarcode: '0003', exchangeSku: 'C', exchangeLabels: '新目标标签' })
|
||||
const missing = await service.getDetails(user, true)
|
||||
expect(missing.rows[0]).toMatchObject({ exchangeBarcode: 'MISSING', exchangeSku: null, exchangeLabels: null })
|
||||
})
|
||||
|
||||
it('loads all target variants and publishes inventory, replacement and classified fields together', async () => {
|
||||
const { service, repository } = setup()
|
||||
repository.listReplacementRules.mockResolvedValue([{ id: 1, barcode: '0001', replacementBarcode: '0003',
|
||||
replacementType: 2, imageChange: 2, differences: '新颜色', createdAt: '2026-11-11' }])
|
||||
repository.listArchive.mockResolvedValueOnce([product, { ...product, barcode: '0002', productStatus: '销售' }])
|
||||
.mockResolvedValueOnce([{ ...product, barcode: '0003', sku: 'B', productStatus: '销售' }])
|
||||
repository.listInventory.mockResolvedValue({ requestedBarcodes: ['0001', '0002', '0003'],
|
||||
inventory: [{ barcode: '0001', warehouseId: 1, quantity: 9, orderLock: 1 }],
|
||||
cloud: [{ barcode: '0001', warehouseId: 1, available: 1 }],
|
||||
warehouses: [{ id: 1, name: '简尚仓', attribute: '成品发货仓-真实库存' }] })
|
||||
const { rows } = await service.getDetails(user)
|
||||
expect(repository.listInventory.mock.calls[0][0]).toEqual(expect.arrayContaining(['0001', '0002', '0003']))
|
||||
expect(rows[0]).toMatchObject({ originalStock: 7, combinedStock: 7, skuStock: 7, replacementBarcode: '0003',
|
||||
replacementSku: 'B', imageChange: '不换图', shortageCategory: '非真实缺货-原商品编码大货仓有库存且能补齐缺货', shortageQuantity: 0 })
|
||||
})
|
||||
|
||||
it('classifies sufficient original stock in a channel warehouse before special labels and excludes it from shortage totals', async () => {
|
||||
const { service, repository } = setup()
|
||||
const barcode = 'SG010508N1436V01'
|
||||
const products = [{ ...product, barcode, sku: 'SG010508', productStatus: '销售' }]
|
||||
repository.listOrderItems.mockResolvedValue([
|
||||
{ ...order, id: 'OTHER:1:1', barcode, quantity: 1, labels: '京东供销订单,京喜' },
|
||||
{ ...order, id: 'OTHER:2:2', internalOrderId: '2', barcode, quantity: 1, labels: '48小时发货订单' },
|
||||
])
|
||||
const inventory = { requestedBarcodes: [barcode],
|
||||
inventory: [{ barcode, warehouseId: 1, quantity: 18, orderLock: 0 }], cloud: [],
|
||||
warehouses: [{ id: 1, name: '渠道仓', attribute: '渠道专用仓-真实库存' }] }
|
||||
repository.listArchive.mockResolvedValue(products)
|
||||
repository.listInventory.mockResolvedValue(inventory)
|
||||
const snapshot = await service.getDetails(user)
|
||||
expect(snapshot.rows).toHaveLength(2)
|
||||
for (const row of snapshot.rows) expect(row).toMatchObject({ barcode, originalStock: 18,
|
||||
totalShortage: 2, combinedMainStock: 0, combinedFrontStock: 0,
|
||||
shortageCategory: '非真实缺货-原商品编码大货仓有库存且能补齐缺货',
|
||||
suggestion: '核实有库存未锁定原因并处理异常', department: '如懿', shortageQuantity: 0 })
|
||||
expect(aggregateShortageReport(snapshot.rows, products, inventory, [], '2026-11-21')).toEqual([])
|
||||
})
|
||||
|
||||
it('loads SKU replacement rules and every target variant before selecting the highest scoped stock', async () => {
|
||||
const { service, repository } = setup()
|
||||
const original = { ...product, barcode: 'DNZ028907N866V01', sku: 'DNZ028907' }
|
||||
const high = { ...product, barcode: 'DNZ028915N866V01', sku: 'DNZ028915', productTag: '目标标签' }
|
||||
const low = { ...high, barcode: 'DNZ028915N887V01', productTag: '其他标签' }
|
||||
repository.listOrderItems.mockResolvedValue([{ ...order, barcode: original.barcode }])
|
||||
repository.listReplacementRules.mockResolvedValue([{ id: 889, barcode: original.sku, replacementBarcode: high.sku,
|
||||
replacementType: 1, imageChange: 0, differences: '新颜色', createdAt: '2026-01-14' }])
|
||||
repository.listArchive.mockResolvedValueOnce([original]).mockResolvedValueOnce([original, high, low])
|
||||
repository.listInventory.mockResolvedValue({ requestedBarcodes: [original.barcode, high.barcode, low.barcode], cloud: [],
|
||||
inventory: [{ barcode: high.barcode, warehouseId: 1, quantity: 25, orderLock: 5 },
|
||||
{ barcode: low.barcode, warehouseId: 1, quantity: 10, orderLock: 1 },
|
||||
{ barcode: low.barcode, warehouseId: 2, quantity: 10000, orderLock: 0 }],
|
||||
warehouses: [{ id: 1, name: '正常大货', attribute: '成品发货仓-真实库存' }, { id: 2, name: '信誉仓', attribute: '信誉代发仓-虚拟库存' }] })
|
||||
const { rows } = await service.getDetails(user)
|
||||
expect(repository.listReplacementRules).toHaveBeenCalledWith(expect.arrayContaining([original.barcode]), [original.sku])
|
||||
expect(repository.listArchive).toHaveBeenLastCalledWith([original.sku, high.sku], [original.sku, high.sku])
|
||||
expect(repository.listInventory).toHaveBeenCalledWith(expect.arrayContaining([high.barcode, low.barcode]))
|
||||
expect(rows[0]).toMatchObject({ replacementSku: high.sku, replacementBarcode: high.barcode,
|
||||
replacementStock: 29, replacementMainStock: 29, replacementLabels: '目标标签', replacementType: '相似款' })
|
||||
})
|
||||
|
||||
it.each(['listInventory', 'listClearance', 'listReplacementRules'] as const)('rejects incomplete supporting data when %s fails', async method => {
|
||||
const { service, repository } = setup()
|
||||
repository[method].mockRejectedValue(new Error('supporting source unavailable'))
|
||||
await expect(service.getDetails(user)).rejects.toThrow('supporting source unavailable')
|
||||
expect(await service.getReadState(user)).toMatchObject({ status: 'error' })
|
||||
})
|
||||
|
||||
it('does not cache failed or incomplete source loads', async () => {
|
||||
const { service, repository } = setup()
|
||||
repository.listOrderItems.mockRejectedValueOnce(new Error('SQL unavailable'))
|
||||
await expect(service.getDetails(user)).rejects.toThrow('SQL unavailable')
|
||||
expect(repository.listArchive).not.toHaveBeenCalled()
|
||||
await expect(service.getDetails(user)).resolves.toHaveProperty('rows')
|
||||
expect(repository.listOrderItems).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('returns progress immediately for a slow source and publishes rows only when the whole load completes', async () => {
|
||||
const { service, repository, permissions } = setup()
|
||||
let resolveSource!: (value: ShortageSourceRow[]) => void
|
||||
repository.listOrderItems.mockImplementation(onProgress => {
|
||||
onProgress({ stage: 'orders', completed: 1, total: 20 })
|
||||
return new Promise(resolve => { resolveSource = resolve })
|
||||
})
|
||||
const first = await service.getReadState(user)
|
||||
expect(first).toEqual({ status: 'loading', progress: { stage: 'orders', completed: 1, total: 20 } })
|
||||
expect(first).not.toHaveProperty('snapshot')
|
||||
await service.getReadState(user)
|
||||
expect(repository.listOrderItems).toHaveBeenCalledTimes(1)
|
||||
permissions.getUserAccess.mockResolvedValue({ view: false })
|
||||
await expect(service.getReadState(user, true)).rejects.toMatchObject({ code: 'AUTH_004' })
|
||||
expect(repository.listOrderItems).toHaveBeenCalledTimes(1)
|
||||
permissions.getUserAccess.mockResolvedValue({ view: true })
|
||||
resolveSource([order])
|
||||
await service.getDetails(user)
|
||||
const ready = await service.getReadState(user)
|
||||
expect(ready).toMatchObject({ status: 'ready', snapshot: { rows: [{ barcode: '0001' }] } })
|
||||
permissions.getUserAccess.mockResolvedValue({ view: false })
|
||||
await expect(service.getReadState(user)).rejects.toMatchObject({ code: 'AUTH_004' })
|
||||
})
|
||||
|
||||
it('keeps a failed job stopped during polling and retries only after an explicit refresh', async () => {
|
||||
const { service, repository } = setup()
|
||||
repository.listOrderItems.mockRejectedValueOnce(new Error('source timeout'))
|
||||
await expect(service.getDetails(user)).rejects.toThrow('source timeout')
|
||||
expect(await service.getReadState(user)).toMatchObject({ status: 'error' })
|
||||
expect(await service.getReadState(user)).toMatchObject({ status: 'error' })
|
||||
expect(repository.listOrderItems).toHaveBeenCalledTimes(1)
|
||||
expect(await service.getReadState(user, true)).toMatchObject({ status: 'loading' })
|
||||
await service.getDetails(user)
|
||||
expect(await service.getReadState(user)).toMatchObject({ status: 'ready' })
|
||||
})
|
||||
|
||||
it('forces a fresh detail scan for an explicit report correction even when the cache is fresh', async () => {
|
||||
const { service, repository } = setup()
|
||||
await service.getSnapshotForReport()
|
||||
await service.getSnapshotForReport()
|
||||
expect(repository.listOrderItems).toHaveBeenCalledTimes(1)
|
||||
await service.getSnapshotForReport(true)
|
||||
expect(repository.listOrderItems).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
@ -0,0 +1,160 @@
|
||||
import type { AuthUser } from '@/server/core/types'
|
||||
import { AppError, ErrorCode } from '@/server/core/errors'
|
||||
import type { ShortageOrderSnapshot, ShortageOrderReadState, ShortageReadProgress } from '@/lib/supply-chain-shortage-orders'
|
||||
import { applyOrderSkuLineCounts, applySkuProductionStatuses, applySkuQuantityTotals } from '@/lib/supply-chain-shortage-rules'
|
||||
import { buildShortageSupportingFields } from '@/lib/supply-chain-shortage-enrichment'
|
||||
import { applyShortageClassification } from '@/lib/supply-chain-shortage-classification'
|
||||
import { applyShortageExchangeRules } from '@/lib/supply-chain-shortage-exchange'
|
||||
import { expandShortageOrderCombos, removeSupersededShortageOrderItems } from '@/lib/supply-chain-shortage-combo'
|
||||
import { supplyChainShortageOrderRepository } from '@/server/repositories/supply-chain-shortage-order.repository'
|
||||
import { supplyChainPermissionSettingsService } from './supply-chain-permission-settings.service'
|
||||
import type { ShortageImportedOrder } from '@/lib/supply-chain-shortage-order-import'
|
||||
import type { ShortageSourceRow } from '@/server/repositories/supply-chain-shortage-order.repository'
|
||||
|
||||
type Repository = Pick<typeof supplyChainShortageOrderRepository, 'listOrderItems' | 'listExchangeRules' | 'listArchive' | 'listReplacementRules' | 'listInventory' | 'listClearance'>
|
||||
type Permissions = Pick<typeof supplyChainPermissionSettingsService, 'getUserAccess'>
|
||||
|
||||
export class SupplyChainShortageOrderService {
|
||||
private snapshot?: ShortageOrderSnapshot
|
||||
private pending?: Promise<ShortageOrderSnapshot>
|
||||
private readError?: string
|
||||
private progress: ShortageReadProgress = { stage: 'orders', completed: 0, total: 0 }
|
||||
|
||||
constructor(
|
||||
private readonly repository: Repository = supplyChainShortageOrderRepository,
|
||||
private readonly permissions: Permissions = supplyChainPermissionSettingsService,
|
||||
) {}
|
||||
|
||||
async getDetails(user: AuthUser, refresh = false): Promise<ShortageOrderSnapshot> {
|
||||
await this.authorize(user)
|
||||
if (!refresh && this.isFresh()) return this.snapshot!
|
||||
return this.startLoad()
|
||||
}
|
||||
|
||||
/** 仅供服务器内部的报表任务使用;与明细读取合并在途请求。 */
|
||||
async getSnapshotForReport(refresh = false): Promise<ShortageOrderSnapshot> {
|
||||
if (!refresh && this.isFresh()) return this.snapshot!
|
||||
return this.startLoad()
|
||||
}
|
||||
|
||||
/** 请求只查询任务状态,完整扫描在服务中执行;轮询不重复启动任务。 */
|
||||
async getReadState(user: AuthUser, refresh = false): Promise<ShortageOrderReadState> {
|
||||
await this.authorize(user)
|
||||
if (!this.pending && (refresh || (!this.readError && !this.isFresh()))) this.startLoad()
|
||||
if (this.pending) return { status: 'loading', progress: { ...this.progress } }
|
||||
if (this.readError) return { status: 'error', message: this.readError }
|
||||
return { status: 'ready', snapshot: this.snapshot! }
|
||||
}
|
||||
|
||||
private async authorize(user: AuthUser) {
|
||||
const access = await this.permissions.getUserAccess(user, 'shortageOrderDetails')
|
||||
if (!access.view) throw new AppError(ErrorCode.AUTH_PERMISSION_DENIED, '当前账号没有缺货订单明细查看权限')
|
||||
}
|
||||
|
||||
getProgress(): ShortageReadProgress { return { ...this.progress } }
|
||||
|
||||
private isFresh() {
|
||||
return this.snapshot && Date.now() - Date.parse(this.snapshot.fetchedAt) < 60_000
|
||||
}
|
||||
|
||||
private startLoad() {
|
||||
if (!this.pending) {
|
||||
this.readError = undefined
|
||||
this.progress = { stage: 'orders', completed: 0, total: 0 }
|
||||
this.pending = this.load().then(snapshot => {
|
||||
this.snapshot = snapshot
|
||||
return snapshot
|
||||
}).catch(error => {
|
||||
this.readError = '订单数据读取未完成,请稍后点击刷新重试。'
|
||||
console.error('[shortage-orders] source read failed', {
|
||||
stage: this.progress.stage,
|
||||
completed: this.progress.completed,
|
||||
total: this.progress.total,
|
||||
code: typeof error === 'object' && error !== null && 'code' in error ? error.code : undefined,
|
||||
})
|
||||
throw error
|
||||
}).finally(() => { this.pending = undefined })
|
||||
// 状态接口不等待此 Promise;显式消费失败,避免未处理的后台异常。
|
||||
void this.pending.catch(() => {})
|
||||
}
|
||||
return this.pending
|
||||
}
|
||||
|
||||
private async load(): Promise<ShortageOrderSnapshot> {
|
||||
const source = expandShortageOrderCombos(removeSupersededShortageOrderItems(
|
||||
await this.repository.listOrderItems(progress => { this.progress = progress }),
|
||||
))
|
||||
return this.enrich(source)
|
||||
}
|
||||
|
||||
/** 网页导出提供基础字段;数据库仅提供库存、规则及完整货号档案。 */
|
||||
async getSnapshotFromImportedOrders(orders: readonly ShortageImportedOrder[]): Promise<ShortageOrderSnapshot> {
|
||||
return this.enrich(expandShortageOrderCombos(removeSupersededShortageOrderItems(orders)), true)
|
||||
}
|
||||
|
||||
private async enrich(source: readonly ShortageSourceRow[], imported = false): Promise<ShortageOrderSnapshot> {
|
||||
this.progress = { stage: 'archive', completed: 0, total: 1 }
|
||||
const barcodes = source.flatMap(row => row.barcode ? [row.barcode] : [])
|
||||
const exchanges = await this.repository.listExchangeRules(barcodes)
|
||||
const importedRows = imported ? source as readonly ShortageImportedOrder[] : []
|
||||
const archiveCodes = [...barcodes, ...exchanges.flatMap(rule => rule.exchangeBarcodes)]
|
||||
const originalArchive = imported
|
||||
? await this.repository.listArchive(archiveCodes, importedRows.flatMap(row => row.sku ? [row.sku] : []))
|
||||
: await this.repository.listArchive(archiveCodes)
|
||||
// 导入编码可能尚未进入档案副本;以文件中的货号与生产状态参与后续货号聚合。
|
||||
if (imported) {
|
||||
const byCode = new Map(originalArchive.map(product => [product.barcode.trim().toUpperCase(), product]))
|
||||
for (const row of importedRows) {
|
||||
const code = row.barcode?.trim().toUpperCase()
|
||||
if (!code) continue
|
||||
const existing = byCode.get(code)
|
||||
byCode.set(code, { ...existing, barcode: row.barcode!, sku: row.sku ?? '', categoryL2: row.category,
|
||||
productName: row.productName, productStatus: row.productionStatus, supplierName: row.supplier,
|
||||
purchaseOwner: null, packType: row.packageType, productTag: existing?.productTag ?? null })
|
||||
}
|
||||
originalArchive.splice(0, originalArchive.length, ...byCode.values())
|
||||
}
|
||||
const replacements = await this.repository.listReplacementRules(
|
||||
[...barcodes, ...originalArchive.map(product => product.barcode)], originalArchive.map(product => product.sku),
|
||||
)
|
||||
const replacementTokens = replacements.flatMap(rule => [rule.barcode, rule.replacementBarcode])
|
||||
const replacementArchive = replacements.length
|
||||
? await this.repository.listArchive(replacementTokens, replacementTokens)
|
||||
: []
|
||||
const archive = [...new Map((imported ? [...replacementArchive, ...originalArchive] : [...originalArchive, ...replacementArchive]).map(product => [product.barcode.trim().toUpperCase(), product])).values()]
|
||||
const allCodes = [...barcodes, ...exchanges.flatMap(rule => rule.exchangeBarcodes), ...archive.map(product => product.barcode), ...replacements.flatMap(rule => [rule.barcode, rule.replacementBarcode])]
|
||||
const [inventory, clearance] = await Promise.all([
|
||||
this.repository.listInventory(allCodes),
|
||||
this.repository.listClearance(allCodes),
|
||||
])
|
||||
const byBarcode = new Map(archive.map(product => [product.barcode.trim().toUpperCase(), product]))
|
||||
const rows = source.map(({ itemId: _itemId, source: _source, skuType: _skuType, comboParentBarcode: _comboParentBarcode, outerItemId: _outerItemId, itemStatus: _itemStatus, ...order }) => {
|
||||
const product = byBarcode.get(order.barcode?.trim().toUpperCase() ?? '')
|
||||
const fileRow = imported ? order as unknown as ShortageImportedOrder : undefined
|
||||
const sku = imported ? fileRow!.sku : product?.sku || null
|
||||
return {
|
||||
...order,
|
||||
sku,
|
||||
category: imported ? fileRow!.category : product?.categoryL2 ?? null,
|
||||
productName: imported ? fileRow!.productName : product?.productName ?? null,
|
||||
productionStatus: imported ? fileRow!.productionStatus : product?.productStatus ?? null,
|
||||
supplier: imported ? fileRow!.supplier : product?.supplierName ?? null,
|
||||
purchaser: imported ? null : product?.purchaseOwner ?? null,
|
||||
packageType: imported ? fileRow!.packageType : product?.packType ?? null,
|
||||
originalProductLabels: product?.productTag ?? null,
|
||||
orderSkuKey: order.onlineOrderId && sku ? `${order.onlineOrderId}&${sku}` : null,
|
||||
}
|
||||
})
|
||||
const rowsWithExchange = applyShortageExchangeRules(rows, exchanges, archive)
|
||||
this.progress = { stage: 'archive', completed: 1, total: 1 }
|
||||
return {
|
||||
rows: applyShortageClassification(buildShortageSupportingFields(
|
||||
applySkuQuantityTotals(applyOrderSkuLineCounts(applySkuProductionStatuses(rowsWithExchange, archive))),
|
||||
archive, replacements, inventory, clearance,
|
||||
)),
|
||||
fetchedAt: new Date().toISOString(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const supplyChainShortageOrderService = new SupplyChainShortageOrderService()
|
||||
@ -0,0 +1,118 @@
|
||||
/** @jest-environment node */
|
||||
import type { AuthUser } from '@/server/core/types'
|
||||
import { SupplyChainShortageReportService } from './supply-chain-shortage-report.service'
|
||||
|
||||
jest.mock('@/server/repositories/supply-chain-shortage-report.repository', () => ({ supplyChainShortageReportRepository: {} }))
|
||||
jest.mock('@/server/repositories/supply-chain-shortage-order.repository', () => ({ supplyChainShortageOrderRepository: {} }))
|
||||
jest.mock('./supply-chain-shortage-order-snapshot.service', () => ({ supplyChainShortageOrderSnapshotService: {} }))
|
||||
jest.mock('./supply-chain-permission-settings.service', () => ({ supplyChainPermissionSettingsService: {} }))
|
||||
const user = { id: 'user' } as AuthUser
|
||||
const settle = () => new Promise(resolve => setTimeout(resolve, 0))
|
||||
function setup(now = '2026-11-12T02:00:00Z') {
|
||||
const release = jest.fn().mockResolvedValue(undefined)
|
||||
const repository = {
|
||||
acquireGenerationLock: jest.fn().mockResolvedValue(release), findSnapshot: jest.fn().mockResolvedValue(null),
|
||||
listRetained: jest.fn().mockResolvedValue([]), publish: jest.fn().mockResolvedValue(true),
|
||||
pruneBefore: jest.fn().mockResolvedValue(undefined), updateManual: jest.fn().mockResolvedValue({ id: 'row', version: 1 }),
|
||||
}
|
||||
const source = { listArchive: jest.fn().mockResolvedValue([]), listInventory: jest.fn().mockResolvedValue({ requestedBarcodes: [], inventory: [], cloud: [], warehouses: [] }), listReportPurchasers: jest.fn().mockResolvedValue([]) }
|
||||
const details = { getSnapshotForReport: jest.fn().mockResolvedValue({ rows: [], fetchedAt: now }) }
|
||||
const permissions = { getUserAccess: jest.fn().mockResolvedValue({ view: true, edit: true }) }
|
||||
const service = new SupplyChainShortageReportService(repository, source, details, permissions, () => new Date(now))
|
||||
return { repository, source, details, permissions, service, release }
|
||||
}
|
||||
|
||||
describe('每日缺货报表服务', () => {
|
||||
it('checks viewing and editing permissions before touching stored or upstream data', async () => {
|
||||
const { service, repository, permissions } = setup()
|
||||
permissions.getUserAccess.mockResolvedValue({ view: false, edit: false })
|
||||
await expect(service.getReadState(user)).rejects.toMatchObject({ code: 'AUTH_004' })
|
||||
expect(repository.findSnapshot).not.toHaveBeenCalled()
|
||||
permissions.getUserAccess.mockResolvedValue({ view: true, edit: false })
|
||||
await expect(service.updateManual(user, {})).rejects.toMatchObject({ code: 'AUTH_004' })
|
||||
expect(repository.updateManual).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not generate a premature snapshot before 09:00 Shanghai', async () => {
|
||||
const { service, repository, details } = setup('2026-11-12T00:59:00Z')
|
||||
expect(await service.generateDailySnapshot()).toMatchObject({ status: 'not-due' })
|
||||
expect(await service.getReadState(user)).toMatchObject({ status: 'ready', generatedAt: null })
|
||||
expect(repository.acquireGenerationLock).not.toHaveBeenCalled()
|
||||
expect(details.getSnapshotForReport).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('leaves archived calculations and manual edits intact on a repeated run and prunes outside six calendar months', async () => {
|
||||
const { service, repository, details, release } = setup()
|
||||
repository.findSnapshot.mockResolvedValue({ generatedAt: new Date() })
|
||||
expect(await service.generateDailySnapshot()).toMatchObject({ status: 'exists' })
|
||||
expect(repository.pruneBefore).toHaveBeenCalledWith('2026-05-12')
|
||||
expect(repository.publish).not.toHaveBeenCalled()
|
||||
expect(details.getSnapshotForReport).not.toHaveBeenCalled()
|
||||
expect(release).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('honors the database lock held by another worker', async () => {
|
||||
const { service, repository, details } = setup()
|
||||
repository.acquireGenerationLock.mockResolvedValue(null)
|
||||
expect(await service.generateDailySnapshot()).toMatchObject({ status: 'busy' })
|
||||
expect(details.getSnapshotForReport).not.toHaveBeenCalled()
|
||||
expect(repository.publish).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('explicitly rebuilds only the report from frozen details while ordinary daily runs keep their snapshot', async () => {
|
||||
const { service, repository, details, release } = setup()
|
||||
repository.findSnapshot.mockResolvedValue({ generatedAt: new Date() })
|
||||
expect(await service.generateDailySnapshot(true)).toMatchObject({ status: 'published', generatedOn: '2026-11-12' })
|
||||
expect(details.getSnapshotForReport).toHaveBeenCalledWith()
|
||||
expect(repository.publish).toHaveBeenCalledWith('2026-11-12', '2026-11-12T02:00:00Z', [], '2026-05-12', true)
|
||||
expect(release).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps an existing snapshot intact if a corrected source cannot finish', async () => {
|
||||
const { service, repository, details, release } = setup()
|
||||
repository.findSnapshot.mockResolvedValue({ generatedAt: new Date() })
|
||||
details.getSnapshotForReport.mockRejectedValue(new Error('source timeout'))
|
||||
await expect(service.generateDailySnapshot(true)).rejects.toThrow('source timeout')
|
||||
expect(repository.publish).not.toHaveBeenCalled()
|
||||
expect(release).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('never publishes a partial result if any supporting source fails and releases the lock', async () => {
|
||||
const { service, source, repository, release } = setup()
|
||||
source.listReportPurchasers.mockRejectedValue(new Error('source unavailable'))
|
||||
await expect(service.generateDailySnapshot()).rejects.toThrow('source unavailable')
|
||||
expect(repository.publish).not.toHaveBeenCalled()
|
||||
expect(release).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('coalesces polling into one generation, then returns stored rows', async () => {
|
||||
const { service, details, repository } = setup()
|
||||
let finish!: (value: { rows: []; fetchedAt: string }) => void
|
||||
details.getSnapshotForReport.mockReturnValue(new Promise(resolve => { finish = resolve }))
|
||||
expect(await service.getReadState(user)).toMatchObject({ status: 'loading' })
|
||||
await settle()
|
||||
expect(await service.getReadState(user)).toMatchObject({ status: 'loading' })
|
||||
expect(details.getSnapshotForReport).toHaveBeenCalledTimes(1)
|
||||
finish({ rows: [], fetchedAt: '2026-11-12T02:00:00Z' })
|
||||
await settle()
|
||||
expect(repository.publish).toHaveBeenCalledTimes(1)
|
||||
repository.findSnapshot.mockResolvedValue({ generatedAt: new Date('2026-11-12T02:01:00Z') })
|
||||
expect(await service.getReadState(user)).toMatchObject({ status: 'ready', today: '2026-11-12', rows: [] })
|
||||
})
|
||||
|
||||
it('accepts blank fields and reported zero, rejects arbitrary computed-field writes and negative transit', async () => {
|
||||
const { service, repository } = setup()
|
||||
const input = { id: 'row', version: 0, expectedArrival: ' ', notes: ' 交期 ', replacementTransit: 0 }
|
||||
await service.updateManual(user, input)
|
||||
expect(repository.updateManual).toHaveBeenCalledWith({ ...input, expectedArrival: null, notes: '交期' }, user.id, '2026-05-12', '2026-11-12')
|
||||
for (const value of [{ ...input, stock: 100 }, { ...input, replacementTransit: -1 }, { ...input, replacementTransit: 1.5 }]) {
|
||||
await expect(service.updateManual(user, value)).rejects.toMatchObject({ code: 'VALIDATION_003' })
|
||||
}
|
||||
})
|
||||
|
||||
it('reports concurrent edits and expired records instead of claiming the save succeeded', async () => {
|
||||
const { service, repository } = setup()
|
||||
repository.updateManual.mockResolvedValue(null)
|
||||
await expect(service.updateManual(user, { id: 'row', version: 0, expectedArrival: null, notes: null, replacementTransit: null })).rejects.toThrow('记录已更新')
|
||||
})
|
||||
})
|
||||
@ -0,0 +1,93 @@
|
||||
import type { AuthUser } from '@/server/core/types'
|
||||
import { AppError, ErrorCode } from '@/server/core/errors'
|
||||
import { aggregateShortageReport } from '@/lib/supply-chain-shortage-report-aggregation'
|
||||
import { getShortageReportDateBounds, prepareShortageReportRows, shortageReportToday, type ShortageReportReadState } from '@/lib/supply-chain-shortage-report'
|
||||
import { shortageReportManualSchema } from '@/lib/supply-chain-shortage-report-input'
|
||||
import { supplyChainShortageReportRepository } from '@/server/repositories/supply-chain-shortage-report.repository'
|
||||
import { supplyChainShortageOrderRepository } from '@/server/repositories/supply-chain-shortage-order.repository'
|
||||
import { supplyChainShortageOrderSnapshotService } from './supply-chain-shortage-order-snapshot.service'
|
||||
import { supplyChainPermissionSettingsService } from './supply-chain-permission-settings.service'
|
||||
|
||||
type Repository = Pick<typeof supplyChainShortageReportRepository, 'acquireGenerationLock' | 'findSnapshot' | 'listRetained' | 'publish' | 'pruneBefore' | 'updateManual'>
|
||||
type Source = Pick<typeof supplyChainShortageOrderRepository, 'listArchive' | 'listInventory' | 'listReportPurchasers'>
|
||||
type Details = Pick<typeof supplyChainShortageOrderSnapshotService, 'getSnapshotForReport'>
|
||||
type Permissions = Pick<typeof supplyChainPermissionSettingsService, 'getUserAccess'>
|
||||
|
||||
export class SupplyChainShortageReportService {
|
||||
private pending?: Promise<unknown>
|
||||
private readError?: string
|
||||
private prunedOn?: string
|
||||
constructor(
|
||||
private readonly repository: Repository = supplyChainShortageReportRepository,
|
||||
private readonly source: Source = supplyChainShortageOrderRepository,
|
||||
private readonly details: Details = supplyChainShortageOrderSnapshotService,
|
||||
private readonly permissions: Permissions = supplyChainPermissionSettingsService,
|
||||
private readonly now: () => Date = () => new Date(),
|
||||
) {}
|
||||
|
||||
async getReadState(user: AuthUser, retry = false): Promise<ShortageReportReadState> {
|
||||
await this.authorize(user)
|
||||
const today = shortageReportToday(this.now())
|
||||
const bounds = getShortageReportDateBounds(today)
|
||||
if (this.prunedOn !== today) { await this.repository.pruneBefore(bounds.min); this.prunedOn = today }
|
||||
const snapshot = await this.repository.findSnapshot(today)
|
||||
if (snapshot || !this.isDue()) {
|
||||
return { status: 'ready', rows: prepareShortageReportRows(await this.repository.listRetained(bounds.min, today), today), today, generatedAt: snapshot?.generatedAt.toISOString() ?? null }
|
||||
}
|
||||
if (retry) this.readError = undefined
|
||||
if (!this.pending && !this.readError) {
|
||||
this.pending = this.generateDailySnapshot().catch(error => {
|
||||
this.readError = '缺货报表生成失败,请点击刷新重试。未发布不完整的报表。'
|
||||
console.error('[shortage-report] generation failed', { code: typeof error === 'object' && error !== null && 'code' in error ? error.code : 'SOURCE_READ_FAILED' })
|
||||
}).finally(() => { this.pending = undefined })
|
||||
}
|
||||
if (this.readError) return { status: 'error', message: this.readError }
|
||||
return { status: 'loading', message: '正在读取完整明细并生成今日报表…' }
|
||||
}
|
||||
|
||||
/** 09:00 Asia/Shanghai 运行;只生成执行当日,不用今天的数据回填过去。 */
|
||||
async generateDailySnapshot(rebuildToday = false) {
|
||||
const today = shortageReportToday(this.now())
|
||||
const bounds = getShortageReportDateBounds(today)
|
||||
if (!this.isDue()) return { status: 'not-due', generatedOn: today } as const
|
||||
const release = await this.repository.acquireGenerationLock()
|
||||
if (!release) return { status: 'busy', generatedOn: today } as const
|
||||
try {
|
||||
if (!rebuildToday && await this.repository.findSnapshot(today)) {
|
||||
await this.repository.pruneBefore(bounds.min)
|
||||
return { status: 'exists', generatedOn: today } as const
|
||||
}
|
||||
const snapshot = await this.details.getSnapshotForReport()
|
||||
const codes = snapshot.rows.flatMap(row => [row.barcode, row.replacementBarcode].filter((code): code is string => Boolean(code)))
|
||||
const products = await this.source.listArchive(codes)
|
||||
const [inventory, purchasers] = await Promise.all([
|
||||
this.source.listInventory(products.map(product => product.barcode)),
|
||||
this.source.listReportPurchasers(products.flatMap(product => product.supplierName ? [product.supplierName] : [])),
|
||||
])
|
||||
const rows = aggregateShortageReport(snapshot.rows, products, inventory, purchasers, today)
|
||||
if (shortageReportToday(this.now()) !== today) throw new Error('Report date changed during source read')
|
||||
const published = await this.repository.publish(today, snapshot.fetchedAt, rows, bounds.min, rebuildToday)
|
||||
return { status: published ? 'published' : 'exists', generatedOn: today, rowCount: rows.length } as const
|
||||
} finally { await release() }
|
||||
}
|
||||
|
||||
async updateManual(user: AuthUser, value: unknown) {
|
||||
await this.authorize(user, true)
|
||||
const parsed = shortageReportManualSchema.safeParse(value)
|
||||
if (!parsed.success) throw new AppError(ErrorCode.VALIDATION_INVALID_FORMAT, '填报格式不正确:到货时间最多120字,缺货原因最多2000字,在途数量须为0至10亿的整数或留空。')
|
||||
const bounds = getShortageReportDateBounds(shortageReportToday(this.now()))
|
||||
const row = await this.repository.updateManual(parsed.data, user.id, bounds.min, bounds.max)
|
||||
if (!row) throw new AppError(ErrorCode.VALIDATION_FAILED, '记录已更新、已过期或不存在,请刷新报表后重新填写。')
|
||||
return row
|
||||
}
|
||||
|
||||
private isDue() {
|
||||
return Number(this.now().toLocaleTimeString('en-GB', { timeZone: 'Asia/Shanghai', hour: '2-digit', hour12: false })) >= 9
|
||||
}
|
||||
private async authorize(user: AuthUser, edit = false) {
|
||||
const access = await this.permissions.getUserAccess(user, 'shortageOrderDetails')
|
||||
if (!access.view || (edit && !access.edit)) throw new AppError(ErrorCode.AUTH_PERMISSION_DENIED, edit ? '当前账号没有报表填报权限' : '当前账号没有缺货报表查看权限')
|
||||
}
|
||||
}
|
||||
|
||||
export const supplyChainShortageReportService = new SupplyChainShortageReportService()
|
||||
@ -0,0 +1,64 @@
|
||||
/** @jest-environment node */
|
||||
import { parseShortageOrderImport } from '@/lib/supply-chain-shortage-order-import'
|
||||
import { SupplyChainShortageWebSourceService } from './supply-chain-shortage-web-source.service'
|
||||
|
||||
jest.mock('@/lib/supply-chain-shortage-order-import', () => ({ parseShortageOrderImport: jest.fn() }))
|
||||
jest.mock('@/server/repositories/supply-chain-shortage-order.repository', () => ({ SupplyChainShortageOrderRepository: jest.fn() }))
|
||||
jest.mock('./supply-chain-shortage-order.service', () => ({ SupplyChainShortageOrderService: jest.fn() }))
|
||||
|
||||
function setup() {
|
||||
const file = { filename: '订单_20261124.xlsx', content: Buffer.from('xlsx') }
|
||||
const exporter = { downloadOrders: jest.fn().mockResolvedValue(file) }
|
||||
const enrichment = { getSnapshotFromImportedOrders: jest.fn().mockResolvedValue({ rows: [], fetchedAt: '2026-11-24T01:00:00Z' }), getProgress: jest.fn() }
|
||||
const prepared = { save: jest.fn().mockResolvedValue({ preparedAt: '2026-11-24T00:50:00Z' }), readToday: jest.fn().mockResolvedValue(file) }
|
||||
jest.mocked(parseShortageOrderImport).mockResolvedValue({ rows: [], importedRows: 0, excludedRows: 2 })
|
||||
return { service: new SupplyChainShortageWebSourceService(exporter, enrichment, prepared), exporter, enrichment, prepared, file }
|
||||
}
|
||||
|
||||
describe('网页下载与每日快照分步处理', () => {
|
||||
beforeEach(() => { jest.clearAllMocks(); jest.useFakeTimers().setSystemTime(new Date('2026-11-24T00:50:00Z')) })
|
||||
afterEach(() => jest.useRealTimers())
|
||||
|
||||
it('downloads and validates at 08:50 without computing or publishing a snapshot', async () => {
|
||||
const { service, exporter, enrichment, prepared, file } = setup()
|
||||
expect(await service.prepareDailyDownload()).toMatchObject({ generatedOn: '2026-11-24', excludedRows: 2 })
|
||||
expect(exporter.downloadOrders).toHaveBeenCalledTimes(1)
|
||||
expect(parseShortageOrderImport).toHaveBeenCalledWith(file.content, file.filename)
|
||||
expect(prepared.save).toHaveBeenCalledWith(file, '2026-11-24')
|
||||
expect(enrichment.getSnapshotFromImportedOrders).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('never marks a failed or invalid download complete', async () => {
|
||||
const { service, exporter, prepared } = setup()
|
||||
exporter.downloadOrders.mockRejectedValueOnce(new Error('download failed'))
|
||||
await expect(service.prepareDailyDownload()).rejects.toThrow('download failed')
|
||||
jest.mocked(parseShortageOrderImport).mockRejectedValueOnce(new Error('invalid workbook'))
|
||||
await expect(service.prepareDailyDownload()).rejects.toThrow('invalid workbook')
|
||||
expect(prepared.save).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('computes the 09:00 snapshot from the prepared workbook without another download', async () => {
|
||||
const { service, exporter, enrichment, prepared, file } = setup()
|
||||
await service.getSnapshotFromPreparedFile()
|
||||
expect(prepared.readToday).toHaveBeenCalledTimes(1)
|
||||
expect(parseShortageOrderImport).toHaveBeenCalledWith(file.content, file.filename)
|
||||
expect(enrichment.getSnapshotFromImportedOrders).toHaveBeenCalledWith([])
|
||||
expect(exporter.downloadOrders).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('fails when no same-day file exists without downloading or computing fallback data', async () => {
|
||||
const { service, exporter, enrichment, prepared } = setup()
|
||||
prepared.readToday.mockRejectedValueOnce(new Error('今日尚无完整订单下载文件'))
|
||||
await expect(service.getSnapshotFromPreparedFile()).rejects.toThrow('今日')
|
||||
expect(exporter.downloadOrders).not.toHaveBeenCalled()
|
||||
expect(enrichment.getSnapshotFromImportedOrders).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('still downloads immediately for an explicit manual webpage refresh', async () => {
|
||||
const { service, exporter, enrichment, prepared } = setup()
|
||||
await service.getSnapshotForReport(true)
|
||||
expect(exporter.downloadOrders).toHaveBeenCalledTimes(1)
|
||||
expect(enrichment.getSnapshotFromImportedOrders).toHaveBeenCalledTimes(1)
|
||||
expect(prepared.readToday).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@ -0,0 +1,58 @@
|
||||
import { parseShortageOrderImport } from '@/lib/supply-chain-shortage-order-import'
|
||||
import type { ShortageOrderSnapshot, ShortageReadProgress } from '@/lib/supply-chain-shortage-orders'
|
||||
import { SupplyChainShortageOrderRepository } from '@/server/repositories/supply-chain-shortage-order.repository'
|
||||
import { supplyChainShortageWebExportRepository } from '@/server/repositories/supply-chain-shortage-web-export.repository'
|
||||
import { supplyChainShortagePreparedFileRepository } from '@/server/repositories/supply-chain-shortage-prepared-file.repository'
|
||||
import { shortageReportToday } from '@/lib/supply-chain-shortage-report'
|
||||
import { SupplyChainShortageOrderService } from './supply-chain-shortage-order.service'
|
||||
import { AppError, ErrorCode } from '@/server/core/errors'
|
||||
|
||||
const enrichmentRepository = new SupplyChainShortageOrderRepository(120_000)
|
||||
|
||||
/** 基础字段只有网页文件一个来源;任一阶段失败时由快照服务保留原成功版本。 */
|
||||
export class SupplyChainShortageWebSourceService {
|
||||
private progress: ShortageReadProgress = { stage: 'download', completed: 0, total: 1 }
|
||||
constructor(
|
||||
private readonly exporter: Pick<typeof supplyChainShortageWebExportRepository, 'downloadOrders'> = supplyChainShortageWebExportRepository,
|
||||
private readonly enrichment: Pick<SupplyChainShortageOrderService, 'getSnapshotFromImportedOrders' | 'getProgress'> = new SupplyChainShortageOrderService(enrichmentRepository),
|
||||
private readonly preparedFiles: Pick<typeof supplyChainShortagePreparedFileRepository, 'save' | 'readToday'> = supplyChainShortagePreparedFileRepository,
|
||||
) {}
|
||||
|
||||
getProgress(): ShortageReadProgress { return this.progress.stage === 'archive' ? this.enrichment.getProgress() : { ...this.progress } }
|
||||
|
||||
async getSnapshotForReport(_refresh = true): Promise<ShortageOrderSnapshot> {
|
||||
this.progress = { stage: 'download', completed: 0, total: 1 }
|
||||
const file = await this.exporter.downloadOrders().catch(error => {
|
||||
throw new AppError(ErrorCode.VALIDATION_FAILED, error instanceof Error ? error.message : '聚水潭网页导出失败')
|
||||
})
|
||||
return this.getSnapshotFromFile(file.content, file.filename)
|
||||
}
|
||||
|
||||
async getSnapshotFromFile(content: Buffer, filename: string): Promise<ShortageOrderSnapshot> {
|
||||
this.progress = { stage: 'import', completed: 0, total: 1 }
|
||||
const imported = await parseShortageOrderImport(content, filename).catch(error => {
|
||||
throw new AppError(ErrorCode.VALIDATION_FAILED, error instanceof Error ? error.message : '订单文件格式不正确')
|
||||
})
|
||||
this.progress = { stage: 'archive', completed: 0, total: 1 }
|
||||
return this.enrichment.getSnapshotFromImportedOrders(imported.rows)
|
||||
}
|
||||
|
||||
/** 每日08:50只下载、校验并落盘,不提前计算或覆盖页面快照。 */
|
||||
async prepareDailyDownload() {
|
||||
const date = shortageReportToday(new Date())
|
||||
const file = await this.exporter.downloadOrders()
|
||||
const imported = await parseShortageOrderImport(file.content, file.filename)
|
||||
const manifest = await this.preparedFiles.save(file, date)
|
||||
return { generatedOn: date, preparedAt: manifest.preparedAt, importedRows: imported.importedRows, excludedRows: imported.excludedRows }
|
||||
}
|
||||
|
||||
/** 每日09:00仅消费当日已完成下载;失败时不回退旧文件或另行网页导出。 */
|
||||
async getSnapshotFromPreparedFile(): Promise<ShortageOrderSnapshot> {
|
||||
const file = await this.preparedFiles.readToday()
|
||||
return this.getSnapshotFromFile(file.content, file.filename)
|
||||
}
|
||||
|
||||
async close() { await enrichmentRepository.close() }
|
||||
}
|
||||
|
||||
export const supplyChainShortageWebSourceService = new SupplyChainShortageWebSourceService()
|
||||
Loading…
x
Reference in New Issue
Block a user