diff --git a/furniture-3d-system/.agents/skills/cabinet-standard-bom/SKILL.md b/furniture-3d-system/.agents/skills/cabinet-standard-bom/SKILL.md index 45723a38..f5c40f2f 100644 --- a/furniture-3d-system/.agents/skills/cabinet-standard-bom/SKILL.md +++ b/furniture-3d-system/.agents/skills/cabinet-standard-bom/SKILL.md @@ -57,7 +57,8 @@ description: 识图拆分板式家具,生成模型、打样资料、分层包 - 带腿开放格书柜先按图和已选板材生成柜身与柜腿,暂用现有连续层板、分段竖隔板和进深做法。没拍到背面时先不画未识别的背板或拉板;槽位不阻塞预览。 - 左侧补充和右侧建模对话都可更新并保存本款。明确的补腿、补背板和两层开放格的槽装后背做法可直接应用到已有模型。其余补充由识图服务解析,无法应用时说明缺项。 -- 两层板式带腿开放格书柜说「拉板+三合板,抽槽安装」时,按 CB-024 先用一块后拉板分隔上下两片三合板。按本款尺寸计算,拉板高度、入槽量及孔槽位置在打样前复核。 +- 两层板式带腿开放格书柜说「拉板+三合板,抽槽安装」时,按 CB-013、CB-024、CB-025 计算槽装后背。单片背板宽为(背部内高-横档根数×横档高)÷(横档根数+1)+两端入槽量。有效限宽取本款主体板件最大宽与本款明确背板限宽的较小值,排除背板自身。先试一根横档、两片背板,超宽时改为共两根横档、均分三片。三片仍超宽时列为待确认。横档高 100 mm 只属于已给出该规格的案例。 +- 分片结果同时生成实际横档和背板,沿用板件编号进入打样、包装及 BOM。增加横档后按实际承接位置暂估连接五金,拉板高度、入槽量、承接及孔位在打样前复核。本款明确的背板限宽随测算保存。 - 系统把已落实的结构纠正保存到「书柜」案例。可复用的结构参数也可在「识别结果与结构确认」逐项确认。槽装后背规则用于两层板式带腿开放格书柜,下次建模按新款尺寸计算。本款尺寸及例外保留在案例内。 - 柜腿由识图或纠正对话给出形状、规格及各根在柜底的相对位置。程序按本款尺寸放置并检查重叠、越界。用户明确给出适用于同类书柜的柜宽下限时,技能库保存阈值和位置;本款明确指定的位置优先,直径等本款规格随测算保存。历史记录的四腿和六腿布局继续可打开。 - 柜腿和只指定位置的后拉板按预览部件处理,工艺和用料待核。按 CB-024 生成的后拉板和三合板同时进入模型、打样、包装和预估 BOM。 @@ -99,7 +100,7 @@ description: 识图拆分板式家具,生成模型、打样资料、分层包 - 输入图片和已有尺寸、板件组材料、封边与本款特殊要求。已给信息直接使用,只问影响当前结果的缺项。 - 模型、六视图/爆炸图/连接明细、包装和成本共用稳定板件编号与连接记录。长宽厚采用含封边成品口径;开料与机加工参数须另核。 - 原标准完整文字及每条状态见 `references/结构标准.json`。填写提示、待填写、待验证与已生效分别处理。不得将案例尺寸升级为所有柜类的默认规则。 -- 程序 0.24.3 支持横板连续、竖隔分段的 3 列 2 层开放格书柜按本款成品宽、深、高和板厚拆板。图文或人工明确的参数优先。隔板和搁板进深缺失时,暂按本款柜深减 30 mm;底板进深缺失时,暂按本款柜深减 15 mm。背板槽和封边可参照六格 B 版暂估,随模型和 BOM 记录,打样前核对。三围均与案例相同时,缺失板厚也可按案例暂估。 +- 程序 0.24.4 支持横板连续、竖隔分段的 3 列 2 层开放格书柜按本款成品宽、深、高和板厚拆板。图文或人工明确的参数优先。隔板和搁板进深缺失时,暂按本款柜深减 30 mm;底板进深缺失时,暂按本款柜深减 15 mm。背板槽和封边可参照六格 B 版暂估,随模型和 BOM 记录,打样前核对。三围均与案例相同时,缺失板厚也可按案例暂估。 - 前踢脚板与后横档各自判断有、无或待确认。格数只决定分格。已确认有才采用本款尺寸或参照同结构案例暂估尺寸;已确认无即不生成。看不清仍生成柜体,待确认条板及相应五金暂不计入。确认是六格 B 版时可沿用已知做法,明确的本款说明优先。旧测算只在主动重算时更新。 - 后横档未确认时先用整片背板预估板材。背板超过包装限宽时,按 CB-013、CB-024、CB-025 核实是否分片、各片尺寸及承接方式;确认前保留摆包预览,不计待确认包材。 - 六格960×300×725 B版案例独立保存在规则文件的 cases 中。该案例板厚15、主体11块、背板2块,偏心32套、5×40螺丝6颗、背板扣8个。图示E1优先于旧PDF的E0;胡桃色的具体花色须匹配或确认。 diff --git a/furniture-3d-system/.agents/skills/cabinet-standard-bom/规则.json b/furniture-3d-system/.agents/skills/cabinet-standard-bom/规则.json index 44e16220..a10e60a4 100644 --- a/furniture-3d-system/.agents/skills/cabinet-standard-bom/规则.json +++ b/furniture-3d-system/.agents/skills/cabinet-standard-bom/规则.json @@ -1,8 +1,9 @@ { - "version": "0.24.3", + "version": "0.24.4", "sourceVersion": "v0.24", "status": "测试中", "scope": "板式开放格书柜:横板连续、竖隔分段;其他结构先确认", + "backPanelSplitting": {"initialRailCount":1,"maximumRailCount":2}, "hardware": {"camPerJoint":2,"camComponents":"一轮一杆","railEndScrews":2,"railJointLimit":400,"railJointSmall":1,"railJointLarge":2,"kickHorizontalLimit":600,"kickHorizontalSmall":1,"kickHorizontalLarge":2,"backLengthLimit":1300,"backClips":4}, "costBudget": {"boardDensity":650,"backDensity":550,"boardPricePerMm":2.5,"backPricePerMm":3,"drillFeet":2,"hardwareSpare":1,"longBackClips":6,"extraHardwarePrice":1,"wipePrice":0.05,"overhead":2.25,"freightPerKg":1}, "cases": { diff --git a/furniture-3d-system/.env.example b/furniture-3d-system/.env.example index a49f5793..dab2307c 100644 --- a/furniture-3d-system/.env.example +++ b/furniture-3d-system/.env.example @@ -152,6 +152,7 @@ DINGTALK_STORE_ACCOUNT_GROUP_WEBHOOK_TIMEOUT_MS=10000 DINGTALK_JD_CONSUMPTION_ORDER_WEBHOOK_URL= DINGTALK_JD_CONSUMPTION_ORDER_WEBHOOK_SECRET= DINGTALK_JD_CONSUMPTION_ORDER_WEBHOOK_TIMEOUT_MS=10000 +PLATFORM_BILL_REMARK_PUSH_ENABLED=true DINGTALK_JD_CONSUMPTION_ORDER_PUSH_ENABLED=false # 人工生成平台账单时,服务器 Chromium RPA 的异步导出等待上限(毫秒)。 diff --git a/furniture-3d-system/.gitignore b/furniture-3d-system/.gitignore index fbf41f3c..6a21243e 100644 --- a/furniture-3d-system/.gitignore +++ b/furniture-3d-system/.gitignore @@ -85,3 +85,6 @@ agents/script-monitor/config.json # 产品档案对账诊断报告 /data/archive-reconcile-diagnostics/ + +# Private daily carrier snapshots and message receipts +.daily-express/ diff --git a/furniture-3d-system/docs/workflow/每日快递承运量看板-实现与核查.md b/furniture-3d-system/docs/workflow/每日快递承运量看板-实现与核查.md new file mode 100644 index 00000000..3fa0027e --- /dev/null +++ b/furniture-3d-system/docs/workflow/每日快递承运量看板-实现与核查.md @@ -0,0 +1,80 @@ +# 快递承运量看版 + +任务:快递承运量看版完整迁入由壹点。更新日期:2026-11-26。 + +## 页面与权限 + +入口:供应链中心 → 经营管理 → 每日快递承运量看板,路径 `/supply-chain/management/daily-express-volume`。页面内有三个分支:各快递30日承运量看版、发货地省份区域承运量、已发货未揽收看版。保留现有 `dailyExpressVolume` 权限节点,页面与 API 均验证查看权限;Excel 导出额外验证下载权限。 + +页面复用 `PlatformSection`、`PlatformMetricStrip` 和 `Button`,使用浅色实体表格。没有占比、已剔除订单统计,也不将未完整取数当作零。 + +## 当前统计口径 + +- 主看板:`jst_Orders` 与 `jst_qmcust_orderlist`,按北京时间发货日期、`Sent` 状态读取。每张 ERP 内部订单计一单,跨来源重复内部单号阻止发布。仓库按 `co_id + wms_co_id` 匹配 `jst_warehouseInfo.name`。剔除空白或含 `@` 的快递单号,以及常州简尚家居有限公司、未设定发货仓库、未匹配、名称含 `配件-` 的仓库。 +- 省份:优先使用订单 `receiver_state`;缺失时以内部单号、线上单号、运单号同时匹配物流记录,读取详细地址的省级部分。冲突阻止发布。 +- 地区分支:省份与区域、仓库与发货地使用已确认映射;默认最新日期,按单日和发货地查询。优先排列常州自有仓、苏北自有仓、山东自有仓、河南自有仓、常州代发仓、河北代发仓-自有快递。 +- 未揽收:`jst_order_express_details` 昨日发货、揽收时间为空、物流状态为未揽收。剔除首次问题类型 `1688一件代发`、空白或含 `@` 的快递单号、指定快递关键词、`ECLP/CLPS/1688一件代发/刷单待处理` 标签、含 `(收)` 或 `BBFF` 的订单备注。通过普通/奇门主表及商品明细核对退款;任一明细 `refund_status=success` 整单剔除。未知退款状态不可冒充无退款。 +- 未揽收分支不套用主看板的仓库剔除规则。 + +## 运行与持久化 + +共享规则及只读 SQL 在 `scripts/daily-express-dashboard/`;`run.mjs` 每次补齐保留窗口缺失日期,再读取最新未揽收与退款信息。所有数据校验完成后,以不可变 generation 目录和原子 `latest.json` 指针发布;页面查询只读快照,不现场发起慢 SQL。 + +`DAILY_EXPRESS_DATA_DIR` 指定持久化目录,生产为 `/opt/furniture-3d-system-prod/shared/daily-express`,不在发布目录中。目录包含 `days/`、`generations/`、`mappings.json`、`notifications/` 和 `last-run.json`。生成物、真实订单、映射数据和凭据不得提交 Git。仅保留最近30天主订单;未揽收只保留最新成功日;旧 generation 发布后移除。 + +数据源使用现有 `JST_REPORT_DB_*` 环境变量。`DAILY_EXPRESS_DINGTALK_CONFIG` 指向服务器本地机器人配置(字段与原员工离职通知的 webhook 配置一致);不要把内容写入文档。普通运行命令: + +```bash +node scripts/daily-express-dashboard/run.mjs +./node_modules/.bin/tsx scripts/verify-daily-express-snapshot.ts +``` + +`--seed=<本地已核对任务目录>` 仅用于首次搬入已核对数据,不查库、不发送消息,不得拿它代替日更。首次基线是 2026-11-24、主看板 7,908 单、未揽收 9 条;这是核对基线,不是每日硬编码数量。 + +本地测试可运行 `node scripts/daily-express-dashboard/run.mjs --skip-notifications`:按相同规则只读查询上游并更新 `DAILY_EXPRESS_DATA_DIR` 中的快照,跳过正常与异常两类钉钉发送,也不创建发送记录。该模式无需机器人配置,`last-run.json` 中通知状态为 `skipped`;生产定时任务不传此参数,继续执行原有通知流程。历史日期核对可追加 `--date=YYYY-MM-DD`,页面筛选和 Excel 导出仍读取同一份已校验快照。 + +## 定时与通知 + +`scripts/install-daily-express-timer.sh` 安装 `furniture-daily-express.service/timer`,每日北京时间09:00执行,失败15分钟后重试,最多4次启动。需要单独执行安装脚本;仅发布代码不会启用。服务器任务确认就绪后才停用电脑同名业务任务,避免重复发送。 + +仅成功更新后发送原钉钉机器人文字消息;同一快递、同一仓库的单号逐行归组,不同仓库分开,相近快递名称用中文自然排序相邻显示。保留每日期发送记录,接口明确拒绝可恢复,网络结果不明时阻止自动重发。迁入既有发送记录,避免首日重复通知。 + +## 验证与限制 + +规则、退款、30日窗口、映射、快递分组排序和通知重试测试:`node --test scripts/daily-express-dashboard/*.test.mjs`。页面/权限/导出回归:对应 `DailyExpressVolumeView.test.tsx`、`daily-express-volume.service.test.ts`、`supply-chain-page-permissions.test.ts`。数据独立核对:`verify-daily-express-snapshot.ts`。 + +生产上线后须核对 commit、PM2、端口、健康检查、三个分支、导出、定时器及日志。此前本地报表查询有 SQL Server 1222 锁等待,迁移不绕过锁读取脏数据;失败保留最后成功快照,并在 `last-run.json` 记录原因,不发送旧数据。 + +规范自审:passed with warnings。这是自审,不是独立复审。架构沿用 Route → Service → Repository,后台复用已核对规则,未改变主数据或 Prisma 模型;视觉复用平台组件;原生快照与严格退款校验保持数据一致性。报表库锁等待风险仍需生产运行持续观察。 + +## 2026-11-26:累计窗口调整为30日 + +主承运量从15日改为30日滚动累计,沿用2026-11-24起始日;未满30日仅展示已累计日期,不补造历史。第31日移除最早日期,日均值按实际累计天数计算。地区分支可选日期沿用所保留的30日数据;未揽收仍只展示最新成功日,通知发送方式和15日发送记录保留期不变。 + +验证:35项数据/通知测试通过,补充30日校验、31日拒绝、30列数据及合计导出检查;8项页面/服务测试通过。本地已发布看板标题及Excel文件名改为30日,63,264个明细单元格核对一致,桌面/手机及下载链接验证通过。 + +规范自审:passed。这是自审,不是独立复审。仅修改累计窗口、对应校验与展示命名,保持数据源、退款剔除和单日未揽收口径不变。 + +## 2026-11-26:主看板按发货日期筛选 + +主看板默认展示保留窗口内的全部日期,每日承运量各占一列;新增发货日期选择和「筛选」按钮。选择日期后点击筛选,汇总、图表、快递列表以及 Excel 汇总/订单明细同时切换到该日;「全部日期」恢复完整窗口。零发货量的已更新日期可正常选择,未发布日期由服务校验拒绝,不回退显示其他日期。日期候选始终来自完整快照,不因当前筛选而丢失。 + +实现保持 Route → Service → Repository 分层:Service 对同一快照执行日期投影,导出使用相同口径;前端复用原平台组件,只增加日期控件和手机端换行样式。切换分支时重置主看板日期条件,其他分支及通知逻辑保持既有行为。未重新查询数据库或发送通知。 + +验证:11项页面/服务测试通过,覆盖默认全部日期、点击后应用筛选、恢复、零发货日、无效日期和同日 Excel 明细;相关生产文件 ESLint 通过。本地日期选择/发布测试3项通过。实际组件浏览器验证多日切换、恢复、零发货日及 1920×1080 / 390×844 布局;本地看板同样验证通过,现有已核对数据仍为 2026-11-24、7,908 单。 + +规范自审:passed。这是自审,不是独立复审。架构边界保留、控件沿用组件库、日期筛选和导出共用数据投影;筛选直接作用于日期数据,未用页面隐藏替代统计计算。线上生效须随共享主线变更合入生产 main 后部署。 + +## 2026-11-26:自动更新与未揽收异常分离 + +排查发现本机09:00任务在订单取数完成后因桌面仓库映射文件缺失失败,服务器原先仅迁入快照,尚未安装日更timer。现已安装并启用服务器 `furniture-daily-express.timer`,每日北京时间09:00执行,使用持久化映射,不依赖电脑桌面文件。确认服务器成功接管后停用旧Windows任务,避免重复发送。 + +用户确认新口径:承运量和区域正常更新;未揽收逐单核对,仅将本次核对成功且符合筛选条件的订单用于列表、导出及正常通知。缺少主表/明细、关联不一致或明细重复的候选进入独立异常清单,不视作无退款、不混入正常数据。正常通知和异常通知使用不同的每日发送记录,重试不会重复发送。 + +承运量先独立校验,再处理未揽收。个别订单异常时发布本次成功记录及异常摘要;整个未揽收查询失败时仍发布有效承运量,页面明确无本次已核对数据,不展示旧数据冒充本次;内部保留上次已校验快照仅供恢复。异常页不展示凭据或SQL。退款成功继续整单排除。 + +2026-11-25主承运量快照已在本机09:27完成且通过服务端规则校验,共7,365单(普通3,271、奇门4,094);和11月24日7,908单累计15,273单。首次服务器补跑因奇门订单10366147缺少商品明细被旧逻辑阻止;未改变源数据库,按上述新口径单独处理异常。 + +验证:39项数据/通知测试、13项页面/服务测试及TypeScript、相关ESLint通过;新增逐单隔离、退款成功仍剔除、完整审计损坏阻止读取、正常/异常通知独立去重等检查。实际组件桌面1920×1080、手机390×844验证本次记录与异常提示共存。 + +规范自审:passed。这是自审,不是独立复审。规则仍位于共享计算与服务层,数据权限及严格退款判断保留;页面沿用平台控件,只增加必要异常状态,修复单个异常阻断无关看板更新的问题。 diff --git a/furniture-3d-system/docs/使用说明/清货任务制定与推送流程-20261110.md b/furniture-3d-system/docs/使用说明/清货任务制定与推送流程-20261110.md index d4be099c..f1d2f17b 100644 --- a/furniture-3d-system/docs/使用说明/清货任务制定与推送流程-20261110.md +++ b/furniture-3d-system/docs/使用说明/清货任务制定与推送流程-20261110.md @@ -290,7 +290,7 @@ ### 11.2 强制推送的适用范围 -固定任务可按配置执行强制推送;普通任务仍需遵循运营确认和经管终审流程。页面和服务端使用同一权限及时间窗口校验。 +审核人可在“批量审核 → 待运营确认”中勾选 `READY` 或兼容的 `REJECTED` 任务并执行“强制推送”。系统保留当前审核人已确认的任务量和折扣,跳过运营确认,直接转为 `APPROVED` 并进入清货任务,同时记录 `FORCE_PUSH` 操作日志。清货池页面不再提供旧的固定任务“强制推送”入口。 ### 11.3 旧草稿接口 @@ -317,8 +317,7 @@ | `POST /api/supply-chain/clearance/tasks/reviewer-edit` | 审核人编辑清货任务 | | `POST /api/supply-chain/clearance/tasks/:id/adjust` | 旧数据兼容接口,页面不再提供调整后通过 | | `POST /api/supply-chain/clearance/tasks/:id/remove` | 旧数据兼容接口,运营删除走 operator-delete | -| `POST /api/supply-chain/clearance/tasks/push-reviewed` | 经管强制推送全部 `READY` | -| `POST /api/supply-chain/clearance/review-workbench` | 批量审核工作台 | +| `POST /api/supply-chain/clearance/review-workbench` | 批量审核工作台;`action=force-push` 强制推送待运营确认任务 | | `POST /api/supply-chain/clearance/price-push` | 生成清货价月度存档 | | `GET /api/supply-chain/clearance/price-push/manual/template` | 下载按明细抬头制作的人工清货价导入模板 | | `POST /api/supply-chain/clearance/price-push/manual/import` | 导入人工补充清货价 | diff --git a/furniture-3d-system/docs/架构设计/24h揽收及时率自动化-数据口径.md b/furniture-3d-system/docs/架构设计/24h揽收及时率自动化-数据口径.md new file mode 100644 index 00000000..15aeca9e --- /dev/null +++ b/furniture-3d-system/docs/架构设计/24h揽收及时率自动化-数据口径.md @@ -0,0 +1,123 @@ +# 24h 揽收及时率自动化 · 数据口径 + +> 需求来源:`24h支揽率详细需求.xlsx` + 人工版模板 `3、24h支揽率人工版模板.xlsx` +> 实现位置:`src/lib/pickup-24h-timeliness.ts`(口径)、`src/server/services/pickup-24h-timeliness-sync.service.ts`(同步)、 +> `src/app/supply-chain/management/pickup-24h-timeliness/`(页面) + +## 1. 一句话口径 + +24h 揽收及时率 = 24h 内揽收的考核单量 / 参与考核的应揽收单量; +单量按「内部订单号 + 是否超时(+ 采购)」分组均摊(1/组内行数),与人工模板的 COUNTIFS 公式一致。 + +## 2. 取数范围与节奏 + +| 项目 | 取值 | +| --- | --- | +| 明细粒度 | 付款日期 + 内部订单号 + 线上订单号 + 商品编码(同单同编码重复行保留多行) | +| 每日任务 | 付款日期 = 今天 - 2 天(10 月 7 日跑 10 月 5 日),`06:10 Asia/Shanghai` | +| 历史回补 | 从 `2026-10-01` 起,按付款日期逐日生成 | +| 页面默认区间 | 付款日期起 = 本月 1 日,付款日期止 = 今天 - 2 天(覆盖本月已同步的全部付款日期) | +| 页面默认筛选 | 是否参与考核 = 是;是否超时 = 全部(两个下拉取值均为 是 / 否 / 全部),其余条件为空;筛选栏「重置」恢复到这套默认值 | +| 页面结构 | 筛选区下方两个页签:24h揽收及时率分析看板(默认)/ 订单明细;共用同一套筛选,看板下钻自动切到订单明细;店铺维度按「平台站点 + 店铺」分组展示 | +| 批次可见性 | 只有 `status = COMPLETED` 的批次对页面可见,写入中途/失败批次不参与读取 | +| 批次重跑 | `--force` 覆盖重写;页面不提供重算入口,需要重跑时用同步脚本(见第 9 节) | +| 订单明细导出 | 单次最多 31 天(按一个月计);后台任务流式生成 xlsx(行数不设上限),进「下载中心」看进度并保存/删除 | +| 批量查询 | 关键词支持逗号/顿号/分号/换行分隔,命中任意一个即显示;关键词框后「批」可打开批量输入框,取消/确认后查询 | + +## 3. 数据来源 + +| 字段组 | 来源 | 说明 | +| --- | --- | --- | +| 快递公司、快递单号、发货时间、店铺名称 | `rpt.jst_qmcust_orderlist`(淘系)/ `rpt.jst_Orders`(其他平台) | **以订单主表为准**;订单表为空时才回退物流明细视图(解决手工改单后物流视图滞后的问题) | +| 付款时间、揽收时间、发货仓、标签、订单备注、买家留言 | `rpt.jst_order_express_details` | 按 `pay_time` 落在付款日期当日筛选;揽收时间、发货仓目前只有该视图提供 | +| 状态、订单类型、异常类型、平台站点、省份、旗帜、外部交易单号 | `rpt.jst_qmcust_orderlist`(淘系)/ `rpt.jst_Orders`(其他平台) | `status` 英文码映射为中文(Sent→已发货、Split→被拆分…) | +| 订单状态归一化 | 订单主表 `status` + 物流明细 `order_status_name` | **取消优先**:任一来源为 Cancelled/Canceled/已取消/取消 → 统一为「取消」;其余按主表映射、物流明细兜底 | +| 商品编码、商品名称、数量、退款状态 | `rpt.jst_qmcust_orderlist_item` / `rpt.jst_OrderItem` | `refund_status`:none→未申请退款、success→成功退款、waiting→等待退款、closed→退款关闭 | +| 货号、分类、商品属性、生产状态、供应商 | `rpt.jst_sku` | 货号取 `other_7`(聚水潭 UI 的“货号”),为空或等于商品编码时回退 `i_id`;注意 `i_id` 是“款式编码”,不能当货号;`item_type` = 成品/配件;`other_5` = 生产状态;`category` 形如「住宅家具 - 书桌」 | +| 组合商品 | 订单明细 `sku_id` 含 `+` | 按 `+` 拆成组件商品编码,逐组件生成明细行(组件数量 = 组合数量 × 组件出现次数),再按组件查商品资料;避免整串编码查不到资料被误剔除 | +| 采购 | `rpt.js_supplier` | 按供应商名称匹配 `buyer` | +| 售后申请时间 | `rpt.jst_qmcust_refundlist(_item)` + `rpt.jst_returnAndRefundInfo(_item)` | 按「内部订单号 + 商品编码」取最早 `as_date`;只取付款日当天 ~ 付款日 + 2 天的窗口(口径只认 24h 内申请) | + +## 4. 计算列 + +| 列 | 口径 | +| --- | --- | +| 是否超时 | 规则见第 5 节 | +| 考核单量 | `1 / COUNT(内部订单号 & 是否超时)`,只统计参与考核的行 | +| 采购考核计数 | `1 / COUNT(内部订单号 & 是否超时 & 采购)`,只统计参与考核的行 | +| 付款日期 | 付款时间的年月日(Asia/Shanghai) | +| 交易单号&货号 | 线上订单号 + 货号(SPU) | +| 单交易单号单货号销售件数 | 同一线上订单号 + 货号的累计数量(含被剔除行,与人工模板透视一致) | +| 售后/揽收/发货时间-付款时间 | 小时差,页面与导出按人工模板习惯折成天数显示 | + +## 5. 是否超时 + +1. 店铺含「京喜」且 发货时间 - 付款时间 ≤ 24h → 否(及时); +2. 快递公司含 京喜 / 京东快运 / 京东自营 / 顺丰 且 揽收时间为空 且 发货时间 - 付款时间 ≤ 24h → 否; +3. 揽收时间 - 付款时间 ≤ 24h → 否; +4. 其余 → 是(超时)。 + +## 6. 是否参与考核(不准入规则,命中第一条即剔除) + +顺序与人工模板 `IF` 链一致: + +1. 分类 = 其他 - 配件 +2. 货号为空 +3. 数量 = 0(或缺失) +4. 供应商命中排除关键词(默认:虚拟、景瓴十方) +5. 状态 = 被合并 / 被拆分 +6. 同一线上订单号 + 同一商品编码的累计销售件数 ≥ 20(经管大单) +7. 售后申请时间 - 付款时间 ≤ 24h(24h 已退款) +8. 商品属性 ≠ 成品(商品编码不在成品商品资料中) +9. 标签命中排除关键词 +10. 快递公司命中排除关键词 +11. 订单备注命中排除关键词 +12. 买家留言命中排除关键词 +13. 状态 = 取消 且 发货时间为空 且 售后申请时间为空 +14. 快递单号命中排除关键词(默认:F800) +15. 异常类型命中排除关键词 +16. 店铺命中排除关键词 +17. 售后申请时间 - 付款时间 ≤ 24h(与第 7 条同口径;晚于 24h 的售后不影响参与考核) + +> 商店含「京喜」且退款状态 ≠ 未申请退款的剔除条件已按业务要求移除(京喜售后可自动下载),京喜订单正常参与考核。 + +## 7. 排除关键词 + +- 按字段生效:`供应商 / 异常类型 / 快递公司 / 快递单号 / 订单备注 / 买家留言 / 标签 / 店铺`; + 配在「供应商」下的词不会命中「标签」,与物流到货签收时长看板一致。 +- 默认值 = 人工模板里写死的名单(标签 24 个、快递公司 6 个、快递单号 1 个、订单备注/买家留言各 13 个、供应商 2 个)。 +- 关键词是**读时过滤**:页面改完立即生效,不需要重跑历史批次; + 但「考核单量 / 采购考核计数」的分母在同步时固化,若需要严格等于新口径,用同步脚本按付款日期重跑(`--force`)。 +- 只有权限管理员可以把新词写入默认排除词;其他用户新增的词只影响本次查询。 + +## 8. 与人工模板的已知差异(需要业务确认) + +1. **经管大单分组字段**:已按需求表口径执行 ——「线上订单号 & **商品编码**」累计件数 ≥ 20。 + 人工模板公式里用的是「线上订单号 & 货号(SPU)」,会把同一货号下多个编码各 10 件的订单误判为大单,已废弃该口径。 + 口径调整后可用 `npm run recompute:pickup-24h-timeliness -- --apply --confirm=recompute-pickup-24h-timeliness` 重算历史批次(不访问上游)。 +2. **售后来源**:需求列的 `ist_qmclist_refundlist` / `ist_returnAndRefundInfo` 在报表库中对应 `jst_qmcust_refundlist` / `jst_returnAndRefundInfo`; + 需求提到的 `pdd_fz_refundlist` 在报表库中不存在,拼多多的售后申请时间只能靠 `jst_returnAndRefundInfo` 覆盖。 +3. **工厂发货单号**:报表库没有稳定来源,当前留空。 +4. **退款状态**:人工模板的「未申请退款 / 成功退款 / 等待退款 / 退款关闭」来自商品明细的 `refund_status`,不是物流明细的 `aftersale_status_name`。 +5. **省市区**:模板里的省份取订单表的 `receiver_state`,取不到时回落到物流明细地址串的第一段。 + +## 9. 常用命令 + +```bash +# 每日(默认付款日期 = 今天 - 2 天) +npm run sync:pickup-24h-timeliness -- --apply --confirm=sync-pickup-24h-timeliness + +# 指定日期 / 历史回补 +npm run sync:pickup-24h-timeliness -- --apply --confirm=sync-pickup-24h-timeliness --date=2026-10-04 --force +npm run sync:pickup-24h-timeliness -- --apply --confirm=sync-pickup-24h-timeliness --from=2026-10-01 --to=2026-10-05 --force + +# 生产每日定时(systemd,06:10 Asia/Shanghai,先准备身份校验 env 文件) +sudo bash scripts/install-pickup-24h-timeliness-timer.sh +``` + +## 10. 验证要点 + +- `Pickup24hTimelinessRun` 中对应付款日期批次 `status = COMPLETED`、`rowCount` 与远端当日订单量级一致(约 1.1 万行)。 +- `Pickup24hTimelinessOrder` 中 `rowKey` 唯一、`included` 为假的行必须带 `excludeReason`。 +- 及时率 = 1 - 超时单量 / 考核单量;抽 1 天与人工版模板核对不准入原因分布。 +- 页面默认展示「本月 1 日 ~ 今天 - 2 天」;改排除关键词后刷新应立即改变及时率。 diff --git a/furniture-3d-system/docs/架构设计/清货管理-20261020.md b/furniture-3d-system/docs/架构设计/清货管理-20261020.md index f02f2cf2..bab8f0c7 100644 --- a/furniture-3d-system/docs/架构设计/清货管理-20261020.md +++ b/furniture-3d-system/docs/架构设计/清货管理-20261020.md @@ -105,7 +105,7 @@ - 运营负责人、部门负责人、利润中心、清货批次和优先级映射当月清货池数据;发货数量统一取聚水潭实际出库单。 - 运营和经管可从清货池工具栏的“运营导入任务”入口通过 5 列 Excel 导入并进入审核;任务运营负责人取表格中的清货负责人,不按执行导入的账号归属。同一清货商品编码允许不同清货负责人分别导入,文件内以“商品编码 + 清货负责人”判断重复。任务量支持小数并统一向上取整;折扣支持“五折”等中文写法,保存和展示统一转换为阿拉伯数字折扣。清货池不提供内联任务量、折扣、原因和任务状态编辑,也不再提供“批量定任务”入口。 -- 清货任务页另提供仅 `clearanceReview.edit` 审核人可用的“导入人工清货任务”直导入口,模板固定为统计月、条码、清货价、任务清货量、利润中心、SPU负责人、部门负责人、优先级。直导按“统计月 + 条码 + 利润中心”更新已有任务或新增任务,写入后直接为 `APPROVED` 并展示在清货任务页。 +- 清货任务页另提供仅 `clearanceReview.edit` 审核人可用的“导入人工清货任务”直导入口,模板固定为统计月、条码、清货价、任务清货量、利润中心、SPU负责人、部门负责人、优先级。直导按“统计月 + 条码 + 利润中心”更新已有任务或新增任务,写入后直接为 `APPROVED` 并展示在清货任务页。导入文件中的 SPU负责人作为清货负责人优先保留,不被清货池 SPU 负责人覆盖;已填写清货价时即使折扣为 `1.00` 无折扣,清货任务页仍展示该价格。 - 导入模板字段固定为:清货商品编码、清货负责人、任务量、折扣、申请原因。清货商品编码在文件内必须唯一,清货负责人必须有效且清货商品编码必须存在于当前清货池。 - 销售状态商品不允许申请折扣;导入时按清货商品编码返回错误原因。任务量超过简尚库存时,按简尚库存截断,并在导入结果中返回被截断编码。 - 导入成功后任务统一进入 `PENDING`,直接出现在批量审核工作台;相同编码、同一清货负责人再次导入会更新原任务并重新进入待审核,同时清空旧审核快照、审核结果和退回原因。不同清货负责人可分别导入同一编码;退回原因保留用于运营确认,但不再设置“历史退回”状态或筛选。 @@ -114,14 +114,14 @@ - 批量审核按清货商品编码排序;同一编码存在多名运营申请时保持相邻展示,在标题和每一行标记“重复申请 ×N”,便于审核人合并比较。重复判断不影响各运营任务独立审核。 - 经管“退回”申请后任务直接进入 `READY` 待运营确认,并展示退回原因;退回和初审通过在界面中统一属于待运营确认,不设置“退回待修改”或“历史退回”筛选项。待运营确认明细顶部提供“修改”按钮,运营进入修改态后可调整任务量和折扣,点击“保存并重新提交”后进入 `CONFIRMED` 已重新提交,自动回到批量审核等待经管终审。待确认明细同时提供“确认无误”和“删除任务”;删除只移除运营任务记录,不修改清货池快照,后续可重新运营导入。 - 终审不得修改运营已确认的任务量和折扣,只能终审通过或再次退回给运营修改。终审通过后进入 `APPROVED`,才出现在清货任务页并同步清货价推送。新的审核流程不再展示“调整后通过”操作。 -- 清货池“固定任务量”允许经管直接编辑,修改值写回当月清货池快照并记录人工来源。经管勾选固定任务商品后点击底部“强制推送”,系统按当前固定任务量创建或更新终审通过的清货任务;已有任务的折扣、原因和申请人信息优先保留,固定任务强制推送不受普通任务通道关闭限制。 +- 清货池“固定任务量”允许经管直接编辑,修改值写回当月清货池快照并记录人工来源。清货池页面不再提供旧的固定任务“强制推送”入口。审核人在批量审核的待运营确认明细中可勾选 `READY` 或兼容的 `REJECTED` 任务执行“强制推送”,系统保留当前任务量、折扣和清货价,跳过运营确认直接转为 `APPROVED`,并记录 `FORCE_PUSH` 操作日志。 - 清货任务页对清货审核人提供“编辑”按钮。进入编辑态后可直接修改任务量、折扣、清货价、成本价、运营负责人、部门负责人、利润中心、申请原因和优先级,保存后写回原始任务并记录 `MANUAL_EDIT` 事件。统计月、发货数量、清货进度、库存、日销、可用天数、运费及折扣预警等派生字段保持只读,避免被后续同步覆盖或破坏统计口径。 - 清货池展示任务流程和「全部任务 / 待审核 / 待运营确认 / 已重新提交 / 已通过」审核结果快捷按钮;经管看到全部申请统计,普通运营仅看到本人申请统计。点击后筛选清货池明细,导出时沿用同一结果。清货任务页不展示利润中心汇总、状态分段按钮、重复搜索框或记录类型切换;任务周期、筛选项、刷新、编辑、导出和列设置合并为同一行。任务明细每页 50 条,表格下方使用紧凑分页控件展示总条数、本页条数和上一页/下一页。没有任务时仍保留完整表头,只在表体显示原有空态提示。 - 清货池顶部不再展示销售、退市、停产三张库存概览卡,改为一条紧凑的审核状态筛选条;优先级调整栏同步压缩,减少顶部占用并为明细释放纵向空间。 - 清货池任务流程和状态概览并入清货月份栏:任务流程压缩为单行步骤条,销售、退市、停产各自展示编码数量、简尚库存和总库存,长期滞销库存当前显示待配置;窄屏时状态卡片自动换行。指标按整个生成月份汇总,不随筛选条件变化,宽屏展示状态卡片后为筛选和明细释放纵向空间。 - 清货池明细最右侧为“审核结果”列。待审核、待运营确认、已重新提交、已通过分别标识;经管退回的申请仍显示在待运营确认中并附带退回原因。经管可点击结果查看申请详情;运营端仅显示本人结果,退回或经管调整后显示修改摘要。运营确认或修改成功后会重新进入经管终审,并刷新清货池、审核计数与任务明细。 -- 审核弹窗顶部展示商品编码、清货商品编码、SPU、运营负责人、部门负责人、利润中心、清货批次、商品状态、优先级、简尚/工厂/总库存、清货总量、7 日销、可用天数、停产时间和入库天数,并展示同商品编码最近月份的任务量、折扣、完成量和完成率。经管可“通过原申请”或“退回”,不再提供独立“调整后通过”操作;退回必须填写退回原因。待审核弹窗不提供强制推送。 -- 正式任务只允许经管在 `CONFIRMED`(运营已重新提交)阶段终审通过后生成。旧的“未确认强制推送”入口和服务方法已移除,避免绕过运营确认和终审。 +- 审核弹窗顶部展示商品编码、清货商品编码、SPU、运营负责人、部门负责人、利润中心、清货批次、商品状态、优先级、简尚/工厂/总库存、清货总量、7 日销、可用天数、停产时间和入库天数,并展示同商品编码最近月份的任务量、折扣、完成量和完成率。经管可“通过原申请”或“退回”,不再提供独立“调整后通过”操作;退回必须填写退回原因。强制推送统一放在批量审核工作台,单条待审核弹窗不提供该入口。 +- 普通审核通过后先进入 `READY` 待运营确认;运营确认或重新提交后再进入 `CONFIRMED` 由经管终审。审核人也可在批量审核的待运营确认明细中执行强制推送,直接将 `READY` 或兼容的 `REJECTED` 任务转为 `APPROVED`,用于审核人确认需要跳过运营确认的场景。 ```text 运营或经管下载人工导入模板 diff --git a/furniture-3d-system/docs/需求设计/库存监控基础版-20261118.md b/furniture-3d-system/docs/需求设计/库存监控基础版-20261118.md new file mode 100644 index 00000000..f0766d80 --- /dev/null +++ b/furniture-3d-system/docs/需求设计/库存监控基础版-20261118.md @@ -0,0 +1,213 @@ +# 库存监控基础版 + +更新时间:2026-11-24 + +## 页面与范围 + +- 入口:供应链中心 → 经营管理 → 库存监控。 +- 页面:`/supply-chain/management/blank-pages/blank-page-9`。 +- 权限节点:`managementBlankPage9`,查看、下载和配置分别独立控制。 +- 库存总览:位于库存监控页面内的“库存总览”页签,不单独占用侧边栏菜单;兼容路由 `/supply-chain/management/blank-pages/blank-page-10`,复用库存监控权限和数据快照。 +- 商品记录、简尚库存、总货值、滞销库存、滞销货值、预警六张关键指标卡位于“库存监控”页签顶部,使用整份快照汇总,不随下方筛选结果变化。 +- 点击商品记录、简尚库存或总货值卡会清除筛选并查看全部商品;点击滞销库存或滞销货值卡会筛选“是否滞销=滞销”;点击预警卡会筛选“滞销预警=预警”,下方明细同步展示对应商品编码。 +- 主表按商品编码聚合,字段顺序沿用《库存监控逻辑.xlsx》的业务列;A 列“数据源”只用于说明来源,不进入页面和导出,业务列从“款式编码”开始。 +- 库存监控明细固定在最左侧展示产品档案商品图片;无图片或图片加载失败时展示占位图标,图片列不参与排序、筛选和普通 Excel 列导出。 +- “入库/发货仓库”直接映射产品全量档案 `inOutWarehouse`,在库存监控明细、筛选和导出中展示。 +- 创建时间严格映射产品全量档案 `businessCreatedAt`,并使用与产品全量档案一致的 UTC 日期展示口径,避免北京时间跨日导致晚一天。 +- 库存监控明细右上角注明“是否动销:销量维度 · 是否滞销:库存维度”,用于明确两个状态字段的判定维度。 +- 仓库范围沿用《仓库配置.xlsx》:14 个黄色字体仓库排除,其余 54 个仓库初始纳入,不按“不可释放”等仓库属性二次过滤。 + +## 仓库库位配置 + +- 配置弹窗页签顺序为“动销配置、滞销库存配置、预警配置、仓库库位配置、备货天数”,备货天数位于仓库库位配置右侧。 +- 仓库库位配置是只读测算页,不修改库存监控规则,也不参与动销、滞销或预警状态计算。 +- 基础数据严格使用《各仓库容情况26.11.16.xlsx》的 14 行:区域、存储类型、租赁面积、托盘库位数、库位长宽高。 +- 附件中的不规范仓库名称统一映射为系统标准名称:崔桥工厂仓、崔桥半成品包装仓、横林二仓、新外贸仓、苏北仓、山青集岗仓、山东品牌仓、洛宁仓、睢宁仓分别映射为简尚-崔桥工厂仓、简尚-崔桥工厂半成品包装项目仓、简尚-横林二仓、简尚-新外贸仓、简尚-新苏北仓、简尚-山东青岗集仓、简尚-山东品牌仓、简尚-河南洛宁仓、简尚-睢宁仓。 +- 附件存储类型“拣选去”按明显错字修正为“拣选区”;金源涌动项目仓归入简尚-新苏北仓的“金源涌动”存储区,品牌仓等仓库别名归入对应标准仓库。 +- 实际库存按产品全量档案长宽高和各实际仓毛库存统计,不使用公有可用数,也不扣减订单占用。运营云仓、外贸仓和专用仓存在实际所在仓时,按 `jst_warehouseInfo.wms_co_id` 对应的实际仓库存归集。 +- `jst_inventoryInfo.qty` 已包含该实际仓的运营云仓库存;`jst_virtualstockStocksInfo.qty` 只用于确认云仓实际所在仓,不再与实体毛库存相加,避免重复占用。若某“商品编码 + 实际仓”没有实体库存行,才以云仓毛库存兜底。 +- 同一“商品编码 + 实际仓”的实际库存计算为:`max(实体仓 qty 汇总, 云仓 qty 汇总)`。 +- 商品档案尺寸单位为厘米,附件库位尺寸单位为米,计算前统一乘以 100 转为厘米。 +- 每个商品对库位尝试六种正交摆放方向,以“单库位可放件数”最大为第一目标、体积利用率为第二目标,得到 `单库位可放件数 = 三个方向向下取整后相乘`。 +- `预计占用库位 = ceil(实际库存 / 单库位可放件数)`。同一仓库存在多个存储区时,优先填满一个存储区,再使用后续存储区;超出全部库位部分回填到首选存储区并判定为爆仓。 +- 爆仓状态:利用率大于 100% 为“爆仓”,90% 至 100% 为“临界”,70% 至 90% 为“紧张”,低于 70% 为“正常”。 +- 尺寸缺失商品的库存仍计入实际库存,但因无法估算占位而不计入库位占用;尺寸过大、六种方向均无法放入标准库位的商品同样只计入实际库存并单独提示。因此当前利用率是偏保守的估算值。 +- 页面按仓库展示实际库存、预计占用库位、库位总数、剩余库位、利用率、状态和建议;存储区明细另行展示各存储区的占用与剩余库位,避免把推算分配误写成真实分区库存。 +- 附件未配置但实际存在库存的仓库只展示库存和未纳入提示,不猜测映射到已有仓库,也不参与爆仓判断。 + +## 库存口径 + +按商品编码先汇总全部纳入仓库的库存、订单占用和云仓占用,再进行一次统一计算: + +```text +总库存 = Σ 纳入仓库库存 qty +总订单占用 = Σ 纳入仓库订单占用 order_lock +总云仓占用 = Σ 纳入仓库运营云仓 order_able_qty + +公有可用数 += 总库存 - 总订单占用 - 总云仓占用 + +简尚库存 += max(0, 公有可用数 + 总云仓占用) +``` + +- 纳入仓库中库存或订单占用不为 0 的明细参与汇总;缺货仓等零库存但存在订单占用的仓库不会被提前剔除。 +- 公有可用数允许显示负数;只有“公有可用数 + 云仓占用”的最终简尚库存为负数时,简尚库存才归零。 +- 公有可用数和云仓占用互斥;简尚库存由两者相加。云仓明细只用于展示来源,不再次重复加入。 +- 总货值 = 成本 × 简尚库存,保留两位小数。 +- 成本严格使用产品全量档案 `costPrice`;档案存在但成本为空时按0计算,不再回退聚水潭成本。 +- 运营负责人默认映射产品全量档案 `opsHead`;通过人员信息判断在职状态,在职或未匹配人员时保留原运营负责人,明确离职时使用 `opsDeptHead` 覆盖运营负责人。`opsHead` 为空且 `opsDeptHead` 有值时同样使用部门负责人兜底。部门负责人本身仍映射 `opsDeptHead`,不使用 SABC 快照中的负责人覆盖档案值。 +- 可用天数 = 简尚库存 / 30日含大单日销并向下取整;日销为 0 显示“无销量”。 + +## 日销、动销和预警 + +- 日销优先直接读取营销日销源 `rpt.op_marketingDailySales.thirtyBigSale` 当日批次;源表不可用或商品未匹配时才回退产品档案 `sales30dWithBig`。 +- 动销、滞销和预警均支持多条有序规则;规则命中后停止继续判断,全部未命中时使用该组兜底状态。 +- 同一轮计算中,预警规则使用刚计算出的动销状态和滞销状态,不读取快照中的旧“待配置”占位值。 +- 配置页不再提供“启用规则”勾选框;组内存在已配置规则时,配置保存后等待人工刷新,再由刷新动作统一应用。 +- 配置弹窗底部固定展示“保存配置”按钮,保存成功后只关闭弹窗并持久化配置,不触发页面查询或状态重算。 +- 系统分别保存“待生效配置”和“最近生效配置”;普通查询、筛选、排序、分页和导出均使用最近生效配置,只有人工刷新的 `refresh=1` 请求会把待生效配置切换为生效配置。 +- 单条规则选择“同时满足全部条件”时,条件行连接词显示“且”;选择“满足任一条件”时显示“或”,与人工刷新后的实际判定逻辑保持一致。 +- 规则字段覆盖库存监控商品行全部标量字段,包括商品信息、成本金额、库存与销售、入库时间、动销/滞销/预警状态、A/C/G/分销铺货数量及中间计算字段。 +- 文本字段的条件值从当前库存监控数据中加载对应字段的真实候选值,例如生产状态、供应商、负责人、编码和状态;数值字段继续使用数字输入。 +- 生产状态、供应商、负责人、新品、SABC、动销/滞销/预警等常用候选值直接复用页面筛选数据;其他文本字段按“当前快照版本+字段”共享缓存,同一字段多个条件只请求一次。 +- 组内没有可用规则时,对应状态显示“待配置”,不推断业务结论。 + +## 滞销模式切换 + +- 主表标题栏右侧可即时切换“30天”和“备货天数”,默认选择 30 天。 +- 30 天:`max(0, ceil(单仓公有可用数 - 日销 × 30))`。 +- 备货天数配置包含“仓库维度”和“供应商维度”。仓库维度来自采购库存监控导出的仓库信息,展示仓库名称、安全库存天数、产品标签、备货天数、最低备货天数和送货单时效;供应商维度来自《品牌项目跟进表交接20261121.xlsx》的 `跟单表`。 +- 2026-11-21 导入的仓库维度共 5 个核心仓、30 条“仓库 + SABC”规则;供应商维度汇总为 95 个供应商,附件中有多个品牌的供应商按供应商统一兜底,页面同时保留涉及品牌供核对。 +- 供应商维度备货天数统一向上取整到整数,例如 74.5 显示和参与计算均为75;手工录入小数时保存前同样向上取整。 +- 库存监控明细计算备货天数时按以下优先级匹配:先使用“入库/发货仓库 + 商品SABC标签”命中仓库维度;未命中时使用商品供应商命中供应商维度;两者都未命中时保留最新 `pm_stockMonitor.safetyDays`,避免漏配商品突然失去值。 +- 备货天数展示命中规则的原始值,小于30天不回写展示值。滞销计算使用 `max(30, 备货天数)`;备货天数配置修改后点击“保存配置”,再点击页面右上角“刷新”后生效。 +- 备货天数滞销库存:`max(0, ceil(单仓公有可用数 - 日销 × 计算备货天数))`。分销仓和外贸仓仍执行到仓入库满90天后全部计滞销的专用规则。 +- 页面“备货天数”列始终展示来源值,例如来源7天仍显示7天;最低30天只用于滞销库存计算,不回写或替换展示值。 +- 分销仓和外贸仓不跟随上述两种模式,无论实体仓还是云仓,均按该商品在该实际仓库的最近入库时间计算:未满 90 天不计滞销,满 90 天后当前未处理库存全部计为滞销。 +- 切换只影响当前查看、筛选、排序和导出,不修改其他用户或全局默认口径。 + +- 滞销货值固定按 30 天模式滞销库存 × 成本计算,不随页面当前模式变化。 +- 最近入库时间只读取实际入库量大于 0 的采购明细;采购单已完结取 `finish_time`,未完结取 `delivery_date`。 +- 最近入库天数按快照生成日与最近入库日期的自然日差计算。 + +## 明细与铺货 + +- 点击商品编码后打开商品库存明细面板,包含“各仓库存”和“各中心铺货”两个页签。 +- 商品明细固定在库存监控明细主表和分页下方,整宽展示;直接点击另一个商品编码即可切换明细,不需要先关闭当前面板。 +- 指标卡、页签和表格工具栏采用紧凑高度,为下方明细保留更多纵向空间;窄屏下页面支持内部滚动,主表固定保留可用行数。 +- 各仓库存同一张表内同时展示库存、订单占用、云仓占用、公有可用数、可用天数、最近入库时间、入库天数、30 天滞销库存、备货天数和备货天数滞销库存。 +- 各仓库存下方单独列出运营云仓明细,包括云仓名称、云仓库存、订单占用和可下单量;云仓占用已经计入简尚库存,不重复使用云仓明细行再次累加。 +- 最近入库时间按“商品编码 + 实际入库仓库”分别读取采购单;同一编码进入崔桥仓、分销仓或外贸仓时分别计算入库天数,不再共用商品编码级的最晚入库时间。 +- 云仓行不使用关联实体仓的采购入库时间,改为读取并原样展示 `jst_virtualstockStocksInfo.modified`,即聚水潭“商品库存(运营云仓)”中的“库存更新时间”(精确到秒)。 +- 各利润中心铺货数量以聚水潭前端当前可见记录为准,合并 `rpt.jst_skumap` 与淘宝系 `rpt.jst_skumap_qmcust_add` 两张表中 `enabled=1` 的记录。 +- 每条源记录按 `shop_id` 匹配 `rpt.op_ShopConfig_view.code`,取 `Department` 作为利润中心;再按“商品编码 + 利润中心”汇总记录条数。 +- 主表铺货总数量按全部已映射利润中心求和,运营中心B及其他利润中心同样计入总数;A/C/G/分销字段继续保留各自专用口径。 +- 同一店铺的多条铺货记录逐条计数,不按店铺或铺货ID去重;按聚水潭前端可见口径只统计 `enabled=1` 的当前链接,已下架历史记录不计入。 +- 2026-11-20 用户确认按“主表 + 淘系表”合并口径计算利润中心铺货数量;当前不合并 `jst_skumap_pdd`,`enabled=0` 的历史记录仍不计入。 +- 未匹配到非空利润中心的源记录不猜测归属,也不计入 A/C/G/分销数量。 +- 两张 `skumap` 表按“来源表 + 店铺 + 商品编码”在源端分批聚合后读取,由独立快照任务生成持久化计数;库存监控页面只读取最近成功快照,避免每次打开或刷新库存页面都扫描源库大表。 +- 源端查询通过既有 `JianSun_Old` 链接,对主表和淘系表按最多 100 个商品编码执行聚合;每批超时后最多重试 3 次并重建连接,每完成 10 批写入一次断点,重复执行不会从头扫描或重复累计。 +- 铺货计数快照 24 小时后标记为过期,但源库暂不可用时继续展示最近成功快照,不阻断库存主表。 +- 铺货快照默认每天 06:30(Asia/Shanghai)自动同步一次;同步成功后立即重建库存监控快照,页面无需人工点击刷新才能看到当天铺货数量。 +- 每日任务写入新的库存快照版本标记;正在运行的服务进程会在下一次页面请求时自动加载新快照,无需重启应用。 +- 每日任务失败时不覆盖上一份可用库存快照,保留铺货断点和最近成功数据;修复源库或网络故障后可重新执行并从断点续跑。 +- “各中心铺货”先展示利润中心汇总数量,点击利润中心行可展开或收起该中心下的店铺,店铺行展示店铺名称、店铺ID和各自铺货记录数。 + +铺货计数快照更新命令: + +```bash +npm run sync:inventory-monitoring-distribution -- --apply --confirm=sync-inventory-monitoring-distribution +``` + +铺货与库存快照联合每日更新: + +```bash +bash scripts/run-inventory-monitoring-daily.sh +``` + +安装每日本地定时器: + +```bash +bash scripts/install-inventory-monitoring-daily-timer.sh +``` + +默认每天 06:30(Asia/Shanghai)执行。macOS 使用 launchd,日志位于 `~/Library/Logs/furniture3d-inventory-monitoring-daily.log`;Linux 使用 systemd timer,日志进入 journal。可通过 `INVENTORY_MONITORING_SCHEDULE_HOUR` 和 `INVENTORY_MONITORING_SCHEDULE_MINUTE` 调整执行时间。 + +## 基础功能 + +- 筛选栏参考清货管理:按启用的筛选标签多选值,支持单个或批量粘贴编码;已选条件以标签展示并可单独清除。 +- 筛选字段包括生产状态、供应商、采购、运营负责人、部门负责人、利润中心、是否新品、SABC、款式编码、货号、商品编码、动销、滞销和预警。 +- 显示设置参考清货管理:支持紧凑展示、列设置和筛选设置;列顺序、显示状态、紧凑模式和筛选字段按当前登录用户在浏览器保存。 +- 表头支持冻结列选择:冻结某一列后,该列及左侧所有可见列在横向滚动时保持固定;表头在纵向滚动时固定,冻结设置按当前用户保存。 +- 表头点击可切换升序/降序;当前排序列旁的下三角表示降序,点击后切换为上三角表示的升序,悬停表头会显示具体排序说明。 +- “是否动销”“是否滞销”列头分别显示口径说明图标,悬停或键盘聚焦时以黑色浮层提示“是否动销:销量维度”“是否滞销:库存维度”。 +- 排序:全部主表列支持升序、降序。 +- 分页:50、100、200 条。 +- 刷新:人工点击后才读取已保存配置并重新计算动销、滞销和预警状态,同时后台更新持久化快照;刷新期间保留上一版可见数据。 +- 库存监控快照缓存有效期 6 小时;筛选、排序和分页直接查询已有快照,不轮询或等待快照重建,“库存总览”页签也不再额外请求库存监控明细接口。 +- 已有数据后的筛选查询不再进入全屏“生成快照”状态,继续保留当前表格并直接替换查询结果。 +- 页面接口遇到短暂网络断开或 5xx 时自动重试;最终失败时保留当前表格,显示中文重试提示,不直接暴露 `Failed to fetch`。 +- 导出:首个“各仓库存明细”工作表按商品一行展开宽表,列顺序为商品信息、全部仓库公有可用数、简尚库存/货值及销售指标、滞销汇总、全部仓库滞销库存;不导出实体仓“总库存”字段,总货值严格按成本 × 简尚库存计算。 +- 实体仓列取该仓公有可用数;运营云仓列取 `order_able_qty` 可下单量,用于与页面云仓占用保持同一口径。 +- 导出仅保留“各仓库存明细”“库存监控”“计算配置”工作表,不生成纵向“各仓库存”子表,也不生成“滞销计算”工作表。 +- “各仓库存明细”逐商品列实体仓和运营云仓的库存、订单占用、云仓占用、公有可用数、30天/备货天数/渠道90天及当前模式滞销库存。 +- 分销/外贸实体仓的90天渠道滞销库存同时计入该仓当前模式滞销库存,保证所有仓库滞销库存逐行合计等于库存监控的当前模式滞销库存。 + +## 库存总览 + +- 数据源直接复用库存监控当前生效配置下的明细行,不重复读取库存、档案或铺货源表。 +- 库存总览不再重复展示六张关键指标卡,直接进入多维分析和维度表格。 +- 支持生产状态、动销、滞销、利润中心、仓库、采购、供应商、类目、重点滞销编码九个分析维度;维度切换和表格排序均复用当前快照,不重新扫描源库。 +- 每个维度统一展示商品数、库存、货值、滞销库存、滞销货值、滞销率、预警数和铺货数量,并用进度条和高滞销风险配色突出异常分组。 +- 仓库维度按各仓公有可用数汇总,库存货值和滞销货值按“商品成本 × 对应仓库数量”计算;该维度不展示铺货数量,避免无法归属的铺货记录被重复分摊。 +- 重点滞销编码按当前滞销库存降序展示前 100 个商品编码,并展示商品名称、库存、货值和滞销状态。 +- 商品维度同时展示商品图片、运营负责人、部门负责人和利润中心,不展示“商品数”列,便于直接判断重点滞销商品的负责人和归属。 +- “生产状态 + 是否滞销”联合汇总继续保留在接口兼容字段中;新版页面默认展示生产状态维度。 +- 全部商品汇总指标只在“库存总览”页签展示;库存监控页签保留筛选和商品明细,不再重复展示同一组汇总卡片。 +- 按钮“更新汇总”只重新读取库存监控当前快照,不触发源库重算。 +- 库存总览在主库存数据加载完成后后台预取并复用组件状态,切换到“库存总览”时直接展示已加载结果;接口允许浏览器私有缓存30秒,“更新汇总”按钮会绕过缓存重新读取。 + +## 分销外贸库存监控 + +- 页面入口位于库存监控页的“库存总览”右侧,页面内分为“外贸库存、分销库存、山东外贸库存”三个子页。 +- 数据直接复用库存监控当前快照,不额外扫描聚水潭库存源;商品字段与库存监控保持一致,包含图片、款式编码、货号、商品编码、生产状态、供应商、采购、创建时间、简尚库存、最近入库时间、最近入库天数、是否滞销、外贸反馈出货时间、运营文本反馈和滞销预警。 +- 外贸库存纳入仓库名称含“外贸”的实体仓,以及云仓名称含“外贸”的运营云仓;当前包含简尚-新外贸仓、简尚-济南外贸仓和渠道-外贸部线下云仓。 +- 分销库存纳入仓库名称含“分销”的实体专用仓,以及云仓名称含“分销”的运营云仓;当前包含 3 个分销部专用仓和渠道-分销部线下云仓。 +- 山东外贸库存只纳入“简尚-济南外贸仓”的实体库存。 +- 实体仓库存按 `qty - order_lock` 计算;云仓库存按 `order_able_qty` 计算。若云仓实际所在仓已经被当前分类纳入,则云仓数量不再重复加入。 +- 同一商品跨多个纳入仓时汇总库存;最近入库时间取所有纳入实体仓及云仓实际仓采购入库时间中的最新值,云仓缺少关联实际仓采购记录时才回退云仓库存更新时间。 +- 分销、外贸页面统一按最近入库时间计算:未满80天为正常且非滞销;满80天但未满90天为预警且非滞销;满90天为预警且滞销;没有可用入库时间显示“待确认”,不推断业务状态。 +- “外贸反馈出货时间”按商品编码保存,外贸库存和山东外贸库存共用同一个反馈时间;分销库存只展示,不提供编辑。 +- 库存监控主页面和主表导出对内部员工默认开放可见、可下载;库存监控配置编辑仍需单独权限。 +- 分销库存仅分销部、经管和管理员可查看、编辑;外贸库存仅外贸部、经管和管理员可查看、编辑;山东外贸库存仅供应链中心、经管和管理员可查看、编辑。 +- 三个子页的数据权限在接口层按当前用户部门路径过滤,未授权子页不会返回对应库存明细,不只是在前端隐藏页签。 +- “运营文本反馈”按商品编码保存,三个子页面共用;用户只能在有权访问的分类内编辑该分类的反馈。外贸反馈出货时间同样受分类查看/编辑权限约束。 +- 每个子页表格底部固定展示当前分类合计:商品数、简尚库存合计、滞销商品数和预警商品数;切换子页时合计随之更新。 +- 三个子页签下方展示联动汇总卡片:商品记录数、简尚库存、滞销商品数、滞销库存、滞销货值和预警商品数;切换外贸、分销或山东外贸子页时,卡片按当前子页数据重新计算。 +- “滞销商品数”按商品编码计数,与底部合计行中的滞销数量口径一致;滞销库存和滞销货值只统计最近入库满90天的滞销商品。 +- 分销外贸数据在进入库存监控页面后后台预取,切换到该页签时直接复用已加载数据;接口允许浏览器私有缓存30秒,页签内“刷新”按钮可主动重新读取最新快照。 +- 当前最近成功快照(2026-11-25 09:59:35,Asia/Shanghai)共有外贸商品 120 个、分销商品 387 个、山东外贸商品 8 个。 + +## 当前数据源状态 + +2026-11-21 11:10:42(Asia/Shanghai)本地最近成功快照: + +- 参与计算商品:7,125 条;已配置标准仓库的实际库存合计 587,000 件,未配置库容的实际仓库存 15,350 件。 +- 附件标准库位共 17,462 个,按最佳摆放方向估算占用 23,735 个库位,整体估算利用率 135.9%。 +- 爆仓仓库 7 个:简尚-崔桥工厂仓 132.9%、简尚-崔桥工厂半成品包装项目仓 165.4%、简尚-横林二仓 157.9%、简尚-山东青岗集仓 107.6%、简尚-山东品牌仓 235.9%、简尚-河南洛宁仓 172.1%、简尚-睢宁仓 219.0%。 +- 简尚-新外贸仓利用率 19.4%,状态正常;简尚-新苏北仓利用率 90.1%,状态临界。 +- 尺寸缺失库存 2,855 件;尺寸过大、无法放入标准库位的库存 56,513 件。两部分库存均已计入实际库存,但未计入库位占用。 +- 未配置库容的实际仓:简尚-分销部专用仓 5,347 件、三方-南昌樵舍仓 3,571 件、简尚-横林三仓 3,490 件、简尚-江西仓送货 2,457 件、常州简尚家居有限公司 485 件。以上仓库暂不参与爆仓判断,等待业务确认标准仓库归属。 + +上一版快照 2026-11-20 16:47:09(Asia/Shanghai): + +- 参与计算商品:7,110 条,其中 5,709 个商品有产品档案图片。 +- 简尚库存合计:590,898;当前 30 天模式滞销库存合计:461,989。 +- 营销日销源最新批次为 2026-11-20;7,110 个在库商品中 4,516 个匹配到大于 0 的含大单日销,其余按 0 参与计算。 +- 铺货数量已改为 `rpt.jst_skumap` 与 `rpt.jst_skumap_qmcust_add` 当前可见记录的逐条计数快照,不依赖当前开发库尚未建立的 `SupplyChainDistributionListing` 表。 +- 本次双表同步匹配 1,514,211 条当前可见记录:主表 1,020,012 条、淘系表 494,199 条;其中 1,512,963 条成功映射到利润中心,形成 404,603 个“商品编码 + 店铺 + 利润中心”组合。 +- 铺货快照只保留 `enabled=1` 的当前记录;与聚水潭前端查询同一商品时,铺货记录条数应一致。 +- 已核对 `SJ038021N1410V02`:主表与淘系表合并后共 529 条,其中运营中心A 311、运营中心G 196、分销部 15、运营中心C 4、运营中心B 3。 +- 已核对 `SJ038025N1410V01`:主表与淘系表合并后共 78 条,其中运营中心A 66、分销部 5、运营中心C 3、外贸部 2、运营中心B 1、运营中心G 1。 +- 推送、反馈、审核属于第二阶段,本基础版未实现。 diff --git a/furniture-3d-system/next.config.js b/furniture-3d-system/next.config.js index b56e81e0..3d39774c 100644 --- a/furniture-3d-system/next.config.js +++ b/furniture-3d-system/next.config.js @@ -400,6 +400,15 @@ const nextConfig = { source: '/(.*)', headers: baseSecurityHeaders, }, + { + source: '/supplier-quote/:path*', + headers: [ + { + key: 'Permissions-Policy', + value: 'camera=(), microphone=(self), geolocation=(), payment=(), usb=(), serial=(), bluetooth=()' + } + ], + }, { // 市场选款看板静态页需要被本平台宿主页同源 iframe 嵌入: // 覆盖基础安全头的 X-Frame-Options DENY / frame-ancestors 'none',仅此路径生效。 diff --git a/furniture-3d-system/package.json b/furniture-3d-system/package.json index df90e1d0..d1bf7b56 100644 --- a/furniture-3d-system/package.json +++ b/furniture-3d-system/package.json @@ -3,6 +3,9 @@ "version": "0.1.0", "private": true, "scripts": { + "snapshot:daily-express": "node scripts/daily-express-dashboard/run.mjs", + "verify:daily-express": "node --test scripts/daily-express-dashboard/*.test.mjs", + "verify:daily-express:snapshot": "tsx scripts/verify-daily-express-snapshot.ts", "worker:ai-image": "node scripts/run-ai-image-worker.mjs", "predev": "npm run prisma:check-client-sync", "dev": "next dev --webpack", @@ -26,8 +29,14 @@ "sync:supply-chain-product-archive": "tsx scripts/sync-supply-chain-product-archive.ts", "sync:supply-chain-product-archive-daily": "tsx scripts/sync-supply-chain-product-archive-sales-performance-daily.ts", "generate:modular-processing-daily-snapshot": "tsx scripts/generate-modular-processing-daily-snapshot.ts", + "sync:pickup-24h-timeliness": "tsx scripts/sync-pickup-24h-timeliness.ts", + "recompute:pickup-24h-timeliness": "tsx scripts/recompute-pickup-24h-timeliness.ts", + "backfill:pickup-24h-order-fields": "tsx scripts/backfill-pickup-24h-order-fields.ts", "sync:supply-chain-product-archive-enrichment": "tsx scripts/sync-supply-chain-product-archive-enrichment.ts", "sync:distribution-listings": "tsx scripts/sync-distribution-listings.ts", + "sync:inventory-monitoring-distribution": "tsx scripts/sync-inventory-monitoring-distribution.ts", + "inventory-monitoring:daily": "tsx scripts/run-inventory-monitoring-daily.ts", + "install:inventory-monitoring-daily": "bash scripts/install-inventory-monitoring-daily-timer.sh", "backfill:product-archive-designer": "tsx scripts/backfill-product-archive-designer-from-jst-sku-info-manage.ts", "backfill:product-archive-designer:apply": "tsx scripts/backfill-product-archive-designer-from-jst-sku-info-manage.ts --apply", "backfill:product-archive-opshead": "tsx scripts/backfill-product-archive-opshead-from-jst-sku-info-manage.ts --mode=regular", diff --git a/furniture-3d-system/prisma/migrations/20261006120000_add_pickup_24h_timeliness/migration.sql b/furniture-3d-system/prisma/migrations/20261006120000_add_pickup_24h_timeliness/migration.sql new file mode 100644 index 00000000..e047d72d --- /dev/null +++ b/furniture-3d-system/prisma/migrations/20261006120000_add_pickup_24h_timeliness/migration.sql @@ -0,0 +1,74 @@ +-- 24h 揽收及时率自动化的批次与考核明细(纯新增表,不改动既有表)。 +CREATE TABLE "Pickup24hTimelinessRun" ( + "id" TEXT NOT NULL, + "paymentDate" DATE NOT NULL, + "status" TEXT NOT NULL DEFAULT 'RUNNING', + "rowCount" INTEGER NOT NULL DEFAULT 0, + "includedCount" INTEGER NOT NULL DEFAULT 0, + "overdueCount" INTEGER NOT NULL DEFAULT 0, + "message" TEXT NOT NULL DEFAULT '', + "startedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "finishedAt" TIMESTAMP(3), + + CONSTRAINT "Pickup24hTimelinessRun_pkey" PRIMARY KEY ("id") +); + +CREATE UNIQUE INDEX "Pickup24hTimelinessRun_paymentDate_key" ON "Pickup24hTimelinessRun"("paymentDate"); + +CREATE INDEX "Pickup24hTimelinessRun_status_payment_date_idx" ON "Pickup24hTimelinessRun"("status", "paymentDate"); + +CREATE TABLE "Pickup24hTimelinessOrder" ( + "id" TEXT NOT NULL, + "paymentDate" DATE NOT NULL, + "rowKey" TEXT NOT NULL, + "included" BOOLEAN NOT NULL DEFAULT true, + "excludeReason" TEXT NOT NULL DEFAULT '', + "overdue" BOOLEAN NOT NULL DEFAULT false, + "assessmentCount" DOUBLE PRECISION NOT NULL DEFAULT 0, + "purchaseAssessmentCount" DOUBLE PRECISION NOT NULL DEFAULT 0, + "bulkQuantity" INTEGER NOT NULL DEFAULT 0, + "tradeKey" TEXT NOT NULL DEFAULT '', + "productAttribute" TEXT NOT NULL DEFAULT '', + "afterSaleApplyTime" TEXT, + "fetchTime" TEXT, + "sendTime" TEXT, + "paymentTime" TEXT, + "afterSaleToPaymentHours" DOUBLE PRECISION, + "fetchToPaymentHours" DOUBLE PRECISION, + "sendToPaymentHours" DOUBLE PRECISION, + "purchaser" TEXT NOT NULL DEFAULT '', + "category" TEXT NOT NULL DEFAULT '', + "spu" TEXT NOT NULL DEFAULT '', + "skuCode" TEXT NOT NULL DEFAULT '', + "productName" TEXT NOT NULL DEFAULT '', + "productionStatus" TEXT NOT NULL DEFAULT '', + "supplier" TEXT NOT NULL DEFAULT '', + "quantity" INTEGER NOT NULL DEFAULT 0, + "orderType" TEXT NOT NULL DEFAULT '', + "exceptionType" TEXT NOT NULL DEFAULT '', + "status" TEXT NOT NULL DEFAULT '', + "innerOrderId" TEXT NOT NULL DEFAULT '', + "onlineOrderId" TEXT NOT NULL DEFAULT '', + "expressCompany" TEXT NOT NULL DEFAULT '', + "expressNo" TEXT NOT NULL DEFAULT '', + "warehouseName" TEXT NOT NULL DEFAULT '', + "refundStatus" TEXT NOT NULL DEFAULT '', + "shopSite" TEXT NOT NULL DEFAULT '', + "outerTradeNo" TEXT NOT NULL DEFAULT '', + "factoryShipNo" TEXT NOT NULL DEFAULT '', + "orderRemark" TEXT NOT NULL DEFAULT '', + "buyerMessage" TEXT NOT NULL DEFAULT '', + "sellerFlag" TEXT NOT NULL DEFAULT '', + "labels" TEXT NOT NULL DEFAULT '', + "province" TEXT NOT NULL DEFAULT '', + "shopName" TEXT NOT NULL DEFAULT '', + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "Pickup24hTimelinessOrder_pkey" PRIMARY KEY ("id") +); + +CREATE UNIQUE INDEX "Pickup24hTimelinessOrder_payment_date_row_key_key" ON "Pickup24hTimelinessOrder"("paymentDate", "rowKey"); + +CREATE INDEX "Pickup24hTimelinessOrder_date_included_overdue_idx" ON "Pickup24hTimelinessOrder"("paymentDate", "included", "overdue"); + +CREATE INDEX "Pickup24hTimelinessOrder_date_inner_order_idx" ON "Pickup24hTimelinessOrder"("paymentDate", "innerOrderId"); diff --git a/furniture-3d-system/prisma/migrations/20261125180000_add_modular_processing_component_snapshot/migration.sql b/furniture-3d-system/prisma/migrations/20261125180000_add_modular_processing_component_snapshot/migration.sql new file mode 100644 index 00000000..b5eaaba0 --- /dev/null +++ b/furniture-3d-system/prisma/migrations/20261125180000_add_modular_processing_component_snapshot/migration.sql @@ -0,0 +1,28 @@ +-- Freeze component-level stock, demand and BOM results together with each +-- modular processing main-table batch. +CREATE TABLE "ModularProcessingComponentBatchSnapshot" ( + "id" TEXT NOT NULL, + "snapshotDate" TEXT NOT NULL, + "batchKey" TEXT NOT NULL, + "generationSlot" TEXT NOT NULL, + "parentBarcode" TEXT NOT NULL, + "componentBarcode" TEXT NOT NULL DEFAULT '', + "recordKey" TEXT NOT NULL, + "rowJson" JSONB NOT NULL, + "generatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "ModularProcessingComponentBatchSnapshot_pkey" PRIMARY KEY ("id") +); + +CREATE UNIQUE INDEX "ModularProcessingComponentBatchSnapshot_batchKey_recordKey_key" + ON "ModularProcessingComponentBatchSnapshot"("batchKey", "recordKey"); + +CREATE INDEX "ModularProcessingComponentBatchSnapshot_batch_parent_idx" + ON "ModularProcessingComponentBatchSnapshot"("batchKey", "parentBarcode"); + +CREATE INDEX "ModularProcessingComponentSnapshot_date_slot_generatedAt_idx" + ON "ModularProcessingComponentBatchSnapshot"("snapshotDate", "generationSlot", "generatedAt"); + +CREATE INDEX "ModularProcessingComponentBatchSnapshot_component_idx" + ON "ModularProcessingComponentBatchSnapshot"("componentBarcode"); diff --git a/furniture-3d-system/prisma/migrations/20261126110000_add_clearance_task_daily_inventory/migration.sql b/furniture-3d-system/prisma/migrations/20261126110000_add_clearance_task_daily_inventory/migration.sql new file mode 100644 index 00000000..a7972452 --- /dev/null +++ b/furniture-3d-system/prisma/migrations/20261126110000_add_clearance_task_daily_inventory/migration.sql @@ -0,0 +1,8 @@ +ALTER TABLE "SupplyChainClearanceTask" + ADD COLUMN "inventoryStockJianshang" INTEGER, + ADD COLUMN "inventoryStockFactory" INTEGER, + ADD COLUMN "inventoryTotalStock" INTEGER, + ADD COLUMN "inventoryDailySales" DECIMAL(18, 4), + ADD COLUMN "inventoryAvailableDays" TEXT NOT NULL DEFAULT '', + ADD COLUMN "inventoryBreakdown" JSONB, + ADD COLUMN "inventoryUpdatedAt" TIMESTAMP(3); diff --git a/furniture-3d-system/prisma/migrations/20261126113000_expand_clearance_task_unique_key_with_owner/migration.sql b/furniture-3d-system/prisma/migrations/20261126113000_expand_clearance_task_unique_key_with_owner/migration.sql new file mode 100644 index 00000000..6aa193bb --- /dev/null +++ b/furniture-3d-system/prisma/migrations/20261126113000_expand_clearance_task_unique_key_with_owner/migration.sql @@ -0,0 +1,11 @@ +DROP INDEX IF EXISTS "SCClearanceTask_period_round_barcode_center_applicant_key"; + +CREATE UNIQUE INDEX "SCClearanceTask_period_round_barcode_center_applicant_owner_key" + ON "SupplyChainClearanceTask"( + "periodKey", + "round", + "barcode", + "profitCenter", + "submittedById", + "ownerName" + ); diff --git a/furniture-3d-system/prisma/migrations/20261126150000_add_pickup24h_supplier_feedback/migration.sql b/furniture-3d-system/prisma/migrations/20261126150000_add_pickup24h_supplier_feedback/migration.sql new file mode 100644 index 00000000..6193c8c6 --- /dev/null +++ b/furniture-3d-system/prisma/migrations/20261126150000_add_pickup24h_supplier_feedback/migration.sql @@ -0,0 +1,21 @@ +CREATE TABLE "Pickup24hTimelinessSupplierFeedback" ( + "id" TEXT NOT NULL, + "feedbackDate" DATE NOT NULL, + "purchaser" TEXT NOT NULL DEFAULT '', + "supplier" TEXT NOT NULL, + "reason" TEXT NOT NULL DEFAULT '', + "solution" TEXT NOT NULL DEFAULT '', + "expectedResolutionDate" DATE, + "createdBy" TEXT NOT NULL DEFAULT '', + "updatedBy" TEXT NOT NULL DEFAULT '', + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "Pickup24hTimelinessSupplierFeedback_pkey" PRIMARY KEY ("id") +); + +CREATE UNIQUE INDEX "Pickup24hTimelinessSupplierFeedback_date_purchaser_supplier_key" +ON "Pickup24hTimelinessSupplierFeedback"("feedbackDate", "purchaser", "supplier"); + +CREATE INDEX "Pickup24hTimelinessSupplierFeedback_supplier_date_idx" +ON "Pickup24hTimelinessSupplierFeedback"("supplier", "feedbackDate"); diff --git a/furniture-3d-system/prisma/migrations/20261126153000_add_purchase_inbound_delivery_fact/migration.sql b/furniture-3d-system/prisma/migrations/20261126153000_add_purchase_inbound_delivery_fact/migration.sql new file mode 100644 index 00000000..81e374d7 --- /dev/null +++ b/furniture-3d-system/prisma/migrations/20261126153000_add_purchase_inbound_delivery_fact/migration.sql @@ -0,0 +1,26 @@ +CREATE TABLE "PurchaseInboundDeliveryFact" ( + "id" TEXT NOT NULL, + "inboundDate" DATE NOT NULL, + "seller" TEXT NOT NULL DEFAULT '', + "purchaserName" TEXT NOT NULL DEFAULT '', + "skuId" TEXT NOT NULL DEFAULT '', + "itemCount" INTEGER NOT NULL DEFAULT 0, + "inboundQuantity" DECIMAL(18, 4) NOT NULL DEFAULT 0, + "cycleMinutes" BIGINT NOT NULL DEFAULT 0, + "sameDayItemCount" INTEGER NOT NULL DEFAULT 0, + "maxCycleDays" INTEGER NOT NULL DEFAULT 0, + "sourceUpdatedAt" TIMESTAMP(3), + "syncedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + CONSTRAINT "PurchaseInboundDeliveryFact_pkey" PRIMARY KEY ("id") +); + +CREATE UNIQUE INDEX "PurchaseInboundDeliveryFact_inboundDate_seller_purchaserName_skuId_key" + ON "PurchaseInboundDeliveryFact"("inboundDate", "seller", "purchaserName", "skuId"); +CREATE INDEX "PurchaseInboundDeliveryFact_inboundDate_idx" + ON "PurchaseInboundDeliveryFact"("inboundDate"); +CREATE INDEX "PurchaseInboundDeliveryFact_seller_idx" + ON "PurchaseInboundDeliveryFact"("seller"); +CREATE INDEX "PurchaseInboundDeliveryFact_skuId_idx" + ON "PurchaseInboundDeliveryFact"("skuId"); diff --git a/furniture-3d-system/prisma/migrations/20261126160000_add_platform_bill_config_transaction_type/migration.sql b/furniture-3d-system/prisma/migrations/20261126160000_add_platform_bill_config_transaction_type/migration.sql new file mode 100644 index 00000000..dfaefbf9 --- /dev/null +++ b/furniture-3d-system/prisma/migrations/20261126160000_add_platform_bill_config_transaction_type/migration.sql @@ -0,0 +1,5 @@ +ALTER TABLE "SupplyChainPlatformBillConfig" + ADD COLUMN "transactionType" VARCHAR(200) NOT NULL DEFAULT ''; + +CREATE INDEX "SCPlatformBillConfig_bill_item_transaction_idx" + ON "SupplyChainPlatformBillConfig"("billKey", "billItem", "transactionType"); diff --git a/furniture-3d-system/prisma/migrations/20261126173000_add_purchase_inbound_delivery_item_fact/migration.sql b/furniture-3d-system/prisma/migrations/20261126173000_add_purchase_inbound_delivery_item_fact/migration.sql new file mode 100644 index 00000000..dcb46990 --- /dev/null +++ b/furniture-3d-system/prisma/migrations/20261126173000_add_purchase_inbound_delivery_item_fact/migration.sql @@ -0,0 +1,31 @@ +CREATE TABLE "PurchaseInboundDeliveryItemFact" ( + "id" TEXT NOT NULL, + "sourceItemId" INTEGER NOT NULL, + "poId" INTEGER NOT NULL, + "poDate" TIMESTAMP(3) NOT NULL, + "confirmDate" TIMESTAMP(3), + "finishTime" TIMESTAMP(3) NOT NULL, + "deliveryDate" TIMESTAMP(3), + "seller" TEXT NOT NULL DEFAULT '', + "purchaserName" TEXT NOT NULL DEFAULT '', + "skuId" TEXT NOT NULL DEFAULT '', + "itemName" TEXT NOT NULL DEFAULT '', + "inboundQuantity" DECIMAL(18, 4) NOT NULL DEFAULT 0, + "cycleMinutes" BIGINT NOT NULL DEFAULT 0, + "sourceUpdatedAt" TIMESTAMP(3), + "syncedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + CONSTRAINT "PurchaseInboundDeliveryItemFact_pkey" PRIMARY KEY ("id") +); + +CREATE UNIQUE INDEX "PurchaseInboundDeliveryItemFact_sourceItemId_key" + ON "PurchaseInboundDeliveryItemFact"("sourceItemId"); +CREATE INDEX "PurchaseInboundDeliveryItemFact_poDate_idx" + ON "PurchaseInboundDeliveryItemFact"("poDate"); +CREATE INDEX "PurchaseInboundDeliveryItemFact_finishTime_idx" + ON "PurchaseInboundDeliveryItemFact"("finishTime"); +CREATE INDEX "PurchaseInboundDeliveryItemFact_seller_idx" + ON "PurchaseInboundDeliveryItemFact"("seller"); +CREATE INDEX "PurchaseInboundDeliveryItemFact_skuId_idx" + ON "PurchaseInboundDeliveryItemFact"("skuId"); diff --git a/furniture-3d-system/prisma/migrations/20261126180000_add_purchase_inbound_item_dimensions/migration.sql b/furniture-3d-system/prisma/migrations/20261126180000_add_purchase_inbound_item_dimensions/migration.sql new file mode 100644 index 00000000..ec6b58c8 --- /dev/null +++ b/furniture-3d-system/prisma/migrations/20261126180000_add_purchase_inbound_item_dimensions/migration.sql @@ -0,0 +1,4 @@ +ALTER TABLE "PurchaseInboundDeliveryItemFact" + ADD COLUMN "skuCategory" TEXT NOT NULL DEFAULT '', + ADD COLUMN "productCategory" TEXT NOT NULL DEFAULT '', + ADD COLUMN "material" TEXT NOT NULL DEFAULT ''; diff --git a/furniture-3d-system/prisma/migrations/20261126193000_supplier_quote_sheet/migration.sql b/furniture-3d-system/prisma/migrations/20261126193000_supplier_quote_sheet/migration.sql new file mode 100644 index 00000000..321504f8 --- /dev/null +++ b/furniture-3d-system/prisma/migrations/20261126193000_supplier_quote_sheet/migration.sql @@ -0,0 +1,24 @@ +CREATE TABLE "SupplierQuoteSheet" ( + "ownerId" TEXT NOT NULL, + "supplierName" TEXT NOT NULL DEFAULT '', + "address" TEXT NOT NULL DEFAULT '', + "phone" TEXT NOT NULL DEFAULT '', + "quoteDate" TEXT NOT NULL DEFAULT '', + "revision" INTEGER NOT NULL DEFAULT 1, + "updatedAt" TIMESTAMP(3) NOT NULL, + CONSTRAINT "SupplierQuoteSheet_pkey" PRIMARY KEY ("ownerId"), + CONSTRAINT "SupplierQuoteSheet_ownerId_fkey" FOREIGN KEY ("ownerId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE +); + +CREATE TABLE "SupplierQuoteLine" ( + "ownerId" TEXT NOT NULL, + "sequence" INTEGER NOT NULL, + "productName" TEXT NOT NULL, + "dimensions" TEXT NOT NULL, + "material" TEXT NOT NULL, + "untaxedPrice" DECIMAL(12,2), + "taxedPrice" DECIMAL(12,2), + "photoKey" TEXT, + CONSTRAINT "SupplierQuoteLine_pkey" PRIMARY KEY ("ownerId", "sequence"), + CONSTRAINT "SupplierQuoteLine_ownerId_fkey" FOREIGN KEY ("ownerId") REFERENCES "SupplierQuoteSheet"("ownerId") ON DELETE CASCADE ON UPDATE CASCADE +); diff --git a/furniture-3d-system/prisma/migrations/20261127113000_add_platform_bill_order_payment_cache/migration.sql b/furniture-3d-system/prisma/migrations/20261127113000_add_platform_bill_order_payment_cache/migration.sql new file mode 100644 index 00000000..7bd39372 --- /dev/null +++ b/furniture-3d-system/prisma/migrations/20261127113000_add_platform_bill_order_payment_cache/migration.sql @@ -0,0 +1,11 @@ +CREATE TABLE "SupplyChainPlatformBillOrderPayment" ( + "orderNo" VARCHAR(100) NOT NULL, + "paymentPeriod" VARCHAR(6) NOT NULL DEFAULT '', + "resolvedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "expiresAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "SupplyChainPlatformBillOrderPayment_pkey" PRIMARY KEY ("orderNo") +); + +CREATE INDEX "SCPlatformBillOrderPayment_expires_idx" + ON "SupplyChainPlatformBillOrderPayment"("expiresAt"); diff --git a/furniture-3d-system/prisma/migrations/20261127140000_add_platform_bill_remark_notification/migration.sql b/furniture-3d-system/prisma/migrations/20261127140000_add_platform_bill_remark_notification/migration.sql new file mode 100644 index 00000000..1a956a54 --- /dev/null +++ b/furniture-3d-system/prisma/migrations/20261127140000_add_platform_bill_remark_notification/migration.sql @@ -0,0 +1,22 @@ +CREATE TABLE "SupplyChainPlatformBillRemarkNotification" ( + "eventKey" VARCHAR(64) NOT NULL, + "periodKey" VARCHAR(7) NOT NULL, + "billKey" VARCHAR(64) NOT NULL, + "kind" VARCHAR(64) NOT NULL, + "status" VARCHAR(32) NOT NULL, + "rowCount" INTEGER NOT NULL DEFAULT 0, + "recipient" VARCHAR(100) NOT NULL DEFAULT '', + "channel" VARCHAR(32) NOT NULL DEFAULT '', + "message" TEXT NOT NULL DEFAULT '', + "sentAt" TIMESTAMP(3), + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "SupplyChainPlatformBillRemarkNotification_pkey" PRIMARY KEY ("eventKey") +); + +CREATE INDEX "SCPlatformBillRemarkNotice_bill_period_kind_idx" + ON "SupplyChainPlatformBillRemarkNotification"("billKey", "periodKey", "kind"); + +CREATE INDEX "SCPlatformBillRemarkNotice_status_updated_idx" + ON "SupplyChainPlatformBillRemarkNotification"("status", "updatedAt"); diff --git a/furniture-3d-system/prisma/schema.prisma b/furniture-3d-system/prisma/schema.prisma index 503b2610..a6e1862c 100644 --- a/furniture-3d-system/prisma/schema.prisma +++ b/furniture-3d-system/prisma/schema.prisma @@ -222,6 +222,57 @@ model FinishedProductDeliveryRecord { @@index([itemId, createdAt]) } +/// 聚水潭采购入库单的本地日聚合快照,用于交期履约总览快速查询。 +model PurchaseInboundDeliveryFact { + id String @id @default(cuid()) + inboundDate DateTime @db.Date + seller String @default("") + purchaserName String @default("") + skuId String @default("") + itemCount Int @default(0) + inboundQuantity Decimal @default(0) @db.Decimal(18, 4) + cycleMinutes BigInt @default(0) + sameDayItemCount Int @default(0) + maxCycleDays Int @default(0) + sourceUpdatedAt DateTime? + syncedAt DateTime @default(now()) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + @@unique([inboundDate, seller, purchaserName, skuId]) + @@index([inboundDate]) + @@index([seller]) + @@index([skuId]) +} + +model PurchaseInboundDeliveryItemFact { + id String @id @default(cuid()) + sourceItemId Int @unique + poId Int + poDate DateTime + confirmDate DateTime? + finishTime DateTime + deliveryDate DateTime? + seller String @default("") + purchaserName String @default("") + skuId String @default("") + itemName String @default("") + skuCategory String @default("") + productCategory String @default("") + material String @default("") + inboundQuantity Decimal @default(0) @db.Decimal(18, 4) + cycleMinutes BigInt @default(0) + sourceUpdatedAt DateTime? + syncedAt DateTime @default(now()) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + @@index([poDate]) + @@index([finishTime]) + @@index([seller]) + @@index([skuId]) +} + model SupplierRecommendedProduct { id String @id @default(cuid()) recommendationDate DateTime? @db.Date @@ -1233,6 +1284,28 @@ model ModularProcessingOrderDailySnapshot { @@map("ModularProcessingBatchSnapshot") } +/// 模块化商品加工主表部件批次快照:冻结生成时的 BOM、库存、需求和判定结果。 +model ModularProcessingComponentDailySnapshot { + id String @id @default(cuid()) + snapshotDate String + /// 日期+时段批次键,例如 2026-11-25:09:00 + batchKey String + /// 北京时间生成时段:09:00 / 15:00 + generationSlot String + parentBarcode String + componentBarcode String @default("") + recordKey String + rowJson Json + generatedAt DateTime @default(now()) + createdAt DateTime @default(now()) + + @@unique([batchKey, recordKey]) + @@index([batchKey, parentBarcode], map: "ModularProcessingComponentBatchSnapshot_batch_parent_idx") + @@index([snapshotDate, generationSlot, generatedAt], map: "ModularProcessingComponentSnapshot_date_slot_generatedAt_idx") + @@index([componentBarcode], map: "ModularProcessingComponentBatchSnapshot_component_idx") + @@map("ModularProcessingComponentBatchSnapshot") +} + /// 模块化商品加工单每日生成运行状态:记录定时生成、人工刷新、失败原因和通知结果。 model ModularProcessingGenerationRun { id String @id @default(cuid()) @@ -4207,6 +4280,8 @@ model User { // 状态 status UserStatus @default(PENDING) + supplierQuoteSheet SupplierQuoteSheet? + // 关联 createdProducts Product[] @relation("ProductCreator") intakePhotoUploadGrants IntakeProductPhotoUploadGrant[] @relation("IntakePhotoUploadRecipient") @@ -5677,6 +5752,32 @@ model Hole { // 系统配置(通用键值存储) // ============================================ +model SupplierQuoteSheet { + ownerId String @id + supplierName String @default("") + address String @default("") + phone String @default("") + quoteDate String @default("") + revision Int @default(1) + updatedAt DateTime @updatedAt + owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade) + lines SupplierQuoteLine[] +} + +model SupplierQuoteLine { + ownerId String + sequence Int + productName String + dimensions String + material String + untaxedPrice Decimal? @db.Decimal(12, 2) + taxedPrice Decimal? @db.Decimal(12, 2) + photoKey String? + sheet SupplierQuoteSheet @relation(fields: [ownerId], references: [ownerId], onDelete: Cascade) + + @@id([ownerId, sequence]) +} + model SystemConfig { key String @id value Json @@ -5974,6 +6075,93 @@ model LogisticsArrivalSigningDurationSnapshot { @@index([snapshotDate, signTime], map: "LogisticsArrivalSigningDurationSnapshot_cover_idx") } +/// 24h 揽收及时率的日批次。每日由 scripts/sync-pickup-24h-timeliness.ts 生成一批, +/// 付款日期取「今天 - 2 天」;读路径只认 status = COMPLETED 的批次。 +model Pickup24hTimelinessRun { + id String @id @default(cuid()) + paymentDate DateTime @unique @db.Date + status String @default("RUNNING") + rowCount Int @default(0) + includedCount Int @default(0) + overdueCount Int @default(0) + message String @default("") + startedAt DateTime @default(now()) + finishedAt DateTime? + + @@index([status, paymentDate], map: "Pickup24hTimelinessRun_status_payment_date_idx") +} + +/// 24h 揽收及时率的考核明细行(付款日期 + 内部订单号 + 线上订单号 + 商品编码唯一)。 +model Pickup24hTimelinessOrder { + id String @id @default(cuid()) + paymentDate DateTime @db.Date + rowKey String + included Boolean @default(true) + excludeReason String @default("") + overdue Boolean @default(false) + assessmentCount Float @default(0) + purchaseAssessmentCount Float @default(0) + bulkQuantity Int @default(0) + tradeKey String @default("") + productAttribute String @default("") + afterSaleApplyTime String? + fetchTime String? + sendTime String? + paymentTime String? + afterSaleToPaymentHours Float? + fetchToPaymentHours Float? + sendToPaymentHours Float? + purchaser String @default("") + category String @default("") + spu String @default("") + skuCode String @default("") + productName String @default("") + productionStatus String @default("") + supplier String @default("") + quantity Int @default(0) + orderType String @default("") + exceptionType String @default("") + status String @default("") + innerOrderId String @default("") + onlineOrderId String @default("") + expressCompany String @default("") + expressNo String @default("") + warehouseName String @default("") + refundStatus String @default("") + shopSite String @default("") + outerTradeNo String @default("") + factoryShipNo String @default("") + orderRemark String @default("") + buyerMessage String @default("") + sellerFlag String @default("") + labels String @default("") + province String @default("") + shopName String @default("") + createdAt DateTime @default(now()) + + @@unique([paymentDate, rowKey], map: "Pickup24hTimelinessOrder_payment_date_row_key_key") + @@index([paymentDate, included, overdue], map: "Pickup24hTimelinessOrder_date_included_overdue_idx") + @@index([paymentDate, innerOrderId], map: "Pickup24hTimelinessOrder_date_inner_order_idx") +} + +/// 供应商维度每日人工反馈。当天未填写时读取前一日记录自动带入。 +model Pickup24hTimelinessSupplierFeedback { + id String @id @default(cuid()) + feedbackDate DateTime @db.Date + purchaser String @default("") + supplier String + reason String @default("") + solution String @default("") + expectedResolutionDate DateTime? @db.Date + createdBy String @default("") + updatedBy String @default("") + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + @@unique([feedbackDate, purchaser, supplier], map: "Pickup24hTimelinessSupplierFeedback_date_purchaser_supplier_key") + @@index([supplier, feedbackDate], map: "Pickup24hTimelinessSupplierFeedback_supplier_date_idx") +} + /// 限价管理 · 破价订单审核:聚水潭订单实收与限价表比对后生成的破价单 model SupplyChainBreachOrder { id String @id @default(cuid()) @@ -6516,6 +6704,13 @@ model SupplyChainClearanceTask { reviewedAt DateTime? rejectReason String @default("") @db.Text priorityOverride String @default("") @db.VarChar(50) + inventoryStockJianshang Int? + inventoryStockFactory Int? + inventoryTotalStock Int? + inventoryDailySales Decimal? @db.Decimal(18, 4) + inventoryAvailableDays String @default("") + inventoryBreakdown Json? + inventoryUpdatedAt DateTime? clearedQty Int @default(0) lastProgressAt DateTime? revision Int @default(1) @@ -6524,7 +6719,7 @@ model SupplyChainClearanceTask { events SupplyChainClearanceTaskEvent[] shipmentDaily SupplyChainClearanceTaskShipmentDaily[] - @@unique([periodKey, round, barcode, profitCenter, submittedById], map: "SCClearanceTask_period_round_barcode_center_applicant_key") + @@unique([periodKey, round, barcode, profitCenter, submittedById, ownerName], map: "SCClearanceTask_period_round_barcode_center_applicant_owner_key") @@index([periodKey, status]) @@index([barcode]) @@index([profitCenter]) @@ -6800,12 +6995,23 @@ model SupplyChainPlatformBillRecord { @@index([values], type: Gin, map: "SCPlatformBillRecord_values_gin_idx") } +/// 平台账单订单付款月份缓存。销售/退款财务备注优先读取本地缓存,避免导出时反复扫描聚水潭大表。 +model SupplyChainPlatformBillOrderPayment { + orderNo String @id @db.VarChar(100) + paymentPeriod String @default("") @db.VarChar(6) + resolvedAt DateTime @default(now()) + expiresAt DateTime + + @@index([expiresAt], map: "SCPlatformBillOrderPayment_expires_idx") +} + /// 平台账单财务备注配置。关键字段同时包含平台和账单,确保不同平台互不覆盖。 model SupplyChainPlatformBillConfig { id String @id @default(cuid()) platformKey String @db.VarChar(32) billKey String @db.VarChar(64) billItem String @db.Text + transactionType String @default("") @db.VarChar(200) financialRemark String @db.Text calculateAmount Boolean @default(false) sourceFileName String @default("") @db.Text @@ -6817,6 +7023,7 @@ model SupplyChainPlatformBillConfig { @@index([platformKey, billKey, sortOrder], map: "SCPlatformBillConfig_platform_bill_sort_idx") @@index([billKey, billItem], map: "SCPlatformBillConfig_bill_item_idx") + @@index([billKey, billItem, transactionType], map: "SCPlatformBillConfig_bill_item_transaction_idx") } /// 京东消费订单:从京东流水中“账单项目/交易备注=消费订单”的明细生成。 @@ -6864,6 +7071,25 @@ model SupplyChainPlatformBillFieldOverride { @@index([platformKey, billKey, periodKey, fieldKey], map: "SCPlatformBillOverride_platform_bill_period_field_idx") } +/// 平台账单待人工填写提醒发送记录,按内容指纹去重。 +model SupplyChainPlatformBillRemarkNotification { + eventKey String @id @db.VarChar(64) + periodKey String @db.VarChar(7) + billKey String @db.VarChar(64) + kind String @db.VarChar(64) + status String @db.VarChar(32) + rowCount Int @default(0) + recipient String @default("") @db.VarChar(100) + channel String @default("") @db.VarChar(32) + message String @default("") @db.Text + sentAt DateTime? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + @@index([billKey, periodKey, kind], map: "SCPlatformBillRemarkNotice_bill_period_kind_idx") + @@index([status, updatedAt], map: "SCPlatformBillRemarkNotice_status_updated_idx") +} + /// 全局平台账单金额计算规则。财务备注相同则跨平台使用同一计算逻辑。 model SupplyChainPlatformBillAmountRule { id String @id @default(cuid()) diff --git a/furniture-3d-system/public/accessory-models/LJG-01.glb b/furniture-3d-system/public/accessory-models/LJG-01.glb new file mode 100644 index 00000000..33273a20 Binary files /dev/null and b/furniture-3d-system/public/accessory-models/LJG-01.glb differ diff --git a/furniture-3d-system/public/accessory-models/LJG-03.glb b/furniture-3d-system/public/accessory-models/LJG-03.glb new file mode 100644 index 00000000..9729b302 Binary files /dev/null and b/furniture-3d-system/public/accessory-models/LJG-03.glb differ diff --git a/furniture-3d-system/public/accessory-models/MLS-01.glb b/furniture-3d-system/public/accessory-models/MLS-01.glb new file mode 100644 index 00000000..10dcd3f7 Binary files /dev/null and b/furniture-3d-system/public/accessory-models/MLS-01.glb differ diff --git a/furniture-3d-system/public/accessory-models/PXL-01.glb b/furniture-3d-system/public/accessory-models/PXL-01.glb new file mode 100644 index 00000000..9c3ebe72 Binary files /dev/null and b/furniture-3d-system/public/accessory-models/PXL-01.glb differ diff --git a/furniture-3d-system/scripts/backfill-clearance-task-audit-snapshots.ts b/furniture-3d-system/scripts/backfill-clearance-task-audit-snapshots.ts index e0c098ca..99ef51ea 100644 --- a/furniture-3d-system/scripts/backfill-clearance-task-audit-snapshots.ts +++ b/furniture-3d-system/scripts/backfill-clearance-task-audit-snapshots.ts @@ -56,10 +56,13 @@ async function main() { ) const priorDiscountByKey = new Map() for (const row of priorDiscountRows) { - const key = `${row.barcode.trim().toUpperCase()}\u0000${row.profitCenter.trim()}` - if (priorDiscountByKey.has(key)) continue + const barcode = row.barcode.trim().toUpperCase() + const centerKey = `${barcode}\u0000${row.profitCenter.trim()}` + const barcodeKey = `${barcode}\u0000` const discount = numeric(row.discount) - if (discount != null) priorDiscountByKey.set(key, discount) + if (discount == null) continue + if (!priorDiscountByKey.has(centerKey)) priorDiscountByKey.set(centerKey, discount) + if (!priorDiscountByKey.has(barcodeKey)) priorDiscountByKey.set(barcodeKey, discount) } const updates: Array> = [] for (const task of targetTasks) { @@ -100,7 +103,7 @@ async function main() { auditSuggestedDiscount: score.suggestedDiscount, auditPreviousMonthDiscount: priorDiscountByKey.get( `${task.barcode.trim().toUpperCase()}\u0000${profitCenter}`, - ) ?? null, + ) ?? priorDiscountByKey.get(`${task.barcode.trim().toUpperCase()}\u0000`) ?? null, auditScoreVersion: score.scoreVersion, auditScoredAt: scoredAt, }, diff --git a/furniture-3d-system/scripts/backfill-pickup-24h-order-fields.ts b/furniture-3d-system/scripts/backfill-pickup-24h-order-fields.ts new file mode 100644 index 00000000..fd2a12cb --- /dev/null +++ b/furniture-3d-system/scripts/backfill-pickup-24h-order-fields.ts @@ -0,0 +1,163 @@ +import { loadEnvConfig } from '@next/env' + +loadEnvConfig(process.cwd()) + +/** + * 历史回填:把已落库明细的快递公司/快递单号/发货时间/店铺名称 + * 改为以订单主表(jst_qmcust_orderlist / jst_Orders)为准,订单表为空才保留原值。 + * + * 用法: + * npm run backfill:pickup-24h-order-fields -- --apply --confirm=backfill-pickup-24h-order-fields + * 可选 --from=2026-11-01 --to=2026-11-18 + */ + +const CONFIRM_TOKEN = 'backfill-pickup-24h-order-fields' + +function arg(name: string) { + const prefix = `--${name}=` + return process.argv.slice(2).find((value) => value.startsWith(prefix))?.slice(prefix.length) ?? '' +} + +function chunk(values: T[], size: number): T[][] { + return Array.from({ length: Math.ceil(values.length / size) }, (_, index) => + values.slice(index * size, index * size + size)) +} + +async function main() { + if (!process.argv.includes('--apply') || arg('confirm') !== CONFIRM_TOKEN) { + throw new Error(`回填需要 --apply 和 --confirm=${CONFIRM_TOKEN}`) + } + const from = arg('from') + const to = arg('to') + + const { prisma } = await import('../src/lib/prisma') + const { + pickup24hTimelinessSourceRepository, + closePickup24hTimelinessSourcePool, + } = await import('../src/server/repositories/pickup-24h-timeliness-source.repository') + const pg = await import('pg') + const local = new pg.Client({ connectionString: process.env.DATABASE_URL }) + await local.connect() + + try { + const distinctOrders = await prisma.pickup24hTimelinessOrder.findMany({ + select: { innerOrderId: true }, + where: { + innerOrderId: { not: '' }, + ...(from || to + ? { + paymentDate: { + ...(from ? { gte: new Date(`${from}T00:00:00.000Z`) } : {}), + ...(to ? { lte: new Date(`${to}T00:00:00.000Z`) } : {}), + }, + } + : {}), + }, + distinct: ['innerOrderId'], + }) + const orderIds = distinctOrders.map((row) => row.innerOrderId) + console.log(`待回填内部订单号 ${orderIds.length} 个`) + + let totalUpdated = 0 + const failedBatches: string[][] = [] + const batches = chunk(orderIds, 200) + for (const [index, batchIds] of batches.entries()) { + let orders: Awaited< + ReturnType + > | null = null + for (let attempt = 1; attempt <= 2 && !orders; attempt += 1) { + try { + orders = await pickup24hTimelinessSourceRepository.listOrderLogisticsByIds(batchIds) + } catch (error) { + const message = error instanceof Error ? error.message : String(error) + console.warn(`批次 ${index + 1}/${batches.length} 第 ${attempt} 次失败:${message}`) + await new Promise((resolve) => setTimeout(resolve, 3000 * attempt)) + } + } + if (!orders) { + failedBatches.push(batchIds) + continue + } + const rows = await prisma.pickup24hTimelinessOrder.findMany({ + where: { innerOrderId: { in: batchIds } }, + select: { + id: true, + innerOrderId: true, + expressCompany: true, + expressNo: true, + sendTime: true, + shopName: true, + }, + }) + const changedByOrder = new Map() + let changedRows = 0 + for (const row of rows) { + const order = orders.get(row.innerOrderId) + if (!order) continue + const next = { + orderId: row.innerOrderId, + company: order.logisticCompany || row.expressCompany, + no: order.logisticId || row.expressNo, + sendTime: order.sendTime || row.sendTime, + shopName: order.shopName || row.shopName, + } + if ( + next.company !== row.expressCompany + || next.no !== row.expressNo + || (next.sendTime ?? null) !== (row.sendTime ?? null) + || next.shopName !== row.shopName + ) { + changedRows += 1 + changedByOrder.set(row.innerOrderId, next) + } + } + for (const group of chunk(Array.from(changedByOrder.values()), 500)) { + await local.query( + `update "Pickup24hTimelinessOrder" o + set "expressCompany" = v.company, + "expressNo" = v.no, + "sendTime" = v.send_time, + "shopName" = v.shop_name + from ( + select unnest($1::text[]) as order_id, + unnest($2::text[]) as company, + unnest($3::text[]) as no, + unnest($4::text[]) as send_time, + unnest($5::text[]) as shop_name + ) v + where o."innerOrderId" = v.order_id`, + [ + group.map((item) => item.orderId), + group.map((item) => item.company), + group.map((item) => item.no), + group.map((item) => item.sendTime), + group.map((item) => item.shopName), + ], + ) + } + totalUpdated += changedRows + if ((index + 1) % 10 === 0 || index === batches.length - 1) { + console.log(`进度 ${index + 1}/${batches.length} 批,累计更新 ${totalUpdated} 行`) + } + } + console.log('合计更新行数:', totalUpdated) + if (failedBatches.length) { + console.error(`有 ${failedBatches.length} 个批次读取失败,可重新运行本脚本补齐`) + process.exitCode = 1 + } + } finally { + await local.end() + await closePickup24hTimelinessSourcePool() + } +} + +main().catch((error) => { + console.error(error instanceof Error ? error.message : error) + process.exit(1) +}) diff --git a/furniture-3d-system/scripts/create-local-supplier-quote-account.ts b/furniture-3d-system/scripts/create-local-supplier-quote-account.ts new file mode 100644 index 00000000..ef6211b5 --- /dev/null +++ b/furniture-3d-system/scripts/create-local-supplier-quote-account.ts @@ -0,0 +1,46 @@ +import { readFileSync } from 'node:fs' +import { prisma } from '../src/lib/prisma' +import { hashPassword, validatePasswordStrength, verifyPassword } from '../src/lib/password' +import { SUPPLIER_QUOTE_LOGIN_SOURCE } from '../src/lib/supplier-quote/access' + +async function main() { + const database = new URL(process.env.DATABASE_URL ?? '') + if (!['127.0.0.1', 'localhost'].includes(database.hostname) || database.port !== '55432' || + !database.pathname.startsWith('/furniture3d_local_')) { + throw new Error('Refusing to provision outside the local 3001 database') + } + const name = process.argv[2]?.trim() + const password = readFileSync(0, 'utf8').replace(/[\r\n]+$/, '') + if (!name || !/^[A-Za-z0-9_]{2,20}$/.test(name) || !validatePasswordStrength(password).isValid) { + throw new Error('Provide a valid account name and pass its password through standard input') + } + const existing = await prisma.user.findUnique({ + where: { name }, + select: { loginSource: true, role: true, businessRoles: true, status: true, password: true }, + }) + if (existing) { + if (existing.loginSource !== SUPPLIER_QUOTE_LOGIN_SOURCE || existing.role !== 'USER' || + existing.businessRoles.length > 0 || existing.status !== 'ACTIVE' || !await verifyPassword(password, existing.password)) { + throw new Error('The account name is already in use; existing account left unchanged') + } + console.log('Local quote account already exists') + return + } + await prisma.user.create({ + data: { + name, email: `${name.toLowerCase()}@supplier-quote.local`, + password: await hashPassword(password), + loginSource: SUPPLIER_QUOTE_LOGIN_SOURCE, + role: 'USER', + status: 'ACTIVE', + isFirstLogin: false, + }, + select: { id: true }, + }) + console.log('Local quote account created') +} + +main().catch((error: unknown) => { + console.error(error instanceof Error && !('code' in error) ? error.message : 'Local account provisioning failed') + process.exitCode = 1 +}).finally(() => prisma.$disconnect()) diff --git a/furniture-3d-system/scripts/daily-express-dashboard/core.mjs b/furniture-3d-system/scripts/daily-express-dashboard/core.mjs new file mode 100644 index 00000000..05b3bd7b --- /dev/null +++ b/furniture-3d-system/scripts/daily-express-dashboard/core.mjs @@ -0,0 +1,93 @@ +export const RULE_VERSION='orders-sent-warehouse-v1'; +export const INITIAL_DATE='2026-11-24'; +export const RETAIN_DAYS=30; +export const SOURCES=['jst_Orders','jst_qmcust_orderlist']; +export const DETAIL_VERSION=1; +export const DETAIL_COLUMNS=[ + ['o_id','ERP 内部订单号(订单编号)'],['so_id','线上订单号(交易单号)'], + ['logistics_company','快递名称'],['l_id','快递单号'],['receiver_state','省份'], + ['send_date','发货日期'],['wms_co_id','发货仓编号'],['warehouse_name','仓库名称'] +]; +export const RULES=[ + ['blankTracking','快递单号为空',r=>String(r.l_id??'').trim()===''], + ['atTracking','快递单号含 @',r=>String(r.l_id??'').includes('@')], + ['mainWarehouse','仓库为常州简尚家居有限公司',r=>String(r.warehouse_name??'').trim()==='常州简尚家居有限公司'], + ['unsetWarehouse','仓库为未设定发货仓库',r=>String(r.warehouse_name??'').trim()==='未设定发货仓库'], + ['unmatchedWarehouse','仓库未匹配',r=>['','未匹配'].includes(String(r.warehouse_name??'').trim())], + ['accessoryWarehouse','仓库包含配件-',r=>String(r.warehouse_name??'').includes('配件-')] +]; +export function assertDate(date){if(!/^\d{4}-\d{2}-\d{2}$/.test(date)||new Date(date+'T00:00:00Z').toISOString().slice(0,10)!==date)throw new Error('INVALID_DATE');return date;} +export function addDays(date,days){assertDate(date);return new Date(Date.parse(date+'T00:00:00Z')+days*86400000).toISOString().slice(0,10);} +export function businessYesterday(now=new Date()){return addDays(new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai',year:'numeric',month:'2-digit',day:'2-digit'}).format(now),-1);} +export function windowDates(end,initialDate=INITIAL_DATE){assertDate(end);assertDate(initialDate);const start=[initialDate,addDays(end,1-RETAIN_DAYS)].sort().at(-1);const dates=[];for(let day=start;day<=end;day=addDays(day,1))dates.push(day);if(!dates.length)throw new Error('NO_DATES');return dates;} +export function expiredSnapshotFiles(files,end){const retained=new Set(windowDates(end).map(day=>day+'.json'));return files.filter(name=>/^\d{4}-\d{2}-\d{2}\.json$/.test(name)&&!retained.has(name));} +export function aggregateDay(date,orders,warehouses,{extractedAt=new Date().toISOString(),seed=false}={}){ + assertDate(date); + const lookup=new Map();for(const warehouse of warehouses){const key=String(warehouse.co_id)+'|'+String(warehouse.wms_co_id);const names=lookup.get(key)||new Set();if(warehouse.name!=null&&String(warehouse.name).trim())names.add(warehouse.name);lookup.set(key,names);} + const snapshot={date,ruleVersion:RULE_VERSION,complete:true,extractedAt,seed,raw:orders.length,excluded:0,total:0,distinctOrders:0,carriers:[],sourceCounts:SOURCES.map(source=>({source,raw:0,total:0})),exclusionRules:RULES.map(([key,label])=>({key,label,totalMatches:0,excludedAfterPriorRules:0}))}; + const ids=new Set(),counts=new Map(),details=[]; + for(const order of orders){ + if(order.send_date?.slice(0,10)!==date||order.status!=='Sent'||!SOURCES.includes(order.source)||!order.o_id)throw new Error('SOURCE_FILTER_MISMATCH'); + if(ids.has(String(order.o_id)))throw new Error('DUPLICATE_ORDER_ID');ids.add(String(order.o_id)); + const source=snapshot.sourceCounts.find(item=>item.source===order.source);source.raw++; + const names=[...(lookup.get(String(order.co_id)+'|'+String(order.wms_co_id))||[])]; + const row={...order,warehouse_name:names.length===1?names[0]:null};let first=-1; + RULES.forEach(([, ,predicate],index)=>{if(predicate(row)){snapshot.exclusionRules[index].totalMatches++;if(first===-1)first=index;}}); + if(first!==-1){snapshot.excluded++;snapshot.exclusionRules[first].excludedAfterPriorRules++;continue;} + snapshot.total++;source.total++; + details.push(Object.fromEntries(DETAIL_COLUMNS.map(([key])=>[key,row[key]==null?'':String(row[key])]))); + const name=row.logistics_company==null||row.logistics_company===''?'未填写快递名称':row.logistics_company; + counts.set(name,(counts.get(name)||0)+1); + } + snapshot.distinctOrders=ids.size; + snapshot.detailVersion=DETAIL_VERSION; + snapshot.details=details.sort((a,b)=>a.send_date.localeCompare(b.send_date)||a.o_id.localeCompare(b.o_id,'en',{numeric:true})); + snapshot.carriers=[...counts].map(([name,count])=>({name,count})).sort((a,b)=>b.count-a.count||a.name.localeCompare(b.name,'zh-CN')); + validateDayDetails(snapshot);return snapshot; +} +export function validateDayDetails(day){ + validateDay(day); + if(day.detailVersion!==DETAIL_VERSION||!Array.isArray(day.details)||day.details.length!==day.total)throw new Error('INVALID_DAY_DETAILS'); + const ids=new Set(),counts=new Map(); + for(const row of day.details){ + if(Object.keys(row).length!==DETAIL_COLUMNS.length||DETAIL_COLUMNS.some(([key])=>typeof row[key]!=='string')||!row.o_id||ids.has(row.o_id)||row.send_date.slice(0,10)!==day.date||RULES.some(([, ,predicate])=>predicate(row)))throw new Error('INVALID_DETAIL_ROW'); + ids.add(row.o_id); + const name=row.logistics_company===''?'未填写快递名称':row.logistics_company;counts.set(name,(counts.get(name)||0)+1); + } + if(counts.size!==day.carriers.length||day.carriers.some(({name,count})=>counts.get(name)!==count))throw new Error('DETAIL_COUNTS_MISMATCH'); + return day; +} +export function collectDetails(snapshots){ + const ids=new Set(),rows=[]; + for(const snapshot of snapshots){validateDayDetails(snapshot);for(const row of snapshot.details){if(ids.has(row.o_id))throw new Error('DUPLICATE_ORDER_ACROSS_DAYS');ids.add(row.o_id);rows.push(row);}} + return rows; +} +export function enrichDayDetails(previous,fresh,baselineRows){ + validateDay(previous);validateDayDetails(fresh); + const shape=day=>JSON.stringify([day.date,day.total,day.sourceCounts.map(r=>[r.source,r.total]),day.carriers]); + if(shape(previous)!==shape(fresh))throw Object.assign(new Error('SNAPSHOT_COUNTS_CHANGED'),{code:'SNAPSHOT_COUNTS_CHANGED_'+previous.date}); + if(baselineRows){ + const baseline=new Map(baselineRows.filter(row=>row.send_date.slice(0,10)===previous.date).map(row=>[String(row.o_id),row])); + if(baseline.size!==fresh.details.length||fresh.details.some(row=>{const old=baseline.get(row.o_id);return !old||DETAIL_COLUMNS.some(([key])=>key!=='receiver_state'&&String(old[key]??'')!==row[key]);}))throw Object.assign(new Error('HISTORICAL_DETAIL_CHANGED'),{code:'HISTORICAL_DETAIL_CHANGED_'+previous.date}); + } + return validateDayDetails({...previous,detailVersion:DETAIL_VERSION,details:fresh.details,detailExtractedAt:fresh.extractedAt,detailBackfillRawDelta:fresh.raw-previous.raw}); +} +export function validateDay(day){ + assertDate(day.date); + if(day.ruleVersion!==RULE_VERSION||day.complete!==true||day.distinctOrders!==day.raw||!Number.isInteger(day.raw)||day.raw<0||!Number.isInteger(day.total)||day.total<0||!Number.isInteger(day.excluded)||day.excluded<0||day.raw!==day.excluded+day.total)throw new Error('INVALID_DAY_SNAPSHOT'); + if(!Array.isArray(day.carriers)||new Set(day.carriers.map(r=>r.name)).size!==day.carriers.length||day.carriers.some(r=>!Number.isInteger(r.count)||r.count<=0)||day.carriers.reduce((a,r)=>a+r.count,0)!==day.total)throw new Error('INVALID_CARRIER_COUNTS'); + if(day.sourceCounts.length!==2||new Set(day.sourceCounts.map(r=>r.source)).size!==2||SOURCES.some(source=>!day.sourceCounts.some(r=>r.source===source))||day.sourceCounts.reduce((a,r)=>a+r.raw,0)!==day.raw||day.sourceCounts.reduce((a,r)=>a+r.total,0)!==day.total)throw new Error('INVALID_SOURCE_COUNTS'); + if(day.exclusionRules.reduce((a,r)=>a+r.excludedAfterPriorRules,0)!==day.excluded)throw new Error('INVALID_EXCLUSION_COUNTS'); + return day; +} +export function buildFacts(snapshots,end,{initialDate=INITIAL_DATE}={}){ + const dates=windowDates(end,initialDate),byDate=new Map();for(const snapshot of snapshots){validateDay(snapshot);if(byDate.has(snapshot.date))throw new Error('DUPLICATE_DATE');byDate.set(snapshot.date,snapshot);} + const days=dates.map(date=>{if(!byDate.has(date))throw new Error('MISSING_DAY_'+date);return byDate.get(date);}); + const counts=new Map();days.forEach((day,index)=>day.carriers.forEach(({name,count})=>{const daily=counts.get(name)||Array(dates.length).fill(0);daily[index]=count;counts.set(name,daily);})); + const ranking=[...counts].map(([name,daily])=>({name,daily,total:daily.reduce((a,b)=>a+b,0)})).sort((a,b)=>b.total-a.total||a.name.localeCompare(b.name,'zh-CN')).map((r,index)=>({...r,rank:index+1})); + const daily=days.map(({date,raw,excluded,total})=>({date,raw,excluded,total})); + const facts={dateFrom:dates[0],dateTo:end,days:dates,daily,original:daily.reduce((a,d)=>a+d.raw,0),excluded:daily.reduce((a,d)=>a+d.excluded,0),total:daily.reduce((a,d)=>a+d.total,0),carrierCount:ranking.length,ranking,sourceCounts:SOURCES.map(source=>({source,raw:days.reduce((a,d)=>a+d.sourceCounts.find(r=>r.source===source).raw,0),count:days.reduce((a,d)=>a+d.sourceCounts.find(r=>r.source===source).total,0)})),ruleVersion:RULE_VERSION,retentionDays:RETAIN_DAYS,extractedAt:days.at(-1).extractedAt,updatedAt:new Date().toISOString(),countUnit:'每张 ERP 内部订单计 1 单,按原始快递名称及发货日期汇总'}; + facts.sourceRevisions=days.filter(day=>day.revision).map(day=>({date:day.date,...day.revision})); + facts.initialDate=initialDate; + if(facts.total+facts.excluded!==facts.original||ranking.reduce((a,r)=>a+r.total,0)!==facts.total)throw new Error('TOTAL_MISMATCH');return facts; +} diff --git a/furniture-3d-system/scripts/daily-express-dashboard/core.test.mjs b/furniture-3d-system/scripts/daily-express-dashboard/core.test.mjs new file mode 100644 index 00000000..0a7dc94f --- /dev/null +++ b/furniture-3d-system/scripts/daily-express-dashboard/core.test.mjs @@ -0,0 +1,66 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import path from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {aggregateDay,buildFacts,addDays,businessYesterday,windowDates,validateDay,validateDayDetails,collectDetails,enrichDayDetails,DETAIL_COLUMNS,expiredSnapshotFiles} from './core.mjs'; +const root=path.dirname(fileURLToPath(import.meta.url)); +const warehouse=[{co_id:'1',wms_co_id:'2',name:'简尚-崔桥工厂仓'},{co_id:'9',wms_co_id:'2',name:'常州简尚家居有限公司'}]; +const order=(id,patch={})=>({o_id:String(id),status:'Sent',send_date:'2026-11-24 13:00:00.000',source:'jst_Orders',logistics_company:'快递甲',l_id:'NUMBER'+id,co_id:'1',wms_co_id:'2',...patch}); +test('one approved day grows to 30 and day 31 removes the first day',()=>{ + assert.deepEqual(windowDates('2026-11-24'),['2026-11-24']); + assert.equal(windowDates('2026-11-25').length,2); + assert.equal(windowDates('2026-12-08').length,15); + assert.deepEqual([windowDates('2026-12-24')[0],windowDates('2026-12-24').at(-1)],['2026-11-25','2026-12-24']); + assert.equal(windowDates('2026-12-23').length,30); +}); +test('day boundaries use Shanghai even when execution host uses UTC',()=>{ + assert.equal(businessYesterday(new Date('2026-11-24T16:01:00Z')),'2026-11-24'); + assert.equal(businessYesterday(new Date('2026-11-24T15:59:00Z')),'2026-11-23'); +}); +test('retention removes only expired snapshots and keeps exactly 30 days',()=>{ + const files=[...Array.from({length:35},(_,i)=>addDays('2026-11-24',i)+'.json'),'notes.json','2026-11-24.json.tmp']; + const removed=expiredSnapshotFiles(files,'2026-12-28'); + assert.deepEqual(removed,['2026-11-24.json','2026-11-25.json','2026-11-26.json','2026-11-27.json','2026-11-28.json']); + assert.equal(files.filter(file=>/^\d{4}-\d{2}-\d{2}\.json$/.test(file)&&!removed.includes(file)).length,30); + assert.deepEqual(expiredSnapshotFiles(windowDates('2026-11-24').map(date=>date+'.json'),'2026-11-24'),[]); +}); +test('applies all approved exclusions once and isolates warehouse companies',()=>{ + const orders=[order(1),order(2,{l_id:' '}),order(3,{l_id:'@bad'}),order(4,{co_id:'9'}),order(5,{wms_co_id:'0'}),order(6,{wms_co_id:'3'}),order(7,{wms_co_id:'4'})]; + const result=aggregateDay('2026-11-24',orders,[...warehouse,{co_id:'1',wms_co_id:'3',name:'未设定发货仓库'},{co_id:'1',wms_co_id:'4',name:'配件-测试仓'}]); + assert.equal(result.raw,7);assert.equal(result.excluded,6);assert.equal(result.total,1);assert.deepEqual(result.carriers,[{name:'快递甲',count:1}]); +}); +test('same order appearing in either source is rejected, and incomplete days cannot pass as zero',()=>{ + assert.throws(()=>aggregateDay('2026-11-24',[order(1),order(1,{source:'jst_qmcust_orderlist'})],warehouse),/DUPLICATE_ORDER_ID/); + const completeZero=aggregateDay('2026-11-24',[],warehouse);assert.equal(completeZero.total,0); + assert.throws(()=>validateDay({...completeZero,complete:false}),/INVALID_DAY/); + assert.throws(()=>buildFacts([completeZero],'2026-11-25'),/MISSING_DAY/); +}); + +test('detail preserves long identifiers and missing province, with the correct company warehouse',()=>{ + const result=aggregateDay('2026-11-24',[order('9007199254740993123',{so_id:'000123456789012345678901',receiver_state:'浙江省'}),order('2',{source:'jst_qmcust_orderlist',receiver_state:null})],warehouse); + const long=result.details.find(row=>row.o_id==='9007199254740993123'); + assert.deepEqual(Object.keys(long),DETAIL_COLUMNS.map(([key])=>key)); + assert.equal(long.so_id,'000123456789012345678901');assert.equal(long.receiver_state,'浙江省');assert.equal(long.warehouse_name,'简尚-崔桥工厂仓'); + assert.equal(result.details.find(row=>row.o_id==='2').receiver_state,''); + assert.equal(result.details.length,result.total);validateDayDetails(result); + const corrupt=structuredClone(result);corrupt.details[0].logistics_company='另一快递';assert.throws(()=>validateDayDetails(corrupt),/DETAIL_COUNTS/); +}); + +test('incomplete detail and duplicate orders on different dates block publication',()=>{ + const a=aggregateDay('2026-11-24',[order(1)],warehouse); + assert.throws(()=>validateDayDetails({...a,details:[]}),/INVALID_DAY_DETAILS/); + const b=aggregateDay('2026-11-25',[order(1,{send_date:'2026-11-25 08:00:00.000'})],warehouse); + assert.throws(()=>collectDetails([a,b]),/DUPLICATE_ORDER_ACROSS_DAYS/); +}); + +test('province enrichment preserves the accepted snapshot when only excluded source rows changed',()=>{ + const original=aggregateDay('2026-11-24',[order(1)],warehouse),prior=structuredClone(original);delete prior.details;delete prior.detailVersion; + const fresh=aggregateDay('2026-11-24',[order(1,{receiver_state:'江苏省'}),order(2,{l_id:''})],warehouse); + const enriched=enrichDayDetails(prior,fresh,original.details); + assert.equal(enriched.raw,1);assert.equal(enriched.excluded,0);assert.equal(enriched.total,1);assert.equal(enriched.details[0].receiver_state,'江苏省');assert.equal(enriched.detailBackfillRawDelta,1); + const differentId=aggregateDay('2026-11-24',[order(3,{receiver_state:'江苏省'})],warehouse); + assert.throws(()=>enrichDayDetails(prior,differentId,original.details),/HISTORICAL_DETAIL_CHANGED/); + const changedCarrier=aggregateDay('2026-11-24',[order(1,{logistics_company:'另一快递'})],warehouse); + assert.throws(()=>enrichDayDetails(prior,changedCarrier,original.details),/SNAPSHOT_COUNTS_CHANGED/); +}); diff --git a/furniture-3d-system/scripts/daily-express-dashboard/environment.cjs b/furniture-3d-system/scripts/daily-express-dashboard/environment.cjs new file mode 100644 index 00000000..41620e52 --- /dev/null +++ b/furniture-3d-system/scripts/daily-express-dashboard/environment.cjs @@ -0,0 +1,6 @@ +const fs=require('node:fs'),path=require('node:path'),{createRequire}=require('node:module'); +const app=path.resolve(__dirname,'../..'),req=createRequire(path.join(app,'package.json')); +const file=process.env.DAILY_EXPRESS_ENV_FILE||path.join(app,'.env'); +const credentials=process.env.DAILY_EXPRESS_ENV_JSON?JSON.parse(fs.readFileSync(process.env.DAILY_EXPRESS_ENV_JSON,'utf8')):{}; +const env={...(fs.existsSync(file)?req('dotenv').parse(fs.readFileSync(file)):{}),...process.env,...credentials}; +module.exports={app,req,env}; diff --git a/furniture-3d-system/scripts/daily-express-dashboard/fetch-refund-checks.cjs b/furniture-3d-system/scripts/daily-express-dashboard/fetch-refund-checks.cjs new file mode 100644 index 00000000..a824905c --- /dev/null +++ b/furniture-3d-system/scripts/daily-express-dashboard/fetch-refund-checks.cjs @@ -0,0 +1,36 @@ +const fs=require('node:fs/promises'),path=require('node:path'); +const {pool,sql,schema}=require('./report-db-readonly.cjs'); +(async()=>{try{ + const {applyUncollectedBaseRules}=await import('./uncollected.mjs'); + const sourceFile=path.resolve(process.argv.find(arg=>arg.startsWith('--source='))?.slice(9)||path.join(__dirname,'staging/uncollected-source.json')); + const output=path.resolve(process.argv.find(arg=>arg.startsWith('--output='))?.slice(9)||path.join(__dirname,'staging/uncollected-refund-checks.json')); + const snapshot=JSON.parse(await fs.readFile(sourceFile,'utf8')),candidates=applyUncollectedBaseRules(snapshot.rows); + const ids=[...new Set(candidates.map(row=>String(row.inner_order_id)))]; + if(ids.some(id=>!/^\d+$/.test(id)))throw new Error('REFUND_INVALID_ORDER_ID'); + const masters=[],items=[],checkedAt=new Date().toISOString(); + if(ids.length){ + await pool.connect(); + for(const table of ['jst_Orders','jst_qmcust_orderlist']){ + const request=pool.request().input('ids',sql.NVarChar(sql.MAX),JSON.stringify(ids));request.timeout=90000; + const rows=(await request.query(`SET LOCK_TIMEOUT 45000; + SELECT CAST(co_id AS varchar(40)) AS co_id,CAST(o_id AS varchar(40)) AS o_id,so_id,l_id + FROM [${schema}].[${table}] WHERE o_id IN (SELECT CONVERT(bigint,value) FROM OPENJSON(@ids));`)).recordset; + masters.push(...rows.map(row=>({...row,source:table}))); + console.log(JSON.stringify({stage:'refund_order_source_checked',source:table,matched:rows.length})); + } + for(const [master,item] of [['jst_Orders','jst_OrderItem'],['jst_qmcust_orderlist','jst_qmcust_orderlist_item']]){ + const target=masters.filter(row=>row.source===master).map(row=>row.o_id);if(!target.length)continue; + const request=pool.request().input('ids',sql.NVarChar(sql.MAX),JSON.stringify(target));request.timeout=90000; + const rows=(await request.query(`SET LOCK_TIMEOUT 45000; + SELECT CAST(o_id AS varchar(40)) AS o_id,CAST(oi_id AS varchar(40)) AS oi_id,raw_so_id,refund_status,item_status,qty + FROM [${schema}].[${item}] WHERE o_id IN (SELECT CONVERT(bigint,value) FROM OPENJSON(@ids));`)).recordset; + items.push(...rows.map(row=>({...row,source:item}))); + console.log(JSON.stringify({stage:'refund_item_source_checked',source:item,items:rows.length})); + } + } + const audit={version:'item-refund-success-v1',date:snapshot.summary.date,sourceQueriedAt:snapshot.summary.queriedAt,checkedAt,completedAt:new Date().toISOString(),candidates:candidates.map(row=>({id:String(row.id),o_id:String(row.inner_order_id),so_id:row.so_id??null,l_id:row.logistic_id??null})),masters,items}; + const {partitionRefundChecks}=await import('./refund.mjs'); + const {checked,exceptions}=partitionRefundChecks(snapshot.rows,audit,snapshot.summary.date); + await fs.mkdir(path.dirname(output),{recursive:true});await fs.writeFile(output+'.tmp',JSON.stringify(audit,null,2));await fs.rename(output+'.tmp',output); + console.log(JSON.stringify({stage:'refund_checks_complete',candidates:candidates.length,checked:checked.length,exceptions:exceptions.length,refundSuccess:checked.filter(row=>row.refund_success).length,retained:checked.filter(row=>!row.refund_success).length})); + }catch(error){console.error(JSON.stringify({errorCode:error.code||error.message||error.name,number:error.number||null}));process.exitCode=1;}finally{await pool.close();}})(); diff --git a/furniture-3d-system/scripts/daily-express-dashboard/fetch-uncollected.cjs b/furniture-3d-system/scripts/daily-express-dashboard/fetch-uncollected.cjs new file mode 100644 index 00000000..f3677c63 --- /dev/null +++ b/furniture-3d-system/scripts/daily-express-dashboard/fetch-uncollected.cjs @@ -0,0 +1,26 @@ +const fs=require('node:fs/promises'),path=require('node:path'); +const {pool,sql,schema}=require('./report-db-readonly.cjs'); +(async()=>{try{ + const {businessYesterday}=await import('./core.mjs'); + const date=process.argv.find(arg=>arg.startsWith('--date='))?.slice(7)||businessYesterday(); + if(!/^\d{4}-\d{2}-\d{2}$/.test(date)||new Date(date+'T00:00:00Z').toISOString().slice(0,10)!==date)throw new Error('INVALID_DATE'); + const from=date+' 00:00:00',to=new Date(Date.parse(date+'T00:00:00Z')+86400000).toISOString().slice(0,10)+' 00:00:00'; + const output=path.resolve(process.argv.find(arg=>arg.startsWith('--output='))?.slice(9)||path.join(__dirname,'staging/uncollected-source.json')); + await pool.connect(); + const startedAt=new Date().toISOString(); + const rows=(await pool.request().input('from',sql.VarChar(19),from).input('to',sql.VarChar(19),to).query(`SET LOCK_TIMEOUT 15000; + SELECT id,CAST(inner_order_id AS varchar(40)) AS inner_order_id,so_id,logistic_id,logistic_company_name, + logistic_status_name,order_status_name,logistic_return_flag,aftersale_status_name, + shop_name,platform_name,dis_co_name,warehouse_name,order_labels,remark, + CONVERT(varchar(19),send_time,120) AS send_time,CONVERT(varchar(19),fetch_time,120) AS fetch_time, + CONVERT(varchar(19),sign_time,120) AS sign_time,CONVERT(varchar(19),logistic_time,120) AS logistic_time, + CONVERT(varchar(19),query_time,120) AS query_time,first_question_type, + CONVERT(varchar(19),first_question_time,120) AS first_question_time,CONVERT(varchar(19),updatedAt,120) AS updatedAt + FROM [${schema}].[jst_order_express_details] + WHERE send_time >= CONVERT(datetime,@from,120) AND send_time < CONVERT(datetime,@to,120) AND fetch_time IS NULL;`)).recordset; + rows.sort((a,b)=>a.send_time.localeCompare(b.send_time)||Number(a.id)-Number(b.id)); + const snapshot={summary:{date,source:schema+'.jst_order_express_details',filters:{send_timeFromInclusive:from,send_timeToExclusive:to,fetch_time:'IS NULL'},startedAt,queriedAt:new Date().toISOString(),rowCount:rows.length},rows}; + const {validateUncollected,summarizeUncollected}=await import('./uncollected.mjs');validateUncollected(snapshot); + await fs.mkdir(path.dirname(output),{recursive:true});await fs.writeFile(output+'.tmp',JSON.stringify(snapshot));await fs.rename(output+'.tmp',output); + console.log(JSON.stringify({stage:'uncollected_fetched',date,total:rows.length,pending:summarizeUncollected(rows).pending})); + }catch(error){console.error(JSON.stringify({errorCode:error.code||error.name,number:error.number||null}));process.exitCode=1;}finally{await pool.close();}})(); diff --git a/furniture-3d-system/scripts/daily-express-dashboard/province.mjs b/furniture-3d-system/scripts/daily-express-dashboard/province.mjs new file mode 100644 index 00000000..f31633ef --- /dev/null +++ b/furniture-3d-system/scripts/daily-express-dashboard/province.mjs @@ -0,0 +1,26 @@ +import {validateDayDetails} from './core.mjs'; +export const PROVINCE_VERSION=1; +const regions=new Set(['北京','北京市','天津','天津市','上海','上海市','重庆','重庆市','河北省','山西省','内蒙古自治区','辽宁省','吉林省','黑龙江省','江苏省','浙江省','安徽省','福建省','江西省','山东省','河南省','湖北省','湖南省','广东省','广西壮族自治区','海南省','四川省','贵州省','云南省','西藏自治区','陕西省','甘肃省','青海省','宁夏回族自治区','新疆维吾尔自治区','台湾省','香港特别行政区','澳门特别行政区']); +const key=row=>JSON.stringify([String(row.o_id??''),String(row.so_id??''),String(row.l_id??'').trim()]); +export function completeDayProvinces(snapshot,candidates,{checkedAt=new Date().toISOString()}={}){ + validateDayDetails(snapshot); + const index=new Map(); + for(const row of candidates){const province=String(row.region??'').split('-')[0].trim();if(!regions.has(province))continue;const id=key(row);const values=index.get(id)||new Set();values.add(province);index.set(id,values);} + const records=[],unresolved=[]; + const details=snapshot.details.map(row=>{ + if(row.receiver_state.trim())return {...row}; + const provinces=[...(index.get(key(row))||[])]; + if(provinces.length>1)throw new Error('CONFLICTING_LOGISTICS_PROVINCES'); + if(!provinces.length){unresolved.push(row.o_id);return {...row};} + records.push({o_id:row.o_id,province:provinces[0]});return {...row,receiver_state:provinces[0]}; + }); + const day={...snapshot,details,provinceEnrichment:{version:PROVINCE_VERSION,source:'jst_order_express_details.receiver_address',checkedAt,requested:records.length+unresolved.length,filled:records.length,unresolved:unresolved.length,records}}; + return validateProvinceEnrichment(day); +} +export function validateProvinceEnrichment(day){ + validateDayDetails(day);const audit=day.provinceEnrichment; + if(audit?.version!==PROVINCE_VERSION||audit.source!=='jst_order_express_details.receiver_address'||!Number.isInteger(audit.filled)||!Number.isInteger(audit.unresolved)||audit.filled<0||audit.unresolved<0||audit.requested!==audit.filled+audit.unresolved||audit.records.length!==audit.filled)throw new Error('INVALID_PROVINCE_AUDIT'); + const byId=new Map(day.details.map(row=>[row.o_id,row])); + if(new Set(audit.records.map(row=>row.o_id)).size!==audit.records.length||audit.records.some(row=>!regions.has(row.province)||byId.get(row.o_id)?.receiver_state!==row.province)||day.details.filter(row=>!row.receiver_state.trim()).length!==audit.unresolved)throw new Error('PROVINCE_AUDIT_MISMATCH'); + return day; +} diff --git a/furniture-3d-system/scripts/daily-express-dashboard/province.test.mjs b/furniture-3d-system/scripts/daily-express-dashboard/province.test.mjs new file mode 100644 index 00000000..c6366e0e --- /dev/null +++ b/furniture-3d-system/scripts/daily-express-dashboard/province.test.mjs @@ -0,0 +1,29 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import path from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {aggregateDay,buildFacts,addDays,windowDates} from './core.mjs'; +import {completeDayProvinces,validateProvinceEnrichment} from './province.mjs'; +const root=path.dirname(fileURLToPath(import.meta.url)); +const warehouse=[{co_id:'1',wms_co_id:'2',name:'核对仓'}]; +const order=(o_id,province='')=>({o_id,so_id:'online-'+o_id,l_id:'waybill-'+o_id,source:'jst_Orders',status:'Sent',send_date:'2026-11-24 13:00:00.000',co_id:'1',wms_co_id:'2',logistics_company:'快递甲',receiver_state:province}); +test('fills only missing provinces and requires internal, online and waybill numbers to match',()=>{ + const original=aggregateDay('2026-11-24',[order('1'),order('2','江苏省'),order('3')],warehouse); + const result=completeDayProvinces(original,[{o_id:'1',so_id:'online-1',l_id:'waybill-1',region:'山东省-德州市'},{o_id:'2',so_id:'online-2',l_id:'waybill-2',region:'广东省'},{o_id:'3',so_id:'online-3',l_id:'different-waybill',region:'北京市'}]); + assert.deepEqual(result.details.map(row=>row.receiver_state),['山东省','江苏省','']); + assert.equal(result.provinceEnrichment.filled,1);assert.equal(result.provinceEnrichment.unresolved,1); + assert.equal(original.details[0].receiver_state,'');validateProvinceEnrichment(result); +}); +test('rejects conflicting logistics regions and accepts municipality aliases',()=>{ + const original=aggregateDay('2026-11-24',[order('1')],warehouse); + const candidate={o_id:'1',so_id:'online-1',l_id:'waybill-1',region:'重庆'}; + assert.equal(completeDayProvinces(original,[candidate]).details[0].receiver_state,'重庆'); + assert.throws(()=>completeDayProvinces(original,[candidate,{...candidate,region:'北京市'}]),/CONFLICTING/); +}); +test('missing dates cannot silently produce a complete 30-day history and repeats do not duplicate orders',()=>{ + const days=Array.from({length:31},(_,i)=>{const date=addDays('2026-11-24',i);return aggregateDay(date,[{...order(String(i)),send_date:date+' 13:00:00.000'}],warehouse);}); + const facts=buildFacts(days,'2026-12-24');assert.equal(facts.days.length,30);assert.equal(facts.total,30);assert.equal(facts.dateFrom,'2026-11-25'); + assert.deepEqual(buildFacts(days,'2026-12-24').ranking,facts.ranking); + assert.throws(()=>buildFacts(days.filter(day=>day.date!=='2026-12-01'),'2026-12-24'),/MISSING_DAY/); +}); diff --git a/furniture-3d-system/scripts/daily-express-dashboard/refund.mjs b/furniture-3d-system/scripts/daily-express-dashboard/refund.mjs new file mode 100644 index 00000000..61069114 --- /dev/null +++ b/furniture-3d-system/scripts/daily-express-dashboard/refund.mjs @@ -0,0 +1,49 @@ +import {applyUncollectedBaseRules,hasAtInTracking} from './uncollected.mjs'; +const text=value=>String(value??'').trim(); +const ITEM_SOURCE={jst_Orders:'jst_OrderItem',jst_qmcust_orderlist:'jst_qmcust_orderlist_item'}; +const identity=row=>({id:String(row.id),o_id:text(row.inner_order_id),so_id:row.so_id??null,l_id:row.logistic_id??null}); +function getRefundCandidates(rows,audit,date){ + if(audit?.version!=='item-refund-success-v1'||audit.date!==date||!Array.isArray(audit.candidates)||!Array.isArray(audit.masters)||!Array.isArray(audit.items)||!Number.isFinite(Date.parse(audit.completedAt)))throw new Error('INVALID_REFUND_AUDIT'); + const candidates=applyUncollectedBaseRules(rows); + // Older audits can include matching source rows that are now excluded by the tracking number rule. + const excluded=new Set(rows.filter(hasAtInTracking).map(row=>JSON.stringify(identity(row)))); + const audited=audit.candidates.filter(candidate=>!excluded.has(JSON.stringify(candidate))); + if(JSON.stringify(candidates.map(identity))!==JSON.stringify(audited))throw new Error('REFUND_CANDIDATE_MISMATCH'); + return candidates; +} +export function attachRefundChecks(rows,audit,date){ + const candidates=getRefundCandidates(rows,audit,date); + const checked=new Map(); + for(const row of candidates){ + const masters=audit.masters.filter(master=>text(master.o_id)===text(row.inner_order_id)); + if(!masters.length)throw new Error('REFUND_ORDER_NOT_FOUND_'+row.inner_order_id); + const statuses=new Set(),itemKeys=new Set();let itemCount=0; + for(const master of masters){ + if(!ITEM_SOURCE[master.source]||text(master.so_id)!==text(row.so_id)||text(master.l_id)!==text(row.logistic_id))throw new Error('REFUND_ORDER_IDENTITY_MISMATCH_'+row.inner_order_id); + const items=audit.items.filter(item=>item.source===ITEM_SOURCE[master.source]&&text(item.o_id)===text(row.inner_order_id)); + if(!items.length)throw new Error('REFUND_ITEMS_NOT_FOUND_'+row.inner_order_id); + for(const item of items){ + if(!text(item.oi_id)||!Object.prototype.hasOwnProperty.call(item,'refund_status'))throw new Error('INVALID_REFUND_ITEM'); + const key=item.source+':'+item.oi_id; + if(itemKeys.has(key))throw new Error('DUPLICATE_REFUND_ITEM');itemKeys.add(key); + statuses.add(text(item.refund_status));itemCount++; + } + } + const raw=[...statuses].filter(Boolean).sort(); + checked.set(String(row.id),{...row,refund_checked:true,refund_status:raw.join(' / '),refund_success:raw.some(status=>status.toLowerCase()==='success'),refund_item_count:itemCount}); + } + return rows.map(row=>checked.get(String(row.id))||row); +} + +export function partitionRefundChecks(rows,audit,date){ + const candidates=getRefundCandidates(rows,audit,date); + const checked=[],exceptions=[]; + for(const row of candidates){ + try{checked.push(...attachRefundChecks([row],{...audit,candidates:[identity(row)]},date));} + catch(error){ + if(!/^(?:REFUND_ORDER_NOT_FOUND_|REFUND_ITEMS_NOT_FOUND_|REFUND_ORDER_IDENTITY_MISMATCH_|INVALID_REFUND_ITEM|DUPLICATE_REFUND_ITEM)/.test(error.message))throw error; + exceptions.push({id:String(row.id),inner_order_id:text(row.inner_order_id),logistic_id:text(row.logistic_id),logistic_company_name:text(row.logistic_company_name),warehouse_name:text(row.warehouse_name),errorCode:error.message}); + } + } + return {checked,exceptions}; +} diff --git a/furniture-3d-system/scripts/daily-express-dashboard/refund.test.mjs b/furniture-3d-system/scripts/daily-express-dashboard/refund.test.mjs new file mode 100644 index 00000000..9284bff3 --- /dev/null +++ b/furniture-3d-system/scripts/daily-express-dashboard/refund.test.mjs @@ -0,0 +1,38 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {attachRefundChecks,partitionRefundChecks} from './refund.mjs'; +import {applyUncollectedRules} from './uncollected.mjs'; +const rows=[{id:1,inner_order_id:'10356744',so_id:'S1',logistic_id:'L1',logistic_status_name:'未揽收',logistic_company_name:'中通速递',order_labels:null,remark:null}]; +const audit=()=>({version:'item-refund-success-v1',date:'2026-11-24',completedAt:'2026-11-25T08:00:00Z',candidates:[{id:'1',o_id:'10356744',so_id:'S1',l_id:'L1'}],masters:[{source:'jst_Orders',o_id:'10356744',so_id:'S1',l_id:'L1'}],items:[{source:'jst_OrderItem',o_id:'10356744',oi_id:'I1',refund_status:'success'}]}); +test('success on any item excludes its order; blank or pending refund values remain distinct from success',()=>{ + assert.equal(applyUncollectedRules(attachRefundChecks(rows,audit(),'2026-11-24')).length,0); + for(const status of [null,'','waiting','closed']){ + const data=audit();data.items[0].refund_status=status; + const enriched=attachRefundChecks(rows,data,'2026-11-24');assert.equal(enriched[0].refund_success,false);assert.equal(applyUncollectedRules(enriched).length,1); + } + const data=audit();data.items.push({...data.items[0],oi_id:'I2',refund_status:''});assert.equal(applyUncollectedRules(attachRefundChecks(rows,data,'2026-11-24')).length,0); +}); +test('Qimen item source is checked and incomplete, mismatched or duplicate evidence cannot pass',()=>{ + const data=audit();data.masters[0].source='jst_qmcust_orderlist';data.items[0].source='jst_qmcust_orderlist_item'; + assert.equal(attachRefundChecks(rows,data,'2026-11-24')[0].refund_success,true); + for(const mutate of [d=>d.masters=[],d=>d.items=[],d=>d.masters[0].so_id='OTHER',d=>d.masters[0].l_id='OTHER',d=>d.date='2026-11-23',d=>d.candidates=[],d=>d.items.push({...d.items[0]}),d=>delete d.items[0].refund_status]){ + const invalid=audit();mutate(invalid);assert.throws(()=>attachRefundChecks(rows,invalid,'2026-11-24')); + } +}); +test('no eligible candidates permits a valid empty audit',()=>{ + const data=audit();data.candidates=[];data.masters=[];data.items=[]; + assert.deepEqual(attachRefundChecks([],data,'2026-11-24'),[]); +}); + +test('one missing item is isolated while current successful and refunded records remain correctly classified',()=>{ + const records=[...rows,{...rows[0],id:2,inner_order_id:'2',so_id:'S2',logistic_id:'L2'},{...rows[0],id:3,inner_order_id:'3',so_id:'S3',logistic_id:'L3'}]; + const data=audit();data.items[0].refund_status=''; + data.candidates.push({id:'2',o_id:'2',so_id:'S2',l_id:'L2'},{id:'3',o_id:'3',so_id:'S3',l_id:'L3'}); + data.masters.push({source:'jst_qmcust_orderlist',o_id:'2',so_id:'S2',l_id:'L2'},{source:'jst_Orders',o_id:'3',so_id:'S3',l_id:'L3'}); + data.items.push({source:'jst_OrderItem',o_id:'3',oi_id:'I3',refund_status:'success'}); + const result=partitionRefundChecks(records,data,'2026-11-24'); + assert.equal(result.exceptions.length,1);assert.equal(result.exceptions[0].inner_order_id,'2');assert.match(result.exceptions[0].errorCode,/ITEMS_NOT_FOUND/); + assert.deepEqual(applyUncollectedRules(result.checked).map(row=>row.id),[1]); + assert.throws(()=>attachRefundChecks(records,data,'2026-11-24'),/ITEMS_NOT_FOUND/); + const corrupt=structuredClone(data);corrupt.candidates.pop();assert.throws(()=>partitionRefundChecks(records,corrupt,'2026-11-24'),/CANDIDATE_MISMATCH/); +}); diff --git a/furniture-3d-system/scripts/daily-express-dashboard/regional.mjs b/furniture-3d-system/scripts/daily-express-dashboard/regional.mjs new file mode 100644 index 00000000..f6bced25 --- /dev/null +++ b/furniture-3d-system/scripts/daily-express-dashboard/regional.mjs @@ -0,0 +1,74 @@ +const text=value=>String(value??'').normalize('NFKC').trim(); +export const UNMAPPED_ORIGIN='未匹配发货地'; +export const UNMAPPED_REGION='未配置区域'; +export const PRIORITY_ORIGINS=['常州自有仓','苏北自有仓','山东自有仓','河南自有仓','常州代发仓','河北代发仓-自有快递']; +function compareOrigins(a,b){ + const aIndex=PRIORITY_ORIGINS.indexOf(a.name),bIndex=PRIORITY_ORIGINS.indexOf(b.name); + const priority=(aIndex<0?PRIORITY_ORIGINS.length:aIndex)-(bIndex<0?PRIORITY_ORIGINS.length:bIndex); + return priority||b.total-a.total||a.name.localeCompare(b.name,'zh-CN'); +} +export function provinceKey(value){ + return text(value).replace(/壮族自治区$|回族自治区$|维吾尔自治区$|自治区$|特别行政区$|省$|市$/u,'').replace(/^黑龙$/u,'黑龙江').replace(/^内蒙$/u,'内蒙古'); +} +export function warehouseKey(value){return text(value).replace(/^(?:仓库|简尚|工厂|三方|京仓)\s*[--—]\s*/u,'').trim();} +export function compileMappings(mapping){ + if(!Array.isArray(mapping?.warehouses)||!mapping.warehouses.length||!Array.isArray(mapping.provinces)||!mapping.provinces.length)throw new Error('LOCAL_LOGISTICS_MAPPINGS_REQUIRED'); + const provinces=new Map(),warehouses=new Map(),aliases=new Map(),regions=[]; + for(const row of mapping.provinces){ + const key=provinceKey(row.province),region=text(row.region); + if(!key)throw new Error('EMPTY_MAPPING_PROVINCE'); + if(provinces.has(key)&&provinces.get(key).region!==region)throw new Error('CONFLICTING_PROVINCE_MAPPING'); + provinces.set(key,{province:text(row.province),region:region||UNMAPPED_REGION,index:provinces.size}); + if(region&&!regions.includes(region))regions.push(region); + } + for(const row of mapping.warehouses){ + const exact=text(row.warehouse),key=warehouseKey(row.warehouse),origin=text(row.origin); + if(!key||!origin)continue; + const exactValues=warehouses.get(exact)||new Set();exactValues.add(origin);warehouses.set(exact,exactValues); + const values=aliases.get(key)||new Set();values.add(origin);aliases.set(key,values); + } + return {provinces,warehouses,aliases,regions:[...regions,UNMAPPED_REGION]}; +} +export function buildRegionalDay(day,mapping){ + const compiled=compileMappings(mapping),rows=new Map(),originCounts=new Map(),unmappedWarehouses=new Map(),unmappedProvinces=new Map(); + const ids=new Set(); + for(const row of day.details){ + if(ids.has(row.o_id))throw new Error('DUPLICATE_REGIONAL_ORDER');ids.add(row.o_id); + if(row.send_date.slice(0,10)!==day.date)throw new Error('REGIONAL_DATE_MISMATCH'); + const exact=compiled.warehouses.get(text(row.warehouse_name)); + if(exact?.size>1)throw new Error('CONFLICTING_WAREHOUSE_ORIGIN_'+row.warehouse_name); + const origins=exact||compiled.aliases.get(warehouseKey(row.warehouse_name)); + const origin=origins?.size===1?[...origins][0]:UNMAPPED_ORIGIN; + const province=compiled.provinces.get(provinceKey(row.receiver_state))||{province:text(row.receiver_state)||'未填写省份',region:UNMAPPED_REGION,index:999}; + if(origin===UNMAPPED_ORIGIN)unmappedWarehouses.set(row.warehouse_name,(unmappedWarehouses.get(row.warehouse_name)||0)+1); + if(province.region===UNMAPPED_REGION)unmappedProvinces.set(province.province,(unmappedProvinces.get(province.province)||0)+1); + const carrier=row.logistics_company||'未填写快递名称'; + const key=JSON.stringify([origin,province.region,province.province,carrier]); + const current=rows.get(key)||{origin,region:province.region,province:province.province,provinceOrder:province.index,carrier,count:0};current.count++;rows.set(key,current); + originCounts.set(origin,(originCounts.get(origin)||0)+1); + } + if(ids.size!==day.total||[...rows.values()].reduce((n,row)=>n+row.count,0)!==day.total)throw new Error('REGIONAL_TOTAL_MISMATCH'); + const provinces=[...compiled.provinces.values()].map(row=>({region:row.region,province:row.province,provinceOrder:row.index})); + for(const row of rows.values())if(!provinces.some(item=>item.province===row.province&&item.region===row.region))provinces.push({region:row.region,province:row.province,provinceOrder:row.provinceOrder}); + return {date:day.date,total:day.total,rows:[...rows.values()],provinces,origins:[...originCounts].map(([name,total])=>({name,total})).sort(compareOrigins),regions:compiled.regions,unmappedWarehouses:[...unmappedWarehouses].map(([name,total])=>({name,total})),unmappedProvinces:[...unmappedProvinces].map(([name,total])=>({name,total}))}; +} +export function regionalPivot(day,origin=''){ + const facts=day.rows.filter(row=>!origin||row.origin===origin),carrierCounts=new Map(),provinceRows=new Map(); + for(const row of day.provinces)provinceRows.set(JSON.stringify([row.region,row.province]),{...row,counts:{},total:0}); + for(const row of facts){ + carrierCounts.set(row.carrier,(carrierCounts.get(row.carrier)||0)+row.count); + const key=JSON.stringify([row.region,row.province]);const province=provinceRows.get(key)||{region:row.region,province:row.province,provinceOrder:row.provinceOrder,counts:{},total:0}; + province.counts[row.carrier]=(province.counts[row.carrier]||0)+row.count;province.total+=row.count;provinceRows.set(key,province); + } + const carriers=[...carrierCounts].sort((a,b)=>b[1]-a[1]||a[0].localeCompare(b[0],'zh-CN')).map(([name])=>name),rows=[]; + for(const region of day.regions){ + const group=[...provinceRows.values()].filter(row=>row.region===region).sort((a,b)=>a.provinceOrder-b.provinceOrder||a.province.localeCompare(b.province,'zh-CN')); + if(!group.length)continue; + rows.push(...group.map(row=>({...row,kind:'province'}))); + const counts=Object.fromEntries(carriers.map(name=>[name,group.reduce((n,row)=>n+(row.counts[name]||0),0)])); + rows.push({region,province:region+'小计',kind:'subtotal',counts,total:group.reduce((n,row)=>n+row.total,0)}); + } + const total=[...carrierCounts.values()].reduce((n,value)=>n+value,0); + rows.push({region:'',province:'总计',kind:'total',counts:Object.fromEntries(carrierCounts),total}); + return {carriers,rows,total}; +} diff --git a/furniture-3d-system/scripts/daily-express-dashboard/regional.test.mjs b/furniture-3d-system/scripts/daily-express-dashboard/regional.test.mjs new file mode 100644 index 00000000..3910809d --- /dev/null +++ b/furniture-3d-system/scripts/daily-express-dashboard/regional.test.mjs @@ -0,0 +1,22 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {buildRegionalDay,regionalPivot,UNMAPPED_ORIGIN,UNMAPPED_REGION} from './regional.mjs'; +const map={provinces:[{province:'江苏',region:'一区'},{province:'山东',region:'二区'}],warehouses:[{warehouse:'崔桥工厂仓',origin:'常州'},{warehouse:'新苏北仓',origin:'苏北'}]}; +const order=(id,province,warehouse,carrier='快递甲')=>({o_id:id,receiver_state:province,warehouse_name:warehouse,logistics_company:carrier,send_date:'2026-11-24 12:00:00'}); +test('province aliases and local warehouse names map without changing totals',()=>{ + const day=buildRegionalDay({date:'2026-11-24',total:3,details:[order('1','江苏省','简尚-崔桥工厂仓'),order('2','山东省','简尚-新苏北仓'),order('3','江苏省','简尚-崔桥工厂仓','快递乙')]},map); + const all=regionalPivot(day),changzhou=regionalPivot(day,'常州');assert.equal(all.total,3);assert.equal(changzhou.total,2); + assert.equal(changzhou.rows.find(row=>row.kind==='subtotal').total,2);assert.deepEqual(changzhou.carriers,['快递甲','快递乙']); + assert.equal(day.rows.find(row=>row.province==='江苏').region,'一区'); +}); +test('unmatched keys stay visible and conflicting local mappings fail',()=>{ + const day=buildRegionalDay({date:'2026-11-24',total:1,details:[order('1','西藏','未知仓')]},map); + assert.equal(day.rows[0].origin,UNMAPPED_ORIGIN);assert.equal(day.rows[0].region,UNMAPPED_REGION);assert.equal(regionalPivot(day).total,1); + assert.throws(()=>buildRegionalDay({date:'2026-11-24',total:1,details:[order('1','江苏','崔桥工厂仓')]},{...map,warehouses:[...map.warehouses,{warehouse:'崔桥工厂仓',origin:'山东'}]}),/CONFLICTING/); +}); +test('missing mappings, duplicate orders and wrong dates cannot pass as valid data',()=>{ + assert.throws(()=>buildRegionalDay({date:'2026-11-24',total:0,details:[]},{provinces:[],warehouses:[]}),/REQUIRED/); + const row=order('1','江苏省','简尚-崔桥工厂仓'); + assert.throws(()=>buildRegionalDay({date:'2026-11-24',total:2,details:[row,row]},map),/DUPLICATE/); + assert.throws(()=>buildRegionalDay({date:'2026-11-25',total:1,details:[row]},map),/DATE/); +}); diff --git a/furniture-3d-system/scripts/daily-express-dashboard/report-db-readonly.cjs b/furniture-3d-system/scripts/daily-express-dashboard/report-db-readonly.cjs new file mode 100644 index 00000000..213d1ee7 --- /dev/null +++ b/furniture-3d-system/scripts/daily-express-dashboard/report-db-readonly.cjs @@ -0,0 +1,6 @@ +const {req,env}=require('./environment.cjs'),sql=req('mssql'); +const required=key=>{if(!env[key])throw new Error('MISSING_'+key);return env[key];}; +const schema=env.JST_REPORT_DB_SCHEMA||'rpt';if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(schema))throw new Error('INVALID_SCHEMA'); +const bool=key=>!['false','0'].includes(String(env[key]??'true').toLowerCase()); +const pool=new sql.ConnectionPool({server:required('JST_REPORT_DB_HOST'),port:Number(env.JST_REPORT_DB_PORT||1433),database:required('JST_REPORT_DB_NAME'),user:required('JST_REPORT_DB_USER'),password:required('JST_REPORT_DB_PASSWORD'),options:{encrypt:bool('JST_REPORT_DB_ENCRYPT'),trustServerCertificate:bool('JST_REPORT_DB_TRUST_SERVER_CERTIFICATE'),readOnlyIntent:true,useUTC:true,appName:'codex-province-alternative-readonly'},pool:{min:0,max:2,idleTimeoutMillis:30000},connectionTimeout:20000,requestTimeout:180000}); +module.exports={pool,sql,schema}; diff --git a/furniture-3d-system/scripts/daily-express-dashboard/run.mjs b/furniture-3d-system/scripts/daily-express-dashboard/run.mjs new file mode 100644 index 00000000..3b1d0506 --- /dev/null +++ b/furniture-3d-system/scripts/daily-express-dashboard/run.mjs @@ -0,0 +1,88 @@ +import fs from 'node:fs/promises'; +import path from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {spawn} from 'node:child_process'; +import environment from './environment.cjs'; +import {aggregateDay,validateDayDetails,windowDates,expiredSnapshotFiles,businessYesterday} from './core.mjs'; +import {completeDayProvinces,validateProvinceEnrichment,PROVINCE_VERSION} from './province.mjs'; +import {openSource} from './source.mjs'; +import {buildSnapshot,buildCarrierSnapshot,buildUncollectedSnapshot,readPreviousUncollected,retainPreviousUncollected,publishSnapshot} from './snapshot.mjs'; +import {deliverNotification,deliverExceptionNotification,validateNotificationReport,validateRobotConfig} from './uncollected-notifications.mjs'; +const root=path.dirname(fileURLToPath(import.meta.url)),{env,app}=environment; +const directory=path.resolve(env.DAILY_EXPRESS_DATA_DIR||path.join(app,'.daily-express')); +const read=async file=>JSON.parse(await fs.readFile(file,'utf8')); +const seed=process.argv.find(arg=>arg.startsWith('--seed='))?.slice(7); +const skipNotifications=process.argv.includes('--skip-notifications'); +const target=process.argv.find(arg=>arg.startsWith('--date='))?.slice(7)||businessYesterday(); +const startedAt=new Date().toISOString(); +async function child(file,args){await new Promise((resolve,reject)=>{ + const proc=spawn(process.execPath,[path.join(root,file),...args],{windowsHide:true,env:{...process.env,...env},stdio:['ignore','pipe','pipe']});let output=''; + proc.stdout.on('data',chunk=>{output+=chunk});proc.stderr.on('data',chunk=>{output+=chunk});proc.on('error',reject); + proc.on('exit',code=>{if(code===0)resolve();else{let last;for(const line of output.split('\n'))try{const item=JSON.parse(line);if(item.errorCode)last=item;}catch{} + reject(Object.assign(new Error('DAILY_EXPRESS_SOURCE_FAILED'),{code:last?.errorCode||'QUERY_FAILED',number:last?.number}));}}); + });} +let source,lock; +try{ + await fs.mkdir(directory,{recursive:true}); + const lockFile=path.join(directory,'generation.lock'); + try{lock=await fs.open(lockFile,'wx');}catch(error){ + if(error.code!=='EEXIST')throw error; + const owner=await read(lockFile); + try{process.kill(owner.pid,0);throw new Error('GENERATION_ALREADY_RUNNING');}catch(check){if(check.code!=='ESRCH')throw check;} + await fs.unlink(lockFile);lock=await fs.open(lockFile,'wx'); + } + await lock.writeFile(JSON.stringify({pid:process.pid,startedAt})); + const daysDir=seed?path.join(seed,'days'):path.join(directory,'days');await fs.mkdir(daysDir,{recursive:true}); + const snapshots=[]; + for(const date of windowDates(target)){ + const file=path.join(daysDir,date+'.json');let day; + try{day=validateDayDetails(await read(file));}catch(error){if(error.code!=='ENOENT')throw error;} + if(!day){if(seed)throw new Error('SEED_MISSING_DATE');source??=await openSource();day=aggregateDay(date,await source.fetchDay(date),source.warehouses);} + if(day.provinceEnrichment?.version!==PROVINCE_VERSION){source??=await openSource();const missing=day.details.filter(row=>!row.receiver_state.trim());day=completeDayProvinces(day,await source.fetchProvinceCandidates(missing));} + validateProvinceEnrichment(day);snapshots.push(day); + if(!seed){await fs.writeFile(file+'.tmp',JSON.stringify(day));await fs.rename(file+'.tmp',file);} + } + if(source){await source.close();source=null;} + const stage=seed?path.join(seed,'staging'):path.join(directory,'staging');await fs.mkdir(stage,{recursive:true}); + const mappings=await read(seed?path.join(seed,'local-logistics-mappings.json'):path.join(directory,'mappings.json')); + let built; + if(seed)built=buildSnapshot(snapshots,await read(path.join(stage,'uncollected-source.json')),await read(path.join(stage,'uncollected-refund-checks.json')),mappings); + else{ + const carrier=buildCarrierSnapshot(snapshots,mappings); + try{ + await child('fetch-uncollected.cjs',['--date='+target,'--output='+path.join(stage,'uncollected-source.json')]); + await child('fetch-refund-checks.cjs',['--source='+path.join(stage,'uncollected-source.json'),'--output='+path.join(stage,'uncollected-refund-checks.json')]); + const {uncollected,uncollectedRefresh}=buildUncollectedSnapshot(await read(path.join(stage,'uncollected-source.json')),await read(path.join(stage,'uncollected-refund-checks.json')),target); + validateNotificationReport(uncollected,{target,refreshedAfter:startedAt}); + built={...carrier,report:{...carrier.report,uncollected,...(uncollectedRefresh?{uncollectedRefresh}:{})}}; + }catch(error){ + const previous=await readPreviousUncollected(directory).catch(()=>{ + console.warn('PREVIOUS_UNCOLLECTED_UNAVAILABLE'); + return null; + }); + built=retainPreviousUncollected(carrier,previous,error); + } + } + const pointer=await publishSnapshot(directory,built); + if(seed){ + await fs.mkdir(path.join(directory,'days'),{recursive:true}); + for(const day of snapshots)await fs.writeFile(path.join(directory,'days',day.date+'.json'),JSON.stringify(day)); + await fs.writeFile(path.join(directory,'mappings.json'),JSON.stringify({version:mappings.version,provinces:mappings.provinces,warehouses:mappings.warehouses})); + } + let notification={status:seed?'seed_not_sent':'skipped'},exceptionNotification={status:'not_required'}; + if(!seed&&!skipNotifications){ + if(!env.DAILY_EXPRESS_DINGTALK_CONFIG)throw new Error('DINGTALK_CONFIG_REQUIRED'); + const config=validateRobotConfig(await read(env.DAILY_EXPRESS_DINGTALK_CONFIG)); + const refresh=built.report.uncollectedRefresh; + if(refresh?.status!=='failed')notification=await deliverNotification({directory:path.join(directory,'notifications'),report:{...built.report.uncollected,exceptionCount:refresh?.exceptions.length||0},config}); + else notification={status:'not_sent_refresh_failed'}; + if(refresh)exceptionNotification=await deliverExceptionNotification({directory:path.join(directory,'notifications'),refresh,config}); + } + else if(!seed&&built.report.uncollectedRefresh)exceptionNotification={status:'skipped'}; + const status={status:built.report.uncollectedRefresh?'partial':'success',date:target,generation:pointer.generation,total:built.report.overview.total,uncollected:built.report.uncollectedRefresh?.status==='failed'?null:built.report.uncollected.summary.total,uncollectedDate:built.report.uncollectedRefresh?.status==='failed'?null:built.report.uncollected.date,...(built.report.uncollectedRefresh?{errorCode:built.report.uncollectedRefresh.errorCode,exceptions:built.report.uncollectedRefresh.exceptions.length}:{}),notification,exceptionNotification,updatedAt:new Date().toISOString()}; + await fs.writeFile(path.join(directory,'last-run.json'),JSON.stringify(status)); + if(!seed)for(const name of expiredSnapshotFiles(await fs.readdir(daysDir),target))await fs.unlink(path.join(daysDir,name)); + console.log(JSON.stringify(status)); + if(built.report.uncollectedRefresh?.status==='failed')process.exitCode=1; +}catch(error){const status={status:'failed',date:target,errorCode:error.code||error.message||error.name,number:error.number||null,updatedAt:new Date().toISOString()};await fs.writeFile(path.join(directory,'last-run.json'),JSON.stringify(status));console.error(JSON.stringify(status));process.exitCode=1;} +finally{if(source)await source.close().catch(()=>{});if(lock){await lock.close();await fs.unlink(path.join(directory,'generation.lock'));}} diff --git a/furniture-3d-system/scripts/daily-express-dashboard/snapshot.mjs b/furniture-3d-system/scripts/daily-express-dashboard/snapshot.mjs new file mode 100644 index 00000000..cf6bf4a4 --- /dev/null +++ b/furniture-3d-system/scripts/daily-express-dashboard/snapshot.mjs @@ -0,0 +1,78 @@ +import fs from 'node:fs/promises'; +import path from 'node:path'; +import {createHash,randomUUID} from 'node:crypto'; +import assert from 'node:assert/strict'; +import {buildFacts,collectDetails,validateDayDetails} from './core.mjs'; +import {buildRegionalDay} from './regional.mjs'; +import {validateUncollected,applyUncollectedRules,hasAtInTracking,summarizeUncollected,UNCOLLECTED_COLUMNS} from './uncollected.mjs'; +import {partitionRefundChecks} from './refund.mjs'; +const hash=data=>createHash('sha256').update(data).digest('hex'); +export function buildSnapshot(days,source,refund,mappings){ + days.forEach(validateDayDetails);validateUncollected(source); + const latest=days.at(-1).date; + if(source.summary.date!==latest||refund.sourceQueriedAt!==source.summary.queriedAt)throw new Error('SNAPSHOT_SOURCE_MISMATCH'); + const carrier=buildCarrierSnapshot(days,mappings); + const {uncollected,uncollectedRefresh}=buildUncollectedSnapshot(source,refund,latest); + return {...carrier,report:{...carrier.report,uncollected,...(uncollectedRefresh?{uncollectedRefresh}:{})}}; +} +export function buildCarrierSnapshot(days,mappings){ + days.forEach(validateDayDetails); + const latest=days.at(-1).date; + const facts=buildFacts(days,latest),details=collectDetails(days); + const overview={dateFrom:facts.dateFrom,dateTo:facts.dateTo,days:facts.days,daily:facts.daily.map(({date,total})=>({date,total})),total:facts.total,carrierCount:facts.carrierCount,ranking:facts.ranking}; + const report={version:1,dateTo:latest,updatedAt:new Date().toISOString(),overview, + regional:{dates:facts.days,latestDate:latest,days:days.map(day=>buildRegionalDay(day,mappings))}}; + return {report,details}; +} +export function buildUncollectedSnapshot(source,refund,latest){ + validateUncollected(source); + if(source.summary.date!==latest||refund.sourceQueriedAt!==source.summary.queriedAt)throw new Error('SNAPSHOT_SOURCE_MISMATCH'); + const {checked,exceptions}=partitionRefundChecks(source.rows,refund,latest),rows=applyUncollectedRules(checked); + return {uncollected:{date:latest,queriedAt:source.summary.queriedAt,refundCheckedAt:refund.completedAt,summary:summarizeUncollected(rows),columns:UNCOLLECTED_COLUMNS.map(([key,label])=>({key,label})),rows}, + ...(exceptions.length?{uncollectedRefresh:{status:'partial',date:latest,attemptedAt:refund.completedAt,errorCode:'REFUND_RECORD_EXCEPTIONS',exceptions}}:{})}; +} +export async function readPreviousUncollected(directory){ + let pointer; + try { + pointer=JSON.parse(await fs.readFile(path.join(directory,'latest.json'),'utf8')); + } catch(error) { + if(error.code==='ENOENT')return null; + throw error; + } + if(!/^\d+-[a-f0-9-]+$/.test(pointer.generation))throw new Error('INVALID_PREVIOUS_GENERATION'); + const bytes=await fs.readFile(path.join(directory,'generations',pointer.generation,'report.json')); + if(hash(bytes)!==pointer.reportHash)throw new Error('PREVIOUS_SNAPSHOT_CORRUPTED'); + const report=JSON.parse(bytes); + const previous=report.uncollected; + if(previous===undefined&&report.uncollectedRefresh?.status==='failed')return null; + if(!previous)throw new Error('INVALID_PREVIOUS_UNCOLLECTED'); + validateUncollected({summary:{date:previous.date,queriedAt:previous.queriedAt,rowCount:previous.rows.length},rows:previous.rows}); + if(!Number.isFinite(Date.parse(previous.refundCheckedAt))||Date.parse(previous.refundCheckedAt)!hasAtInTracking(row)); + assert.deepEqual(applyUncollectedRules(rows),rows); + return rows.length===previous.rows.length?previous:{...previous,rows,summary:summarizeUncollected(rows)}; +} +export function retainPreviousUncollected(carrier,previous,error){ + if(previous&&previous.date>carrier.report.dateTo)throw new Error('PREVIOUS_UNCOLLECTED_FROM_FUTURE'); + const code=String(error.code||error.message||error.name); + return {...carrier,report:{...carrier.report,...(previous?{uncollected:previous}:{}), + uncollectedRefresh:{status:'failed',date:carrier.report.dateTo,attemptedAt:new Date().toISOString(),errorCode:/^[A-Z0-9_]{1,160}$/.test(code)?code:'UNCOLLECTED_REFRESH_FAILED',exceptions:[]}}}; +} +export async function publishSnapshot(directory,{report,details}){ + await fs.mkdir(directory,{recursive:true}); + let previous;try{previous=JSON.parse(await fs.readFile(path.join(directory,'latest.json'),'utf8'));}catch(error){if(error.code!=='ENOENT')throw error;} + if(previous&&previous.dateTo>report.dateTo)throw new Error('CANNOT_PUBLISH_OLDER_DATE'); + const generation=report.updatedAt.replace(/[^0-9]/g,'')+'-'+randomUUID(); + const target=path.join(directory,'generations',generation);await fs.mkdir(target,{recursive:true}); + const reportBytes=JSON.stringify(report),detailsBytes=JSON.stringify(details); + await fs.writeFile(path.join(target,'report.json'),reportBytes);await fs.writeFile(path.join(target,'details.json'),detailsBytes); + const pointer={version:1,generation,dateTo:report.dateTo,updatedAt:report.updatedAt,reportHash:hash(reportBytes),detailsHash:hash(detailsBytes)}; + const temporary=path.join(directory,'latest.'+randomUUID()+'.tmp');await fs.writeFile(temporary,JSON.stringify(pointer));await fs.rename(temporary,path.join(directory,'latest.json')); + // Expired generations contain order details; retain only the atomically selected generation. + for(const name of await fs.readdir(path.join(directory,'generations'))){if(name===generation||!/^\d+-[a-f0-9-]+$/.test(name))continue; + const expired=path.resolve(directory,'generations',name);if(path.dirname(expired)!==path.resolve(directory,'generations'))throw new Error('INVALID_RETENTION_PATH'); + await fs.rm(expired,{recursive:true,force:true}); + } + return pointer; +} diff --git a/furniture-3d-system/scripts/daily-express-dashboard/snapshot.test.mjs b/furniture-3d-system/scripts/daily-express-dashboard/snapshot.test.mjs new file mode 100644 index 00000000..5635752e --- /dev/null +++ b/furniture-3d-system/scripts/daily-express-dashboard/snapshot.test.mjs @@ -0,0 +1,105 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import {createHash} from 'node:crypto'; +import {aggregateDay} from './core.mjs'; +import {buildSnapshot,buildCarrierSnapshot,retainPreviousUncollected,readPreviousUncollected,publishSnapshot} from './snapshot.mjs'; +import {summarizeUncollected} from './uncollected.mjs'; +test('published snapshots reconcile all views and refuse older dates',async()=>{ + const day=aggregateDay('2026-11-24',[{o_id:'1',so_id:'001',source:'jst_Orders',status:'Sent',send_date:'2026-11-24 10:00:00',l_id:'001234',logistics_company:'测试快递',receiver_state:'江苏',co_id:'1',wms_co_id:'2'}],[{co_id:'1',wms_co_id:'2',name:'测试仓'}]); + const queriedAt='2026-11-25T01:00:00Z',source={summary:{date:day.date,queriedAt,rowCount:0},rows:[]}; + const refund={version:'item-refund-success-v1',date:day.date,sourceQueriedAt:queriedAt,completedAt:queriedAt,candidates:[],masters:[],items:[]}; + const built=buildSnapshot([day],source,refund,{provinces:[{province:'江苏',region:'华东'}],warehouses:[{warehouse:'测试仓',origin:'常州自有仓'}]}); + assert.equal(built.report.overview.total,1);assert.equal(built.report.regional.days[0].total,1);assert.equal(built.report.uncollected.summary.total,0);assert.equal(built.details[0].l_id,'001234'); + assert.throws(()=>buildSnapshot([day],{...source,summary:{...source.summary,date:'2026-11-23'}},refund,{}),/SOURCE_MISMATCH/); + const root=await fs.mkdtemp(path.join(os.tmpdir(),'express-snapshot-')); + try{await publishSnapshot(root,built);const pointer=JSON.parse(await fs.readFile(path.join(root,'latest.json'),'utf8'));const bytes=await fs.readFile(path.join(root,'generations',pointer.generation,'report.json'));assert.equal(pointer.reportHash,createHash('sha256').update(bytes).digest('hex'));await assert.rejects(()=>publishSnapshot(root,{...built,report:{...built.report,dateTo:'2026-11-23'}}),/OLDER_DATE/);} + finally{assert.equal(path.dirname(root),os.tmpdir());await fs.rm(root,{recursive:true,force:true});} +}); + +test('a failed pickup refresh preserves verified prior pickup while advancing carrier and regional dates',async()=>{ + const mapping={provinces:[{province:'江苏',region:'华东'}],warehouses:[{warehouse:'测试仓',origin:'常州自有仓'}]}; + const warehouse=[{co_id:'1',wms_co_id:'2',name:'测试仓'}]; + const day=date=>aggregateDay(date,[{o_id:date,so_id:'001',source:'jst_Orders',status:'Sent',send_date:date+' 10:00:00',l_id:'001234',logistics_company:'测试快递',receiver_state:'江苏',co_id:'1',wms_co_id:'2'}],warehouse); + const first=day('2026-11-24'),second=day('2026-11-25'),queriedAt='2026-11-25T01:00:00Z'; + const initial=buildSnapshot([first],{summary:{date:first.date,queriedAt,rowCount:0},rows:[]},{version:'item-refund-success-v1',date:first.date,sourceQueriedAt:queriedAt,completedAt:queriedAt,candidates:[],masters:[],items:[]},mapping); + const root=await fs.mkdtemp(path.join(os.tmpdir(),'express-partial-')); + try{ + await publishSnapshot(root,initial); + const previous=await readPreviousUncollected(root); + const next=retainPreviousUncollected(buildCarrierSnapshot([first,second],mapping),previous,new Error('REFUND_ITEMS_NOT_FOUND_10366147')); + assert.deepEqual(next.report.overview.days,['2026-11-24','2026-11-25']);assert.equal(next.report.overview.total,2); + assert.equal(next.report.regional.latestDate,'2026-11-25');assert.deepEqual(next.report.uncollected,initial.report.uncollected); + assert.equal(next.report.uncollectedRefresh.date,'2026-11-25');assert.equal(next.report.uncollectedRefresh.errorCode,'REFUND_ITEMS_NOT_FOUND_10366147'); + await publishSnapshot(root,next); + assert.deepEqual(await readPreviousUncollected(root),previous); + assert.throws(()=>retainPreviousUncollected(buildCarrierSnapshot([first],mapping),{...previous,date:'2026-11-26'},new Error('FAIL')),/FROM_FUTURE/); + const pointer=JSON.parse(await fs.readFile(path.join(root,'latest.json'),'utf8')); + await fs.appendFile(path.join(root,'generations',pointer.generation,'report.json'),' '); + await assert.rejects(()=>readPreviousUncollected(root),/CORRUPTED/); + }finally{assert.equal(path.dirname(root),os.tmpdir());await fs.rm(root,{recursive:true,force:true});} +}); + +test('carrier and regional data can publish when pickup has never refreshed successfully', async () => { + const day = aggregateDay('2026-11-24', [], []); + const carrier = buildCarrierSnapshot([day], { + provinces: [{ province: '江苏', region: '华东' }], + warehouses: [{ warehouse: '测试仓', origin: '常州自有仓' }], + }); + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'express-first-refresh-')); + try { + const previous = await readPreviousUncollected(root); + assert.equal(previous, null); + const failed = retainPreviousUncollected(carrier, previous, new Error('QUERY_FAILED')); + assert.equal(failed.report.uncollected, undefined); + assert.equal(failed.report.uncollectedRefresh.status, 'failed'); + assert.equal(failed.report.overview.dateTo, day.date); + assert.equal(failed.report.regional.latestDate, day.date); + await publishSnapshot(root, failed); + assert.equal(await readPreviousUncollected(root), null); + } finally { + assert.equal(path.dirname(root), os.tmpdir()); + await fs.rm(root, { recursive: true, force: true }); + } +}); + +test('the published current pickup includes verified rows and separately records incomplete orders',()=>{ + const date='2026-11-25',queriedAt='2026-11-26T01:00:00Z'; + const day=aggregateDay(date,[],[]); + const records=[1,2].map(id=>({id,inner_order_id:String(id),so_id:'S'+id,logistic_id:'L'+id,logistic_company_name:'测试快递',warehouse_name:'测试仓',send_time:date+' 10:00:00',fetch_time:null,logistic_status_name:'未揽收',first_question_type:null,order_labels:null,remark:null})); + const excluded={...records[0],id:3,inner_order_id:'3',so_id:'S3',logistic_id:'L3@L4'}; + const source={summary:{date,queriedAt,rowCount:3},rows:[...records,excluded]}; + const audit={version:'item-refund-success-v1',date,sourceQueriedAt:queriedAt,completedAt:queriedAt,candidates:records.map(row=>({id:String(row.id),o_id:row.inner_order_id,so_id:row.so_id,l_id:row.logistic_id})),masters:records.map(row=>({source:'jst_qmcust_orderlist',o_id:row.inner_order_id,so_id:row.so_id,l_id:row.logistic_id})),items:[{source:'jst_qmcust_orderlist_item',o_id:'1',oi_id:'I1',refund_status:''}]}; + const days=[aggregateDay('2026-11-24',[],[]),day]; + const mappings={provinces:[{province:'江苏',region:'华东'}],warehouses:[{warehouse:'测试仓',origin:'常州'}]}; + const built=buildSnapshot(days,source,audit,mappings); + assert.equal(built.report.uncollected.date,date);assert.deepEqual(built.report.uncollected.rows.map(row=>row.id),[1]); + assert.equal(built.report.uncollected.summary.total,1);assert.equal(built.report.uncollectedRefresh.status,'partial'); + assert.equal(built.report.uncollectedRefresh.exceptions[0].inner_order_id,'2');assert.equal(built.report.overview.dateTo,date); + assert.equal(built.report.uncollectedRefresh.exceptions.length,1); + const legacyCandidate={id:'3',o_id:'3',so_id:'S3',l_id:excluded.logistic_id}; + const legacyAudit={...audit,candidates:[...audit.candidates,legacyCandidate]}; + assert.deepEqual(buildSnapshot(days,source,legacyAudit,mappings).report.uncollected,built.report.uncollected); + assert.throws(()=>buildSnapshot(days,source,{...audit,candidates:[...audit.candidates,{...legacyCandidate,so_id:'WRONG'}]},mappings),/REFUND_CANDIDATE_MISMATCH/); +}); + +test('legacy pickup snapshots retain their verified rows with refreshed totals after removing @ tracking numbers', async () => { + const date='2026-11-24',queriedAt='2026-11-25T01:00:00Z'; + const row={id:1,inner_order_id:'1',logistic_id:'001234',logistic_status_name:'未揽收',send_time:date+' 10:00:00',fetch_time:null,order_labels:null,remark:null,refund_checked:true,refund_success:false}; + const rows=[row,{...row,id:2,inner_order_id:'2',logistic_id:'00234@00567'}]; + const carrier=buildCarrierSnapshot([aggregateDay(date,[],[])],{ + provinces:[{province:'江苏',region:'华东'}], + warehouses:[{warehouse:'测试仓',origin:'常州自有仓'}], + }); + const root=await fs.mkdtemp(path.join(os.tmpdir(),'express-legacy-tracking-')); + try { + const uncollected={date,queriedAt,refundCheckedAt:queriedAt,columns:[],rows,summary:summarizeUncollected(rows)}; + await publishSnapshot(root,{...carrier,report:{...carrier.report,uncollected}}); + assert.deepEqual(await readPreviousUncollected(root),{...uncollected,rows:[row],summary:summarizeUncollected([row])}); + } finally { + assert.equal(path.dirname(root),os.tmpdir()); + await fs.rm(root,{recursive:true,force:true}); + } +}); diff --git a/furniture-3d-system/scripts/daily-express-dashboard/source.mjs b/furniture-3d-system/scripts/daily-express-dashboard/source.mjs new file mode 100644 index 00000000..c99b8942 --- /dev/null +++ b/furniture-3d-system/scripts/daily-express-dashboard/source.mjs @@ -0,0 +1,40 @@ +import fs from 'node:fs'; +import {createRequire} from 'node:module'; +import {addDays,assertDate,SOURCES} from './core.mjs'; +import environment from './environment.cjs'; +const {app}=environment; +const require=createRequire(app+'/package.json'),sql=require('mssql'); +export async function openSource(){ + const {env}=environment; + const required=key=>{if(!env[key])throw Object.assign(new Error('Missing configuration'),{code:'MISSING_'+key});return env[key];}; + const schema=env.JST_REPORT_DB_SCHEMA||'rpt';if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(schema))throw new Error('INVALID_SCHEMA'); + const bool=key=>!['false','0'].includes(String(env[key]??'true').toLowerCase()); + const pool=new sql.ConnectionPool({server:required('JST_REPORT_DB_HOST'),port:Number(env.JST_REPORT_DB_PORT||1433),database:required('JST_REPORT_DB_NAME'),user:required('JST_REPORT_DB_USER'),password:required('JST_REPORT_DB_PASSWORD'),options:{encrypt:bool('JST_REPORT_DB_ENCRYPT'),trustServerCertificate:bool('JST_REPORT_DB_TRUST_SERVER_CERTIFICATE'),readOnlyIntent:true,appName:'codex-carrier-daily-readonly',useUTC:true},pool:{min:0,max:2,idleTimeoutMillis:30000},connectionTimeout:20000,requestTimeout:180000}); + await pool.connect(); + try{ + const warehouses=(await pool.request().query(`SET LOCK_TIMEOUT 15000; SELECT CAST(co_id AS varchar(40)) AS co_id,CAST(wms_co_id AS varchar(40)) AS wms_co_id,name FROM [${schema}].[jst_warehouseInfo];`)).recordset; + const fetchRange=async(from,to)=>{ + assertDate(from);assertDate(to);if(to<=from)throw new Error('INVALID_SOURCE_RANGE'); + const results=await Promise.allSettled(SOURCES.map(async source=>{ + const startedAt=Date.now();console.log(JSON.stringify({from,toExclusive:to,source,stage:'source_started'})); + const result=await pool.request().input('start',sql.Date,from).input('end',sql.Date,to).query(`SET LOCK_TIMEOUT 15000; +SELECT CAST(o_id AS varchar(40)) AS o_id,so_id,logistics_company,l_id,receiver_state,CONVERT(varchar(23),send_date,121) AS send_date,CAST(co_id AS varchar(40)) AS co_id,CAST(wms_co_id AS varchar(40)) AS wms_co_id,status +FROM [${schema}].[${source}] WHERE send_date>=@start AND send_date<@end;`); + const rows=result.recordset.filter(r=>r.status==='Sent').map(r=>({...r,source})); + console.log(JSON.stringify({from,toExclusive:to,source,stage:'source_complete',rows:rows.length,elapsedSeconds:Math.round((Date.now()-startedAt)/1000)}));return rows; + })); + for(const result of results)if(result.status==='rejected')throw result.reason; + return results.flatMap(result=>result.value); + }; + const fetchProvinceCandidates=async details=>{ + if(!details.length)return []; + const result=await pool.request().input('ids',sql.NVarChar(sql.MAX),JSON.stringify(details.map(row=>row.o_id))).query(`SET LOCK_TIMEOUT 15000; +SELECT CAST(inner_order_id AS varchar(40)) AS o_id,so_id,logistic_id AS l_id, +LEFT(LTRIM(receiver_address),CHARINDEX(N'-',LTRIM(receiver_address)+N'-')-1) AS region +FROM [${schema}].[jst_order_express_details] +WHERE inner_order_id IN (SELECT CONVERT(bigint,value) FROM OPENJSON(@ids));`); + return result.recordset; + }; + return {warehouses,close:()=>pool.close(),fetchRange,fetchDay:date=>fetchRange(date,addDays(date,1)),fetchProvinceCandidates}; + }catch(error){await pool.close();throw error;} +} diff --git a/furniture-3d-system/scripts/daily-express-dashboard/uncollected-notifications.mjs b/furniture-3d-system/scripts/daily-express-dashboard/uncollected-notifications.mjs new file mode 100644 index 00000000..3387c7a6 --- /dev/null +++ b/furniture-3d-system/scripts/daily-express-dashboard/uncollected-notifications.mjs @@ -0,0 +1,212 @@ +import fs from 'node:fs/promises'; +import path from 'node:path'; +import assert from 'node:assert/strict'; +import {createHash,createHmac} from 'node:crypto'; +import {businessYesterday,addDays} from './core.mjs'; +import {validateUncollected,applyUncollectedRules,summarizeUncollected} from './uncollected.mjs'; +import {attachRefundChecks} from './refund.mjs'; + +const hash=value=>createHash('sha256').update(value).digest('hex'); +const fail=code=>Object.assign(new Error(code),{code}); +const readJson=async file=>JSON.parse(await fs.readFile(file,'utf8')); +const singleLine=value=>String(value??'').replace(/[\r\n\t]+/g,' ').trim()||'未填写'; +const localTime=value=>new Intl.DateTimeFormat('sv-SE',{timeZone:'Asia/Shanghai',year:'numeric',month:'2-digit',day:'2-digit',hour:'2-digit',minute:'2-digit',second:'2-digit',hour12:false}).format(new Date(value)); +async function saveJson(file,value){ + await fs.writeFile(file+'.tmp',JSON.stringify(value,null,2)); + await fs.rename(file+'.tmp',file); +} + +export function validateNotificationReport(report,{target,now=new Date(),refreshedAfter,reviewedSnapshot=false}){ + if(target!==businessYesterday(now)||report.date!==target)throw fail('NOTIFICATION_NOT_YESTERDAY'); + const queried=Date.parse(report.queriedAt),refund=Date.parse(report.refundCheckedAt); + if(!Number.isFinite(queried)||!Number.isFinite(refund)||queried>+now||refund>+now||refundBuffer.byteLength(messagePrefix+block,'utf8')<=budget; + // Keep all tracking numbers of a carrier together, but never mix their warehouses. + const carriers=new Map(); + for(const row of report.rows){ + const carrier=String(row.logistic_company_name??'').trim(),warehouse=String(row.warehouse_name??'').trim(); + if(!carriers.has(carrier))carriers.set(carrier,new Map()); + const warehouses=carriers.get(carrier); + if(!warehouses.has(warehouse))warehouses.set(warehouse,[]); + warehouses.get(warehouse).push(singleLine(row.logistic_id)); + } + const blocks=[];let groupIndex=0; + const carrierOrder=new Intl.Collator('zh-CN',{numeric:true}); + for(const [carrier,warehouses] of [...carriers].sort(([a],[b])=>carrierOrder.compare(a,b)))for(const [warehouse,trackingNumbers] of warehouses){ + groupIndex++;let currentTracking=[],continuation=false; + const render=numbers=>`${groupIndex}. 快递单号${continuation?'(续)':''}:\n${numbers.join('\n')}\n快递名称:${singleLine(carrier)}\n发货仓库:${singleLine(warehouse)}`; + for(const tracking of trackingNumbers){ + if(!fits(render([...currentTracking,tracking]))){ + if(!currentTracking.length)throw fail('NOTIFICATION_ROW_TOO_LONG'); + blocks.push(render(currentTracking));currentTracking=[];continuation=true; + } + if(!fits(render([tracking])))throw fail('NOTIFICATION_ROW_TOO_LONG'); + currentTracking.push(tracking); + } + if(currentTracking.length)blocks.push(render(currentTracking)); + } + const groups=[];let current=[]; + for(const block of blocks){ + if(current.length&&!fits([...current,block].join('\n\n'))){groups.push(current);current=[];} + current.push(block); + } + if(current.length||groups.length===0)groups.push(current); + return groups.map((group,index)=>header+(groups.length>1?`\n第 ${index+1}/${groups.length} 条消息`:'')+'\n\n'+(group.length?group.join('\n\n'):(report.exceptionCount?'本次暂无已核对成功的未揽收订单。':'昨日无符合条件的未揽收订单。'))); +} + +export function exceptionReason(code){ + if(code.startsWith('REFUND_ITEMS_NOT_FOUND_'))return '缺少商品明细,退款状态未核实'; + if(code.startsWith('REFUND_ORDER_NOT_FOUND_'))return '未找到源订单,退款状态未核实'; + if(code.startsWith('REFUND_ORDER_IDENTITY_MISMATCH_'))return '源订单与物流信息不一致'; + if(code==='INVALID_REFUND_ITEM')return '商品明细缺少退款核对字段'; + if(code==='DUPLICATE_REFUND_ITEM')return '商品明细重复,需核对'; + return '本次数据查询或校验未完成'; +} +export function buildExceptionTexts(report,{keyword=''}={}){ + const header=`未揽收数据核对异常\n发货日期:${report.date}\n核对时间:${localTime(report.queriedAt)}(北京时间)\n${report.rows.length?`异常:${report.rows.length} 条,未计入正常未揽收明细。`:'本次数据更新未完成,未发送正常未揽收明细。'}`; + const blocks=report.rows.map((row,index)=>`${index+1}. ERP内部订单号:${singleLine(row.inner_order_id)}\n快递单号:${singleLine(row.logistic_id)}\n快递名称:${singleLine(row.logistic_company_name)}\n发货仓库:${singleLine(row.warehouse_name)}\n异常原因:${exceptionReason(row.errorCode)}`); + if(!blocks.length)blocks.push(exceptionReason(report.errorCode)); + const messages=[];let current=[]; + const fits=body=>Buffer.byteLength(header+'\n第 999999/999999 条消息\n\n'+body,'utf8')<=14000-Buffer.byteLength(keyword,'utf8'); + for(const block of blocks){if(!fits(block))throw fail('NOTIFICATION_ROW_TOO_LONG');if(current.length&&!fits([...current,block].join('\n\n'))){messages.push(current);current=[];}current.push(block);} + if(current.length)messages.push(current); + return messages.map((parts,i)=>header+(messages.length>1?`\n第 ${i+1}/${messages.length} 条消息`:'')+'\n\n'+parts.join('\n\n')); +} +export async function deliverExceptionNotification({refresh,now=new Date(),...options}){ + if(refresh.date!==businessYesterday(now)||!Number.isFinite(Date.parse(refresh.attemptedAt))||!Array.isArray(refresh.exceptions))throw fail('INVALID_EXCEPTION_REPORT'); + for(const row of refresh.exceptions)if(!row.id||!row.inner_order_id||!row.errorCode)throw fail('INVALID_EXCEPTION_ROW'); + return deliverNotification({...options,kind:'exceptions',deliveryRevision:'exceptions-v1',report:{date:refresh.date,queriedAt:refresh.attemptedAt,refundCheckedAt:refresh.attemptedAt,errorCode:refresh.errorCode,rows:refresh.exceptions}}); +} + +export function validateRobotConfig(config){ + let url;try{url=new URL(config.webhook);}catch{throw fail('INVALID_DINGTALK_CONFIGURATION');} + if(url.protocol!=='https:'||url.hostname!=='oapi.dingtalk.com'||url.port||url.pathname!=='/robot/send'||url.username||url.password||url.hash||!url.searchParams.get('access_token')||url.searchParams.has('sign')||url.searchParams.has('timestamp'))throw fail('INVALID_DINGTALK_CONFIGURATION'); + if(!Array.isArray(config.atMobiles)||typeof config.isAtAll!=='boolean')throw fail('INVALID_DINGTALK_RECIPIENTS'); + return config; +} + +export async function loadNotificationConfig(root){ + const settings=await readJson(path.join(root,'notification-config.json')); + if(settings.enabled!==true)throw fail('NOTIFICATIONS_DISABLED'); + const original=await readJson(settings.offboardingTaskConfigPath); + if(!path.isAbsolute(original.notificationConfigPath))throw fail('INVALID_ORIGINAL_NOTIFICATION_PATH'); + return validateRobotConfig(await readJson(original.notificationConfigPath)); +} + +export function buildRobotRequest(config,text,now=Date.now()){ + validateRobotConfig(config); + const url=new URL(config.webhook); + if(config.secret){ + const timestamp=String(now); + const signature=createHmac('sha256',config.secret).update(timestamp+'\n'+config.secret).digest('base64'); + url.searchParams.set('timestamp',timestamp);url.searchParams.set('sign',signature); + } + const content=(config.keyword?config.keyword+'\n':'')+text; + const body=JSON.stringify({msgtype:'text',text:{content},at:{atMobiles:config.atMobiles,isAtAll:config.isAtAll}}); + if(Buffer.byteLength(body,'utf8')>18000)throw fail('NOTIFICATION_MESSAGE_TOO_LONG'); + return {url:url.href,body}; +} + +export async function sendRobotText(config,text){ + const request=buildRobotRequest(config,text); + let response,answer; + try{ + response=await fetch(request.url,{method:'POST',headers:{'Content-Type':'application/json; charset=utf-8'},body:request.body,redirect:'error',signal:AbortSignal.timeout(15000)}); + answer=await response.json(); + }catch{throw fail('DINGTALK_DELIVERY_UNKNOWN');} + if(!response.ok||!Number.isInteger(answer?.errcode))throw fail('DINGTALK_DELIVERY_UNKNOWN'); + if(answer.errcode!==0)throw Object.assign(fail('DINGTALK_REJECTED_'+answer.errcode),{definitelyRejected:true}); + return {accepted:true,acceptedAt:new Date().toISOString()}; +} + +async function lockDelivery(directory){ + await fs.mkdir(directory,{recursive:true}); + const file=path.join(directory,'send.lock'); + const open=async()=>{const handle=await fs.open(file,'wx');await handle.writeFile(JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()}));return handle;}; + let handle; + try{handle=await open();}catch(error){ + if(error.code!=='EEXIST')throw error; + const holder=await readJson(file); + try{process.kill(holder.pid,0);throw fail('NOTIFICATION_ALREADY_RUNNING');}catch(check){if(check.code!=='ESRCH')throw check;} + await fs.unlink(file);handle=await open(); + } + return async()=>{await handle.close();await fs.unlink(file);}; +} + +export async function deliverNotification({directory,report,config,reviewedSnapshot=false,deliveryRevision='',kind='uncollected',transport=sendRobotText,pause=ms=>new Promise(resolve=>setTimeout(resolve,ms))}){ + validateRobotConfig(config); + if(!['uncollected','exceptions'].includes(kind))throw fail('INVALID_NOTIFICATION_KIND'); + if(deliveryRevision&&!/^[a-z][a-z0-9-]{0,40}$/.test(deliveryRevision))throw fail('INVALID_NOTIFICATION_REVISION'); + const release=await lockDelivery(directory); + try{ + const filename=path.join(directory,report.date+(deliveryRevision?'.'+deliveryRevision:'')+'.json'); + const destination=hash(config.webhook); + let state;try{state=await readJson(filename);}catch(error){if(error.code!=='ENOENT')throw error;} + if(state&&state.destination!==destination)throw fail('NOTIFICATION_DESTINATION_CHANGED'); + if(state?.status==='sent')return {status:'already_sent',date:state.date,total:state.total,parts:state.parts.length,sentAt:state.sentAt}; + if(state?.parts.some(part=>part.status==='sending'||part.status==='unknown'))throw fail('DINGTALK_DELIVERY_NEEDS_RECONCILIATION'); + if(!state){ + state={version:1,format:kind==='exceptions'?'exceptions-v1':'carrier-name-sorted-v3',deliveryRevision,date:report.date,total:report.rows.length,queriedAt:report.queriedAt,refundCheckedAt:report.refundCheckedAt,destination,reviewedSnapshot,status:'pending',createdAt:new Date().toISOString(),parts:(kind==='exceptions'?buildExceptionTexts:buildNotificationTexts)(report,{keyword:config.keyword,reviewedSnapshot}).map((text,index)=>({index,text,status:'pending',attempts:0}))}; + await saveJson(filename,state); + } + // Retain only this task's last 15 shipment dates, including message bodies. + for(const name of await fs.readdir(directory))if(/^\d{4}-\d{2}-\d{2}(?:\.[a-z][a-z0-9-]{0,40})?\.json$/.test(name)&&name.slice(0,10)({id,inner_order_id:String(id),logistic_id:'3311719'+String(id).padStart(6,'0'),logistic_company_name:'测试中通',warehouse_name:'常州测试仓',send_time:'2026-11-24 11:15:00',fetch_time:null,logistic_status_name:'未揽收',order_status_name:'已发货',first_question_type:null,order_labels:'',remark:'',refund_checked:true,refund_success:false}); +function report(count=2){const rows=Array.from({length:count},(_,i)=>row(i+1));return {date:'2026-11-24',queriedAt:'2026-11-25T01:01:00Z',refundCheckedAt:'2026-11-25T01:02:00Z',rows,summary:summarizeUncollected(rows)};} +const gate={target:'2026-11-24',now:new Date('2026-11-25T01:05:00Z'),refreshedAfter:'2026-11-25T01:00:00Z'}; +async function fixture(action){const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jst-notification-test-'));try{await action(dir);}finally{assert.ok(path.resolve(dir).startsWith(path.resolve(os.tmpdir())+path.sep));await fs.rm(dir,{recursive:true,force:true});}} +const accepted=()=>Promise.resolve({accepted:true,acceptedAt:'2026-11-25T01:05:00Z'}); + +test('successful current rows and exceptions use separate idempotent messages and receipts',async()=>{ + const value=report(1);value.exceptionCount=1; + const refresh={status:'partial',date:value.date,attemptedAt:value.refundCheckedAt,errorCode:'REFUND_RECORD_EXCEPTIONS',exceptions:[{id:'2',inner_order_id:'10366147',logistic_id:'773453795323647',logistic_company_name:'异常测试快递',warehouse_name:'异常测试仓',errorCode:'REFUND_ITEMS_NOT_FOUND_10366147'}]}; + assert.match(buildNotificationTexts(value)[0],/已核对成功的未揽收:1 单/); + assert.doesNotMatch(buildNotificationTexts(value)[0],/773453795323647/); + const errorText=buildExceptionTexts({date:value.date,queriedAt:value.refundCheckedAt,rows:refresh.exceptions})[0]; + assert.match(errorText,/10366147/);assert.match(errorText,/缺少商品明细/);assert.match(errorText,/未计入正常未揽收明细/); + await fixture(async directory=>{ + const messages=[],transport=async(_,text)=>{messages.push(text);return accepted();}; + await deliverNotification({directory,report:value,config,transport}); + await deliverExceptionNotification({directory,refresh,config,transport,now:gate.now}); + await deliverNotification({directory,report:value,config,transport}); + await deliverExceptionNotification({directory,refresh,config,transport,now:gate.now}); + assert.equal(messages.length,2);assert.match(messages[0],/昨日未揽收订单提醒/);assert.match(messages[1],/未揽收数据核对异常/); + assert.deepEqual((await fs.readdir(directory)).sort(),['2026-11-24.exceptions-v1.json','2026-11-24.json']); + }); +}); + +test('same carrier and warehouse share one tracking list, name and warehouse label',()=>{ + const value=report();validateNotificationReport(value,gate); + const texts=buildNotificationTexts(value); + assert.equal(texts.length,1);assert.match(texts[0],/发货日期:2026-11-24/);assert.match(texts[0],/数据查询:2026-11-25 09:01:00/); + assert.ok(texts[0].includes('快递单号:\n'+value.rows.map(item=>item.logistic_id).join('\n'))); + assert.equal(texts[0].split('快递名称:测试中通').length-1,1);assert.equal(texts[0].split('发货仓库:常州测试仓').length-1,1); + assert.ok(!texts[0].includes('内部订单号'));assert.ok(!texts[0].includes('已剔除'));assert.ok(!texts[0].includes('占比')); +}); +test('carriers stay together and separate warehouses preserve the correct tracking lists',()=>{ + const value=report(5); + value.rows[1].logistic_company_name='另一家快递'; + value.rows[2].warehouse_name='山东测试仓'; + value.rows[4].warehouse_name='山东测试仓'; + const text=buildNotificationTexts(value)[0]; + const blocks=text.split(/\n\n/).slice(1); + assert.equal(blocks.length,3); + assert.ok(blocks[0].includes(value.rows[0].logistic_id+'\n'+value.rows[3].logistic_id)); + assert.ok(blocks[0].endsWith('快递名称:测试中通\n发货仓库:常州测试仓')); + assert.ok(blocks[1].includes(value.rows[2].logistic_id+'\n'+value.rows[4].logistic_id)); + assert.ok(blocks[1].endsWith('快递名称:测试中通\n发货仓库:山东测试仓')); + assert.ok(blocks[2].endsWith('快递名称:另一家快递\n发货仓库:常州测试仓')); +}); +test('failed refresh, stale date, unchecked refund and mismatched totals cannot send',()=>{ + assert.throws(()=>validateNotificationReport(report(),{...gate,refreshedAfter:'2026-11-25T01:03:00Z'}),/NOT_REFRESHED/); + assert.throws(()=>validateNotificationReport(report(),{...gate,target:'2026-11-23'}),/NOT_YESTERDAY/); + const stale=report();stale.queriedAt='2026-11-24T00:00:00Z';assert.throws(()=>validateNotificationReport(stale,{...gate,reviewedSnapshot:true}),/STALE_QUERY/); + const unchecked=report();unchecked.rows[0].refund_checked=false;assert.throws(()=>validateNotificationReport(unchecked,gate),/REFUND_STATUS_NOT_CHECKED/); + const refund=report();refund.rows[0].refund_success=true;assert.throws(()=>validateNotificationReport(refund,gate)); + const atTracking=report();atTracking.rows[0].logistic_id+='@123';assert.throws(()=>validateNotificationReport(atTracking,gate),/excluded records/); + const wrong=report();wrong.summary.total++;assert.throws(()=>validateNotificationReport(wrong,gate)); +}); +test('large results split without truncation, zero results still notify, request preserves recipient settings and signing',()=>{ + const value=report(1500),texts=buildNotificationTexts(value,{keyword:config.keyword});assert.ok(texts.length>1); + for(const text of texts){const request=buildRobotRequest(config,text,1795568700000);assert.ok(Buffer.byteLength(request.body)<18000);const body=JSON.parse(request.body);assert.deepEqual(body.at,{atMobiles:[],isAtAll:false});assert.equal(body.msgtype,'text');assert.ok(body.text.content.startsWith(config.keyword+'\n'));const u=new URL(request.url);assert.equal(u.searchParams.get('sign'),createHmac('sha256',config.secret).update('1795568700000\n'+config.secret).digest('base64'));} + for(const item of value.rows)assert.equal(texts.join('\n').split('\n'+item.logistic_id+'\n').length-1,1); + for(const text of texts){assert.match(text,/快递名称:测试中通/);assert.match(text,/发货仓库:常州测试仓/);} + assert.match(texts[1],/快递单号(续)/); + assert.match(buildNotificationTexts(report(0))[0],/未揽收:0 单/); + assert.throws(()=>buildRobotRequest({...config,webhook:'https://example.com/robot/send?access_token=x'},'test'),/INVALID_DINGTALK/); +}); +test('successful daily delivery does not resend even if later data changes',async()=>fixture(async directory=>{ + let calls=0;const transport=async()=>{calls++;return accepted();}; + assert.equal((await deliverNotification({directory,report:report(),config,transport})).status,'sent'); + assert.equal((await deliverNotification({directory,report:report(3),config,transport})).status,'already_sent');assert.equal(calls,1); +})); +test('explicit rejection resumes only unsent parts and retains the original report',async()=>fixture(async directory=>{ + let calls=0,first; + const many=report(1500); + await assert.rejects(()=>deliverNotification({directory,report:many,config,pause:async()=>{},transport:async(_,text)=>{calls++;if(calls===1){first=text;return accepted();}throw Object.assign(new Error('reject'),{code:'DINGTALK_REJECTED_130101',definitelyRejected:true});}}),/DINGTALK_REJECTED/); + const saved=JSON.parse(await fs.readFile(path.join(directory,many.date+'.json'),'utf8')); + assert.equal(saved.parts[0].status,'sent');assert.equal(saved.parts[1].status,'pending'); + const resumed=[];const result=await deliverNotification({directory,report:report(1),config,pause:async()=>{},transport:async(_,text)=>{resumed.push(text);return accepted();}}); + assert.equal(result.total,1500);assert.ok(!resumed.includes(first));assert.equal(resumed.length,saved.parts.length-1); +})); +test('explicit grouped revision can be sent once without changing the daily receipt',async()=>fixture(async directory=>{ + let calls=0;const transport=async()=>{calls++;return accepted();}; + await deliverNotification({directory,report:report(),config,transport}); + const original=await fs.readFile(path.join(directory,'2026-11-24.json'),'utf8'); + await fs.writeFile(path.join(directory,'2026-11-01.carrier-grouped-v2.json'),'{}'); + const options={directory,report:report(),config,transport,deliveryRevision:'carrier-grouped-v2'}; + assert.equal((await deliverNotification(options)).status,'sent'); + assert.equal((await deliverNotification(options)).status,'already_sent'); + assert.equal((await deliverNotification({directory,report:report(),config,transport})).status,'already_sent'); + assert.equal(calls,2);assert.equal(await fs.readFile(path.join(directory,'2026-11-24.json'),'utf8'),original); + await assert.rejects(()=>fs.access(path.join(directory,'2026-11-01.carrier-grouped-v2.json'))); +})); +test('ambiguous network delivery is retained for reconciliation and is never automatically resent',async()=>fixture(async directory=>{ + let calls=0; + await assert.rejects(()=>deliverNotification({directory,report:report(),config,transport:async()=>{calls++;throw new Error('network failure containing secrets');}}),/DINGTALK_DELIVERY_UNKNOWN/); + await assert.rejects(()=>deliverNotification({directory,report:report(),config,transport:accepted}),/NEEDS_RECONCILIATION/);assert.equal(calls,1); + const saved=await fs.readFile(path.join(directory,'2026-11-24.json'),'utf8');assert.ok(!saved.includes('containing secrets')); +})); +test('destination changes and concurrent sending stop without contacting a new recipient',async()=>fixture(async directory=>{ + await deliverNotification({directory,report:report(),config,transport:accepted}); + await assert.rejects(()=>deliverNotification({directory,report:report(),config:{...config,webhook:config.webhook+'2'},transport:accepted}),/DESTINATION_CHANGED/); + await fs.writeFile(path.join(directory,'send.lock'),JSON.stringify({pid:process.pid})); + await assert.rejects(()=>deliverNotification({directory,report:report(),config,transport:accepted}),/ALREADY_RUNNING/); +})); diff --git a/furniture-3d-system/scripts/daily-express-dashboard/uncollected.mjs b/furniture-3d-system/scripts/daily-express-dashboard/uncollected.mjs new file mode 100644 index 00000000..62d1522f --- /dev/null +++ b/furniture-3d-system/scripts/daily-express-dashboard/uncollected.mjs @@ -0,0 +1,55 @@ +export const UNCOLLECTED_COLUMNS=[ + ['inner_order_id','ERP 内部订单号',23],['so_id','线上订单号(交易单号)',34],['logistic_company_name','快递名称',26],['logistic_id','快递单号',30], + ['warehouse_name','仓库名称',35],['send_time','发货时间',24],['fetch_time','揽收时间',24],['order_status_name','订单状态',15], + ['logistic_status_name','物流状态',15],['logistic_return_flag','拦截状态',15],['aftersale_status_name','售后状态',15], + ['shop_name','店铺名称',35],['platform_name','平台名称',20],['dis_co_name','分销商名称',30],['sign_time','签收时间',24], + ['logistic_time','物流时间(logistic_time)',28],['query_time','物流查询时间',24],['first_question_type','首次问题类型',30], + ['first_question_time','首次问题时间',24],['updatedAt','数据更新时间',24],['id','来源记录 ID',16],['order_labels','订单标签',65],['remark','订单备注',75],['refund_status','商品明细退款状态',26] +]; +const text=value=>String(value??'').trim(); +export const hasAtInTracking=row=>text(row.logistic_id).includes('@'); +export const UNCOLLECTED_EXCLUSIONS={firstQuestionType:'1688一件代发',carrierContains:['京喜','京东自营','顺丰','京东','中铁','自提','武进安能','壹米滴答专线'],blankTracking:true,labelContains:['ECLP','CLPS','1688一件代发','刷单待处理'],remarkContains:['(收)','BBFF'],refundSuccess:true}; +export function uncollectedExclusionReasons(row){ + const reasons=[]; + if(text(row.first_question_type)===UNCOLLECTED_EXCLUSIONS.firstQuestionType)reasons.push('first_question_type'); + if(UNCOLLECTED_EXCLUSIONS.carrierContains.some(keyword=>text(row.logistic_company_name).includes(keyword)))reasons.push('carrier'); + if(UNCOLLECTED_EXCLUSIONS.blankTracking&&!text(row.logistic_id))reasons.push('blank_tracking'); + if(hasAtInTracking(row))reasons.push('at_tracking'); + if(UNCOLLECTED_EXCLUSIONS.labelContains.some(keyword=>text(row.order_labels).toUpperCase().includes(keyword.toUpperCase())))reasons.push('order_labels'); + const remark=text(row.remark).normalize('NFKC').toUpperCase(); + if(UNCOLLECTED_EXCLUSIONS.remarkContains.some(keyword=>remark.includes(keyword.normalize('NFKC').toUpperCase())))reasons.push('remark'); + return reasons; +} +export const applyUncollectedExclusions=rows=>rows.filter(row=>uncollectedExclusionReasons(row).length===0); +export const isUncollected=row=>text(row.logistic_status_name)==='未揽收'; +export const applyUncollectedBaseRules=rows=>applyUncollectedExclusions(rows).filter(isUncollected); +export function applyUncollectedRules(rows){ + const candidates=applyUncollectedBaseRules(rows); + for(const row of candidates)if(row.refund_checked!==true||typeof row.refund_success!=='boolean')throw new Error('REFUND_STATUS_NOT_CHECKED_'+row.inner_order_id); + return candidates.filter(row=>!row.refund_success); +} +export function groupUncollected(rows,key){ + const map=new Map();for(const row of rows){const name=text(row[key])||'未填写';map.set(name,(map.get(name)||0)+1);} + return [...map].map(([name,count])=>({name,count})).sort((a,b)=>b.count-a.count||a.name.localeCompare(b.name,'zh-CN')); +} +export function validateUncollected(snapshot){ + const date=snapshot?.summary?.date; + if(!/^\d{4}-\d{2}-\d{2}$/.test(date||'')||!Array.isArray(snapshot.rows)||!Number.isFinite(Date.parse(snapshot.summary.queriedAt)))throw new Error('INVALID_UNCOLLECTED_SNAPSHOT'); + const ids=new Set(); + for(const row of snapshot.rows){ + if(!Object.prototype.hasOwnProperty.call(row,'order_labels'))throw new Error('UNCOLLECTED_ORDER_LABELS_REQUIRED'); + if(!Object.prototype.hasOwnProperty.call(row,'remark'))throw new Error('UNCOLLECTED_ORDER_REMARK_REQUIRED'); + if(!/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(row.send_time||'')||row.send_time.slice(0,10)!==date||row.fetch_time!==null)throw new Error('UNCOLLECTED_SOURCE_FILTER_MISMATCH'); + if(row.id==null||ids.has(String(row.id)))throw new Error('DUPLICATE_UNCOLLECTED_RECORD');ids.add(String(row.id)); + } + if(snapshot.summary.rowCount!==snapshot.rows.length)throw new Error('UNCOLLECTED_SOURCE_COUNT_MISMATCH'); + return snapshot; +} +export function selectUncollected(rows,{pendingOnly=false,query=''}={}){ + const search=text(query).toLocaleLowerCase('zh-CN'); + return rows.filter(row=>(!pendingOnly||isUncollected(row))&&(!search||UNCOLLECTED_COLUMNS.slice(0,11).some(([key])=>text(row[key]).toLocaleLowerCase('zh-CN').includes(search)))); +} +export function summarizeUncollected(rows){ + return {total:rows.length,pending:rows.filter(isUncollected).length,uniqueOrders:new Set(rows.map(row=>text(row.inner_order_id)).filter(Boolean)).size, + carriers:groupUncollected(rows,'logistic_company_name'),warehouses:groupUncollected(rows,'warehouse_name'),statuses:groupUncollected(rows,'logistic_status_name'),orderStatuses:groupUncollected(rows,'order_status_name')}; +} diff --git a/furniture-3d-system/scripts/daily-express-dashboard/uncollected.test.mjs b/furniture-3d-system/scripts/daily-express-dashboard/uncollected.test.mjs new file mode 100644 index 00000000..2c893694 --- /dev/null +++ b/furniture-3d-system/scripts/daily-express-dashboard/uncollected.test.mjs @@ -0,0 +1,63 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {selectUncollected,summarizeUncollected,validateUncollected,applyUncollectedExclusions,applyUncollectedRules,uncollectedExclusionReasons} from './uncollected.mjs'; +const row=(id,status)=>({id,inner_order_id:String(id),send_time:'2026-11-24 12:00:00',fetch_time:null,logistic_status_name:status,warehouse_name:'常州仓',logistic_company_name:'快递A',order_labels:null,remark:null,refund_checked:true,refund_success:false}); +test('pending selection uses the logistics status, preserving signed or in-transit rows in the full set',()=>{ + const rows=[row(1,'未揽收'),row(2,'已签收'),row(3,'运输中'),row(4,null)]; + assert.equal(selectUncollected(rows).length,4); + assert.deepEqual(selectUncollected(rows,{pendingOnly:true}).map(r=>r.id),[1]); + assert.equal(summarizeUncollected(rows).pending,1); + assert.equal(selectUncollected(rows,{pendingOnly:true,query:'已签收'}).length,0); + assert.equal(selectUncollected(rows,{query:'快递a'}).length,4); +}); +test('refund success is excluded and an unchecked candidate blocks publication',()=>{ + const base={...row(1,'未揽收'),logistic_id:'012345',logistic_company_name:'中通速递'}; + assert.deepEqual(applyUncollectedRules([base,{...base,id:2,refund_success:true}]),[base]); + assert.throws(()=>applyUncollectedRules([{...base,refund_checked:false}]),/REFUND_STATUS_NOT_CHECKED/); + const missing={...base};delete missing.refund_success;assert.throws(()=>applyUncollectedRules([missing]),/REFUND_STATUS_NOT_CHECKED/); +}); +test('tracking numbers containing @ are excluded before refund checks',()=>{ + const valid={...row(1,'未揽收'),logistic_id:'001234'}; + for(const logistic_id of ['@001234','001@234','001234@']){ + const excluded={...row(2,'未揽收'),logistic_id,refund_checked:false}; + assert.deepEqual(uncollectedExclusionReasons(excluded),['at_tracking']); + assert.deepEqual(applyUncollectedRules([valid,excluded]),[valid]); + } +}); +test('wrong shipping dates, populated pickup times and duplicate source records cannot be published',()=>{ + const snapshot={summary:{date:'2026-11-24',queriedAt:'2026-11-25T07:00:00Z',rowCount:1},rows:[row(1,'未揽收')]}; + assert.equal(validateUncollected(snapshot),snapshot); + for(const change of [{send_time:'2026-11-25 00:00:00'},{fetch_time:'2026-11-25 01:00:00'},{fetch_time:''}])assert.throws(()=>validateUncollected({...snapshot,rows:[{...snapshot.rows[0],...change}]})); + const missingLabels={...snapshot.rows[0]};delete missingLabels.order_labels;assert.throws(()=>validateUncollected({...snapshot,rows:[missingLabels]}),/ORDER_LABELS_REQUIRED/); + const missingRemark={...snapshot.rows[0]};delete missingRemark.remark;assert.throws(()=>validateUncollected({...snapshot,rows:[missingRemark]}),/ORDER_REMARK_REQUIRED/); + assert.throws(()=>validateUncollected({...snapshot,summary:{...snapshot.summary,rowCount:2},rows:[snapshot.rows[0],snapshot.rows[0]]})); +}); +test('any excluded order label matches inside a multi-label value and Latin label matching ignores case',()=>{ + const base={...row(1,'未揽收'),logistic_id:'012345',logistic_company_name:'中通速递'}; + for(const order_labels of ['其他,ECLP,普通','【CLPS】','其他;1688一件代发仓','1688一件代发','其他,1688一件代发订单','刷单待处理,有赠品','eclp','clps'])assert.equal(applyUncollectedExclusions([{...base,order_labels}]).length,0); + for(const order_labels of [null,'','普通订单,有赠品'])assert.equal(applyUncollectedExclusions([{...base,order_labels}]).length,1); + assert.deepEqual(uncollectedExclusionReasons({...base,order_labels:'ECLP,CLPS,刷单待处理'}),['order_labels']); +}); +test('published data contains only uncollected logistics status after every exclusion',()=>{ + const base={...row(1,'未揽收'),logistic_id:'012345',logistic_company_name:'中通速递'}; + const records=[base,{...base,id:2,logistic_status_name:'运输中'},{...base,id:3,logistic_status_name:'已签收'},{...base,id:4,logistic_status_name:null},{...base,id:5,order_labels:'1688一件代发'},{...base,id:6,logistic_company_name:'京喜京东快递'}]; + assert.deepEqual(applyUncollectedRules(records),[base]); + assert.deepEqual(applyUncollectedRules([]),[]); +}); +test('a zero-record day keeps valid empty summaries and filters',()=>{ + const snapshot={summary:{date:'2026-11-24',queriedAt:'2026-11-25T07:00:00Z',rowCount:0},rows:[]}; + validateUncollected(snapshot);assert.equal(summarizeUncollected([]).total,0);assert.deepEqual(selectUncollected([],{pendingOnly:true}),[]); +}); +test('business exclusions match the exact first problem, all specified carrier substrings and blank tracking',()=>{ + const base={...row(1,'未揽收'),logistic_id:'012345',logistic_company_name:'中通速递',first_question_type:null}; + assert.deepEqual(applyUncollectedExclusions([base]),[base]); + for(const patch of [{first_question_type:' 1688一件代发 '},{logistic_company_name:'京喜京东快递'},{logistic_company_name:'京东自营快递贝壳家'},{logistic_company_name:'横林顺丰干配'},{logistic_company_name:'京东快递'},{logistic_company_name:'中铁物流'},{logistic_company_name:'客户自提'},{logistic_company_name:'武进安能-大件'},{logistic_company_name:'壹米滴答专线-干线'},{logistic_id:null},{logistic_id:''},{logistic_id:' \t '}])assert.deepEqual(applyUncollectedExclusions([{...base,...patch}]),[]); + assert.equal(applyUncollectedExclusions([{...base,first_question_type:'1688一件代发-其他'}]).length,1); + assert.deepEqual(uncollectedExclusionReasons({...base,first_question_type:'1688一件代发',logistic_company_name:'顺丰速运',logistic_id:null}),['first_question_type','carrier','blank_tracking']); +}); +test('remark exclusions use the order remark, normalize parentheses and Latin case, and preserve ordinary remarks',()=>{ + const base={...row(1,'未揽收'),logistic_id:'012345',logistic_company_name:'名屋居安能快运'}; + for(const remark of ['(收)发货','(收)订单','前缀BBFF后缀','bbff','BBFF'])assert.deepEqual(applyUncollectedRules([{...base,remark}]),[]); + for(const remark of [null,'','正常发货','收到货后处理'])assert.deepEqual(applyUncollectedRules([{...base,remark}]),[{...base,remark}]); + assert.equal(applyUncollectedRules([{...base,remark_content:'BBFF',buyer_message:'(收)'}]).length,1); +}); diff --git a/furniture-3d-system/scripts/install-daily-express-timer.sh b/furniture-3d-system/scripts/install-daily-express-timer.sh new file mode 100644 index 00000000..b7a7ce99 --- /dev/null +++ b/furniture-3d-system/scripts/install-daily-express-timer.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +set -euo pipefail +BASE="/opt/furniture-3d-system-prod" +test -d "$BASE/current/furniture-3d-system" +test -s "$BASE/shared/daily-express/mappings.json" +test -s "$BASE/shared/daily-express/dingtalk-config.json" +cat > /etc/systemd/system/furniture-daily-express.service <<'EOF' +[Unit] +Description=Daily carrier volume and uncollected shipments +After=network-online.target +StartLimitIntervalSec=3600 +StartLimitBurst=4 +[Service] +Type=oneshot +WorkingDirectory=/opt/furniture-3d-system-prod/current/furniture-3d-system +EnvironmentFile=/opt/furniture-3d-system-prod/shared/.env +Environment=DAILY_EXPRESS_DATA_DIR=/opt/furniture-3d-system-prod/shared/daily-express +Environment=DAILY_EXPRESS_DINGTALK_CONFIG=/opt/furniture-3d-system-prod/shared/daily-express/dingtalk-config.json +Environment=DAILY_EXPRESS_ENV_JSON=/opt/furniture-3d-system-prod/shared/daily-express/report-env.json +ExecStart=/usr/bin/env node scripts/daily-express-dashboard/run.mjs +TimeoutStartSec=1800 +Restart=on-failure +RestartSec=900 +UMask=0077 +EOF +cat > /etc/systemd/system/furniture-daily-express.timer <<'EOF' +[Unit] +Description=Refresh carrier dashboards daily at 09:00 Asia/Shanghai +[Timer] +OnCalendar=*-*-* 09:00:00 Asia/Shanghai +Persistent=true +Unit=furniture-daily-express.service +[Install] +WantedBy=timers.target +EOF +systemctl daemon-reload +systemctl enable --now furniture-daily-express.timer +systemctl list-timers furniture-daily-express.timer --no-pager diff --git a/furniture-3d-system/scripts/install-inventory-monitoring-daily-timer.sh b/furniture-3d-system/scripts/install-inventory-monitoring-daily-timer.sh new file mode 100755 index 00000000..330f7337 --- /dev/null +++ b/furniture-3d-system/scripts/install-inventory-monitoring-daily-timer.sh @@ -0,0 +1,151 @@ +#!/usr/bin/env bash +set -euo pipefail + +# 默认每天 06:30(Asia/Shanghai)同步铺货快照并重建库存监控快照。 +# macOS:launchd;Linux:systemd timer。 +APP_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +LABEL="${INVENTORY_MONITORING_TIMER_LABEL:-com.furniture3d.inventory-monitoring-daily}" +SERVICE="${INVENTORY_MONITORING_SERVICE_NAME:-furniture-inventory-monitoring-daily}" +HOUR="${INVENTORY_MONITORING_SCHEDULE_HOUR:-6}" +MINUTE="${INVENTORY_MONITORING_SCHEDULE_MINUTE:-30}" +RUNNER="$APP_ROOT/scripts/run-inventory-monitoring-daily.sh" + +case "$HOUR" in + ''|*[!0-9]*) echo "INVENTORY_MONITORING_SCHEDULE_HOUR 必须是 0-23 的整数" >&2; exit 1 ;; +esac +case "$MINUTE" in + ''|*[!0-9]*) echo "INVENTORY_MONITORING_SCHEDULE_MINUTE 必须是 0-59 的整数" >&2; exit 1 ;; +esac +if [ "$HOUR" -gt 23 ] || [ "$MINUTE" -gt 59 ]; then + echo "定时器时间无效:$HOUR:$MINUTE" >&2 + exit 1 +fi +SCHEDULE_TEXT="$(printf '%02d:%02d' "$HOUR" "$MINUTE")" + +if [ "${1:-}" = "--uninstall" ]; then + if [ "$(uname -s)" = "Darwin" ]; then + PLIST="$HOME/Library/LaunchAgents/$LABEL.plist" + launchctl bootout "gui/$(id -u)" "$PLIST" 2>/dev/null || true + rm -f "$PLIST" + echo "已卸载 $LABEL" + else + test "$(id -u)" = 0 || { echo 'Root required' >&2; exit 1; } + systemctl disable --now "$SERVICE.timer" 2>/dev/null || true + rm -f "/etc/systemd/system/$SERVICE.service" "/etc/systemd/system/$SERVICE.timer" + systemctl daemon-reload + echo "已卸载 $SERVICE.timer" + fi + exit 0 +fi + +if [ ! -f "$APP_ROOT/.env" ]; then + echo "缺少 $APP_ROOT/.env,无法读取聚水潭配置" >&2 + exit 1 +fi +if [ ! -f "$RUNNER" ]; then + echo "缺少每日任务入口:$RUNNER" >&2 + exit 1 +fi +if [ ! -f "$APP_ROOT/node_modules/tsx/dist/cli.mjs" ]; then + echo "缺少 tsx 运行环境,请先安装项目依赖" >&2 + exit 1 +fi + +NODE_BIN="${INVENTORY_MONITORING_NODE_BIN:-}" +if [ -z "$NODE_BIN" ]; then + if command -v node >/dev/null 2>&1; then + NODE_BIN="$(command -v node)" + elif [ -x "$HOME/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/bin/node" ]; then + NODE_BIN="$HOME/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/bin/node" + else + echo "找不到 node,请安装 Node.js 或设置 INVENTORY_MONITORING_NODE_BIN。" >&2 + exit 1 + fi +fi +chmod 0755 "$RUNNER" + +if [ "$(uname -s)" = "Darwin" ]; then + PLIST="$HOME/Library/LaunchAgents/$LABEL.plist" + LOG="$HOME/Library/Logs/furniture3d-inventory-monitoring-daily.log" + mkdir -p "$HOME/Library/LaunchAgents" "$HOME/Library/Logs" + cat >"$PLIST" < + + + + Label + $LABEL + ProgramArguments + + /bin/bash + $RUNNER + + WorkingDirectory + $APP_ROOT + EnvironmentVariables + + PATH + $(dirname "$NODE_BIN"):/usr/local/bin:/usr/bin:/bin + TZ + Asia/Shanghai + INVENTORY_MONITORING_NODE_BIN + $NODE_BIN + + StartCalendarInterval + + Hour + $HOUR + Minute + $MINUTE + + RunAtLoad + + StandardOutPath + $LOG + StandardErrorPath + $LOG + + +PLIST_EOF + launchctl bootout "gui/$(id -u)" "$PLIST" 2>/dev/null || true + launchctl bootstrap "gui/$(id -u)" "$PLIST" + echo "已安装 ${LABEL}:每天 ${SCHEDULE_TEXT} 执行(Asia/Shanghai)" + echo "日志:$LOG" + echo "手动触发:launchctl kickstart -k gui/$(id -u)/$LABEL" +else + test "$(id -u)" = 0 || { echo 'Root required' >&2; exit 1; } + cat >"/etc/systemd/system/$SERVICE.service" <"/etc/systemd/system/$SERVICE.timer" <&2 + exit 1 +fi +if [ ! -f "$APP_ROOT/.env" ]; then + echo "缺少 $APP_ROOT/.env,无法读取数据库配置" >&2 + exit 1 +fi + +mkdir -p "$HOME/Library/LaunchAgents" "$LOG_DIR" + +cat >"$PLIST" < + + + + Label + $LABEL + ProgramArguments + + /bin/bash + -lc + cd "$APP_ROOT" && export PATH="$NODE_BIN:\$PATH" && export PICKUP_24H_REQUEST_TIMEOUT_MS="$PICKUP_24H_REQUEST_TIMEOUT_MS" && npm run prisma:generate && npm run sync:pickup-24h-timeliness -- --apply --confirm=sync-pickup-24h-timeliness --lookback-days=7 + + StartCalendarInterval + + Hour + $HOUR + Minute + $MINUTE + + RunAtLoad + + StandardOutPath + $LOG_FILE + StandardErrorPath + $LOG_FILE + + +EOF + +launchctl bootout "gui/$(id -u)" "$PLIST" 2>/dev/null || true +launchctl bootstrap "gui/$(id -u)" "$PLIST" +launchctl enable "gui/$(id -u)/$LABEL" + +echo "已安装每日同步任务:$LABEL" +echo " 执行时间:每天 $HOUR:$(printf '%02d' "$MINUTE")(Asia/Shanghai)" +echo " 项目目录:$APP_ROOT" +echo " 日志文件:$LOG_FILE" +echo " 手动立刻跑一次:launchctl kickstart -k \"gui/$(id -u)/$LABEL\"" +launchctl print "gui/$(id -u)/$LABEL" 2>/dev/null | grep -E "state =|runs =|last exit code" | head -5 || true diff --git a/furniture-3d-system/scripts/install-pickup-24h-timeliness-timer.sh b/furniture-3d-system/scripts/install-pickup-24h-timeliness-timer.sh new file mode 100755 index 00000000..d1f2cb39 --- /dev/null +++ b/furniture-3d-system/scripts/install-pickup-24h-timeliness-timer.sh @@ -0,0 +1,67 @@ +#!/usr/bin/env bash +set -euo pipefail + +# 24h 揽收及时率每日同步(付款日期 = 今天 - 2 天)。 +# 生产用法:sudo bash scripts/install-pickup-24h-timeliness-timer.sh + +BASE="${FURNITURE_PROD_BASE:-/opt/furniture-3d-system-prod}" +APP_ROOT="$BASE/current/furniture-3d-system" +SERVICE_NAME="${PICKUP_24H_SERVICE_NAME:-furniture-pickup-24h-timeliness-sync}" +SYNC_ENV="$BASE/shared/pickup-24h-timeliness.env" +CALENDAR="${PICKUP_24H_CALENDAR:-*-*-* 06:10:00 Asia/Shanghai}" + +if [ "$(id -u)" -ne 0 ]; then + echo "This installer requires root." >&2 + exit 1 +fi +if [ ! -f "$APP_ROOT/scripts/sync-pickup-24h-timeliness.ts" ]; then + echo "Missing deployed sync script: $APP_ROOT/scripts/sync-pickup-24h-timeliness.ts" >&2 + exit 1 +fi + +if [ ! -f "$SYNC_ENV" ]; then + umask 077 + cat >"$SYNC_ENV" <"/etc/systemd/system/$SERVICE_NAME.service" <"/etc/systemd/system/$SERVICE_NAME.timer" < value.startsWith(prefix))?.slice(prefix.length) ?? '' +} + +function dateString(value: Date) { + return new Date(value.getTime() + 8 * 3_600_000).toISOString().slice(0, 10) +} + +async function main() { + if (!process.argv.includes('--apply') || arg('confirm') !== CONFIRM_TOKEN) { + throw new Error(`重新计算需要 --apply 和 --confirm=${CONFIRM_TOKEN}`) + } + const from = arg('from') + const to = arg('to') + + const { prisma } = await import('../src/lib/prisma') + const { + buildPickup24hTimelinessAssessmentCounts, + evaluatePickup24hTimelinessAdmission, + evaluatePickup24hTimelinessOverdue, + pickup24hTimelinessRowKey, + pickup24hTimelinessTradeKey, + } = await import('../src/lib/pickup-24h-timeliness') + const { pickup24hTimelinessRepository } = await import( + '../src/server/repositories/pickup-24h-timeliness.repository' + ) + + const distinctDates = await prisma.pickup24hTimelinessOrder.findMany({ + select: { paymentDate: true }, + distinct: ['paymentDate'], + orderBy: { paymentDate: 'asc' }, + }) + const targets = distinctDates + .map((row) => dateString(row.paymentDate)) + .filter((date) => (!from || date >= from) && (!to || date <= to)) + + console.log(`待重算付款日期 ${targets.length} 天:${targets[0] ?? '-'} ~ ${targets[targets.length - 1] ?? '-'}`) + + for (const target of targets) { + const rows = await prisma.pickup24hTimelinessOrder.findMany({ + where: { paymentDate: new Date(`${target}T00:00:00.000Z`) }, + orderBy: { id: 'asc' }, + }) + if (!rows.length) continue + + // 经管大单:同一线上订单号 + 同一商品编码 的累计件数 + const bulkBySku = new Map() + for (const row of rows) { + const key = pickup24hTimelinessTradeKey(row.onlineOrderId, row.skuCode) + bulkBySku.set(key, (bulkBySku.get(key) ?? 0) + row.quantity) + } + + const computed = rows.map((row) => { + const tradeKey = pickup24hTimelinessTradeKey(row.onlineOrderId, row.skuCode) + const bulkQuantity = bulkBySku.get(tradeKey) ?? row.quantity + const admission = evaluatePickup24hTimelinessAdmission({ + paymentTime: row.paymentTime, + sendTime: row.sendTime, + afterSaleApplyTime: row.afterSaleApplyTime, + category: row.category, + spu: row.spu, + quantity: row.quantity, + supplier: row.supplier, + status: row.status, + bulkQuantity, + productAttribute: row.productAttribute, + labels: row.labels, + expressCompany: row.expressCompany, + orderRemark: row.orderRemark, + buyerMessage: row.buyerMessage, + expressNo: row.expressNo, + exceptionType: row.exceptionType, + shopName: row.shopName, + refundStatus: row.refundStatus, + }, {}) + const overdue = evaluatePickup24hTimelinessOverdue({ + paymentTime: row.paymentTime, + sendTime: row.sendTime, + fetchTime: row.fetchTime, + shopName: row.shopName, + expressCompany: row.expressCompany, + }) + return { + ...row, + tradeKey, + bulkQuantity, + included: admission.included, + excludeReason: admission.excludeReason, + overdue, + } + }) + + const lineIndex = new Map() + const withKeys = computed.map((row) => { + const base = pickup24hTimelinessRowKey({ + innerOrderId: row.innerOrderId, + onlineOrderId: row.onlineOrderId, + skuCode: row.skuCode, + }) + const index = lineIndex.get(base) ?? 0 + lineIndex.set(base, index + 1) + return { ...row, rowKey: `${base}\u0001${index}` } + }) + const withCounts = buildPickup24hTimelinessAssessmentCounts(withKeys) + const writeRows = withCounts.map((row) => { + const { id: _id, paymentDate: _paymentDate, createdAt: _createdAt, ...rest } = row + return rest + }) + + await pickup24hTimelinessRepository.replaceOrders(target, writeRows) + const includedCount = withCounts.filter((row) => row.included).length + const overdueCount = withCounts.filter((row) => row.included && row.overdue).length + await pickup24hTimelinessRepository.completeRun({ + paymentDate: target, + rowCount: withCounts.length, + includedCount, + overdueCount, + }) + console.log(`${target} 完成:${withCounts.length} 行,参与考核 ${includedCount},超时 ${overdueCount}`) + } +} + +main().catch((error) => { + console.error(error instanceof Error ? error.message : error) + process.exit(1) +}) diff --git a/furniture-3d-system/scripts/repair-clearance-task-owner-profit-centers.ts b/furniture-3d-system/scripts/repair-clearance-task-owner-profit-centers.ts new file mode 100644 index 00000000..9e9b6c20 --- /dev/null +++ b/furniture-3d-system/scripts/repair-clearance-task-owner-profit-centers.ts @@ -0,0 +1,92 @@ +import 'dotenv/config' +import { prisma } from '../src/lib/prisma' +import { supplyChainClearanceRepository } from '../src/server/repositories/supply-chain-clearance.repository' + +function argumentValue(name: string) { + const prefix = `--${name}=` + return process.argv.find((argument) => argument.startsWith(prefix))?.slice(prefix.length) ?? '' +} + +function eventObject(value: unknown) { + return value && typeof value === 'object' && !Array.isArray(value) + ? value as Record + : {} +} + +async function main() { + const apply = process.argv.includes('--apply') + const periodKey = argumentValue('period').trim() + if (!/^\d{4}-(0[1-9]|1[0-2])$/.test(periodKey)) { + throw new Error('必须提供 --period=YYYY-MM') + } + + const ownerCenters = await supplyChainClearanceRepository.listOwnerProfitCenters() + const profitCenterByOwner = new Map(ownerCenters.map((row) => [ + row.operationOwner.trim(), + row.profitCenter.trim(), + ])) + const tasks = await supplyChainClearanceRepository.listTasks({ periodKey }) + + const planned = tasks.flatMap((task) => { + if (task.status === 'REMOVED') return [] + const lastImportIndex = task.events.reduce((latest, event, index) => ( + event.action === 'MANUAL_IMPORT' ? index : latest + ), -1) + if (lastImportIndex < 0) return [] + const importEvent = task.events[lastImportIndex] + const ownerName = String( + eventObject(importEvent.after).clearanceOwner ?? task.ownerName, + ).trim() + const expectedProfitCenter = profitCenterByOwner.get(ownerName) ?? '' + const currentProfitCenter = task.profitCenter.trim() + if (!expectedProfitCenter || expectedProfitCenter === currentProfitCenter) return [] + return [{ + id: task.id, + barcode: task.barcode, + ownerName, + before: currentProfitCenter, + after: expectedProfitCenter, + }] + }) + + if (apply && planned.length) { + await prisma.$transaction(planned.map((row) => prisma.supplyChainClearanceTask.update({ + where: { id: row.id }, + data: { + profitCenter: row.after, + revision: { increment: 1 }, + events: { + create: { + action: 'OWNER_CENTER_REPAIR', + actorId: 'system', + actorName: '系统数据修复', + note: `按清货负责人 ${row.ownerName} 的利润中心修正任务归属`, + before: { + profitCenter: row.before, + }, + after: { + profitCenter: row.after, + }, + }, + }, + }, + }))) + } + + console.log(JSON.stringify({ + periodKey, + mode: apply ? 'APPLY' : 'DRY_RUN', + scanned: tasks.length, + planned: planned.length, + samples: planned.slice(0, 30), + }, null, 2)) +} + +main() + .catch((error) => { + console.error(error) + process.exitCode = 1 + }) + .finally(async () => { + await prisma.$disconnect() + }) diff --git a/furniture-3d-system/scripts/run-clearance-daily.mjs b/furniture-3d-system/scripts/run-clearance-daily.mjs index 52467e74..de30f615 100755 --- a/furniture-3d-system/scripts/run-clearance-daily.mjs +++ b/furniture-3d-system/scripts/run-clearance-daily.mjs @@ -113,9 +113,9 @@ async function main() { } finally { await pool.end() } - console.log(`[clearance-daily] ${today} 前置数据已就绪,开始刷新清货库存和任务进度`) + console.log(`[clearance-daily] ${today} 前置数据已就绪,开始刷新清货任务库存和任务进度`) await runClearanceProgress() - console.log(`[clearance-daily] ${today} 清货库存和任务进度刷新完成`) + console.log(`[clearance-daily] ${today} 清货任务库存和任务进度刷新完成`) } void main().catch((error) => { diff --git a/furniture-3d-system/scripts/run-inventory-monitoring-daily.sh b/furniture-3d-system/scripts/run-inventory-monitoring-daily.sh new file mode 100755 index 00000000..5aeb3d18 --- /dev/null +++ b/furniture-3d-system/scripts/run-inventory-monitoring-daily.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +set -euo pipefail + +APP_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +NODE_BIN="${INVENTORY_MONITORING_NODE_BIN:-}" +if [ -z "$NODE_BIN" ]; then + if command -v node >/dev/null 2>&1; then + NODE_BIN="$(command -v node)" + elif [ -x "$HOME/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/bin/node" ]; then + NODE_BIN="$HOME/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/bin/node" + else + echo "找不到 node,请安装 Node.js 或设置 INVENTORY_MONITORING_NODE_BIN。" >&2 + exit 1 + fi +fi + +cd "$APP_ROOT" +export TZ="${TZ:-Asia/Shanghai}" +exec "$NODE_BIN" \ + "$APP_ROOT/node_modules/tsx/dist/cli.mjs" \ + "$APP_ROOT/scripts/run-inventory-monitoring-daily.ts" \ + --apply \ + --confirm=run-inventory-monitoring-daily diff --git a/furniture-3d-system/scripts/run-inventory-monitoring-daily.ts b/furniture-3d-system/scripts/run-inventory-monitoring-daily.ts new file mode 100644 index 00000000..e758f882 --- /dev/null +++ b/furniture-3d-system/scripts/run-inventory-monitoring-daily.ts @@ -0,0 +1,74 @@ +import { loadEnvConfig } from '@next/env' + +loadEnvConfig(process.cwd()) +process.env.TZ ||= 'Asia/Shanghai' + +const CONFIRM_TOKEN = 'run-inventory-monitoring-daily' + +function readArgument(name: string) { + const prefix = `--${name}=` + return process.argv.slice(2) + .find((argument) => argument.startsWith(prefix)) + ?.slice(prefix.length) ?? '' +} + +async function main() { + if (!process.argv.includes('--apply')) { + throw new Error('This command refreshes production data. Pass --apply.') + } + if (readArgument('confirm') !== CONFIRM_TOKEN) { + throw new Error(`Pass --confirm=${CONFIRM_TOKEN}.`) + } + + const { inventoryMonitoringRepository } = await import( + '../src/server/repositories/inventory-monitoring.repository' + ) + const { jstSkumapDistributionRepository } = await import( + '../src/server/repositories/jst-skumap-distribution.repository' + ) + const { InventoryMonitoringDistributionService } = await import( + '../src/server/services/inventory-monitoring-distribution.service' + ) + const { inventoryMonitoringService } = await import( + '../src/server/services/inventory-monitoring.service' + ) + const { runInventoryMonitoringDailyUpdate } = await import( + '../src/server/services/inventory-monitoring-daily.service' + ) + + const distributionService = new InventoryMonitoringDistributionService({ + loadInventoryBarcodes: async () => ( + await inventoryMonitoringRepository.loadInventorySources() + ).map((row) => row.barcode), + skumapRepository: jstSkumapDistributionRepository, + }) + const startedAt = Date.now() + try { + const result = await runInventoryMonitoringDailyUpdate({ + distributionService, + rebuildSnapshot: () => inventoryMonitoringService.rebuildSnapshot(), + }, (message) => console.log(new Date().toISOString(), message)) + console.log('[inventory-monitoring-daily] complete', { + generatedAt: result.snapshot.generatedAt, + distributionGeneratedAt: result.distribution.generatedAt, + inventoryRows: result.snapshot.rows.length, + distributionBarcodes: result.distribution.barcodes, + distributionListings: result.distribution.listings, + warningCount: result.snapshot.warnings.length, + elapsedSeconds: Math.round((Date.now() - startedAt) / 1000), + }) + } finally { + await Promise.allSettled([ + jstSkumapDistributionRepository.close(), + inventoryMonitoringRepository.close(), + ]) + } +} + +main().catch((error) => { + console.error( + '[inventory-monitoring-daily] failed:', + error instanceof Error ? error.message : String(error), + ) + process.exitCode = 1 +}) diff --git a/furniture-3d-system/scripts/run-reissue-wecom-daily.ts b/furniture-3d-system/scripts/run-reissue-wecom-daily.ts index 2e9fc5b6..d5a4d192 100644 --- a/furniture-3d-system/scripts/run-reissue-wecom-daily.ts +++ b/furniture-3d-system/scripts/run-reissue-wecom-daily.ts @@ -16,9 +16,6 @@ async function main() { const dispatch = mode === 'followup-14' ? await wecomReissueService.dispatchUnrespondedFollowup() : await wecomReissueService.dispatchDue(true) - const deliveryAlerts = await wecomReissueService.dispatchDeliveryNodeAlerts({ - includeQa: mode === 'initial', - }) console.log(JSON.stringify({ mode, syncedAt: sync.syncedAt, @@ -31,7 +28,6 @@ async function main() { attempted: dispatch.attempted, created: dispatch.created, failures: dispatch.failures, - deliveryNodeAlerts: deliveryAlerts, })) await prisma.$disconnect() } diff --git a/furniture-3d-system/scripts/sync-clearance-progress.ts b/furniture-3d-system/scripts/sync-clearance-progress.ts index 55e24fc4..112ddc04 100644 --- a/furniture-3d-system/scripts/sync-clearance-progress.ts +++ b/furniture-3d-system/scripts/sync-clearance-progress.ts @@ -29,11 +29,11 @@ async function main() { )) const results = [] for (const periodKey of periods) { - const poolMetrics = await supplyChainClearanceService.refreshClearanceDailyMetrics( + const taskMetrics = await supplyChainClearanceService.refreshClearanceTaskDailyMetrics( periodKey, ) const taskProgress = await supplyChainClearanceService.syncTaskProgress(periodKey) - results.push({ ...taskProgress, poolMetrics }) + results.push({ ...taskProgress, taskMetrics }) } console.log(JSON.stringify({ results }, null, 2)) } diff --git a/furniture-3d-system/scripts/sync-inventory-monitoring-distribution.ts b/furniture-3d-system/scripts/sync-inventory-monitoring-distribution.ts new file mode 100644 index 00000000..6de3a873 --- /dev/null +++ b/furniture-3d-system/scripts/sync-inventory-monitoring-distribution.ts @@ -0,0 +1,71 @@ +import { loadEnvConfig } from '@next/env' + +loadEnvConfig(process.cwd()) + +const CONFIRM_TOKEN = 'sync-inventory-monitoring-distribution' + +function readArgument(name: string) { + const prefix = `--${name}=` + return process.argv.slice(2) + .find((argument) => argument.startsWith(prefix)) + ?.slice(prefix.length) ?? '' +} + +async function main() { + if (!process.argv.includes('--apply')) { + throw new Error('This command writes the local distribution count snapshot. Pass --apply.') + } + if (readArgument('confirm') !== CONFIRM_TOKEN) { + throw new Error(`Pass --confirm=${CONFIRM_TOKEN}.`) + } + + const { jstSkumapDistributionRepository } = await import( + '../src/server/repositories/jst-skumap-distribution.repository' + ) + const { InventoryMonitoringDistributionService } = await import( + '../src/server/services/inventory-monitoring-distribution.service' + ) + const { INVENTORY_MONITORING_CACHE_VERSION } = await import( + '../src/server/services/inventory-monitoring.service' + ) + const { readPersistentDataCache } = await import( + '../src/server/services/persistent-data-cache' + ) + const loadInventoryBarcodes = async () => { + for (const version of [ + INVENTORY_MONITORING_CACHE_VERSION, + INVENTORY_MONITORING_CACHE_VERSION - 1, + ]) { + const cached = await readPersistentDataCache<{ + rows: Array<{ barcode: string }> + }>('inventory-monitoring', version) + if (!cached) continue + return cached.data.rows + .map((row) => row.barcode) + .filter(Boolean) + } + throw new Error('库存监控快照不存在,请先打开一次库存监控页面') + } + + const service = new InventoryMonitoringDistributionService({ + loadInventoryBarcodes, + skumapRepository: jstSkumapDistributionRepository, + }) + const startedAt = Date.now() + try { + const result = await service.syncAll((message) => { + console.log(new Date().toISOString(), message) + }) + console.log('[inventory-distribution] complete', { + ...result, + elapsedSeconds: Math.round((Date.now() - startedAt) / 1000), + }) + } finally { + await jstSkumapDistributionRepository.close() + } +} + +main().catch((error) => { + console.error('[inventory-distribution] failed:', error) + process.exitCode = 1 +}) diff --git a/furniture-3d-system/scripts/sync-pickup-24h-timeliness.ts b/furniture-3d-system/scripts/sync-pickup-24h-timeliness.ts new file mode 100644 index 00000000..0ecfcf1b --- /dev/null +++ b/furniture-3d-system/scripts/sync-pickup-24h-timeliness.ts @@ -0,0 +1,129 @@ +import { loadEnvConfig } from '@next/env' +import { + PICKUP_24H_TIMELINESS_HISTORY_START_DATE, + pickup24hTimelinessDefaultPaymentDate, + pickup24hTimelinessToday, + shiftPickup24hTimelinessDate, +} from '../src/lib/pickup-24h-timeliness' + +loadEnvConfig(process.cwd()) + +/** + * 24h 揽收及时率的每日同步脚本。 + * + * 默认拉取「今天 - 2 天」的付款日期(例如 10 月 6 日跑 10 月 4 日): + * npm run sync:pickup-24h-timeliness -- --apply --confirm=sync-pickup-24h-timeliness \ + * --expected-database-identity="<本地库身份>" \ + * --expected-source-database-identity="<远端报表身份>" + * + * 历史回补(从 11 月 1 日开始): + * npm run sync:pickup-24h-timeliness -- --apply --confirm=sync-pickup-24h-timeliness \ + * --from=2026-11-01 --to=2026-11-24 --force ... + */ + +const CONFIRM_TOKEN = 'sync-pickup-24h-timeliness' + +function arg(name: string) { + const prefix = `--${name}=` + return process.argv.slice(2).find((value) => value.startsWith(prefix))?.slice(prefix.length) ?? '' +} + +function required(name: string) { + const value = process.env[name]?.trim() + if (!value) throw new Error(`${name} is required.`) + return value +} + +function identity(url: string) { + const parsed = new URL(url) + return [ + parsed.protocol.replace(':', ''), + decodeURIComponent(parsed.username || ''), + parsed.hostname, + parsed.port || '', + parsed.pathname.replace(/^\//, ''), + parsed.searchParams.get('schema') ?? '', + ].join('|') +} + +function sourceIdentity() { + return [ + 'sqlserver', + required('JST_REPORT_DB_USER'), + required('JST_REPORT_DB_HOST'), + process.env.JST_REPORT_DB_PORT?.trim() || '1433', + required('JST_REPORT_DB_NAME'), + process.env.JST_REPORT_DB_SCHEMA?.trim() || 'rpt', + ].join('|') +} + +async function main() { + const apply = process.argv.includes('--apply') + if (!apply || arg('confirm') !== CONFIRM_TOKEN) { + throw new Error(`写入 24h 揽收及时率明细需要 --apply 和 --confirm=${CONFIRM_TOKEN}`) + } + + const databaseUrl = required('DATABASE_URL') + const expectedDatabaseIdentity = arg('expected-database-identity') + if (expectedDatabaseIdentity && expectedDatabaseIdentity !== identity(databaseUrl)) { + throw new Error('expected database identity mismatch') + } + const expectedSourceIdentity = arg('expected-source-database-identity') + if (expectedSourceIdentity && expectedSourceIdentity !== sourceIdentity()) { + throw new Error('expected source identity mismatch') + } + + const singleDate = arg('date') + const from = arg('from') + const to = arg('to') + const force = process.argv.includes('--force') + + const { pickup24hTimelinessSyncService } = await import( + '../src/server/services/pickup-24h-timeliness-sync.service' + ) + + try { + if (singleDate) { + const result = await pickup24hTimelinessSyncService.syncDate(singleDate, { + force, + onProgress: (progress) => console.log(JSON.stringify(progress)), + }) + console.log(JSON.stringify(result, null, 2)) + if (result.status === 'failed') process.exitCode = 1 + return + } + + const today = pickup24hTimelinessToday() + const defaultTo = pickup24hTimelinessDefaultPaymentDate(today) + // --lookback-days=N:从「今天 - 2 天」往回补 N 天(默认 1 天,只跑当天)。 + // 已完成批次会自动跳过,因此每日任务带 7 天回看可以自动补上之前失败的日期。 + const lookbackDays = Math.min(Math.max(Number(arg('lookback-days')) || 1, 1), 60) + const rangeTo = to || defaultTo + const rangeFrom = from || ( + lookbackDays > 1 + ? shiftPickup24hTimelinessDate(rangeTo, -(lookbackDays - 1)) + : rangeTo + ) + if (rangeFrom < PICKUP_24H_TIMELINESS_HISTORY_START_DATE && !process.argv.includes('--allow-early')) { + console.warn( + `[pickup-24h-timeliness] 付款日期 ${rangeFrom} 早于历史回补起始日 ${PICKUP_24H_TIMELINESS_HISTORY_START_DATE},` + + '如确认需要请追加 --allow-early。', + ) + } + const result = await pickup24hTimelinessSyncService.syncRange({ + from: rangeFrom, + to: rangeTo, + force, + onProgress: (progress) => console.log(JSON.stringify(progress)), + }) + console.log(JSON.stringify(result, null, 2)) + if (result.results.some((item) => item.status === 'failed')) process.exitCode = 1 + } finally { + await pickup24hTimelinessSyncService.close() + } +} + +main().catch((error) => { + console.error(error instanceof Error ? error.message : error) + process.exit(1) +}) diff --git a/furniture-3d-system/scripts/verify-daily-express-snapshot.ts b/furniture-3d-system/scripts/verify-daily-express-snapshot.ts new file mode 100644 index 00000000..9e039e58 --- /dev/null +++ b/furniture-3d-system/scripts/verify-daily-express-snapshot.ts @@ -0,0 +1,22 @@ +import { DailyExpressVolumeRepository } from '../src/server/repositories/daily-express-volume.repository' +import { expressRegionalPivot } from '../src/lib/daily-express-snapshot' +import assert from 'node:assert/strict' +async function main() { + const repository = new DailyExpressVolumeRepository() + const { report, pointer } = await repository.readLatest() + const details = await repository.readDetails(pointer) + assert.equal(details.length, report.overview.total) + assert.equal(report.overview.ranking.reduce((total, row) => total + row.total, 0), details.length) + for (const day of report.regional.days) { + assert.equal(expressRegionalPivot(day, '').total, details.filter(row => row.send_date.startsWith(day.date)).length) + for (const origin of day.origins) assert.equal(expressRegionalPivot(day, origin.name).total, origin.total) + } + const pickup = report.uncollected + if (pickup) { + assert.equal(pickup.rows.length, pickup.summary.total) + assert.ok(pickup.rows.every(row => row.refund_checked === true && row.refund_success === false && String(row.logistic_status_name).trim() === '未揽收')) + } + const uncollected = report.uncollectedRefresh?.status === 'failed' ? null : pickup?.summary.total + console.log(JSON.stringify({ date: report.dateTo, total: report.overview.total, days: report.overview.days.length, uncollected, verified: true })) +} +void main().catch(error => { console.error(error instanceof Error ? error.message : 'Snapshot verification failed'); process.exitCode = 1 }) diff --git a/furniture-3d-system/scripts/warm-platform-bill-order-payments.ts b/furniture-3d-system/scripts/warm-platform-bill-order-payments.ts new file mode 100644 index 00000000..776e5f3d --- /dev/null +++ b/furniture-3d-system/scripts/warm-platform-bill-order-payments.ts @@ -0,0 +1,54 @@ +import { prisma } from '@/lib/prisma' +import { + normalizePlatformBillPeriod, + previousPlatformBillPeriod, +} from '@/lib/platform-bill-periods' +import { + supplyChainPlatformBillRepository, +} from '@/server/repositories/supply-chain-platform-bill.repository' +import { + supplyChainPlatformBillOrderPaymentRepository, +} from '@/server/repositories/supply-chain-platform-bill-order-payment.repository' + +const PAYMENT_BILL_KEYS = ['jd-statement', 'jd-flow', 'wechat'] as const + +function argument(name: string) { + const prefix = `--${name}=` + return process.argv.find((value) => value.startsWith(prefix))?.slice(prefix.length) +} + +async function main() { + const periodKey = normalizePlatformBillPeriod( + argument('period') || previousPlatformBillPeriod(), + ) + if (!periodKey) throw new Error('账期格式必须是 YYYY-MM') + + const orderNumbers = await supplyChainPlatformBillRepository + .listDistinctPaymentOrderNumbers({ + periodKey, + billKeys: PAYMENT_BILL_KEYS, + }) + console.log(`[平台账单付款月份] ${periodKey} 共 ${orderNumbers.length} 个订单号`) + + const startedAt = Date.now() + const result = await supplyChainPlatformBillOrderPaymentRepository.refresh( + orderNumbers, + undefined, + { retryEmpty: true }, + ) + const resolved = [...result.values()].filter(Boolean).length + console.log( + `[平台账单付款月份] 已缓存 ${result.size} 个订单号,` + + `命中付款月份 ${resolved} 个,未命中 ${result.size - resolved} 个,` + + `耗时 ${((Date.now() - startedAt) / 1_000).toFixed(1)} 秒`, + ) +} + +main() + .catch((error) => { + console.error('[平台账单付款月份] 刷新失败:', error) + process.exitCode = 1 + }) + .finally(async () => { + await prisma.$disconnect() + }) diff --git a/furniture-3d-system/src/app/admin/ai-render/AiRenderConfigClient.tsx b/furniture-3d-system/src/app/admin/ai-render/AiRenderConfigClient.tsx index a86b2c7d..16545778 100644 --- a/furniture-3d-system/src/app/admin/ai-render/AiRenderConfigClient.tsx +++ b/furniture-3d-system/src/app/admin/ai-render/AiRenderConfigClient.tsx @@ -24,6 +24,7 @@ import { Eye, EyeOff, ScanLine, + Mic, Plug, Save, X, @@ -42,7 +43,7 @@ interface ProviderConfig { createdAt: string } -type ActiveTab = 'ai-render' | 'prompt-optimizer' | 'image-background-removal' +type ActiveTab = 'ai-render' | 'prompt-optimizer' | 'image-background-removal' | 'supplier-quote-speech' interface TestResult { status: 'idle' | 'testing' | 'success' | 'error'; message: string } interface ModelOption { value: string; label: string; source?: 'gateway' | 'async-matting' } @@ -78,6 +79,7 @@ function readBackgroundRemovalApiMode(config?: ProviderConfig | null): Backgroun export const TAB_META: Record = { 'ai-render': { label: '生图服务', icon: Sparkles, desc: '辅助装配 AI 效果图的外部生图接口', serviceType: 'ai-render' }, 'prompt-optimizer': { label: '提示词优化', icon: Wand2, desc: '用 AI 优化用户的粗糙描述为高质量生图 prompt', serviceType: 'prompt-optimizer' }, + 'supplier-quote-speech': { label: '报价语音识别', icon: Mic, desc: '供应商报价页面的语音转文字服务', serviceType: 'supplier-quote-speech' }, 'image-background-removal': { label: '商品抠图', icon: ScanLine, diff --git a/furniture-3d-system/src/app/api/admin/test-connection/route.ts b/furniture-3d-system/src/app/api/admin/test-connection/route.ts index ddc3de94..4ffb84d8 100644 --- a/furniture-3d-system/src/app/api/admin/test-connection/route.ts +++ b/furniture-3d-system/src/app/api/admin/test-connection/route.ts @@ -6,7 +6,7 @@ import { providerModelCatalogService } from '@/server/services' const schema = z.object({ baseUrl: z.string().url('地址格式不正确'), - serviceType: z.enum(['ai-render', 'prompt-optimizer', 'image-background-removal']), + serviceType: z.enum(['ai-render', 'prompt-optimizer', 'image-background-removal', 'supplier-quote-speech']), apiMode: z.enum(['external-image-gateway', 'openai-compatible-image-edit', 'async-media-task']).optional(), }) diff --git a/furniture-3d-system/src/app/api/intake/accessory-model-drafts/route.ts b/furniture-3d-system/src/app/api/intake/accessory-model-drafts/route.ts index 500e456e..dc8fc56a 100644 --- a/furniture-3d-system/src/app/api/intake/accessory-model-drafts/route.ts +++ b/furniture-3d-system/src/app/api/intake/accessory-model-drafts/route.ts @@ -6,8 +6,8 @@ import { accessoryModelDraftService } from '@/server/services/intake-accessory-m export async function GET(request: NextRequest) { return handleRequest(request, async (ctx) => { - await assertAccessoryAccess(ctx.user) - return jsonSuccess(await accessoryModelDraftService.list(), 200, ctx.requestId) + const access = await assertAccessoryAccess(ctx.user) + return jsonSuccess({ ...await accessoryModelDraftService.list(), ...access }, 200, ctx.requestId) }, { requireAuth: true }) } diff --git a/furniture-3d-system/src/app/api/intake/accessory-model-drafts/weight/route.ts b/furniture-3d-system/src/app/api/intake/accessory-model-drafts/weight/route.ts new file mode 100644 index 00000000..0e718fec --- /dev/null +++ b/furniture-3d-system/src/app/api/intake/accessory-model-drafts/weight/route.ts @@ -0,0 +1,22 @@ +import type { NextRequest } from 'next/server' +import { accessoryWeightInputSchema } from '@/lib/accessory-weight' +import { AppError, ErrorCode } from '@/server/core/errors' +import { handleRequest, jsonSuccess } from '@/server/core/response' +import { assertAccessoryAccess } from '@/server/services/intake-accessory-models/access' +import { estimateAccessoryWeight } from '@/server/services/intake-accessory-models/weight' + +export const runtime = 'nodejs' + +export async function POST(request: NextRequest) { + return handleRequest(request, async (ctx) => { + await assertAccessoryAccess(ctx.user, true) + if (Number(request.headers.get('content-length')) > 32_768) throw new AppError(ErrorCode.VALIDATION_FAILED, '预估参数过大') + const raw = await request.text() + if (raw.length > 32_768) throw new AppError(ErrorCode.VALIDATION_FAILED, '预估参数过大') + let body: unknown + try { body = JSON.parse(raw) } catch { body = null } + const parsed = accessoryWeightInputSchema.safeParse(body) + if (!parsed.success) throw new AppError(ErrorCode.VALIDATION_FAILED, parsed.error.issues[0]?.message ?? '预估参数不正确') + return jsonSuccess(await estimateAccessoryWeight(parsed.data), 200, ctx.requestId) + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/api/intake/product-library/estimate-link/route.ts b/furniture-3d-system/src/app/api/intake/product-library/estimate-link/route.ts index 7efa5f8f..af70152d 100644 --- a/furniture-3d-system/src/app/api/intake/product-library/estimate-link/route.ts +++ b/furniture-3d-system/src/app/api/intake/product-library/estimate-link/route.ts @@ -1,4 +1,5 @@ import type { NextRequest } from 'next/server' +import { hasProductLibraryImportRole } from '@/lib/intake-library-access' import { estimateLinkSchema } from '@/lib/product-library/contracts' import { ErrorCode } from '@/server/core/errors' import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' @@ -6,6 +7,9 @@ import { productLibraryService } from '@/server/services/product-library.service export function POST(request: NextRequest) { return handleRequest(request, async ({ user, requestId }) => { + if (!hasProductLibraryImportRole(user)) { + return jsonError(ErrorCode.AUTH_PERMISSION_DENIED, '仅设计师和管理员可以导入产品资料', 403, requestId) + } const input = estimateLinkSchema.safeParse(await request.json().catch(() => null)) if (!input.success) { return jsonError(ErrorCode.VALIDATION_FAILED, '请选择已保存的测算单及修订版本', 400, requestId) diff --git a/furniture-3d-system/src/app/api/intake/product-library/import-permission.test.ts b/furniture-3d-system/src/app/api/intake/product-library/import-permission.test.ts new file mode 100644 index 00000000..847c9180 --- /dev/null +++ b/furniture-3d-system/src/app/api/intake/product-library/import-permission.test.ts @@ -0,0 +1,67 @@ +/** @jest-environment node */ +import { NextRequest } from 'next/server' +import type { AuthUser } from '@/server/core/types' +import { productLibraryService } from '@/server/services/product-library.service' +import { productLibraryProductInfoService } from '@/server/services/product-library-product-info.service' +import { POST as importEstimate } from './route' +import { POST as pushEstimate } from './estimate-link/route' +import { POST as importProductInfo } from './product-info/route' + +let mockUser: AuthUser + +jest.mock('@/server/core/response', () => ({ + handleRequest: (request: NextRequest, handler: (context: { + request: NextRequest; user: AuthUser; requestId: string + }) => unknown) => handler({ request, user: mockUser, requestId: 'req-import' }), + jsonError: (code: string, message: string, status: number) => Response.json({ error: { code, message } }, { status }), + jsonSuccess: (data: unknown, status: number) => Response.json({ data }, { status }), +})) +jest.mock('@/server/services/product-library.service', () => ({ + productLibraryService: { linkEstimate: jest.fn(async () => ({ id: 'archive' })) }, +})) +jest.mock('@/server/services/product-library-product-info.service', () => ({ + productLibraryProductInfoService: { + pull: jest.fn(async () => ({ archive: { id: 'archive' }, created: true })), + link: jest.fn(async () => ({ id: 'archive' })), + }, +})) + +const estimate = { estimateId: 'estimate', revision: 2 } +const product = { source: 'product-information', id: 'product' } +const base = 'http://localhost/api/intake/product-library' +const post = (url: string, value: unknown) => + new NextRequest(base + url, { method: 'POST', body: JSON.stringify(value) }) + +beforeEach(() => { + jest.clearAllMocks() + mockUser = { + id: 'viewer', name: '采购', email: 'viewer@example.test', role: 'USER', status: 'ACTIVE', businessRoles: ['PURCHASING'], + } +}) + +it('denies all archive creation paths to users outside the allowed roles', async () => { + expect((await importEstimate(post('', estimate))).status).toBe(403) + expect((await pushEstimate(post('/estimate-link', estimate))).status).toBe(403) + expect((await importProductInfo(post('/product-info', product))).status).toBe(403) + expect(productLibraryService.linkEstimate).not.toHaveBeenCalled() + expect(productLibraryProductInfoService.pull).not.toHaveBeenCalled() +}) + +it('passes designers and administrators to the existing operation and source permission checks', async () => { + mockUser = { ...mockUser, businessRoles: ['DESIGN'] } + expect((await importEstimate(post('', estimate))).status).toBe(200) + expect((await pushEstimate(post('/estimate-link', estimate))).status).toBe(200) + expect(productLibraryService.linkEstimate).toHaveBeenCalledTimes(2) + expect(productLibraryService.linkEstimate).toHaveBeenCalledWith(estimate, mockUser) + + mockUser = { ...mockUser, role: 'ADMIN', businessRoles: [] } + expect((await importProductInfo(post('/product-info', product))).status).toBe(200) + expect(productLibraryProductInfoService.pull).toHaveBeenCalledWith(product, mockUser) +}) + +it('leaves association of an existing archive to the current maintenance permission check', async () => { + const id = '36aa5f82-853f-47aa-b887-b7f794776265' + expect((await importProductInfo(post('/product-info?archiveId=' + id, product))).status).toBe(200) + expect(productLibraryProductInfoService.link).toHaveBeenCalledWith(id, product, mockUser) + expect(productLibraryProductInfoService.pull).not.toHaveBeenCalled() +}) diff --git a/furniture-3d-system/src/app/api/intake/product-library/product-info/route.ts b/furniture-3d-system/src/app/api/intake/product-library/product-info/route.ts index 479ebad6..e1d651ff 100644 --- a/furniture-3d-system/src/app/api/intake/product-library/product-info/route.ts +++ b/furniture-3d-system/src/app/api/intake/product-library/product-info/route.ts @@ -1,5 +1,6 @@ import type { NextRequest } from 'next/server' import { z } from 'zod' +import { hasProductLibraryImportRole } from '@/lib/intake-library-access' import { archiveIdSchema, productInfoSelectionSchema } from '@/lib/product-library/contracts' import { ErrorCode } from '@/server/core/errors' import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' @@ -13,15 +14,21 @@ export function GET(request: NextRequest) { const q = querySchema.safeParse(spu ?? request.nextUrl.searchParams.get('q') ?? '') if (!q.success) return jsonError(ErrorCode.VALIDATION_FAILED, '搜索内容不能超过 100 个字符', 400, requestId) if (spu !== null && !q.data) return jsonError(ErrorCode.VALIDATION_FAILED, '请输入完整 SPU', 400, requestId) - return jsonSuccess(await productLibraryProductInfoService.search(q.data, user, spu !== null), 200, requestId) + const archive = request.nextUrl.searchParams.get('archiveId') + const id = archiveIdSchema.optional().safeParse(archive ?? undefined) + if (!id.success) return jsonError(ErrorCode.RESOURCE_NOT_FOUND, '产品资料不存在', 404, requestId) + return jsonSuccess(await productLibraryProductInfoService.search(q.data, user, spu !== null, id.data), 200, requestId) }, { requireAuth: true }) } export function POST(request: NextRequest) { return handleRequest(request, async ({ user, requestId }) => { + const archiveId = request.nextUrl.searchParams.get('archiveId') + if (archiveId === null && !hasProductLibraryImportRole(user)) { + return jsonError(ErrorCode.AUTH_PERMISSION_DENIED, '仅设计师和管理员可以导入产品资料', 403, requestId) + } const input = productInfoSelectionSchema.safeParse(await request.json().catch(() => null)) if (!input.success) return jsonError(ErrorCode.VALIDATION_FAILED, '请选择一条产品信息记录', 400, requestId) - const archiveId = request.nextUrl.searchParams.get('archiveId') if (archiveId !== null) { const id = archiveIdSchema.safeParse(archiveId) if (!id.success) return jsonError(ErrorCode.RESOURCE_NOT_FOUND, '产品资料不存在', 404, requestId) diff --git a/furniture-3d-system/src/app/api/intake/product-library/route.ts b/furniture-3d-system/src/app/api/intake/product-library/route.ts index 5219d1ae..64cd7570 100644 --- a/furniture-3d-system/src/app/api/intake/product-library/route.ts +++ b/furniture-3d-system/src/app/api/intake/product-library/route.ts @@ -1,4 +1,5 @@ import type { NextRequest } from 'next/server' +import { hasProductLibraryImportRole } from '@/lib/intake-library-access' import { adoptEstimateSchema } from '@/lib/product-library/contracts' import { ErrorCode } from '@/server/core/errors' import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' @@ -11,6 +12,9 @@ export function GET(request: NextRequest) { export function POST(request: NextRequest) { return handleRequest(request, async ({ user, requestId }) => { + if (!hasProductLibraryImportRole(user)) { + return jsonError(ErrorCode.AUTH_PERMISSION_DENIED, '仅设计师和管理员可以导入产品资料', 403, requestId) + } const parsed = adoptEstimateSchema.safeParse(await request.json().catch(() => null)) if (!parsed.success) { return jsonError(ErrorCode.VALIDATION_FAILED, '请选择已保存的测算单及修订版本', 400, requestId) diff --git a/furniture-3d-system/src/app/api/intake/supplier-quotes/excel/route.ts b/furniture-3d-system/src/app/api/intake/supplier-quotes/excel/route.ts new file mode 100644 index 00000000..94dbcb24 --- /dev/null +++ b/furniture-3d-system/src/app/api/intake/supplier-quotes/excel/route.ts @@ -0,0 +1,20 @@ +import { NextResponse, type NextRequest } from 'next/server' +import { handleRequest } from '@/server/core/response' +import { AppError, ErrorCode } from '@/server/core/errors' +import { exportSupplierQuote } from '@/server/services/supplier-quote/export.service' +import { assertInternalQuoteAccess, readInternalQuote } from '@/server/services/supplier-quote/internal.service' + +export function GET(request: NextRequest) { + return handleRequest(request, async ({ user }) => { + await assertInternalQuoteAccess(user, true) + const ownerId = request.nextUrl.searchParams.get('ownerId') + if (!ownerId) throw new AppError(ErrorCode.VALIDATION_REQUIRED_FIELD, '请选择报价单') + await readInternalQuote(ownerId) + const { bytes, filename } = await exportSupplierQuote(ownerId) + return new NextResponse(new Uint8Array(bytes), { headers: { + 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Content-Disposition': `attachment; filename="supplier-quote.xlsx"; filename*=UTF-8''${encodeURIComponent(filename).replace(/['()*]/g, (ch) => '%' + ch.charCodeAt(0).toString(16))}`, + 'Cache-Control': 'private, no-store', + } }) + }) +} diff --git a/furniture-3d-system/src/app/api/intake/supplier-quotes/photo/route.ts b/furniture-3d-system/src/app/api/intake/supplier-quotes/photo/route.ts new file mode 100644 index 00000000..246343f2 --- /dev/null +++ b/furniture-3d-system/src/app/api/intake/supplier-quotes/photo/route.ts @@ -0,0 +1,17 @@ +import { NextResponse, type NextRequest } from 'next/server' +import { AppError, ErrorCode } from '@/server/core/errors' +import { handleRequest } from '@/server/core/response' +import { assertInternalQuoteAccess, readInternalQuote } from '@/server/services/supplier-quote/internal.service' +import { readSupplierQuotePhoto } from '@/server/services/supplier-quote/photos.service' + +export function GET(request: NextRequest) { + return handleRequest(request, async ({ user }) => { + await assertInternalQuoteAccess(user) + const ownerId = request.nextUrl.searchParams.get('ownerId') ?? '' + const key = request.nextUrl.searchParams.get('key') ?? '' + const quote = await readInternalQuote(ownerId) + if (!quote.lines.some((line) => line.photoKey === key)) throw new AppError(ErrorCode.AUTH_PERMISSION_DENIED, '照片不属于此报价单') + const bytes = await readSupplierQuotePhoto(ownerId, key) + return new NextResponse(bytes, { headers: { 'Content-Type': 'image/jpeg', 'Cache-Control': 'private, no-store' } }) + }) +} diff --git a/furniture-3d-system/src/app/api/intake/supplier-quotes/route.ts b/furniture-3d-system/src/app/api/intake/supplier-quotes/route.ts new file mode 100644 index 00000000..1c9cbade --- /dev/null +++ b/furniture-3d-system/src/app/api/intake/supplier-quotes/route.ts @@ -0,0 +1,16 @@ +import type { NextRequest } from 'next/server' +import { handleRequest, jsonSuccess } from '@/server/core/response' +import { assertInternalQuoteAccess, listInternalQuotes, readInternalQuote } from '@/server/services/supplier-quote/internal.service' + +export function GET(request: NextRequest) { + return handleRequest(request, async ({ user, requestId }) => { + await assertInternalQuoteAccess(user) + const ownerId = request.nextUrl.searchParams.get('ownerId') + const parsedPage = Number(request.nextUrl.searchParams.get('page') ?? 1) + const page = Number.isSafeInteger(parsedPage) && parsedPage > 0 ? parsedPage : 1 + const parsedLimit = Number(request.nextUrl.searchParams.get('limit') ?? 20) + const limit = [20, 50, 100].includes(parsedLimit) ? parsedLimit : 20 + const data = ownerId ? await readInternalQuote(ownerId) : await listInternalQuotes(page, limit) + return jsonSuccess(data, 200, requestId) + }) +} diff --git a/furniture-3d-system/src/app/api/materials/route.ts b/furniture-3d-system/src/app/api/materials/route.ts index 2f7e93ef..6d1ef813 100644 --- a/furniture-3d-system/src/app/api/materials/route.ts +++ b/furniture-3d-system/src/app/api/materials/route.ts @@ -1,19 +1,26 @@ /** * 材质列表 API * GET /api/materials - 获取所有材质(按分类分组,需要登录) + * GET /api/materials?texture=bound - 只返回资料库已绑定纹理贴图的材质 * POST /api/materials - 新建材质 */ -import { NextRequest } from 'next/server' +import { NextRequest, NextResponse } from 'next/server' import { AppError, ErrorCode } from '@/server/core/errors' -import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' +import { handleRequest, jsonError, jsonSuccess, success } from '@/server/core/response' +import type { ApiResponse } from '@/server/core/types' import { materialService } from '@/server/services' export async function GET(request: NextRequest) { return handleRequest( request, async (ctx) => { - const result = await materialService.findAllGroupedByCategory() + const requireBoundTexture = request.nextUrl.searchParams.get('texture') === 'bound' + const result = await materialService.findAllGroupedByCategory({ requireBoundTexture }) + if (requireBoundTexture) { + // The estimator persists stable texture paths; the default response rewrites them to CDN URLs. + return NextResponse.json>({ ...success(null, { requestId: ctx.requestId }), data: result }) + } return jsonSuccess(result, 200, ctx.requestId) }, { requireAuth: true } diff --git a/furniture-3d-system/src/app/api/storage/object/route.ts b/furniture-3d-system/src/app/api/storage/object/route.ts index 04e0680b..f66ead36 100644 --- a/furniture-3d-system/src/app/api/storage/object/route.ts +++ b/furniture-3d-system/src/app/api/storage/object/route.ts @@ -11,6 +11,7 @@ import { ObjectReadProxyError, } from '@/lib/object-storage-read-response' import { intakeNonIntegratedProductService } from '@/server/services/intake-non-integrated-product.service' +import { isSupplierQuoteAccount, isSupplierQuotePhotoKey, SUPPLIER_QUOTE_IMAGE_ROOT } from '@/lib/supplier-quote/access' export const dynamic = 'force-dynamic' @@ -61,6 +62,12 @@ export async function GET(request: NextRequest) { ) } + const relativeKey = stripConfiguredStoragePrefix(key) + if (relativeKey.startsWith(SUPPLIER_QUOTE_IMAGE_ROOT) && + (!isSupplierQuoteAccount(user) || !isSupplierQuotePhotoKey(relativeKey, user.id))) { + return jsonError(ErrorCode.AUTH_PERMISSION_DENIED, '没有权限查看此报价照片', 403, requestId) + } + const nonIntegratedScope = parseNonIntegratedObjectScope(key) if (nonIntegratedScope) { try { diff --git a/furniture-3d-system/src/app/api/supplier-quote/excel/route.ts b/furniture-3d-system/src/app/api/supplier-quote/excel/route.ts new file mode 100644 index 00000000..baf33611 --- /dev/null +++ b/furniture-3d-system/src/app/api/supplier-quote/excel/route.ts @@ -0,0 +1,17 @@ +import { NextResponse, type NextRequest } from 'next/server' +import { handleRequest } from '@/server/core/response' +import { requireQuoteOwner } from '@/server/services/supplier-quote/sheet.service' +import { exportSupplierQuote } from '@/server/services/supplier-quote/export.service' + +export function GET(request: NextRequest) { + return handleRequest(request, async ({ user }) => { + const { bytes, filename } = await exportSupplierQuote(requireQuoteOwner(user)) + return new NextResponse(new Uint8Array(bytes), { + headers: { + 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Content-Disposition': `attachment; filename="supplier-quote.xlsx"; filename*=UTF-8''${encodeURIComponent(filename).replace(/['()*]/g, (ch) => '%' + ch.charCodeAt(0).toString(16))}`, + 'Cache-Control': 'private, no-store', + }, + }) + }) +} diff --git a/furniture-3d-system/src/app/api/supplier-quote/photo/route.ts b/furniture-3d-system/src/app/api/supplier-quote/photo/route.ts new file mode 100644 index 00000000..3002cb8b --- /dev/null +++ b/furniture-3d-system/src/app/api/supplier-quote/photo/route.ts @@ -0,0 +1,17 @@ +import type { NextRequest } from 'next/server' +import { AppError, ErrorCode } from '@/server/core/errors' +import { handleRequest, jsonSuccess } from '@/server/core/response' +import { MAX_QUOTE_PHOTO_BYTES } from '@/lib/supplier-quote/sheet' +import { requireQuoteOwner } from '@/server/services/supplier-quote/sheet.service' +import { uploadSupplierQuotePhoto } from '@/server/services/supplier-quote/photos.service' + +export function POST(request: NextRequest) { + return handleRequest(request, async ({ user, requestId }) => { + const owner = requireQuoteOwner(user) + if (Number(request.headers.get('content-length')) > MAX_QUOTE_PHOTO_BYTES + 64 * 1024) { + throw new AppError(ErrorCode.FILE_TOO_LARGE, '照片不能超过 12 MB') + } + const form = await request.formData().catch(() => null) + return jsonSuccess(await uploadSupplierQuotePhoto(owner, form?.get('photo') ?? null), 201, requestId) + }) +} diff --git a/furniture-3d-system/src/app/api/supplier-quote/route.ts b/furniture-3d-system/src/app/api/supplier-quote/route.ts new file mode 100644 index 00000000..0b92e97a --- /dev/null +++ b/furniture-3d-system/src/app/api/supplier-quote/route.ts @@ -0,0 +1,13 @@ +import type { NextRequest } from 'next/server' +import { handleRequest, jsonSuccess } from '@/server/core/response' +import { readSupplierQuote, requireQuoteOwner, saveSupplierQuote } from '@/server/services/supplier-quote/sheet.service' + +export function GET(request: NextRequest) { + return handleRequest(request, async ({ user, requestId }) => + jsonSuccess(await readSupplierQuote(requireQuoteOwner(user)), 200, requestId)) +} + +export function PUT(request: NextRequest) { + return handleRequest(request, async ({ user, requestId }) => + jsonSuccess(await saveSupplierQuote(requireQuoteOwner(user), await request.json().catch(() => null)), 200, requestId)) +} diff --git a/furniture-3d-system/src/app/api/supplier-quote/speech/route.ts b/furniture-3d-system/src/app/api/supplier-quote/speech/route.ts new file mode 100644 index 00000000..fda41a82 --- /dev/null +++ b/furniture-3d-system/src/app/api/supplier-quote/speech/route.ts @@ -0,0 +1,12 @@ +import type { NextRequest } from 'next/server' +import { handleRequest, jsonSuccess } from '@/server/core/response' +import { requireQuoteOwner } from '@/server/services/supplier-quote/sheet.service' +import { transcribeQuoteSpeech } from '@/server/services/supplier-quote/speech.service' + +export function POST(request: NextRequest) { + return handleRequest(request, async ({ user, requestId }) => { + requireQuoteOwner(user) + const form = await request.formData() + return jsonSuccess({ text: await transcribeQuoteSpeech(form.get('audio')) }, 200, requestId) + }) +} diff --git a/furniture-3d-system/src/app/api/supplier-response/[token]/route.ts b/furniture-3d-system/src/app/api/supplier-response/[token]/route.ts index 39e6d2c6..3f320647 100644 --- a/furniture-3d-system/src/app/api/supplier-response/[token]/route.ts +++ b/furniture-3d-system/src/app/api/supplier-response/[token]/route.ts @@ -5,11 +5,14 @@ import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' import type { SupplierReissueResponseInput } from '@/lib/supplier-reissue-response' import { checkShareAccessRateLimit } from '@/server/services/share-rate-limit.service' import { supplierReissueResponseService } from '@/server/services/supplier-reissue-response.service' +import { wecomReissueService } from '@/server/services/wecom-reissue.service' const payloadSchema = z.object({ items: z.array(z.object({ recordId: z.string().trim().min(1).max(200), + reasonRoot: z.string().trim().min(1).max(40), reasonCategory: z.string().trim().min(1).max(300), + reasonOtherNote: z.string().trim().max(1000).optional().default(''), solution: z.string().trim().min(2).max(1000), expectedSolveDate: z.string().trim().regex(/^\d{4}-\d{2}-\d{2}$/), })).min(1).max(200), @@ -51,19 +54,26 @@ export async function POST( if (!parsed.success) { return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '填报数据格式不正确或字段未填写完整', 400, ctx.requestId) } - return jsonSuccess( - await supplierReissueResponseService.submitResponses( - token, - parsed.data.items as SupplierReissueResponseInput[], - { + const submission = await supplierReissueResponseService.submitResponses( + token, + parsed.data.items as SupplierReissueResponseInput[], + { ip: request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() || request.headers.get('x-real-ip')?.trim() || '', userAgent: request.headers.get('user-agent')?.trim() || '', - }, - ), - 200, - ctx.requestId, + }, ) + if (submission.pendingReasonReviewRecordIds.length) { + void wecomReissueService + .notifyPendingReasonReviews(submission.pendingReasonReviewRecordIds) + .catch((error) => { + console.warn( + '非工厂原因待判定提醒发送失败:', + error instanceof Error ? error.message : '未知错误', + ) + }) + } + return jsonSuccess(submission, 200, ctx.requestId) }, { requireAuth: false }) } diff --git a/furniture-3d-system/src/app/api/supply-chain/brand-upgrade-approvals/[id]/route.ts b/furniture-3d-system/src/app/api/supply-chain/brand-upgrade-approvals/[id]/route.ts index cbb391bd..3912121f 100644 --- a/furniture-3d-system/src/app/api/supply-chain/brand-upgrade-approvals/[id]/route.ts +++ b/furniture-3d-system/src/app/api/supply-chain/brand-upgrade-approvals/[id]/route.ts @@ -1,9 +1,16 @@ import { NextRequest } from 'next/server' -import { handleRequest, jsonSuccess } from '@/server/core/response' -import { supplyChainBrandUpgradeApprovalService } from '@/server/services/supply-chain-brand-upgrade-approval.service' +import { ErrorCode } from '@/server/core/errors' +import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' +import { + hasBrandUpgradeApprovalAccess, + supplyChainBrandUpgradeApprovalService, +} from '@/server/services/supply-chain-brand-upgrade-approval.service' export async function GET(request: NextRequest, context: { params: Promise<{ id: string }> }) { return handleRequest(request, async (ctx) => { + if (!(await hasBrandUpgradeApprovalAccess(ctx.user))) { + return jsonError(ErrorCode.AUTH_PERMISSION_DENIED, '当前账号没有品牌升级审核查看权限', 403, ctx.requestId) + } const { id } = await context.params return jsonSuccess(await supplyChainBrandUpgradeApprovalService.get(id), 200, ctx.requestId) }, { requireAuth: true }) diff --git a/furniture-3d-system/src/app/api/supply-chain/brand-upgrade-approvals/config/route.ts b/furniture-3d-system/src/app/api/supply-chain/brand-upgrade-approvals/config/route.ts index e992d45c..5ae967a5 100644 --- a/furniture-3d-system/src/app/api/supply-chain/brand-upgrade-approvals/config/route.ts +++ b/furniture-3d-system/src/app/api/supply-chain/brand-upgrade-approvals/config/route.ts @@ -1,9 +1,14 @@ import { NextRequest } from 'next/server' -import { handleRequest, jsonSuccess } from '@/server/core/response' +import { isAdmin } from '@/lib/role-scope' +import { ErrorCode } from '@/server/core/errors' +import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' import { supplyChainBrandUpgradeApprovalService } from '@/server/services/supply-chain-brand-upgrade-approval.service' export async function GET(request: NextRequest) { return handleRequest(request, async (ctx) => { + if (!isAdmin(ctx.user)) { + return jsonError(ErrorCode.AUTH_PERMISSION_DENIED, '只有管理员可以配置审批人', 403, ctx.requestId) + } return jsonSuccess(await supplyChainBrandUpgradeApprovalService.getConfig(), 200, ctx.requestId) }, { requireAuth: true }) } diff --git a/furniture-3d-system/src/app/api/supply-chain/brand-upgrade-approvals/route.ts b/furniture-3d-system/src/app/api/supply-chain/brand-upgrade-approvals/route.ts index ed2e5160..d3bba845 100644 --- a/furniture-3d-system/src/app/api/supply-chain/brand-upgrade-approvals/route.ts +++ b/furniture-3d-system/src/app/api/supply-chain/brand-upgrade-approvals/route.ts @@ -1,9 +1,16 @@ import { NextRequest } from 'next/server' -import { handleRequest, jsonSuccess } from '@/server/core/response' -import { supplyChainBrandUpgradeApprovalService } from '@/server/services/supply-chain-brand-upgrade-approval.service' +import { ErrorCode } from '@/server/core/errors' +import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' +import { + hasBrandUpgradeApprovalAccess, + supplyChainBrandUpgradeApprovalService, +} from '@/server/services/supply-chain-brand-upgrade-approval.service' export async function GET(request: NextRequest) { return handleRequest(request, async (ctx) => { + if (!(await hasBrandUpgradeApprovalAccess(ctx.user))) { + return jsonError(ErrorCode.AUTH_PERMISSION_DENIED, '当前账号没有品牌升级审核查看权限', 403, ctx.requestId) + } const periodKey = request.nextUrl.searchParams.get('period')?.trim() || undefined const status = request.nextUrl.searchParams.get('status')?.trim() || undefined return jsonSuccess({ diff --git a/furniture-3d-system/src/app/api/supply-chain/clearance/review-workbench/route.test.ts b/furniture-3d-system/src/app/api/supply-chain/clearance/review-workbench/route.test.ts new file mode 100644 index 00000000..1f28f420 --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/clearance/review-workbench/route.test.ts @@ -0,0 +1,82 @@ +import type { NextRequest } from 'next/server' + +const mockHandleRequest = jest.fn() +const mockJsonSuccess = jest.fn() +const mockJsonError = jest.fn() +const mockGetUserAccess = jest.fn() +const mockBatchReviewTasks = jest.fn() +const mockForcePushReviewTasks = jest.fn() + +jest.mock('@/server/core/response', () => ({ + handleRequest: (...args: unknown[]) => mockHandleRequest(...args), + jsonSuccess: (...args: unknown[]) => mockJsonSuccess(...args), + jsonError: (...args: unknown[]) => mockJsonError(...args), +})) + +jest.mock('@/server/services/supply-chain-clearance.service', () => ({ + supplyChainClearanceService: { + batchReviewTasks: (...args: unknown[]) => mockBatchReviewTasks(...args), + forcePushReviewTasks: (...args: unknown[]) => mockForcePushReviewTasks(...args), + }, +})) + +jest.mock('@/server/services/supply-chain-permission-settings.service', () => ({ + supplyChainPermissionSettingsService: { + getUserAccess: (...args: unknown[]) => mockGetUserAccess(...args), + }, +})) + +const { POST } = require('./route') + +describe('POST /api/supply-chain/clearance/review-workbench', () => { + beforeEach(() => { + jest.clearAllMocks() + mockHandleRequest.mockImplementation(async ( + _request: NextRequest, + handler: (ctx: unknown) => unknown, + ) => handler({ + requestId: 'req-review-workbench', + user: { id: 'manager-1', name: '测试经管', role: 'MANAGEMENT' }, + })) + mockJsonSuccess.mockImplementation((data) => ({ data })) + mockJsonError.mockImplementation((code, message, status) => ({ + rejected: true, + code, + message, + status, + })) + mockGetUserAccess.mockResolvedValue({ view: true, download: true, edit: true }) + mockForcePushReviewTasks.mockResolvedValue({ + count: 1, + ids: ['task-a'], + stage: 'APPROVED', + approvedCount: 1, + awaitingConfirmationCount: 0, + }) + }) + + it('dispatches force-push to the dedicated reviewer action', async () => { + const response = await POST({ + json: async () => ({ + items: [{ id: 'task-a' }], + action: 'force-push', + }), + } as NextRequest) + + expect(response).toEqual({ + data: { + count: 1, + ids: ['task-a'], + stage: 'APPROVED', + approvedCount: 1, + awaitingConfirmationCount: 0, + }, + }) + expect(mockForcePushReviewTasks).toHaveBeenCalledWith({ + ids: ['task-a'], + note: undefined, + user: expect.objectContaining({ id: 'manager-1' }), + }) + expect(mockBatchReviewTasks).not.toHaveBeenCalled() + }) +}) diff --git a/furniture-3d-system/src/app/api/supply-chain/clearance/review-workbench/route.ts b/furniture-3d-system/src/app/api/supply-chain/clearance/review-workbench/route.ts index 4511e069..b4ef8db2 100644 --- a/furniture-3d-system/src/app/api/supply-chain/clearance/review-workbench/route.ts +++ b/furniture-3d-system/src/app/api/supply-chain/clearance/review-workbench/route.ts @@ -11,7 +11,7 @@ const reviewSchema = z.object({ taskQty: z.number().int().min(1).optional(), discount: z.number().min(0.1).max(1).optional(), }).strict()).min(1).max(500), - action: z.enum(['approve', 'reject']), + action: z.enum(['approve', 'reject', 'force-push']), note: z.string().trim().max(1000).optional(), }).strict() @@ -27,6 +27,15 @@ export async function GET(request: NextRequest) { const roundValue = Number(request.nextUrl.searchParams.get('round') ?? '') const pageValue = Number(request.nextUrl.searchParams.get('page') ?? '') const pageSizeValue = Number(request.nextUrl.searchParams.get('pageSize') ?? '') + const rawFilters = request.nextUrl.searchParams.get('filters') + let filters: unknown = [] + if (rawFilters) { + try { + filters = JSON.parse(rawFilters) + } catch { + return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '自定义筛选参数格式不正确', 400, ctx.requestId) + } + } return jsonSuccess(await supplyChainClearanceService.getReviewWorkbench({ periodKey: request.nextUrl.searchParams.get('period'), round: roundValue === 1 || roundValue === 2 ? roundValue : null, @@ -35,6 +44,7 @@ export async function GET(request: NextRequest) { query: request.nextUrl.searchParams.get('query') ?? '', profitCenter: request.nextUrl.searchParams.get('profitCenter') ?? '', status: request.nextUrl.searchParams.get('status') ?? '', + filters, }), 200, ctx.requestId) }, { requireAuth: true }) } @@ -53,9 +63,21 @@ export async function POST(request: NextRequest) { if (!parsed.success) { return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '批量审核参数不正确', 400, ctx.requestId) } - return jsonSuccess(await supplyChainClearanceService.batchReviewTasks({ - ...parsed.data, - user: ctx.user, - }), 200, ctx.requestId) + let result + if (parsed.data.action === 'force-push') { + result = await supplyChainClearanceService.forcePushReviewTasks({ + ids: parsed.data.items.map((item) => item.id), + note: parsed.data.note, + user: ctx.user, + }) + } else { + const action: 'approve' | 'reject' = parsed.data.action + result = await supplyChainClearanceService.batchReviewTasks({ + ...parsed.data, + action, + user: ctx.user, + }) + } + return jsonSuccess(result, 200, ctx.requestId) }, { requireAuth: true }) } diff --git a/furniture-3d-system/src/app/api/supply-chain/management/daily-express-volume/export/route.ts b/furniture-3d-system/src/app/api/supply-chain/management/daily-express-volume/export/route.ts new file mode 100644 index 00000000..c1eaf0af --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/management/daily-express-volume/export/route.ts @@ -0,0 +1,14 @@ +import { NextResponse, type NextRequest } from 'next/server' +import { handleRequest } from '@/server/core/response' +import { dailyExpressVolumeService } from '@/server/services/daily-express-volume.service' +export const dynamic = 'force-dynamic' +export async function GET(request: NextRequest) { + return handleRequest(request, async (ctx) => { + const params = request.nextUrl.searchParams + const file = await dailyExpressVolumeService.export({ + view: params.get('view') || 'overview', date: params.get('date') || undefined, origin: params.get('origin') || '', + dateFrom: params.get('dateFrom') ?? undefined, dateTo: params.get('dateTo') ?? undefined, + }, ctx.user) + return new NextResponse(new Uint8Array(file.bytes), { headers: { 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(file.filename)}`, 'Cache-Control': 'private, no-store' } }) + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/api/supply-chain/management/daily-express-volume/route.ts b/furniture-3d-system/src/app/api/supply-chain/management/daily-express-volume/route.ts new file mode 100644 index 00000000..3e798cc5 --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/management/daily-express-volume/route.ts @@ -0,0 +1,14 @@ +import type { NextRequest } from 'next/server' +import { handleRequest, jsonSuccess } from '@/server/core/response' +import { dailyExpressVolumeService } from '@/server/services/daily-express-volume.service' +export const dynamic = 'force-dynamic' +export async function GET(request: NextRequest) { + return handleRequest(request, async (ctx) => { + const params = request.nextUrl.searchParams + const response = jsonSuccess(await dailyExpressVolumeService.getDashboard({ + view: params.get('view') || 'overview', date: params.get('date') || undefined, origin: params.get('origin') || '', + dateFrom: params.get('dateFrom') ?? undefined, dateTo: params.get('dateTo') ?? undefined, + }, ctx.user), 200, ctx.requestId) + response.headers.set('Cache-Control', 'private, no-store'); return response + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/api/supply-chain/management/inventory-monitoring/config/route.ts b/furniture-3d-system/src/app/api/supply-chain/management/inventory-monitoring/config/route.ts new file mode 100644 index 00000000..f38d12f3 --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/management/inventory-monitoring/config/route.ts @@ -0,0 +1,50 @@ +import { NextRequest } from 'next/server' +import { ErrorCode } from '@/server/core/errors' +import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' +import { inventoryMonitoringService } from '@/server/services/inventory-monitoring.service' +import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service' + +export const dynamic = 'force-dynamic' + +export async function GET(request: NextRequest) { + return handleRequest(request, async (ctx) => { + const access = await supplyChainPermissionSettingsService.getUserAccess( + ctx.user, + 'managementBlankPage9', + ) + if (!access.view) { + return jsonError(ErrorCode.AUTH_PERMISSION_DENIED, '没有库存监控查看权限', 403, ctx.requestId) + } + return jsonSuccess( + await inventoryMonitoringService.getConfig(), + 200, + ctx.requestId, + ) + }, { requireAuth: true }) +} + +export async function PUT(request: NextRequest) { + return handleRequest(request, async (ctx) => { + const access = await supplyChainPermissionSettingsService.getUserAccess( + ctx.user, + 'managementBlankPage9', + ) + if (!access.edit) { + return jsonError(ErrorCode.AUTH_PERMISSION_DENIED, '没有库存监控配置权限', 403, ctx.requestId) + } + const body = await request.json().catch(() => null) + if (!body || typeof body !== 'object' || Array.isArray(body)) { + return jsonError( + ErrorCode.VALIDATION_INVALID_FORMAT, + '库存监控配置格式不正确', + 400, + ctx.requestId, + ) + } + return jsonSuccess( + await inventoryMonitoringService.saveConfig(body), + 200, + ctx.requestId, + ) + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/api/supply-chain/management/inventory-monitoring/distribution-foreign/operation-feedback/route.ts b/furniture-3d-system/src/app/api/supply-chain/management/inventory-monitoring/distribution-foreign/operation-feedback/route.ts new file mode 100644 index 00000000..4e2bc933 --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/management/inventory-monitoring/distribution-foreign/operation-feedback/route.ts @@ -0,0 +1,57 @@ +import { NextRequest } from 'next/server' +import { ErrorCode } from '@/server/core/errors' +import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' +import { inventoryMonitoringService } from '@/server/services/inventory-monitoring.service' +import { resolveDistributionForeignAccess } from '@/server/services/inventory-monitoring-distribution-foreign-access' +import type { DistributionForeignChannel } from '@/lib/inventory-monitoring-distribution-foreign' + +export const dynamic = 'force-dynamic' + +export async function POST(request: NextRequest) { + return handleRequest(request, async (ctx) => { + const body = await request.json().catch(() => null) as Record | null + const channel = String(body?.channel ?? '') as DistributionForeignChannel + if (!['foreign', 'distribution', 'shandongForeign'].includes(channel)) { + return jsonError( + ErrorCode.VALIDATION_INVALID_FORMAT, + '运营文本反馈必须指定有效分类', + 400, + ctx.requestId, + ) + } + const access = resolveDistributionForeignAccess(ctx.user) + if (!access[channel].edit) { + return jsonError( + ErrorCode.AUTH_PERMISSION_DENIED, + '当前账号没有该分类的运营文本反馈编辑权限', + 403, + ctx.requestId, + ) + } + if (!body || typeof body.barcode !== 'string' || typeof body.operationFeedback !== 'string') { + return jsonError( + ErrorCode.VALIDATION_INVALID_FORMAT, + '运营文本反馈参数格式不正确', + 400, + ctx.requestId, + ) + } + const current = await inventoryMonitoringService.getDistributionForeignInventory(access) + if (!current.rows[channel].some((row) => row.barcode === String(body.barcode).toUpperCase())) { + return jsonError( + ErrorCode.AUTH_PERMISSION_DENIED, + '当前账号不能编辑该商品的运营文本反馈', + 403, + ctx.requestId, + ) + } + return jsonSuccess( + await inventoryMonitoringService.saveOperationFeedback({ + barcode: body.barcode, + operationFeedback: body.operationFeedback, + }), + 200, + ctx.requestId, + ) + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/api/supply-chain/management/inventory-monitoring/distribution-foreign/route.ts b/furniture-3d-system/src/app/api/supply-chain/management/inventory-monitoring/distribution-foreign/route.ts new file mode 100644 index 00000000..6a7848a9 --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/management/inventory-monitoring/distribution-foreign/route.ts @@ -0,0 +1,84 @@ +import { NextRequest } from 'next/server' +import { ErrorCode } from '@/server/core/errors' +import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' +import { inventoryMonitoringService } from '@/server/services/inventory-monitoring.service' +import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service' +import { resolveDistributionForeignAccess } from '@/server/services/inventory-monitoring-distribution-foreign-access' +import type { DistributionForeignChannel } from '@/lib/inventory-monitoring-distribution-foreign' + +export const dynamic = 'force-dynamic' + +export async function GET(request: NextRequest) { + return handleRequest(request, async (ctx) => { + const access = await supplyChainPermissionSettingsService.getUserAccess( + ctx.user, + 'managementBlankPage9', + ) + if (!access.view) { + return jsonError( + ErrorCode.AUTH_PERMISSION_DENIED, + '当前账号没有库存监控查看权限', + 403, + ctx.requestId, + ) + } + const data = await inventoryMonitoringService.getDistributionForeignInventory( + resolveDistributionForeignAccess(ctx.user), + ) + const response = jsonSuccess(data, 200, ctx.requestId) + response.headers.set( + 'Cache-Control', + 'private, max-age=30, stale-while-revalidate=60', + ) + return response + }, { requireAuth: true }) +} + +export async function POST(request: NextRequest) { + return handleRequest(request, async (ctx) => { + const body = await request.json().catch(() => null) as Record | null + const channel = String(body?.channel ?? '') as DistributionForeignChannel + if (!['foreign', 'shandongForeign'].includes(channel)) { + return jsonError( + ErrorCode.VALIDATION_INVALID_FORMAT, + '外贸反馈出货时间必须指定有效分类', + 400, + ctx.requestId, + ) + } + const access = resolveDistributionForeignAccess(ctx.user) + if (!access[channel].edit) { + return jsonError( + ErrorCode.AUTH_PERMISSION_DENIED, + '当前账号没有该分类的外贸反馈出货时间编辑权限', + 403, + ctx.requestId, + ) + } + if (!body || typeof body.barcode !== 'string' || typeof body.feedbackShipTime !== 'string') { + return jsonError( + ErrorCode.VALIDATION_INVALID_FORMAT, + '外贸反馈出货时间参数格式不正确', + 400, + ctx.requestId, + ) + } + const current = await inventoryMonitoringService.getDistributionForeignInventory(access) + if (!current.rows[channel].some((row) => row.barcode === String(body.barcode).toUpperCase())) { + return jsonError( + ErrorCode.AUTH_PERMISSION_DENIED, + '当前账号不能编辑该商品的外贸反馈出货时间', + 403, + ctx.requestId, + ) + } + return jsonSuccess( + await inventoryMonitoringService.saveForeignFeedbackShipTime({ + barcode: body.barcode, + feedbackShipTime: body.feedbackShipTime, + }), + 200, + ctx.requestId, + ) + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/api/supply-chain/management/inventory-monitoring/export/route.ts b/furniture-3d-system/src/app/api/supply-chain/management/inventory-monitoring/export/route.ts new file mode 100644 index 00000000..17b1e7ea --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/management/inventory-monitoring/export/route.ts @@ -0,0 +1,37 @@ +import { NextRequest, NextResponse } from 'next/server' +import { ErrorCode } from '@/server/core/errors' +import { handleRequest, jsonError } from '@/server/core/response' +import { inventoryMonitoringService } from '@/server/services/inventory-monitoring.service' +import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service' +import { parseInventoryMonitoringQuery } from '../query' + +export const dynamic = 'force-dynamic' + +export async function GET(request: NextRequest) { + return handleRequest(request, async (ctx) => { + const access = await supplyChainPermissionSettingsService.getUserAccess( + ctx.user, + 'managementBlankPage9', + ) + if (!access.download) { + return jsonError(ErrorCode.AUTH_PERMISSION_DENIED, '没有库存监控导出权限', 403, ctx.requestId) + } + const query = parseInventoryMonitoringQuery(request) + if (!query) { + return jsonError( + ErrorCode.VALIDATION_INVALID_FORMAT, + '库存监控导出参数不正确', + 400, + ctx.requestId, + ) + } + const file = await inventoryMonitoringService.export(query) + return new NextResponse(new Uint8Array(file.content), { + headers: { + 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(file.fileName)}`, + 'Cache-Control': 'private, no-store', + }, + }) + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/api/supply-chain/management/inventory-monitoring/options/route.ts b/furniture-3d-system/src/app/api/supply-chain/management/inventory-monitoring/options/route.ts new file mode 100644 index 00000000..1e102683 --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/management/inventory-monitoring/options/route.ts @@ -0,0 +1,42 @@ +import { NextRequest } from 'next/server' +import { z } from 'zod' +import { + INVENTORY_MONITORING_TEXT_RULE_FIELDS, + type InventoryMonitoringRuleField, +} from '@/lib/inventory-monitoring' +import { ErrorCode } from '@/server/core/errors' +import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' +import { inventoryMonitoringService } from '@/server/services/inventory-monitoring.service' +import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service' + +const querySchema = z.object({ + field: z.enum(INVENTORY_MONITORING_TEXT_RULE_FIELDS), + q: z.string().trim().max(200).default(''), + limit: z.coerce.number().int().min(1).max(500).default(200), +}) + +export const dynamic = 'force-dynamic' + +export async function GET(request: NextRequest) { + return handleRequest(request, async (ctx) => { + const access = await supplyChainPermissionSettingsService.getUserAccess( + ctx.user, + 'managementBlankPage9', + ) + if (!access.view) { + return jsonError(ErrorCode.AUTH_PERMISSION_DENIED, '没有库存监控查看权限', 403, ctx.requestId) + } + const parsed = querySchema.safeParse( + Object.fromEntries(request.nextUrl.searchParams.entries()), + ) + if (!parsed.success) { + return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '筛选字段不正确', 400, ctx.requestId) + } + const values = await inventoryMonitoringService.getFilterOptions({ + field: parsed.data.field as InventoryMonitoringRuleField, + query: parsed.data.q, + limit: parsed.data.limit, + }) + return jsonSuccess({ values }, 200, ctx.requestId) + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/api/supply-chain/management/inventory-monitoring/overview/route.ts b/furniture-3d-system/src/app/api/supply-chain/management/inventory-monitoring/overview/route.ts new file mode 100644 index 00000000..157cc963 --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/management/inventory-monitoring/overview/route.ts @@ -0,0 +1,29 @@ +import { NextRequest } from 'next/server' +import { ErrorCode } from '@/server/core/errors' +import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' +import { inventoryMonitoringService } from '@/server/services/inventory-monitoring.service' +import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service' + +export const dynamic = 'force-dynamic' + +export async function GET(request: NextRequest) { + return handleRequest(request, async (ctx) => { + const access = await supplyChainPermissionSettingsService.getUserAccess( + ctx.user, + 'managementBlankPage9', + ) + if (!access.view) { + return jsonError(ErrorCode.AUTH_PERMISSION_DENIED, '没有库存总览查看权限', 403, ctx.requestId) + } + const response = jsonSuccess( + await inventoryMonitoringService.getOverview(), + 200, + ctx.requestId, + ) + response.headers.set( + 'Cache-Control', + 'private, max-age=30, stale-while-revalidate=60', + ) + return response + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/api/supply-chain/management/inventory-monitoring/query.ts b/furniture-3d-system/src/app/api/supply-chain/management/inventory-monitoring/query.ts new file mode 100644 index 00000000..4d4778ff --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/management/inventory-monitoring/query.ts @@ -0,0 +1,88 @@ +import { NextRequest } from 'next/server' +import { z } from 'zod' +import { + INVENTORY_MONITORING_COLUMNS, + type InventoryMonitoringFilters, + type InventoryMonitoringSort, +} from '@/lib/inventory-monitoring' + +const filterValue = z.union([ + z.string().trim().max(200), + z.array(z.string().trim().min(1).max(200)).min(1).max(200), +]).optional() + +const filtersSchema = z.object({ + keyword: z.string().trim().max(200).optional(), + styleCode: filterValue, + itemNumber: filterValue, + barcode: filterValue, + productionStatus: filterValue, + supplier: filterValue, + purchaser: filterValue, + inOutWarehouse: filterValue, + opsHead: filterValue, + opsDeptHead: filterValue, + profitCenter: filterValue, + isNewProduct: filterValue, + sabcRating: filterValue, + movingStatus: filterValue, + slowStatus: filterValue, + warningStatus: filterValue, +}) + +const querySchema = z.object({ + page: z.coerce.number().int().min(1).default(1), + pageSize: z.coerce.number().int().min(1).max(200).default(50), + refresh: z.enum(['0', '1']).default('0'), + slowMode: z.enum(['30d', 'stocking']).default('30d'), + sortKey: z.string().trim().max(50).default('totalValue'), + sortDirection: z.enum(['asc', 'desc']).default('desc'), + filters: z.string().trim().max(10_000).optional(), + columns: z.string().trim().max(10_000).optional(), +}) + +const allowedSortKeys: ReadonlySet = new Set( + INVENTORY_MONITORING_COLUMNS.map((column) => column.key), +) + +export function parseInventoryMonitoringQuery(request: NextRequest) { + const parsed = querySchema.safeParse( + Object.fromEntries(request.nextUrl.searchParams.entries()), + ) + if (!parsed.success) return null + let filters: InventoryMonitoringFilters = {} + if (parsed.data.filters) { + try { + const parsedFilters = filtersSchema.safeParse(JSON.parse(parsed.data.filters)) + if (!parsedFilters.success) return null + filters = parsedFilters.data + } catch { + return null + } + } + const sort: InventoryMonitoringSort = { + key: allowedSortKeys.has(parsed.data.sortKey) ? parsed.data.sortKey : 'totalValue', + direction: parsed.data.sortDirection, + } + let columns: string[] | undefined + if (parsed.data.columns) { + try { + const parsedColumns = JSON.parse(parsed.data.columns) + if (!Array.isArray(parsedColumns)) return null + columns = Array.from(new Set(parsedColumns.filter((key): key is string => ( + typeof key === 'string' && allowedSortKeys.has(key) + )))) + } catch { + return null + } + } + return { + filters, + sort, + page: parsed.data.page, + pageSize: parsed.data.pageSize, + refresh: parsed.data.refresh === '1', + slowMode: parsed.data.slowMode, + columns, + } +} diff --git a/furniture-3d-system/src/app/api/supply-chain/management/inventory-monitoring/route.ts b/furniture-3d-system/src/app/api/supply-chain/management/inventory-monitoring/route.ts new file mode 100644 index 00000000..14c94fd1 --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/management/inventory-monitoring/route.ts @@ -0,0 +1,38 @@ +import { NextRequest } from 'next/server' +import { ErrorCode } from '@/server/core/errors' +import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' +import { inventoryMonitoringService } from '@/server/services/inventory-monitoring.service' +import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service' +import { parseInventoryMonitoringQuery } from './query' + +export const dynamic = 'force-dynamic' + +export async function GET(request: NextRequest) { + return handleRequest(request, async (ctx) => { + const access = await supplyChainPermissionSettingsService.getUserAccess( + ctx.user, + 'managementBlankPage9', + ) + if (!access.view) { + return jsonError( + ErrorCode.AUTH_PERMISSION_DENIED, + '当前账号没有库存监控查看权限', + 403, + ctx.requestId, + ) + } + const query = parseInventoryMonitoringQuery(request) + if (!query) { + return jsonError( + ErrorCode.VALIDATION_INVALID_FORMAT, + '库存监控查询参数不正确', + 400, + ctx.requestId, + ) + } + const data = await inventoryMonitoringService.getPage(query) + const response = jsonSuccess(data, 200, ctx.requestId) + response.headers.set('Cache-Control', 'private, no-store') + return response + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/api/supply-chain/management/modular-product-processing-orders/components/column-options/route.ts b/furniture-3d-system/src/app/api/supply-chain/management/modular-product-processing-orders/components/column-options/route.ts index 8ec358d0..ba7bf41c 100644 --- a/furniture-3d-system/src/app/api/supply-chain/management/modular-product-processing-orders/components/column-options/route.ts +++ b/furniture-3d-system/src/app/api/supply-chain/management/modular-product-processing-orders/components/column-options/route.ts @@ -24,6 +24,9 @@ const querySchema = z.object({ column: z.string().trim().min(1).max(64), keyword: z.string().trim().max(160).optional(), limit: z.coerce.number().int().min(1).max(200).optional(), + snapshotDate: z.string().trim().regex(/^\d{4}-\d{2}-\d{2}$/).optional(), + batchKey: z.string().trim().regex(/^\d{4}-\d{2}-\d{2}:(?:09:00|15:00|legacy)$/).optional(), + generationSlot: z.enum(['09:00', '15:00']).optional(), filters: z.string().max(3000).optional().transform((value, context) => { if (!value) return undefined try { @@ -60,6 +63,9 @@ export async function GET(request: NextRequest) { keyword: parsed.data.keyword, limit: parsed.data.limit, columnFilters: parsed.data.filters?.columnFilters, + snapshotDate: parsed.data.snapshotDate, + batchKey: parsed.data.batchKey, + generationSlot: parsed.data.generationSlot, }), 200, ctx.requestId, diff --git a/furniture-3d-system/src/app/api/supply-chain/management/modular-product-processing-orders/components/route.ts b/furniture-3d-system/src/app/api/supply-chain/management/modular-product-processing-orders/components/route.ts index 2744d7e0..eb7e7cb1 100644 --- a/furniture-3d-system/src/app/api/supply-chain/management/modular-product-processing-orders/components/route.ts +++ b/furniture-3d-system/src/app/api/supply-chain/management/modular-product-processing-orders/components/route.ts @@ -22,6 +22,9 @@ const querySchema = z.object({ barcode: z.string().trim().min(1).max(160), page: z.coerce.number().int().min(1).default(1), pageSize: z.coerce.number().int().min(1).max(1000).default(50), + snapshotDate: z.string().trim().regex(/^\d{4}-\d{2}-\d{2}$/).optional(), + batchKey: z.string().trim().regex(/^\d{4}-\d{2}-\d{2}:(?:09:00|15:00|legacy)$/).optional(), + generationSlot: z.enum(['09:00', '15:00']).optional(), sortKey: z.string().trim().max(64).optional(), sortDirection: z.enum(['asc', 'desc']).optional(), columnFilters: z.string().max(3000).optional().transform((value, context) => { @@ -64,6 +67,9 @@ export async function GET(request: NextRequest) { columnFilters: parsed.data.columnFilters, sortKey: parsed.data.sortKey, sortDirection: parsed.data.sortDirection, + snapshotDate: parsed.data.snapshotDate, + batchKey: parsed.data.batchKey, + generationSlot: parsed.data.generationSlot, }, ), 200, diff --git a/furniture-3d-system/src/app/api/supply-chain/management/modular-product-processing-orders/export/route.ts b/furniture-3d-system/src/app/api/supply-chain/management/modular-product-processing-orders/export/route.ts index 6cb7cc7b..214ac0e5 100644 --- a/furniture-3d-system/src/app/api/supply-chain/management/modular-product-processing-orders/export/route.ts +++ b/furniture-3d-system/src/app/api/supply-chain/management/modular-product-processing-orders/export/route.ts @@ -40,6 +40,8 @@ const payloadSchema = z.object({ sortDirection: z.enum(['asc', 'desc']).optional(), componentSortKey: z.string().trim().max(64).optional(), componentSortDirection: z.enum(['asc', 'desc']).optional(), + snapshotDate: z.string().trim().regex(/^\d{4}-\d{2}-\d{2}$/).optional(), + generationSlot: z.enum(['09:00', '15:00']).optional(), }).refine((filters) => !filters.sortKey || isModularProcessingOrderSortKey(filters.sortKey), { message: '主表排序字段不正确', path: ['sortKey'], diff --git a/furniture-3d-system/src/app/api/supply-chain/management/pickup-24h-timeliness/alert-recipients/route.ts b/furniture-3d-system/src/app/api/supply-chain/management/pickup-24h-timeliness/alert-recipients/route.ts new file mode 100644 index 00000000..6835c3d4 --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/management/pickup-24h-timeliness/alert-recipients/route.ts @@ -0,0 +1,33 @@ +import { NextRequest } from 'next/server' +import { handleRequest, jsonSuccess } from '@/server/core/response' +import { pickup24hTimelinessAlertRecipientService } from '@/server/services/pickup-24h-timeliness-alert-recipient.service' + +export async function GET(request: NextRequest) { + return handleRequest( + request, + async (ctx) => jsonSuccess( + await pickup24hTimelinessAlertRecipientService.getSettings(ctx.user), + 200, + ctx.requestId, + ), + { requireAuth: true }, + ) +} + +export async function PUT(request: NextRequest) { + return handleRequest( + request, + async (ctx) => { + const body = await request.json().catch(() => null) as { userIds?: unknown } | null + return jsonSuccess( + await pickup24hTimelinessAlertRecipientService.saveSettings( + ctx.user, + body?.userIds, + ), + 200, + ctx.requestId, + ) + }, + { requireAuth: true }, + ) +} diff --git a/furniture-3d-system/src/app/api/supply-chain/management/pickup-24h-timeliness/analysis/export/route.ts b/furniture-3d-system/src/app/api/supply-chain/management/pickup-24h-timeliness/analysis/export/route.ts new file mode 100644 index 00000000..9e3864fd --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/management/pickup-24h-timeliness/analysis/export/route.ts @@ -0,0 +1,124 @@ +import { NextRequest, NextResponse } from 'next/server' +import { z } from 'zod' +import { ErrorCode } from '@/server/core/errors' +import { handleRequest, jsonError } from '@/server/core/response' +import { + PICKUP_24H_TIMELINESS_EXPORT_MAX_DAYS, + pickup24hTimelinessDateRange, +} from '@/lib/pickup-24h-timeliness' +import { + PICKUP_24H_TIMELINESS_ANALYSIS_EXPORT_DIMENSIONS, + createPickup24hTimelinessAnalysisWorkbook, + pickup24hTimelinessAnalysisExportFileName, +} from '@/server/services/pickup-24h-timeliness-analysis-export.service' +import { + PICKUP_24H_TIMELINESS_COMBINED_EXPORT_CONTENT_TYPE, + createPickup24hTimelinessCombinedExportStream, + pickup24hTimelinessCombinedExportFileName, +} from '@/server/services/pickup-24h-timeliness-combined-export.service' +import { pickup24hTimelinessService } from '@/server/services/pickup-24h-timeliness.service' + +const EXPORT_DIMENSIONS = [ + ...PICKUP_24H_TIMELINESS_ANALYSIS_EXPORT_DIMENSIONS, + 'combined', +] as const + +const payloadSchema = z.object({ + dimension: z.enum(EXPORT_DIMENSIONS), + paymentDateFrom: z.string().trim().max(10).optional(), + paymentDateTo: z.string().trim().max(10).optional(), + keyword: z.string().trim().max(4_000).optional(), + purchaser: z.string().trim().max(120).optional(), + supplier: z.string().trim().max(120).optional(), + shopName: z.string().trim().max(200).optional(), + excludeReason: z.string().trim().max(200).optional(), + columnFilters: z.record(z.string(), z.unknown()).optional(), +}) + +export async function POST(request: NextRequest) { + return handleRequest(request, async (ctx) => { + const body = await request.json().catch(() => null) + const parsed = payloadSchema.safeParse(body) + if (!parsed.success) { + return jsonError( + ErrorCode.VALIDATION_INVALID_FORMAT, + '分析看板导出条件不正确', + 400, + ctx.requestId, + ) + } + const { supplyChainPermissionSettingsService } = await import( + '@/server/services/supply-chain-permission-settings.service' + ) + const targetKey = parsed.data.dimension === 'shops' + ? 'pickup24hTimelinessShopsExport' + : parsed.data.dimension === 'purchasers' + ? 'pickup24hTimelinessPurchasersExport' + : parsed.data.dimension === 'suppliers' + ? 'pickup24hTimelinessSuppliersExport' + : 'pickup24hTimelinessCombinedExport' + const access = await supplyChainPermissionSettingsService.getUserAccess(ctx.user, targetKey) + if (!access.download) { + return jsonError( + ErrorCode.AUTH_PERMISSION_DENIED, + '当前账号没有该项导出权限', + 403, + ctx.requestId, + ) + } + if (parsed.data.dimension === 'combined') { + const [analysis, orderExport] = await Promise.all([ + pickup24hTimelinessService.analysis({ ...parsed.data, columnFilters: undefined }), + pickup24hTimelinessService.iterateForExport(parsed.data), + ]) + const exportDays = pickup24hTimelinessDateRange( + orderExport.filters.paymentDateFrom, + orderExport.filters.paymentDateTo, + PICKUP_24H_TIMELINESS_EXPORT_MAX_DAYS + 1, + ).length + if (exportDays > PICKUP_24H_TIMELINESS_EXPORT_MAX_DAYS) { + return jsonError( + ErrorCode.VALIDATION_INVALID_FORMAT, + `含订单明细的合并导出单次最多 ${PICKUP_24H_TIMELINESS_EXPORT_MAX_DAYS} 天,` + + '请缩小付款日期范围后再导出。', + 400, + ctx.requestId, + ) + } + const fileName = pickup24hTimelinessCombinedExportFileName(orderExport.filters) + const stream = createPickup24hTimelinessCombinedExportStream({ + analysis, + orderBatches: orderExport.batches, + }) + return new NextResponse(stream, { + status: 200, + headers: { + 'Content-Type': PICKUP_24H_TIMELINESS_COMBINED_EXPORT_CONTENT_TYPE, + 'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(fileName)}`, + 'Cache-Control': 'no-store', + }, + }) + } + const analysis = await pickup24hTimelinessService.analysis({ + ...parsed.data, + columnFilters: undefined, + }) + const result = await createPickup24hTimelinessAnalysisWorkbook( + analysis, + parsed.data.dimension, + ) + const fileName = pickup24hTimelinessAnalysisExportFileName( + analysis.filters, + parsed.data.dimension, + ) + return new NextResponse(new Uint8Array(result.buffer), { + status: 200, + headers: { + 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(fileName)}`, + 'Cache-Control': 'no-store', + 'X-Export-Row-Count': String(result.rowCount), + }, + }) + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/api/supply-chain/management/pickup-24h-timeliness/analysis/route.ts b/furniture-3d-system/src/app/api/supply-chain/management/pickup-24h-timeliness/analysis/route.ts new file mode 100644 index 00000000..63295201 --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/management/pickup-24h-timeliness/analysis/route.ts @@ -0,0 +1,26 @@ +import { NextRequest } from 'next/server' +import { z } from 'zod' +import { ErrorCode } from '@/server/core/errors' +import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' +import { pickup24hTimelinessService } from '@/server/services/pickup-24h-timeliness.service' + +const querySchema = z.object({ + paymentDateFrom: z.string().trim().max(10).optional(), + paymentDateTo: z.string().trim().max(10).optional(), + keyword: z.string().trim().max(4_000).optional(), + purchaser: z.string().trim().max(120).optional(), + supplier: z.string().trim().max(120).optional(), + shopName: z.string().trim().max(200).optional(), + excludeReason: z.string().trim().max(200).optional(), +}) + +/** 店铺 / 采购 / 供应商 三个维度的 24h 揽收及时率分析看板。 */ +export async function GET(request: NextRequest) { + return handleRequest(request, async (ctx) => { + const parsed = querySchema.safeParse(Object.fromEntries(request.nextUrl.searchParams.entries())) + if (!parsed.success) { + return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '分析看板查询条件不正确', 400, ctx.requestId) + } + return jsonSuccess(await pickup24hTimelinessService.analysis(parsed.data), 200, ctx.requestId) + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/api/supply-chain/management/pickup-24h-timeliness/column-options/route.ts b/furniture-3d-system/src/app/api/supply-chain/management/pickup-24h-timeliness/column-options/route.ts new file mode 100644 index 00000000..3afb9d07 --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/management/pickup-24h-timeliness/column-options/route.ts @@ -0,0 +1,39 @@ +import { NextRequest } from 'next/server' +import { z } from 'zod' +import { ErrorCode } from '@/server/core/errors' +import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' +import { pickup24hTimelinessService } from '@/server/services/pickup-24h-timeliness.service' + +const querySchema = z.object({ + field: z.string().trim().min(1).max(64), + search: z.string().trim().max(200).optional(), + paymentDateFrom: z.string().trim().max(10).optional(), + paymentDateTo: z.string().trim().max(10).optional(), + keyword: z.string().trim().max(4_000).optional(), + included: z.enum(['all', 'yes', 'no']).optional(), + overdue: z.enum(['all', 'yes', 'no']).optional(), + purchaser: z.string().trim().max(120).optional(), + supplier: z.string().trim().max(120).optional(), + shopName: z.string().trim().max(200).optional(), + excludeReason: z.string().trim().max(200).optional(), + columnFilters: z.string().max(1_000_000).optional(), +}) + +export async function GET(request: NextRequest) { + return handleRequest(request, async (ctx) => { + const parsed = querySchema.safeParse(Object.fromEntries(request.nextUrl.searchParams.entries())) + if (!parsed.success) { + return jsonError( + ErrorCode.VALIDATION_INVALID_FORMAT, + '列筛选候选值条件不正确', + 400, + ctx.requestId, + ) + } + return jsonSuccess( + await pickup24hTimelinessService.columnFilterOptions(parsed.data), + 200, + ctx.requestId, + ) + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/api/supply-chain/management/pickup-24h-timeliness/export/route.ts b/furniture-3d-system/src/app/api/supply-chain/management/pickup-24h-timeliness/export/route.ts new file mode 100644 index 00000000..cdbf0db1 --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/management/pickup-24h-timeliness/export/route.ts @@ -0,0 +1,45 @@ +import { NextRequest, NextResponse } from 'next/server' +import { z } from 'zod' +import { ErrorCode } from '@/server/core/errors' +import { handleRequest, jsonError } from '@/server/core/response' +import { + PICKUP_24H_TIMELINESS_EXPORT_CONTENT_TYPE, + createPickup24hTimelinessExportStream, + pickup24hTimelinessExportFileName, +} from '@/server/services/pickup-24h-timeliness-export.service' +import { pickup24hTimelinessService } from '@/server/services/pickup-24h-timeliness.service' + +const payloadSchema = z.object({ + paymentDateFrom: z.string().trim().max(10).optional(), + paymentDateTo: z.string().trim().max(10).optional(), + keyword: z.string().trim().max(4_000).optional(), + included: z.enum(['all', 'yes', 'no']).optional(), + overdue: z.enum(['all', 'yes', 'no']).optional(), + purchaser: z.string().trim().max(120).optional(), + supplier: z.string().trim().max(120).optional(), + shopName: z.string().trim().max(200).optional(), + excludeReason: z.string().trim().max(200).optional(), + sortKey: z.string().trim().max(64).optional(), + sortDirection: z.enum(['asc', 'desc']).optional(), +}) + +export async function POST(request: NextRequest) { + return handleRequest(request, async (ctx) => { + const body = await request.json().catch(() => ({})) + const parsed = payloadSchema.safeParse(body ?? {}) + if (!parsed.success) { + return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '导出筛选条件不正确', 400, ctx.requestId) + } + const result = await pickup24hTimelinessService.iterateForExport(parsed.data) + const stream = createPickup24hTimelinessExportStream(result.batches) + const fileName = pickup24hTimelinessExportFileName(result.filters) + return new NextResponse(stream, { + status: 200, + headers: { + 'Content-Type': PICKUP_24H_TIMELINESS_EXPORT_CONTENT_TYPE, + 'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(fileName)}`, + 'Cache-Control': 'no-store', + }, + }) + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/api/supply-chain/management/pickup-24h-timeliness/options/route.ts b/furniture-3d-system/src/app/api/supply-chain/management/pickup-24h-timeliness/options/route.ts new file mode 100644 index 00000000..de73ceec --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/management/pickup-24h-timeliness/options/route.ts @@ -0,0 +1,22 @@ +import { NextRequest } from 'next/server' +import { ErrorCode } from '@/server/core/errors' +import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' +import { pickup24hTimelinessService } from '@/server/services/pickup-24h-timeliness.service' + +const DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/ + +export async function GET(request: NextRequest) { + return handleRequest(request, async (ctx) => { + const params = request.nextUrl.searchParams + const from = params.get('paymentDateFrom')?.trim() ?? '' + const to = params.get('paymentDateTo')?.trim() ?? from + if (!DATE_PATTERN.test(from) || !DATE_PATTERN.test(to)) { + return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '日期格式不正确', 400, ctx.requestId) + } + return jsonSuccess( + await pickup24hTimelinessService.filterOptions(from, to < from ? from : to), + 200, + ctx.requestId, + ) + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/api/supply-chain/management/pickup-24h-timeliness/route.ts b/furniture-3d-system/src/app/api/supply-chain/management/pickup-24h-timeliness/route.ts new file mode 100644 index 00000000..eaff49a7 --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/management/pickup-24h-timeliness/route.ts @@ -0,0 +1,32 @@ +import { NextRequest } from 'next/server' +import { z } from 'zod' +import { ErrorCode } from '@/server/core/errors' +import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' +import { pickup24hTimelinessService } from '@/server/services/pickup-24h-timeliness.service' + +const querySchema = z.object({ + paymentDateFrom: z.string().trim().max(10).optional(), + paymentDateTo: z.string().trim().max(10).optional(), + keyword: z.string().trim().max(4_000).optional(), + included: z.enum(['all', 'yes', 'no']).optional(), + overdue: z.enum(['all', 'yes', 'no']).optional(), + purchaser: z.string().trim().max(120).optional(), + supplier: z.string().trim().max(120).optional(), + shopName: z.string().trim().max(200).optional(), + excludeReason: z.string().trim().max(200).optional(), + page: z.coerce.number().int().min(1).max(100_000).optional(), + pageSize: z.coerce.number().int().min(1).max(500).optional(), + sortKey: z.string().trim().max(64).optional(), + sortDirection: z.enum(['asc', 'desc']).optional(), + columnFilters: z.string().max(1_000_000).optional(), +}) + +export async function GET(request: NextRequest) { + return handleRequest(request, async (ctx) => { + const parsed = querySchema.safeParse(Object.fromEntries(request.nextUrl.searchParams.entries())) + if (!parsed.success) { + return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '查询条件不正确', 400, ctx.requestId) + } + return jsonSuccess(await pickup24hTimelinessService.list(parsed.data), 200, ctx.requestId) + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/api/supply-chain/management/pickup-24h-timeliness/settings/route.test.ts b/furniture-3d-system/src/app/api/supply-chain/management/pickup-24h-timeliness/settings/route.test.ts new file mode 100644 index 00000000..8aa85fe6 --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/management/pickup-24h-timeliness/settings/route.test.ts @@ -0,0 +1,69 @@ +jest.mock('@/server/core/response', () => ({ + handleRequest: jest.fn(async (_request, handler) => handler({ + requestId: 'test-request', + user: { id: 'user-1', role: 'USER' }, + })), + jsonSuccess: jest.fn((data, status) => ({ success: true, data, status })), + jsonError: jest.fn((code, message, status) => ({ success: false, code, message, status })), +})) + +jest.mock('@/server/services/pickup-24h-timeliness-settings.service', () => ({ + pickup24hTimelinessSettingsService: { + getExcludeKeywords: jest.fn(), + updateExcludeKeywords: jest.fn(), + }, +})) + +import { NextRequest } from 'next/server' +import { ErrorCode } from '@/server/core/errors' +import { pickup24hTimelinessSettingsService } from '@/server/services/pickup-24h-timeliness-settings.service' +import { GET, PUT } from './route' + +function request(body: unknown) { + return { json: async () => body } as NextRequest +} + +describe('24h pickup exclude-keyword settings route', () => { + beforeEach(() => { + jest.clearAllMocks() + }) + + it('passes the specific write operation to the service', async () => { + const excludeKeywords = { supplier: ['已有词', '新词'] } + jest.mocked(pickup24hTimelinessSettingsService.updateExcludeKeywords) + .mockResolvedValue({ excludeKeywords, count: 2 }) + + const response = await PUT(request({ excludeKeywords, operation: 'create' })) + + expect(pickup24hTimelinessSettingsService.updateExcludeKeywords).toHaveBeenCalledWith( + excludeKeywords, + expect.objectContaining({ id: 'user-1' }), + 'create', + ) + expect(response).toMatchObject({ success: true, status: 200, data: { excludeKeywords } }) + }) + + it('rejects a missing or invalid operation', async () => { + const response = await PUT(request({ excludeKeywords: { supplier: [] } })) + + expect(response).toMatchObject({ + success: false, + code: ErrorCode.VALIDATION_INVALID_FORMAT, + status: 400, + }) + expect(pickup24hTimelinessSettingsService.updateExcludeKeywords).not.toHaveBeenCalled() + }) + + it('returns the current exclude-keyword configuration', async () => { + const excludeKeywords = { supplier: ['已有词'] } + jest.mocked(pickup24hTimelinessSettingsService.getExcludeKeywords) + .mockResolvedValue({ excludeKeywords, customized: true }) + + const response = await GET({} as NextRequest) + + expect(response).toMatchObject({ + success: true, + data: { excludeKeywords, customized: true }, + }) + }) +}) diff --git a/furniture-3d-system/src/app/api/supply-chain/management/pickup-24h-timeliness/settings/route.ts b/furniture-3d-system/src/app/api/supply-chain/management/pickup-24h-timeliness/settings/route.ts new file mode 100644 index 00000000..f03ba2d9 --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/management/pickup-24h-timeliness/settings/route.ts @@ -0,0 +1,48 @@ +import { NextRequest } from 'next/server' +import { AppError, ErrorCode } from '@/server/core/errors' +import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' +import { + pickup24hTimelinessSettingsService, + type Pickup24hExcludeKeywordOperation, +} from '@/server/services/pickup-24h-timeliness-settings.service' + +function parseOperation(value: unknown): Pickup24hExcludeKeywordOperation | null { + return value === 'create' || value === 'delete' || value === 'toggle' ? value : null +} + +export async function GET(request: NextRequest) { + return handleRequest(request, async (ctx) => jsonSuccess( + await pickup24hTimelinessSettingsService.getExcludeKeywords(), + 200, + ctx.requestId, + ), { requireAuth: true }) +} + +export async function PUT(request: NextRequest) { + return handleRequest(request, async (ctx) => { + const body = await request.json().catch(() => null) + if (!body || typeof body !== 'object' || Array.isArray(body)) { + return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '排除关键词格式不正确', 400, ctx.requestId) + } + const value = (body as { excludeKeywords?: unknown }).excludeKeywords + if (!value || typeof value !== 'object' || Array.isArray(value)) { + return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '排除关键词格式不正确', 400, ctx.requestId) + } + const operation = parseOperation((body as { operation?: unknown }).operation) + if (!operation) { + return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '排除关键词操作类型不正确', 400, ctx.requestId) + } + try { + return jsonSuccess( + await pickup24hTimelinessSettingsService.updateExcludeKeywords(value, ctx.user, operation), + 200, + ctx.requestId, + ) + } catch (error) { + if (error instanceof AppError) { + return jsonError(error.code, error.message, error.statusCode, ctx.requestId) + } + throw error + } + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/api/supply-chain/management/pickup-24h-timeliness/supplier-feedback/route.ts b/furniture-3d-system/src/app/api/supply-chain/management/pickup-24h-timeliness/supplier-feedback/route.ts new file mode 100644 index 00000000..2cc555e4 --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/management/pickup-24h-timeliness/supplier-feedback/route.ts @@ -0,0 +1,43 @@ +import { NextRequest } from 'next/server' +import { z } from 'zod' +import { ErrorCode } from '@/server/core/errors' +import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' +import { pickup24hTimelinessService } from '@/server/services/pickup-24h-timeliness.service' + +const DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/ + +const payloadSchema = z.object({ + feedbackDate: z.string().trim().regex(DATE_PATTERN), + purchaser: z.string().trim().max(120).optional(), + supplier: z.string().trim().min(1).max(200), + reason: z.string().max(4_000).optional(), + solution: z.string().max(4_000).optional(), + expectedResolutionDate: z.union([ + z.string().trim().regex(DATE_PATTERN), + z.literal(''), + z.null(), + ]).optional(), +}) + +export async function POST(request: NextRequest) { + return handleRequest(request, async (ctx) => { + const body = await request.json().catch(() => null) + const parsed = payloadSchema.safeParse(body) + if (!parsed.success) { + return jsonError( + ErrorCode.VALIDATION_INVALID_FORMAT, + '供应商反馈内容格式不正确', + 400, + ctx.requestId, + ) + } + return jsonSuccess( + await pickup24hTimelinessService.saveSupplierFeedback( + parsed.data, + ctx.user.name || ctx.user.email, + ), + 200, + ctx.requestId, + ) + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/api/supply-chain/management/platform-bills/config/route.ts b/furniture-3d-system/src/app/api/supply-chain/management/platform-bills/config/route.ts index ae470c60..5d24fae5 100644 --- a/furniture-3d-system/src/app/api/supply-chain/management/platform-bills/config/route.ts +++ b/furniture-3d-system/src/app/api/supply-chain/management/platform-bills/config/route.ts @@ -13,11 +13,13 @@ const identitySchema = z.object({ const createSchema = identitySchema.extend({ billItem: z.string().trim().min(1).max(500), + transactionType: z.string().trim().max(200).optional().default(''), financialRemark: z.string().trim().min(1).max(200), }) const updateSchema = identitySchema.extend({ id: z.string().trim().min(1).max(64), + transactionType: z.string().trim().max(200).optional(), financialRemark: z.string().trim().min(1).max(200), }) diff --git a/furniture-3d-system/src/app/api/supply-chain/management/platform-bills/records/export/route.ts b/furniture-3d-system/src/app/api/supply-chain/management/platform-bills/records/export/route.ts index 413286d1..d5f958b6 100644 --- a/furniture-3d-system/src/app/api/supply-chain/management/platform-bills/records/export/route.ts +++ b/furniture-3d-system/src/app/api/supply-chain/management/platform-bills/records/export/route.ts @@ -1,15 +1,26 @@ +import { Readable } from 'node:stream' import { NextRequest, NextResponse } from 'next/server' +import { z } from 'zod' import { ErrorCode } from '@/server/core/errors' import { handleRequest, jsonError } from '@/server/core/response' import { supplyChainPlatformBillService } from '@/server/services/supply-chain-platform-bill.service' -import { parsePlatformBillFilters, parsePlatformBillQuery } from '../query' +import { parsePlatformBillFilters } from '../query' export const runtime = 'nodejs' -export const maxDuration = 300 +export const maxDuration = 900 + +const exportQuerySchema = z.object({ + billKey: z.string().trim().min(1).max(64).default('jd-statement'), + billKeys: z.string().trim().max(1_000).optional(), + periodKey: z.string().trim().regex(/^\d{4}-(0[1-9]|1[0-2])$/), + filters: z.string().trim().max(10_000).optional(), +}) export async function GET(request: NextRequest) { return handleRequest(request, async (ctx) => { - const parsed = parsePlatformBillQuery(request) + const parsed = exportQuerySchema.safeParse( + Object.fromEntries(request.nextUrl.searchParams.entries()), + ) if (!parsed.success) { return jsonError( ErrorCode.VALIDATION_INVALID_FORMAT, @@ -18,38 +29,49 @@ export async function GET(request: NextRequest) { ctx.requestId, ) } - const filters = parsePlatformBillFilters(parsed.data.filters) - if (!filters) { - return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '京东账单导出参数不正确', 400, ctx.requestId) + const billKeys = [...new Set( + (parsed.data.billKeys ?? parsed.data.billKey) + .split(',') + .map((billKey) => billKey.trim()) + .filter(Boolean), + )] + if (billKeys.length === 0 || billKeys.length > 9) { + return jsonError( + ErrorCode.VALIDATION_INVALID_FORMAT, + '请选择 1 至 9 个账单页面', + 400, + ctx.requestId, + ) } - const iterator = supplyChainPlatformBillService.exportBillCsv({ - billKey: parsed.data.billKey, + const filters = parsePlatformBillFilters(parsed.data.filters) + if (billKeys.length === 1 && !filters) { + return jsonError( + ErrorCode.VALIDATION_INVALID_FORMAT, + '账单筛选参数不正确', + 400, + ctx.requestId, + ) + } + const workbook = await supplyChainPlatformBillService.openBillWorkbook({ periodKey: parsed.data.periodKey, - values: filters, + bills: billKeys.map((billKey) => ({ + billKey, + values: billKeys.length === 1 ? filters ?? {} : undefined, + })), }) - const encoder = new TextEncoder() - const stream = new ReadableStream({ - async pull(controller) { - try { - const next = await iterator.next() - if (next.done) { - controller.close() - return - } - controller.enqueue(encoder.encode(next.value)) - } catch (error) { - console.error(`[${ctx.requestId}] Platform bill export failed:`, error) - controller.error(error) - } + void workbook.completion.catch((error) => { + console.error(`[${ctx.requestId}] Platform bill XLSX export failed:`, error) + }) + return new NextResponse( + Readable.toWeb(workbook.stream) as ReadableStream, + { + status: 200, + headers: { + 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(workbook.fileName)}`, + 'Cache-Control': 'no-store', + }, }, - }) - return new NextResponse(stream, { - status: 200, - headers: { - 'Content-Type': 'text/csv; charset=utf-8', - 'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent('平台账单-筛选结果.csv')}`, - 'Cache-Control': 'no-store', - }, - }) + ) }, { requireAuth: true }) } diff --git a/furniture-3d-system/src/app/api/supply-chain/management/platform-bills/records/override/route.ts b/furniture-3d-system/src/app/api/supply-chain/management/platform-bills/records/override/route.ts new file mode 100644 index 00000000..394e0b09 --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/management/platform-bills/records/override/route.ts @@ -0,0 +1,35 @@ +import { NextRequest } from 'next/server' +import { z } from 'zod' +import { ErrorCode } from '@/server/core/errors' +import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' +import { + supplyChainPlatformBillService, +} from '@/server/services/supply-chain-platform-bill.service' + +export const runtime = 'nodejs' + +const overrideSchema = z.object({ + billKey: z.string().trim().min(1).max(64), + periodKey: z.string().trim().regex(/^\d{4}-(0[1-9]|1[0-2])$/), + sourceRowNumber: z.coerce.number().int().positive(), + value: z.string().trim().max(200), +}) + +export async function PATCH(request: NextRequest) { + return handleRequest(request, async (ctx) => { + const parsed = overrideSchema.safeParse(await request.json().catch(() => null)) + if (!parsed.success) { + return jsonError( + ErrorCode.VALIDATION_INVALID_FORMAT, + '财务备注保存参数不正确', + 400, + ctx.requestId, + ) + } + const data = await supplyChainPlatformBillService.saveFinancialRemarkOverride({ + ...parsed.data, + user: ctx.user, + }) + return jsonSuccess(data, 200, ctx.requestId) + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/api/supply-chain/purchase/followup-overview/route.ts b/furniture-3d-system/src/app/api/supply-chain/purchase/followup-overview/route.ts new file mode 100644 index 00000000..f0f602e9 --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/purchase/followup-overview/route.ts @@ -0,0 +1,53 @@ +import { NextRequest } from 'next/server' +import { z } from 'zod' +import { ErrorCode } from '@/server/core/errors' +import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' +import { deliveryFulfillmentOverviewService } from '@/server/services/delivery-fulfillment-overview.service' +import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service' + +const rangeSchema = z.coerce.number().int().refine( + (value) => value === 90, + '统计范围只支持近 90 天', +) + +export async function GET(request: NextRequest) { + return handleRequest(request, async (ctx) => { + const access = await supplyChainPermissionSettingsService.getUserAccess( + ctx.user, + 'purchaseFollowupOverview', + ) + if (!access.view) { + return jsonError(ErrorCode.AUTH_PERMISSION_DENIED, '没有交期履约总览查看权限', 403, ctx.requestId) + } + const parsed = rangeSchema.safeParse(request.nextUrl.searchParams.get('range') || '90') + if (!parsed.success) { + return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, parsed.error.issues[0]?.message || '统计范围不正确', 400, ctx.requestId) + } + return jsonSuccess( + await deliveryFulfillmentOverviewService.getOverviewData(parsed.data), + 200, + ctx.requestId, + ) + }, { requireAuth: true }) +} + +export async function POST(request: NextRequest) { + return handleRequest(request, async (ctx) => { + const access = await supplyChainPermissionSettingsService.getUserAccess( + ctx.user, + 'purchaseFollowupOverview', + ) + if (!access.view) { + return jsonError(ErrorCode.AUTH_PERMISSION_DENIED, '没有交期履约总览查看权限', 403, ctx.requestId) + } + const parsed = rangeSchema.safeParse(request.nextUrl.searchParams.get('range') || '90') + if (!parsed.success) { + return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, parsed.error.issues[0]?.message || '统计范围不正确', 400, ctx.requestId) + } + return jsonSuccess( + await deliveryFulfillmentOverviewService.refresh(parsed.data), + 200, + ctx.requestId, + ) + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/api/supply-chain/purchase/legacy/[module]/route.ts b/furniture-3d-system/src/app/api/supply-chain/purchase/legacy/[module]/route.ts index f099a862..c38a6f4b 100644 --- a/furniture-3d-system/src/app/api/supply-chain/purchase/legacy/[module]/route.ts +++ b/furniture-3d-system/src/app/api/supply-chain/purchase/legacy/[module]/route.ts @@ -1,5 +1,6 @@ import { NextRequest } from 'next/server' import { z } from 'zod' +import { reissueHasCallback, type ReissueRecord } from '@/lib/purchase-legacy-modules' import { ErrorCode } from '@/server/core/errors' import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' import { purchaseLegacyModulesService } from '@/server/services/purchase-legacy-modules.service' @@ -79,6 +80,17 @@ export async function PUT( ctx.requestId, ) } + if (parsed.data.records.some((record) => + record.reasonReviewStatus === 'PENDING_FOLLOWUP' + && reissueHasCallback(record as ReissueRecord), + )) { + return jsonError( + ErrorCode.VALIDATION_INVALID_FORMAT, + '非工厂原因尚未完成跟单员最终判定,暂不能回传闭环', + 400, + ctx.requestId, + ) + } const saved = await purchaseLegacyModulesService.saveReissueStore(parsed.data as never) await reissueHistoryService.refreshCurrent(saved) return jsonSuccess(saved, 200, ctx.requestId) diff --git a/furniture-3d-system/src/app/api/supply-chain/purchase/legacy/reissue-reminder/reason-review/route.ts b/furniture-3d-system/src/app/api/supply-chain/purchase/legacy/reissue-reminder/reason-review/route.ts new file mode 100644 index 00000000..89437298 --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/purchase/legacy/reissue-reminder/reason-review/route.ts @@ -0,0 +1,44 @@ +import { NextRequest } from 'next/server' +import { z } from 'zod' +import { ErrorCode } from '@/server/core/errors' +import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' +import { getPurchaseLegacyModuleAccess } from '@/server/services/supply-chain-purchase-page-permission' +import { supplierReissueResponseService } from '@/server/services/supplier-reissue-response.service' + +const payloadSchema = z.object({ + recordId: z.string().trim().min(1).max(200), + finalReasonCategory: z.string().trim().min(1).max(300), + reasonNote: z.string().trim().max(1000).default(''), + feedbackContent: z.string().trim().max(3000).optional().default(''), +}).strict() + +export async function POST(request: NextRequest) { + return handleRequest(request, async (ctx) => { + const access = await getPurchaseLegacyModuleAccess(ctx.user, 'reissue-reminder') + if (!access.edit) { + return jsonError( + ErrorCode.AUTH_PERMISSION_DENIED, + '没有应发未发提醒最终判定权限', + 403, + ctx.requestId, + ) + } + const parsed = payloadSchema.safeParse(await request.json().catch(() => null)) + if (!parsed.success) { + return jsonError( + ErrorCode.VALIDATION_INVALID_FORMAT, + '最终原因判定数据格式不正确', + 400, + ctx.requestId, + ) + } + return jsonSuccess( + await supplierReissueResponseService.completeReasonReview( + parsed.data as never, + ctx.user.name, + ), + 200, + ctx.requestId, + ) + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/database/bom-library/accessory-models/AccessoryGlbPreview.tsx b/furniture-3d-system/src/app/database/bom-library/accessory-models/AccessoryGlbPreview.tsx index 932f6cbf..0cdca468 100644 --- a/furniture-3d-system/src/app/database/bom-library/accessory-models/AccessoryGlbPreview.tsx +++ b/furniture-3d-system/src/app/database/bom-library/accessory-models/AccessoryGlbPreview.tsx @@ -1,27 +1,24 @@ 'use client' -import { useEffect, useRef, useState } from 'react' -import { RotateCcw } from 'lucide-react' +import { useCallback, useEffect, useRef, useState } from 'react' +import { createPortal } from 'react-dom' +import { Maximize2, RotateCcw, ZoomIn, ZoomOut } from 'lucide-react' +import Button from '@/components/ui/Button' +import Modal from '@/components/ui/Modal' import * as THREE from 'three' import { OrbitControls } from 'three/addons/controls/OrbitControls.js' import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js' +import { applyAccessorySurface, type AccessorySurfaceInput } from '@/lib/accessory-model-surface' import type { DraftModel } from './draft-client' +import { configureAccessoryRenderer, createAccessoryCamera, createAccessoryScene, disposeAccessoryModel, frameAccessoryModel, prepareAccessoryPreview, resetAccessoryCamera } from './model-view' -function disposeModel(model: THREE.Object3D) { - const materials = new Set() - model.traverse((object) => { - if (!(object instanceof THREE.Mesh)) return - object.geometry.dispose() - for (const material of [object.material].flat()) materials.add(material) - }) - materials.forEach((material) => material.dispose()) -} - -export function AccessoryGlbPreview({ blob, url }: Pick) { +function AccessoryGlbCanvas({ blob, url, color, material, onExpand }: Pick & AccessorySurfaceInput & { onExpand?: () => void }) { const host = useRef(null) const reset = useRef<(() => void) | null>(null) + const zoom = useRef<((factor: number) => void) | null>(null) + const changeSurface = useRef<((surface: AccessorySurfaceInput) => void) | null>(null) const [ready, setReady] = useState(false) - const [error, setError] = useState(false) + const [error, setError] = useState('') useEffect(() => { const element = host.current @@ -31,42 +28,37 @@ export function AccessoryGlbPreview({ blob, url }: Pick renderer.render(scene, camera) let centerY = 0 let modelRadius = 0 const home = () => { - const halfFov = THREE.MathUtils.degToRad(camera.fov / 2) - const fitAngle = Math.min(halfFov, Math.atan(Math.tan(halfFov) * camera.aspect)) - const distance = Math.max(3.7, modelRadius * 1.12 / Math.sin(fitAngle)) - camera.position.set(2.2, 1.6, 2.8).setLength(distance) - camera.position.y += centerY + resetAccessoryCamera(camera, centerY, modelRadius) controls.target.set(0, centerY, 0) controls.update() render() } reset.current = home + zoom.current = (factor) => { + const offset = camera.position.clone().sub(controls.target) + const distance = THREE.MathUtils.clamp(offset.length() * factor, controls.minDistance, controls.maxDistance) + camera.position.copy(controls.target).add(offset.setLength(distance)) + controls.update() + render() + } controls.addEventListener('change', render) const resize = new ResizeObserver(() => { if (!element.clientWidth || !element.clientHeight) return @@ -77,65 +69,111 @@ export function AccessoryGlbPreview({ blob, url }: Pick { + if (!request.signal.aborted) setError(error instanceof Error ? error.message : '无法预览 GLB') + } + changeSurface.current = (next) => { + surface = next + void display().catch(failed) + } async function load() { - let data: ArrayBuffer - if (blob) { - data = await blob.arrayBuffer() - } else { + if (blob) data = await blob.arrayBuffer() + else { const response = await fetch(url, { signal: request.signal }) if (!response.ok) throw new Error('GLB 加载失败') data = await response.arrayBuffer() } - if (request.signal.aborted) return - const { scene: model } = await new GLTFLoader().parseAsync(data, '') - if (request.signal.aborted) { disposeModel(model); return } - sceneModel = model - const bounds = new THREE.Box3().setFromObject(model) - const size = bounds.getSize(new THREE.Vector3()) - const center = bounds.getCenter(new THREE.Vector3()) - const scale = 1.8 / Math.max(size.x, size.y, size.z) - if (!Number.isFinite(scale)) throw new Error('GLB 模型没有可预览的网格') - centerY = size.y * scale / 2 - .44 - modelRadius = size.length() * scale / 2 - const frame = new THREE.Group() - frame.scale.setScalar(scale) - frame.position.copy(center).multiplyScalar(-scale) - frame.position.y += centerY - frame.add(model) - scene.add(frame) - home() - setReady(true) + await display() } - void load().catch(() => { if (!request.signal.aborted) setError(true) }) + void load().catch(failed) return () => { request.abort() reset.current = null + zoom.current = null + changeSurface.current = null resize.disconnect() controls.removeEventListener('change', render) controls.dispose() - if (sceneModel) disposeModel(sceneModel) - grid.dispose() + if (sceneModel) disposeAccessoryModel(sceneModel) + disposeScene() renderer.dispose() renderer.domElement.remove() } }, [blob, url]) + useEffect(() => { changeSurface.current?.({ color, material }) }, [blob, url, color, material]) + return (
{ready && !error && ( - +
+ + + + {onExpand && } +
)} {(!ready || error) && ( - {error ? '无法预览 GLB' : '正在加载模型…'} + {error || '正在加载模型…'} )}
) } + +export function AccessoryGlbPreview({ blob, url, color, material }: Pick & AccessorySurfaceInput) { + const [expanded, setExpanded] = useState(false) + const closeExpanded = useCallback(() => setExpanded(false), []) + + return ( + <> + setExpanded(true)} /> + {createPortal( + +
+ + GLB +
+
, document.body, + )} + + ) +} diff --git a/furniture-3d-system/src/app/database/bom-library/accessory-models/AccessoryModelCover.test.tsx b/furniture-3d-system/src/app/database/bom-library/accessory-models/AccessoryModelCover.test.tsx new file mode 100644 index 00000000..8fee0d77 --- /dev/null +++ b/furniture-3d-system/src/app/database/bom-library/accessory-models/AccessoryModelCover.test.tsx @@ -0,0 +1,62 @@ +import { act, render, screen, waitFor } from '@testing-library/react' +import { AccessoryModelCover } from './AccessoryModelCover' +import { renderModelCover } from './render-model-cover' + +jest.mock('./render-model-cover', () => ({ renderModelCover: jest.fn() })) + +const photo = { id: 'photo-1', name: 'reference.png', url: '/reference.png' } +const observers: { callback: IntersectionObserverCallback; observer: IntersectionObserver }[] = [] +const originalObserver = global.IntersectionObserver + +beforeEach(() => { + jest.clearAllMocks() + observers.length = 0 + global.IntersectionObserver = jest.fn((callback: IntersectionObserverCallback) => { + const observer = { observe: jest.fn(), disconnect: jest.fn(), unobserve: jest.fn() } as unknown as IntersectionObserver + observers.push({ callback, observer }) + return observer + }) as unknown as typeof IntersectionObserver +}) + +afterAll(() => { global.IntersectionObserver = originalObserver }) + +function enterViewport() { + const { callback, observer } = observers[observers.length - 1] + act(() => callback([{ isIntersecting: true } as IntersectionObserverEntry], observer)) +} + +test('已有模型的零件使用模型封面,保留对应颜色和材质', async () => { + jest.mocked(renderModelCover).mockResolvedValue('data:image/webp;base64,model') + render() + expect(screen.queryByRole('img')).not.toBeInTheDocument() + expect(renderModelCover).not.toHaveBeenCalled() + enterViewport() + expect(await screen.findByRole('img', { name: '模型封面' })).toHaveAttribute('src', 'data:image/webp;base64,model') + expect(renderModelCover).toHaveBeenCalledWith('/model.glb', expect.any(AbortSignal), { + color: '彩锌色/蓝色', material: '锌合金/塑料', + }) + expect(screen.queryByRole('img', { name: '配件参考图' })).not.toBeInTheDocument() +}) + +test('同一模型改色后更新封面,迟到的旧颜色结果不会覆盖新颜色', async () => { + let finishOld!: (value: string) => void + jest.mocked(renderModelCover) + .mockImplementationOnce(() => new Promise(resolve => { finishOld = resolve })) + .mockResolvedValueOnce('data:image/webp;base64,silver') + const { rerender } = render() + enterViewport() + await waitFor(() => expect(renderModelCover).toHaveBeenCalledTimes(1)) + const oldSignal = jest.mocked(renderModelCover).mock.calls[0][1] + rerender() + expect(oldSignal.aborted).toBe(true) + enterViewport() + expect(await screen.findByRole('img', { name: '模型封面' })).toHaveAttribute('src', 'data:image/webp;base64,silver') + await act(async () => { finishOld('data:image/webp;base64,zinc') }) + expect(screen.getByRole('img', { name: '模型封面' })).toHaveAttribute('src', 'data:image/webp;base64,silver') +}) + +test('尚未生成模型的资料继续显示参考图', () => { + render() + expect(screen.getByRole('img', { name: '配件参考图' })).toHaveAttribute('src', photo.url) + expect(renderModelCover).not.toHaveBeenCalled() +}) diff --git a/furniture-3d-system/src/app/database/bom-library/accessory-models/AccessoryModelCover.tsx b/furniture-3d-system/src/app/database/bom-library/accessory-models/AccessoryModelCover.tsx index f58f2319..ce463b86 100644 --- a/furniture-3d-system/src/app/database/bom-library/accessory-models/AccessoryModelCover.tsx +++ b/furniture-3d-system/src/app/database/bom-library/accessory-models/AccessoryModelCover.tsx @@ -1,41 +1,42 @@ import { Box, ImageIcon } from 'lucide-react' import { useEffect, useRef, useState } from 'react' import type { AccessoryPhoto } from '@/lib/intake-accessory-models' +import type { AccessorySurfaceInput } from '@/lib/accessory-model-surface' -export function AccessoryModelCover({ photo, modelUrl }: { +export function AccessoryModelCover({ photo, modelUrl, color, material }: { photo?: AccessoryPhoto modelUrl?: string -}) { +} & AccessorySurfaceInput) { const target = useRef(null) const [failedPhoto, setFailedPhoto] = useState() - const [cover, setCover] = useState<{ url: string; image: string }>() + const [cover, setCover] = useState() const photoUrl = photo && photo.url !== failedPhoto ? photo.url : undefined - const generated = cover?.url === modelUrl ? cover?.image : undefined - const image = photoUrl || generated + const generated = cover?.url === modelUrl && cover?.color === color && cover?.material === material ? cover?.image : undefined + const image = modelUrl ? generated : photoUrl useEffect(() => { - if (photoUrl || !modelUrl || !target.current) return + if (!modelUrl || !target.current) return const controller = new AbortController() const observer = new IntersectionObserver(([entry]) => { if (!entry.isIntersecting) return observer.disconnect() void import('./render-model-cover') - .then(({ renderModelCover }) => renderModelCover(modelUrl, controller.signal)) + .then(({ renderModelCover }) => renderModelCover(modelUrl, controller.signal, { color, material })) .then((image) => { - if (!controller.signal.aborted) setCover({ url: modelUrl, image }) + if (!controller.signal.aborted) setCover({ url: modelUrl, color, material, image }) }) .catch(() => {}) }, { rootMargin: '100px' }) observer.observe(target.current) return () => { observer.disconnect(); controller.abort() } - }, [photoUrl, modelUrl]) + }, [modelUrl, color, material]) return (
{image ? ( // eslint-disable-next-line @next/next/no-img-element -- authenticated storage or locally rendered model cover - {photoUrl setFailedPhoto(photoUrl) : undefined} className="absolute inset-0 h-full w-full object-contain" /> + {modelUrl setFailedPhoto(photoUrl) : undefined} className="absolute inset-0 h-full w-full object-contain" /> ) : modelUrl ?
diff --git a/furniture-3d-system/src/app/database/bom-library/accessory-models/AccessoryModelDetail.tsx b/furniture-3d-system/src/app/database/bom-library/accessory-models/AccessoryModelDetail.tsx index f164bbd0..dc888ebe 100644 --- a/furniture-3d-system/src/app/database/bom-library/accessory-models/AccessoryModelDetail.tsx +++ b/furniture-3d-system/src/app/database/bom-library/accessory-models/AccessoryModelDetail.tsx @@ -3,7 +3,7 @@ import { ArrowLeft, Download, Pencil, Trash2 } from 'lucide-react' import { useState } from 'react' import Button from '@/components/ui/Button' import { accessorySpec, CAM_KIT_KIND, type AccessoryDraft } from '@/lib/intake-accessory-models' -import { downloadAccessoryModel, downloadAccessoryStep } from './draft-client' +import { downloadAccessoryGlb, downloadAccessoryStep } from './draft-client' const Preview = dynamic(() => import('./AccessoryGlbPreview').then((mod) => mod.AccessoryGlbPreview), { ssr: false, @@ -19,20 +19,32 @@ export function AccessoryModelDetail({ item, feedback, onBack, onEdit, onRemove }) { const [activePhoto, setActivePhoto] = useState(null) const [stepBusy, setStepBusy] = useState(false) + const [glbBusy, setGlbBusy] = useState(false) const [stepError, setStepError] = useState('') const model = item.model + const dimensions = model && (model.kind ?? item.kind) === item.kind ? model.dimensions : item.dimensions const photo = item.photos.find((entry) => entry.id === activePhoto) const priceUnit = item.priceUnit === undefined ? '件' : item.priceUnit const price = item.price?.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 20, useGrouping: false }) const fields = [ ['配件编号', item.code], ['品类', [item.category, item.kind].filter((part, index, list) => list.indexOf(part) === index).join(' / ')], - ['规格', item.spec || accessorySpec(item.kind, model?.dimensions ?? item.dimensions)], + ['规格', item.spec || accessorySpec(item.kind, dimensions)], ['材质', item.material || '未填写'], + ['颜色', item.color || '未填写'], [priceUnit === '套' ? '单套重量' : '单件重量', item.weightGrams == null ? '未填写' : item.weightGrams + ' 克'], ['单价', price === undefined ? '未填写' : '¥' + price + (priceUnit ? ' / ' + priceUnit : '')], ] + async function saveGlb() { + if (!model || glbBusy) return + setGlbBusy(true) + setStepError('') + try { await downloadAccessoryGlb(model, item.code, item) } + catch (error) { setStepError(error instanceof Error ? error.message : 'GLB 下载失败') } + finally { setGlbBusy(false) } + } + async function saveStep() { if (!model || stepBusy) return setStepBusy(true) @@ -58,7 +70,7 @@ export function AccessoryModelDetail({ item, feedback, onBack, onEdit, onRemove {photo || (!model && item.photos[0]) ? ( // eslint-disable-next-line @next/next/no-img-element -- authenticated storage {item.name - ) : model ? + ) : model ? :
待生成模型
}
{!!item.photos.length &&
@@ -76,10 +88,10 @@ export function AccessoryModelDetail({ item, feedback, onBack, onEdit, onRemove ))}
} {model &&
- - {(model.cad || item.kind === CAM_KIT_KIND) && } diff --git a/furniture-3d-system/src/app/database/bom-library/accessory-models/AccessoryModelEditor.test.tsx b/furniture-3d-system/src/app/database/bom-library/accessory-models/AccessoryModelEditor.test.tsx new file mode 100644 index 00000000..18d25ae9 --- /dev/null +++ b/furniture-3d-system/src/app/database/bom-library/accessory-models/AccessoryModelEditor.test.tsx @@ -0,0 +1,155 @@ +import { fireEvent, render, screen, waitFor, within } from '@testing-library/react' +import { AccessoryModelEditor } from './AccessoryModelEditor' +import { estimateAccessoryDraftWeight, saveAccessoryDraft } from './draft-client' +import { generateAccessoryModel } from './generate-model' +import type { AccessoryDraft } from '@/lib/intake-accessory-models' + +jest.mock('next/dynamic', () => ({ __esModule: true, default: () => function Preview() { return
} })) +jest.mock('./draft-client', () => ({ saveAccessoryDraft: jest.fn(), estimateAccessoryDraftWeight: jest.fn() })) +jest.mock('./generate-model', () => ({ generateAccessoryModel: jest.fn() })) + +const initial: AccessoryDraft = { + id: 'draft-1', revision: '2026-11-25T01:00:00.000Z', + module: 'connector', category: '圆棒榫', kind: '圆棒榫', code: 'PEG-001', name: '圆棒榫', + material: '木材', color: '本色', price: .1, priceUnit: '个', weightGrams: 2, + dimensions: { diameter: 8, length: 30 }, pending: [], + photos: [{ id: '00000000-0000-4000-8000-000000000002', name: '参考图.png', url: '/photo.png' }], + model: { + id: '00000000-0000-4000-8000-000000000001', url: '/model.glb', + dimensions: { diameter: 8, length: 30 }, pending: [], note: '', createdAt: '2026-11-25T01:00:00.000Z', + }, +} + +const change = (label: string, value: string) => fireEvent.change(screen.getByLabelText(label, { exact: true }), { target: { value } }) + +beforeEach(() => { + jest.clearAllMocks() + URL.createObjectURL = jest.fn(() => 'blob:preview') + URL.revokeObjectURL = jest.fn() + jest.mocked(saveAccessoryDraft).mockResolvedValue({ item: initial }) + jest.mocked(estimateAccessoryDraftWeight).mockResolvedValue({ + weightGrams: 3.95, volumeMm3: 500, densityGramsPerCm3: 7.9, material: '不锈钢', basis: '当前 CAD 模型实体体积', notes: ['密度为参考值'], + }) +}) + +test('已有模型时所有基本信息可编辑,跨模块保存保留参考图和模型快照', async () => { + const onSaved = jest.fn() + render() + const dialog = await screen.findByRole('dialog') + for (const label of ['所属模块', '品类', '子类', '配件编号', '配件名称', '规格', '颜色', '材质', '单价(元)', '计价单位', '单件重量(克)']) { + expect(within(dialog).getByLabelText(label, { exact: true })).toBeEnabled() + } + change('所属模块', 'accessory') + change('品类', '装饰类') + change('子类', '拉手') + change('配件编号', 'HANDLE-002') + change('配件名称', '柜门拉手') + change('规格', '128 mm') + change('颜色', '银色') + change('材质', '不锈钢') + change('单价(元)', '0.25') + change('计价单位', '件') + change('单件重量(克)', '5') + fireEvent.click(screen.getByRole('button', { name: '保存资料', exact: true })) + await waitFor(() => expect(onSaved).toHaveBeenCalled()) + expect(saveAccessoryDraft).toHaveBeenCalledWith(expect.objectContaining({ + module: 'accessory', category: '装饰类', kind: '拉手', code: 'HANDLE-002', name: '柜门拉手', + spec: '128 mm', color: '银色', material: '不锈钢', price: .25, priceUnit: '件', weightGrams: 5, + dimensions: {}, pending: [], model: expect.objectContaining({ id: initial.model!.id, kind: initial.kind, dimensions: initial.model!.dimensions }), + }), initial.photos, expect.objectContaining({ ...initial.model, kind: initial.kind, sourceSpec: '' })) +}) + +test('待生成资料的尺寸可以保存并在重新打开后继续编辑', async () => { + render() + await screen.findByRole('dialog') + fireEvent.click(screen.getByRole('button', { name: '保存资料', exact: true })) + await waitFor(() => expect(saveAccessoryDraft).toHaveBeenCalled()) + expect(saveAccessoryDraft).toHaveBeenCalledWith(expect.objectContaining({ dimensions: initial.dimensions, model: null }), initial.photos, null) +}) + +test('生成预览后也可修改分类,新子类生成不继承旧子类模型', async () => { + jest.mocked(generateAccessoryModel).mockResolvedValue({ + accessory: { ...initial.model!, kind: initial.kind }, blob: new Blob(['preview']), + }) + render() + await screen.findByRole('dialog') + fireEvent.click(screen.getByRole('button', { name: '重新生成' })) + await screen.findByRole('button', { name: '保存并替换模型' }) + expect(screen.getByLabelText('所属模块')).toBeEnabled() + expect(screen.getByLabelText('品类')).toBeEnabled() + expect(screen.getByLabelText('子类')).toBeEnabled() + change('所属模块', 'accessory') + change('品类', '装饰类') + change('子类', '拉手') + fireEvent.click(screen.getByRole('button', { name: '重新生成' })) + await waitFor(() => expect(generateAccessoryModel).toHaveBeenCalledTimes(2)) + expect(generateAccessoryModel).toHaveBeenLastCalledWith(expect.objectContaining({ kind: '拉手', currentModel: null, dimensions: {}, readPhotos: true })) + await screen.findByRole('button', { name: '保存并替换模型' }) +}) + +test('已有模型只读访问仍遵守账号权限', async () => { + render() + await screen.findByRole('dialog') + expect(screen.getByLabelText('所属模块')).toBeDisabled() + expect(screen.getByLabelText('配件名称')).toBeDisabled() + expect(screen.queryByRole('button', { name: '保存资料' })).not.toBeInTheDocument() + expect(screen.queryByRole('button', { name: '预估克重' })).not.toBeInTheDocument() +}) + +test('点击才填入预估克重,允许手改并保存;改材质提示重估', async () => { + render() + await screen.findByRole('dialog') + expect(screen.getByLabelText('单件重量(克)')).toHaveValue(2) + change('材质', '不锈钢') + expect(estimateAccessoryDraftWeight).not.toHaveBeenCalled() + fireEvent.click(screen.getByRole('button', { name: '预估克重' })) + await waitFor(() => expect(screen.getByLabelText('单件重量(克)')).toHaveValue(3.95)) + expect(screen.getByText(/预估值/)).toBeInTheDocument() + change('单件重量(克)', '4.2') + expect(screen.getByText('已手动修改克重')).toBeInTheDocument() + change('材质', '铝合金') + expect(screen.getByText('资料已修改,请重新预估或手动填写')).toBeInTheDocument() + expect(screen.getByLabelText('单件重量(克)')).toHaveValue(4.2) + fireEvent.click(screen.getByRole('button', { name: '保存资料', exact: true })) + await waitFor(() => expect(saveAccessoryDraft).toHaveBeenCalledWith(expect.objectContaining({ weightGrams: 4.2 }), expect.anything(), expect.anything())) +}) + +test('预估失败保留原重量,并在当前字段显示错误', async () => { + jest.mocked(estimateAccessoryDraftWeight).mockRejectedValue(new Error('请填写直径和长度')) + render() + await screen.findByRole('dialog') + fireEvent.click(screen.getByRole('button', { name: '预估克重' })) + expect(await screen.findByRole('alert')).toHaveTextContent('请填写直径和长度') + expect(screen.getByLabelText('单件重量(克)')).toHaveValue(2) +}) + +test('请求过程中变更资料时丢弃旧估算结果', async () => { + let resolve: (value: Awaited>) => void + jest.mocked(estimateAccessoryDraftWeight).mockImplementation(() => new Promise((done) => { resolve = done })) + render() + await screen.findByRole('dialog') + fireEvent.click(screen.getByRole('button', { name: '预估克重' })) + change('材质', '铝合金') + resolve!({ weightGrams: 3.95, volumeMm3: 500, densityGramsPerCm3: 7.9, material: '不锈钢', basis: '模型', notes: [] }) + await screen.findByRole('button', { name: '预估克重' }) + expect(screen.getByLabelText('单件重量(克)')).toHaveValue(2) +}) + +test('改规格后保留模型原规格标记,避免保存重开后沿用旧模型估重', async () => { + const cad = { + engine: 'photo-cad-v1' as const, scale: 'dimensioned' as const, review: ['已标注尺寸'], + parts: [{ name: '圆棒', color: '#aaaaaa', base: { shape: 'cylinder' as const, at: [0, 0, 0] as [number, number, number], axis: 'z' as const, diameter: 8, length: 30 }, operations: [] }], + } + const current = { ...initial, spec: 'Ø8×30', dimensions: {}, model: { ...initial.model!, dimensions: {}, sourceSpec: 'Ø8×25', cad } } + render() + await screen.findByRole('dialog') + fireEvent.click(screen.getByRole('button', { name: '预估克重' })) + await waitFor(() => expect(estimateAccessoryDraftWeight).toHaveBeenCalledWith(expect.objectContaining({ + spec: 'Ø8×30', model: expect.objectContaining({ outdated: true }), + }))) + await screen.findByRole('button', { name: '预估克重' }) + fireEvent.click(screen.getByRole('button', { name: '保存资料', exact: true })) + await waitFor(() => expect(saveAccessoryDraft).toHaveBeenCalledWith(expect.objectContaining({ + model: expect.objectContaining({ sourceSpec: 'Ø8×25' }), + }), expect.anything(), expect.anything())) +}) diff --git a/furniture-3d-system/src/app/database/bom-library/accessory-models/AccessoryModelEditor.tsx b/furniture-3d-system/src/app/database/bom-library/accessory-models/AccessoryModelEditor.tsx index 051e218c..1d73556d 100644 --- a/furniture-3d-system/src/app/database/bom-library/accessory-models/AccessoryModelEditor.tsx +++ b/furniture-3d-system/src/app/database/bom-library/accessory-models/AccessoryModelEditor.tsx @@ -1,9 +1,9 @@ -import { useEffect, useRef, useState } from 'react' +import { useEffect, useId, useRef, useState } from 'react' import Button from '@/components/ui/Button' import Modal from '@/components/ui/Modal' import { ACCESSORY_IMAGE_LIMIT, ACCESSORY_IMAGE_TYPES, ACCESSORY_PHOTO_COUNT, ACCESSORY_SAMPLE_URL, - accessoryCatalog, accessoryCategories, accessoryDraftInputSchema, accessoryPriceUnits, modelFields, + accessoryCatalog, accessoryCategories, accessoryColorOptions, accessoryDraftInputSchema, accessoryPriceUnits, modelFields, type AccessoryDimensions, type AccessoryDraft, type AccessoryDraftInput, type AccessoryModule, type CamPhotoChoice, } from '@/lib/intake-accessory-models' import { CamPhotoChoices } from './CamPhotoChoices' @@ -11,6 +11,7 @@ import { AccessoryModelPhoto } from './AccessoryModelPhoto' import { accessoryInput, AccessoryModelWorkspace } from './AccessoryModelWorkspace' import { saveAccessoryDraft, type DraftModel, type DraftPhoto } from './draft-client' import { generateAccessoryModel } from './generate-model' +import { AccessoryWeightField } from './AccessoryWeightField' const messageOf = (error: unknown) => error instanceof Error ? error.message : '操作失败,请重试' @@ -29,6 +30,8 @@ export function AccessoryModelEditor({ initial, initialModule, initialCategory, const [code, setCode] = useState(initial?.code ?? '') const [name, setName] = useState(initial?.name ?? '') const [material, setMaterial] = useState(initial?.material ?? '') + const [color, setColor] = useState(initial?.color ?? '') + const colorOptionsId = useId() const [spec, setSpec] = useState(initial?.spec ?? '') const [price, setPrice] = useState(initial?.price?.toString() ?? '') const [priceUnit, setPriceUnit] = useState( @@ -39,8 +42,8 @@ export function AccessoryModelEditor({ initial, initialModule, initialCategory, const [camChoices, setCamChoices] = useState([]) const [camChoice, setCamChoice] = useState() const [preview, setPreview] = useState(null) - const [dimensions, setDimensions] = useState(initial?.model?.dimensions ?? initial?.dimensions ?? {}) - const [pending, setPending] = useState(initial?.model?.pending ?? initial?.pending ?? []) + const [dimensions, setDimensions] = useState(initial?.dimensions ?? initial?.model?.dimensions ?? {}) + const [pending, setPending] = useState(initial?.pending ?? initial?.model?.pending ?? []) const [correction, setCorrection] = useState('') const [status, setStatus] = useState('') const [error, setError] = useState('') @@ -58,28 +61,36 @@ export function AccessoryModelEditor({ initial, initialModule, initialCategory, objectUrls.current.add(url) return url } - const savedModel = initial?.model ?? null + const savedModel = initial?.model ? { + ...initial.model, kind: initial.model.kind ?? initial.kind, sourceSpec: initial.model.sourceSpec ?? initial.spec ?? '', + } : null const currentModel = preview ?? savedModel - const fields = modelFields(kind, currentModel?.camGeometry) - const dimensionsChanged = currentModel !== null && fields.some(([key]) => - dimensions[key] !== currentModel.dimensions[key] || pending.includes(key) !== currentModel.pending.includes(key)) + const generationModel = currentModel?.kind === kind ? currentModel : null + const fields = generationModel?.cad ? [] : modelFields(kind, generationModel?.camGeometry) + const dimensionsChanged = generationModel !== null && fields.some(([key]) => + dimensions[key] !== generationModel.dimensions[key] || pending.includes(key) !== generationModel.pending.includes(key)) const canSaveModel = preview && !correction.trim() && !dimensionsChanged && !photosChanged const disabled = !canEdit || busy !== null - const categoryChangeDisabled = disabled || currentModel !== null - const canGenerate = !!kind && (photos.length > 0 || (!!currentModel && (dimensionsChanged || !!correction.trim()))) + const canGenerate = !!kind && (photos.length > 0 || (!!generationModel && (dimensionsChanged || !!correction.trim()))) function changeKind(value: string) { + if (value === kind) return setKind(value) - setPhotosChanged(false) setCamChoices([]) setCamChoice(undefined) - setDimensions({}) - setPending([]) - setCorrection('') + const matchingModel = currentModel?.kind === value ? currentModel : null + setDimensions(matchingModel?.dimensions ?? {}) + setPending(matchingModel?.pending ?? []) setStatus('') setGenerationError('') } + function changeCategory(nextModule: AccessoryModule, nextCategory: string) { + setModule(nextModule) + setCategory(nextCategory) + if (!accessoryCategories(nextModule)[nextCategory]?.includes(kind)) changeKind('') + } + function appendPhotos(files: File[]) { if (!files.length) return setError('') @@ -119,9 +130,9 @@ export function AccessoryModelEditor({ initial, initialModule, initialCategory, try { const note = correction.trim() const result = await generateAccessoryModel({ - kind, dimensions, pending, note, photos, currentModel, choice, progress: setStatus, + kind, dimensions, pending, note, photos, currentModel: generationModel, choice, progress: setStatus, surface: { color, material }, readPhotos: photos.length > 0 && (photosChanged || - (!dimensionsChanged && (!note || !currentModel || !!currentModel.cad))), + (!dimensionsChanged && (!note || !generationModel || !!generationModel.cad))), usePriorCad: photosChanged || !!note, }) if ('choices' in result) { @@ -130,7 +141,7 @@ export function AccessoryModelEditor({ initial, initialModule, initialCategory, return } const { blob, model } = result - const nextModel = { ...result.accessory, blob, url: objectUrl(blob) } + const nextModel = { ...result.accessory, sourceSpec: spec.trim(), blob, url: objectUrl(blob) } if (preview) { URL.revokeObjectURL(preview.url) objectUrls.current.delete(preview.url) @@ -152,11 +163,10 @@ export function AccessoryModelEditor({ initial, initialModule, initialCategory, if (disabled || !canSave || (includeModel && !canSaveModel)) return const model = includeModel ? preview : savedModel const input = accessoryDraftInputSchema.safeParse({ - id: initial?.id, revision: initial?.revision, module, category, kind, code, name, material, spec, + id: initial?.id, revision: initial?.revision, module, category, kind, code, name, material, color, spec, price: price === '' ? null : Number(price), priceUnit, weightGrams: weight === '' ? null : Number(weight), photos, model, - dimensions: model?.dimensions ?? initial?.dimensions ?? {}, - pending: model?.pending ?? initial?.pending ?? [], + dimensions, pending, }) if (!input.success) { setError(input.error.issues[0]?.message || '请补全资料') @@ -196,20 +206,23 @@ export function AccessoryModelEditor({ initial, initialModule, initialCategory, }}>
- - +
- { const next = { ...dimensions } if (Number.isFinite(value)) next[key] = value diff --git a/furniture-3d-system/src/app/database/bom-library/accessory-models/AccessoryModelGallery.tsx b/furniture-3d-system/src/app/database/bom-library/accessory-models/AccessoryModelGallery.tsx index 495ec495..d3b8b73c 100644 --- a/furniture-3d-system/src/app/database/bom-library/accessory-models/AccessoryModelGallery.tsx +++ b/furniture-3d-system/src/app/database/bom-library/accessory-models/AccessoryModelGallery.tsx @@ -13,7 +13,7 @@ export function AccessoryModelGallery({ items, onOpen }: {