From e2d66eb7c74c4b2d5af95ed9ee4b9e2970285820 Mon Sep 17 00:00:00 2001 From: abaishu0730 Date: Mon, 19 Oct 2026 15:49:34 +0800 Subject: [PATCH] feat(web): promote order notifications and add segmented navigation --- README.md | 9 +- docs/HANDOFF.md | 4 +- docs/design-requirements.md | 6 +- ...tion-navigation-verification-2026-10-19.md | 40 ++++++ docs/order-rules-guide.md | 2 +- .../2026-10-19-notification-navigation.md | 25 ++++ docs/web-action-inventory.md | 6 +- src/app/assets.cjs | 2 + src/modules/dashboard/api.cjs | 2 +- src/modules/health/runtime-health.cjs | 6 +- tests/app/execution-contract-ui.test.cjs | 13 +- tests/app/navigation-ui.test.cjs | 10 +- tests/app/notification-navigation.test.cjs | 117 ++++++++++++++++++ tests/app/web-closure-review-ui.test.cjs | 21 +++- tests/app/web-closure-ui.test.cjs | 21 +++- tests/bpm/bpm-ui.test.cjs | 2 +- tests/mail/mail-ui.test.cjs | 2 +- tests/order-rules/section-ui.test.cjs | 18 +++ tests/order-rules/web.test.cjs | 27 ++-- web/app.css | 18 ++- web/app.js | 51 +++++--- web/index.html | 2 +- web/modules/navigation/view.js | 50 +++++++- web/modules/order-notifications/shared.js | 21 ++++ web/modules/order-notifications/view.js | 52 ++++++++ web/modules/order-rules/view.js | 65 +++------- web/modules/workspace/view.js | 3 +- 27 files changed, 475 insertions(+), 120 deletions(-) create mode 100644 docs/notification-navigation-verification-2026-10-19.md create mode 100644 docs/plans/2026-10-19-notification-navigation.md create mode 100644 tests/app/notification-navigation.test.cjs create mode 100644 tests/order-rules/section-ui.test.cjs create mode 100644 web/modules/order-notifications/shared.js create mode 100644 web/modules/order-notifications/view.js diff --git a/README.md b/README.md index 54e2c49..c430683 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ 面向团队的 BPM 订单工作台,提供业务日历、异常待办与转交、连接管理和运行监管配置;保留 Chrome 已登录订单页导出本地 PDF 的能力。 -**项目最终目标**:无人值守识别匹配订单、按模板整理、上传 210、按产品线群组每天两次自动发送邮件。当前实现团队工作台与 BPM Web 登录、会话保存,订单处理规则后续确定;BPM 知会不自动处理。已接入新版门户只读扫描、可配置 SMB 归档、通用通知队列、受控 ZCode 对话,以及服务守护和健康面板。实际 BPM 简要说明字段与产业接口人规则等待同事整理后配置。完整流程背景见 [无人值守系统设计](docs/unattended-system-design.md),登录实现见 [BPM 登录设计](docs/superpowers/specs/2026-10-16-bpm-login-design.md)。 +**订单通知流程**:以 Excel 的15类为准,从真实 BPM 待办按流程、版本和节点识别订单,导出并校验归档文件,按北京时间每天两个有效时段同类别汇总一封。收件人由分类规则维护,BPM 节点人工办理,惠州额外通知条件待确认。自动发信保持暂停,类别字段、目录、邮箱与预览须现场核验后才可启用。旧通用通知写入和调度已退役,历史记录保留查询。当前要求见[设计要求](docs/design-requirements.md)。 ## 设计与部署入口 @@ -10,20 +10,21 @@ - [设计要求(当前基准)](docs/design-requirements.md):功能范围、架构、数据存储、权限、验收和实施顺序。 - [模块重构方案(2026-10-19)](docs/superpowers/specs/2026-10-19-modular-refactor-design.md):代码职责、兼容约束及七项鲁棒性修复。 - [本轮重构验证](docs/modular-refactor-verification-2026-10-19.md):故障回归、全量结果和实机验证边界。 +- [订单通知管理与分段横栏验收](docs/notification-navigation-verification-2026-10-19.md):新入口、独立路由、角色/手机及正式更新证据。 - [部署说明](docs/deployment.md):安装、HTTPS、状态目录及备份。 - [后续业务资料整理表](docs/business-configuration.md):SMB 参数、来源字段和产业接口人需要整理的信息。 - [扫描验证记录](docs/bpm-scan-verification-2026-10-16.md):最近验证及实际范围。 ## Web 看板 -侧栏保留工作总览、订单与导出记录、异常待办、ZCode 助手、业务设置和系统设置六个入口。业务设置集中分类通知规则、发送计划、业务日历及模板与收件群组,兼容业务通知折叠在“兼容配置”中;系统设置集中 BPM、邮箱、存储、服务接入、运行监管、系统健康、团队账号和操作记录。团队账号仅管理员可见。设置子页面提供返回所属设置的入口,原页面链接仍然有效;个人修改密码保留在右上角。 +侧栏七项:工作总览、订单通知管理、订单与导出记录、异常待办、ZCode 助手、业务设置、系统设置。订单通知管理集中通知总览、订单执行、通知订单、待发批次、发送记录,以及发送计划/日历/模板/发送设置。业务设置维护分类通知规则与字段映射,系统设置维护服务连接、健康、账号及审计。顶部直接接入 Tabler 1.6.1 圆角分段横栏,支持手机滚动和旧地址;团队账号仅管理员可见,个人改密保留右上角。 1. 启动工具后,在部署机打开 http://127.0.0.1:18766 ,自行创建管理员账号(至少 12 位密码)。没有默认账号或默认密码。 2. 管理员在“团队账号”中创建同事账号;同事使用启动窗口打印的局域网地址访问。默认监听 0.0.0.0:18766,能否跨机器访问取决于路由和 Windows 防火墙;本工具不自动修改防火墙。 3. 业务日历支持月历、公司工作日/休息日/停发覆盖,采集与发送分别设置;可恢复每周默认规则,并预览发送时段。保存配置不会执行采集或发送。 4. 异常待办支持创建、认领、转交、提交验证、填写人工核验依据后关闭和重新打开;显示负责人和流转记录,防止多人同时覆盖。operator 可处理异常,viewer 只读,admin 可管理全部配置。 -5. BPM 连接支持创建、账号托管、网页登录、检查保存、重启复用和停用。每个连接独立保存会话,由负责人或管理员操作。运行监管目前保存默认负责人、通知方式和重试上限草稿,不调用 ZCode、不执行恢复、不发送通知。 -6. 邮箱管理支持公司 SMTP / IMAP、模板邮件收取、预览确认和历史版本;原 PDF 记录、每日两次时间、产品线群组、团队账号和操作记录继续可用。新版 BPM 扫描结果按流程到达日期分区;业务通知使用独立通用队列,默认暂停,BPM 来源适配等待字段核实。 +5. BPM 连接支持创建、账号托管、网页登录、检查保存、重启复用和停用。每个连接独立保存会话,由负责人或管理员操作。系统健康提供守护状态和按权限过滤的执行阻塞信息;旧监管草稿入口已退役。 +6. 邮箱管理支持公司 SMTP / IMAP、模板邮件收取、预览确认和历史版本;模板按 Excel 类别显式关联,收件人在分类规则维护。只读 BPM 到达历史按日期分区,独立于通知执行;旧群组与通用通知记录仅供历史查询。 界面复用 [Tabler](https://tabler.io/admin-template) 免费开源版(@tabler/core 1.6.1),CSS/JS 全部在本机提供;MIT 原文见 licenses/Tabler-MIT.txt。青龙已有独立部署准备和 CLI,尚未接通业务,本次不启动它或复制其内部源码。 diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index 6517696..3786532 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -2,7 +2,7 @@ ## 工作区与版本 -当前本地开发分支为 codex/modular-refactor,工作区 C:/Users/ABS/.codex/worktrees/modular-refactor/Order Notification Automation。原Z盘源码不改。未推送或合并;部署检查结果以[本轮验收](web-closure-verification-2026-10-19.md)为准。 +当前本地开发分支为 codex/modular-refactor,工作区 C:/Users/ABS/.codex/worktrees/modular-refactor/Order Notification Automation。原Z盘源码不改。未推送或合并;本轮导航及部署检查见[订单通知管理验收](notification-navigation-verification-2026-10-19.md),前次执行闭环见[执行闭环验收](web-closure-verification-2026-10-19.md)。 源码模块:BPM会话与只读接口在src/modules/bpm;15类规则、窗口、冻结批次及受控发送在order-rules;执行协调与字段证据在order-execution;归档提供器在storage/order-archive.cjs。扩展原PDF四字段文件名保持兼容。web/modules/navigation/lifecycle.js负责页面生命周期。 @@ -10,7 +10,7 @@ [设计要求](design-requirements.md)是当前权威入口,[操作清单](web-action-inventory.md)记录页面动作、权限、前置条件、结果、失败路径与验收。 -- 六项侧栏,业务/系统设置顶部横栏。团队账号管理员可见;个人改密右上角。助手接入配置移到系统设置。 +- 七项侧栏,新增一级“订单通知管理”(总览、执行、通知订单、批次、发送记录、通知配置);业务设置仅规则/字段映射。所有模块接入 Tabler nav-segmented 圆角横栏,通知配置内为计划/日历/模板/发送设置。团队账号管理员可见;个人改密右上角。助手接入配置移到系统设置。 - Excel15类精确匹配流程/版本/节点,同窗口同类别一封。收件人由分类规则维护,模板显式关联类别;归档与附件要求以Excel类别为准。 - 标题按订单号拆段提取。惠州额外通知待确认;BPM节点人工办理。 - 北京时间、公司日历,周一首封从上个发送工作日最后截止起,历史不自动处理/追补。 diff --git a/docs/design-requirements.md b/docs/design-requirements.md index 6ed4ade..681abce 100644 --- a/docs/design-requirements.md +++ b/docs/design-requirements.md @@ -4,9 +4,11 @@ ## 界面与权限 -沿用 Tabler,侧栏六项:工作台、处理记录、异常待办、助手、业务设置、系统设置。设置入口直接打开第一项,用顶部横栏切换;原 hash、刷新、浏览器前后退继续有效。390px 下横栏滚动,当前项高亮并进入视口。 +沿用 Tabler 1.6.1,侧栏七项:工作总览、订单通知管理、订单与导出记录、异常待办、助手、业务设置、系统设置。顶部接入原生 nav-segmented 圆角分段横栏:灰底、白色选中项、SVG图标、清晰焦点。390px 单行滚动且选中项自动进入横栏视口。所有页签为真实 hash 链接,默认首项,刷新及浏览器前后退继续有效。 -业务横栏:分类规则、发送计划、业务日历、邮件模板。系统横栏:BPM连接、邮箱管理、存储服务器、助手设置、系统健康、团队账号、操作记录。团队账号仅管理员可见;个人改密在右上角。助手主页面只保留对话和授权操作卡片。 +订单通知管理:通知总览、订单执行、通知订单、待发批次、发送记录、通知配置。通知配置卡片内为发送计划、业务日历、邮件模板、发送设置;规则收件人在业务设置维护。通知总览显示真实时段、下一计划时点、待发数及阻塞原因;通知订单关联冻结批次及归档证据,导出记录仍独立查询采集/PDF。顶部通知状态以服务端为准,查询失败为待确认,不猜测暂停或启用。 + +业务横栏:分类通知规则、字段映射。系统横栏:BPM连接、邮箱管理、存储服务器、助手设置、系统健康、团队账号、操作记录。团队账号仅管理员可见;个人改密在右上角。助手主页面只保留对话和授权操作卡片。 表单离开保护提供保存并继续/放弃/留下;密码、新建账号等敏感或不可自动提交表单只允许放弃或留下。刷新受浏览器原生 beforeunload 保护,不可能自定义其三个按钮。提交禁重、错误保留输入;持久保存与刷新失败分别提示;旧页/旧登录响应不得覆盖当前页面。 diff --git a/docs/notification-navigation-verification-2026-10-19.md b/docs/notification-navigation-verification-2026-10-19.md new file mode 100644 index 0000000..b66d8d1 --- /dev/null +++ b/docs/notification-navigation-verification-2026-10-19.md @@ -0,0 +1,40 @@ +# 订单通知管理与分段横栏验收(2026-10-19) + +## 变更 + +七项侧栏新增一级“订单通知管理”,包含总览、执行、通知订单、待发批次、发送记录和通知配置;通知配置内是计划、日历、模板与发送设置。业务设置仅规则、字段映射,系统设置原七项及管理员权限保留。每项均为独立 hash 地址;旧 rules/notifications、order-rules、schedule、calendar、templates 地址继续有效。 + +直接接入现有 Tabler 1.6.1 nav-segmented,未引入 React/Tailwind;灰底白选中、SVG图标、焦点、移动单行滚动及窗口缩小时选中项可见。通知总览的时间范围和下一计划来自服务器,并排展示以便桌面首屏看到数量。 + +原规则中心拆为 rule view、notification view 和小型共享渲染辅助模块;分别拥有请求、事件及销毁。执行/字段继续复用原模块。未更改后端业务 API、数据库结构、发送窗口、冻结/幂等语义、权限和人工恢复要求。顶部及工作总览改用服务端实际通知状态,失败显示待确认。 + +## 验证证据 + +- 新增独立视图专项5项:订单批次及归档证据、字段页面请求边界、下一时点与阻塞修复入口、邮箱读取失败提示、离页后写入完成不得再发起读取。 +- 新导航专项5项:新旧地址/历史、三角色/390px、未保存保护/窗口缩小、实际通知状态及迟到响应、轮询较旧成功和初始失败均不得覆盖较新页面。测试使用真实 Chromium 与隔离账号/数据库;必要故障由本地HTTP响应注入。 +- 原编辑器、扫描、字段绑定、补发、结果核验、保存失败、迟到401和敏感表单测试保留业务断言,入口迁移为真实路由链接。 +- npm ci 与 npm ls 成功;188个已跟踪及新增JS/CJS语法检查、git diff --check通过。 +- 独立审查发现同页总览轮询响应覆盖问题;成功路径和失败路径分别观察测试失败,修复后通过,审查复核通过。使用独立请求版本,不以轮询改变全页生命周期。 + +首轮全量:376项,373通过、2失败、1跳过,460.06秒。两个失败均为旧测试导航契约:模板迁移到通知配置,BPM生命周期单元测试需声明新增导航接口;修正后对应2项通过。可选官方CLI集成测试未设置ORDER_TEST_ZCODE_CLI,仍跳过。 + +最终代码全量结果与正式更新核验记录见下方追加。完整日志保存在忽略目录 output/verification/notification-navigation-final-tests.log;首轮保留 notification-navigation-full-tests.log。 + +最终代码全量:377项,376通过、0失败、1可选CLI跳过,439.57秒,进程退出码0。最终实现无后续变更。专项覆盖管理员、操作员、只读角色,390px、快速切换、历史导航、未保存保护、重复提交、过期响应和登录失效;原业务回归全部通过。 + +## 正式更新 + +- 更新前停止守护服务并完成受当前用户ACL保护的备份:`%LOCALAPPDATA%/OrderNotificationAutomationBackups/notification-navigation-20261019-154441`,3409个状态文件;12个SQLite数据库只读`quick_check`全部为ok。 +- 从隔离工作树`codex/modular-refactor`重新启动,守护状态running/healthy,两个端口内部健康检查通过;登录自启动仍为原值false。 +- 更新前后用户/设置摘要、3354个已有密钥摘要、BPM账号、邮箱、存储身份均一致;正式自动发送仍为false,配置版本仍为1。19条已有服务器登录会话逐条比较保留。 +- HTTP核验:18766首页200;18765无扩展来源403、合法扩展来源无配对密钥401;未登录访问业务脚本401,认证边界保留。 +- 浏览器隔离预览曾在同一127.0.0.1主机的不同端口登录,导致共享名称Cookie覆盖正式浏览器Cookie。已停止隔离服务;用户自行重新登录后,原管理员账号进入正式页面成功。服务器会话保存通过,原浏览器Cookie连续性不记为通过;后续预览需使用独立浏览器上下文或独立主机名。 +- 正式1440px桌面核验七项菜单、六个主标签、四个配置子页签、规则/字段和七项系统设置;390px手机核验主/子选中项均可见,页面宽375px不超过视口390px,两个导航仅自身滚动。没有保存业务配置或触发邮件/BPM操作,最终回到通知总览并恢复默认视口。 + +## 现场限制 + +正式自动发信继续暂停,不发送真实邮件、不办理BPM节点、不改变任何密码。15类真实字段、目录、邮箱与冻结预览仍须现场核验。隔离测试邮件仅发本地SMTP;未用样本测试冒充公司系统已就绪。 + +## 界面证据 + +[正式桌面](../output/verification/notification-nav-formal-desktop.png)、[正式390px手机](../output/verification/notification-nav-formal-mobile.png)。截图与完整日志保留在本机忽略目录,不随源码提交。 diff --git a/docs/order-rules-guide.md b/docs/order-rules-guide.md index 82b0677..e632596 100644 --- a/docs/order-rules-guide.md +++ b/docs/order-rules-guide.md @@ -1,6 +1,6 @@ # 分类通知规则首版 -入口:业务设置顶部横栏“分类规则”。内部还提供订单执行、真实字段目录、待发批次和发送记录。 +入口:业务设置顶部横栏“分类通知规则”;相邻“字段映射”维护真实字段目录。订单执行、通知订单、待发批次和发送记录迁至一级“订单通知管理”;发送计划、日历、模板和发送设置统一在其“通知配置”中。原页面地址仍有效。 ## 收单范围 diff --git a/docs/plans/2026-10-19-notification-navigation.md b/docs/plans/2026-10-19-notification-navigation.md new file mode 100644 index 0000000..8899907 --- /dev/null +++ b/docs/plans/2026-10-19-notification-navigation.md @@ -0,0 +1,25 @@ +# 订单通知管理与分段横栏实施 + +已批准设计:订单通知作为一级菜单,现有 Tabler 1.6.1 nav-segmented 横栏;通知配置独立,规则和字段留在业务设置。保留全部发送状态限制、持久数据、权限和页面生命周期。工作目录为现有 codex/modular-refactor 隔离检出,不修改原 Z: 检出,不推送、不合并、不发送真实邮件或办理 BPM。 + +## Task 1: 拆分通知运行与规则配置 + +所有权:web/modules/order-rules/view.js,新增 web/modules/order-notifications/ 下的视图、共享辅助模块,必要的 tests/order-rules、tests/app/execution-contract-ui.test.cjs 及涉及旧内部按钮的 UI 测试。不要修改 app.js、navigation、app.css、index.html、后端静态路由(主协调者负责)。 + +将原八按钮视图拆为 OrderRuleViews.render(container,isActive,section='rules')(rules / fields),和 OrderNotificationViews.render(container,isActive,section='workbench')(workbench / execution / orders / pending / history / settings)。各自 configure 接受原辅助函数;共享操作/状态/数据读取可独立成模块,禁止复制整个旧视图做假拆分。通知运行与规则各自负责请求、事件和销毁。固定路由从外部传入 section,不再渲染内部八按钮导航。保留原 id 与操作语义便于回归。 + +新增通知总览的下一发送时点(使用 /overview 的 nextSlots 与 /order-rules 的真实 window;勿本地自造调度)、受阻原因和入口。通知订单详情展示 batchId、规则版本、归档证据(若存在),链接 #notification-batches 和 #records;导出记录链接由协调者负责。规则模块只读规则/字段所需数据,不读取邮箱运行列表。通知模块只在 settings 读取邮箱;状态刷新不得覆盖输入,离页请求不得更新新页面。 + +规则、字段分别由 OrderRuleViews 渲染;订单执行复用 OrderExecutionViews.execution,字段复用 OrderExecutionViews.fields。保留未保存保护、版本/幂等、prepare/recheck/resend/resolve 权限,禁止因为更换入口启用发信。缺失能力展示具体原因及字段/BPM/存储入口。 + +测试先写/迁移行为场景,再观察因缺少新接口而失败。原内部按钮测试改为真实路由链接;不要删除业务验收断言。提供模块加载顺序、静态文件 URL 及接口给协调者。不要提交,报告变更和测试到本计划 workspace/task-1-report.md,不派发子代理。 + +## Task 2: 路由与 Tabler 横栏集成 + +七项侧栏依次 overview、order-notifications、records、exceptions、assistant、business-settings、system-settings。通知主路由 order-notifications / notification-execution / notification-orders / notification-batches / notification-history / schedule,标签为通知总览 / 订单执行 / 通知订单 / 待发批次 / 发送记录 / 通知配置。配置子路由 schedule / calendar / templates / notification-settings,主标签始终选中通知配置。业务 order-rules / rule-fields。系统原七项。各页为真实 hash 链接,由 PageLifecycle guard 处理。 + +统一 nav-segmented 灰底白选中,SVG 小图标,focus-visible,单行移动滚动且选中项仅在横栏内滚入可见。配置四子项在卡片内展示。首次默认 overview / rules / bpm。保留旧地址,rules 和 notifications 兼容分类规则入口。每个路由正确标题、所属菜单、面包屑。顶部运行状态读取服务端 /order-rules,未知/失败不可显示暂停或已就绪,错误可从刷新重试,离页/退出旧响应无效。配套后端静态文件映射和 index 脚本加载顺序。 + +## Task 3: 验收、文档、状态备份与本地更新 + +新增并运行集成验收:三角色、桌面及390px、所有路由与旧地址、快速切换、刷新/前进后退/dirty guard、菜单收起、通知配置四页、只读和管理员权限、无后台写入。完整 npm ci / npm test、JS/CJS检查、独立代码审查。更新设计、HANDOFF 和 action inventory。备份当前正式状态与加密身份,核验未改动后验证双端口、登录、静态文件与导航,自动通知继续暂停。保留独立验收报告和截图。 diff --git a/docs/web-action-inventory.md b/docs/web-action-inventory.md index 4ebb5b2..89b0ca2 100644 --- a/docs/web-action-inventory.md +++ b/docs/web-action-inventory.md @@ -1,12 +1,14 @@ # 全站操作清单与验收 -适用:2026-10-19 设置横栏与执行协调版本。状态“已验证可用”指隔离环境对应行为通过测试,外部系统现场核验另列。所有写操作先校验登录、同源、角色、版本及前置条件;失败保留输入,结果不明查询实际状态,不自动重复写入或发信。所有查询支持重新进入刷新;无真实取消能力的动作不提供取消。 +适用:2026-10-19 订单通知管理、分段横栏与执行协调版本。状态“已验证可用”指隔离环境对应行为通过测试,外部系统现场核验另列。所有写操作先校验登录、同源、角色、版本及前置条件;失败保留输入,结果不明查询实际状态,不自动重复写入或发信。所有查询支持重新进入刷新;无真实取消能力的动作不提供取消。 + +操作归属:业务设置维护规则/字段映射;订单通知管理维护运行任务、通知订单、批次、发送记录和计划/日历/模板/发送设置;系统设置维护服务与账号。导出记录保留只读到达历史和PDF任务,与通知订单互相链接。 ## 共用交互 | 编号 / 操作 | 权限、前置条件 | 实际执行及结果位置 | 失败 / 验收 | 状态 | |---|---|---|---|---| -| N01 六项侧栏、横栏、返回、旧链接 | 已登录;账号页管理员 | hash路由、选中高亮、直接加载子页 | 深链接、刷新、前进后退、390px滚动;web-closure-ui/navigation-ui | 已验证可用 | +| N01 七项侧栏、分段横栏、返回、旧链接 | 已登录;账号页管理员 | hash路由、选中高亮、直接加载子页 | 深链接、刷新、前进后退、390px滚动;web-closure-ui/navigation-ui/notification-navigation | 已验证可用 | | N02 保存并继续、放弃、留下 | 有未保存配置;密码/新账号只允许后两项 | 保存成功后导航;放弃不写入 | 保存失败保留草稿;Back后留下不破坏历史;web-closure-ui | 已验证可用 | | N03 表单保存、重复点击、快速切换 | 各表单权限与有效输入 | 提交期间禁用;以服务端持久结果确认,保存与刷新分别反馈 | 写超时先读取状态;迟到401/写响应不影响新会话,刷新失败保留新版本;web-closure-review-ui/final-auth-ownership | 已验证可用 | | N04 搜索、筛选、分页、刷新 | 查询权限 | 重查并显示当前条件下结果、空状态及总数 | 查询失败可重试;bpm-scan-http-ui/storage-ui/history-ui | 已验证可用 | diff --git a/src/app/assets.cjs b/src/app/assets.cjs index bb22cdb..ce3da42 100644 --- a/src/app/assets.cjs +++ b/src/app/assets.cjs @@ -22,6 +22,8 @@ function createAssets(){ '/order-rules-editor.js':{path:path.join(webRoot,'modules/order-rules/editor.js'),type:'text/javascript'}, '/order-rules-preview.js':{path:path.join(webRoot,'modules/order-rules/preview.js'),type:'text/javascript'}, '/order-execution.js':{path:path.join(webRoot,'modules/order-rules/execution.js'),type:'text/javascript'}, + '/order-notifications-shared.js':{path:path.join(webRoot,'modules/order-notifications/shared.js'),type:'text/javascript'}, + '/order-notifications.js':{path:path.join(webRoot,'modules/order-notifications/view.js'),type:'text/javascript'}, '/order-rules.js':{path:path.join(webRoot,'modules/order-rules/view.js'),type:'text/javascript'}, '/notifications.js':{path:path.join(webRoot,'modules/notifications/view.js'),type:'text/javascript'}, '/assistant.js':{path:path.join(webRoot,'modules/assistant/view.js'),type:'text/javascript'}, diff --git a/src/modules/dashboard/api.cjs b/src/modules/dashboard/api.cjs index f6b1c0d..2802420 100644 --- a/src/modules/dashboard/api.cjs +++ b/src/modules/dashboard/api.cjs @@ -11,7 +11,7 @@ const handled=(...args)=>{reply(...args);return true;}; const rules=orderRules?.snapshot(),published=rules?.rules?.filter(r=>r.status==='enabled')||[]; const capabilities=rules?.capabilities||{},ready=['liveTodo','pdfExport','automaticArchive'].every(key=>capabilities[key]===true); const automation={enabled:rules?.settings?.enabled===true,ready,reason:rules?.settings?.enabled!==true?'分类自动发信已暂停;请先完成类别字段、目录、邮箱与预览核验。':ready?'分类执行链路已完成实际接入检查。':'分类执行链路仍有未通过的实际检查,请查看订单执行中的阻塞原因。'}; - return handled(200,{stats:{total:jobs.length,today:todayJobs.length,completed:jobs.filter(job=>job.status==='success').length,failed:jobs.filter(job=>['error','interrupted'].includes(job.status)).length,running:jobs.filter(job=>job.status==='running').length},scan,automation,connections:[{name:'PDF 导出',ready:true,detail:'浏览器扩展导出与任务记录已接入'},{name:'Excel 分类规则',ready:published.length>0,detail:`15类规则,已发布 ${published.length} 类;实际字段按流程版本核验`},{name:'BPM 待办执行',ready:capabilities.liveTodo===true,detail:capabilities.liveTodo===true?'真实待办接口检查通过;各类别仍需字段核验':'请在分类规则的订单执行中检查真实待办及字段'},{name:'到达历史扫描',ready:!!scan?.runs.some(r=>r.status==='success'),detail:scan?`${scan.config.enabled?'已开启':'已暂停'},每 ${scan.config.intervalMinutes} 分钟扫描 · 已收录 ${scan.total} 条流程`:'历史扫描服务未启动'},{name:'存储服务器',ready:!!storage?.store.servers().some(s=>s.enabled&&s.state.readable&&s.state.writable),detail:storage?`已配置 ${storage.store.servers().length} 个 SMB 存储服务器`:'存储服务未启动'},{name:'邮件渠道',ready:mailChannels.some(c=>!c.readOnly&&c.state.smtp),detail:`已配置 ${mailChannels.length} 个邮箱`},{name:'邮件模板',ready:mailTemplates.some(t=>t.status==='active'),detail:`${mailTemplates.filter(t=>t.status==='active').length} 个已生效,${mailTemplates.filter(t=>t.status==='pending').length} 个待确认;按类别显式关联`}],nextSlots:nextSlots(settings.schedule,new Date(),2,workspace?workspace.snapshot(store.users()).calendar.overrides:[]),schedule:settings.schedule,jobs:jobs.slice(0,6).map(publicJob),audit:store.audit().slice(0,5)}); + return handled(200,{stats:{total:jobs.length,today:todayJobs.length,completed:jobs.filter(job=>job.status==='success').length,failed:jobs.filter(job=>['error','interrupted'].includes(job.status)).length,running:jobs.filter(job=>job.status==='running').length},scan,automation,connections:[{name:'PDF 导出',ready:true,detail:'浏览器扩展导出与任务记录已接入'},{name:'Excel 分类规则',ready:published.length>0,detail:`15类规则,已发布 ${published.length} 类;实际字段按流程版本核验`},{name:'BPM 待办执行',ready:capabilities.liveTodo===true,detail:capabilities.liveTodo===true?'真实待办接口检查通过;各类别仍需字段核验':'请在订单通知管理的订单执行中检查实时待办,字段映射在业务设置维护'},{name:'到达历史扫描',ready:!!scan?.runs.some(r=>r.status==='success'),detail:scan?`${scan.config.enabled?'已开启':'已暂停'},每 ${scan.config.intervalMinutes} 分钟扫描 · 已收录 ${scan.total} 条流程`:'历史扫描服务未启动'},{name:'存储服务器',ready:!!storage?.store.servers().some(s=>s.enabled&&s.state.readable&&s.state.writable),detail:storage?`已配置 ${storage.store.servers().length} 个 SMB 存储服务器`:'存储服务未启动'},{name:'邮件渠道',ready:mailChannels.some(c=>!c.readOnly&&c.state.smtp),detail:`已配置 ${mailChannels.length} 个邮箱`},{name:'邮件模板',ready:mailTemplates.some(t=>t.status==='active'),detail:`${mailTemplates.filter(t=>t.status==='active').length} 个已生效,${mailTemplates.filter(t=>t.status==='pending').length} 个待确认;按类别显式关联`}],nextSlots:nextSlots(settings.schedule,new Date(),2,workspace?workspace.snapshot(store.users()).calendar.overrides:[]),schedule:settings.schedule,jobs:jobs.slice(0,6).map(publicJob),audit:store.audit().slice(0,5)}); } if(route==='/api/settings') { if(request.method==='GET')return handled(200,store.settings()); diff --git a/src/modules/health/runtime-health.cjs b/src/modules/health/runtime-health.cjs index 39ab102..8d881d6 100644 --- a/src/modules/health/runtime-health.cjs +++ b/src/modules/health/runtime-health.cjs @@ -40,11 +40,11 @@ class RuntimeHealth { const checkedAt=timestamp(c.state?.checkedAt),status=!checkedAt?'pending':c.state.smtp&&c.state.imap?'healthy':'error'; return {id:c.id,name:redact(c.name||'托管邮箱'),status,checkedAt,detail:redact(c.state?.message||'尚未检查 SMTP / IMAP。'),...this.remember('mail',c.id,{successAt:status==='healthy'?checkedAt:null,failureAt:status==='error'?checkedAt:null})}; })); - if(this.sources.execution)safe('execution','分类订单执行','#order-rules',()=>{ + if(this.sources.execution)safe('execution','分类订单执行','#notification-execution',()=>{ const data=this.sources.execution.snapshot(),names={liveTodo:'真实待办',pdfExport:'PDF 导出',automaticArchive:'归档校验'}; - const items=Object.entries(names).map(([id,name])=>({id,name,global:true,status:data.capabilities?.[id]===true?'healthy':'pending',detail:data.capabilities?.[id]===true?'实际检查已通过;各类别仍需现场核验。':'尚未通过实际接入检查,请在分类规则查看阻塞原因。'})); + const items=Object.entries(names).map(([id,name])=>({id,name,global:true,status:data.capabilities?.[id]===true?'healthy':'pending',detail:data.capabilities?.[id]===true?'实际检查已通过;各类别仍需现场核验。':'尚未通过实际接入检查,请在订单通知管理的订单执行查看阻塞原因。'})); for(const task of data.tasks||[]){const status=['blocked','failed'].includes(task.status)?'error':task.status==='unknown'?'unknown':['capturing','preparing','archiving','running','sending'].includes(task.status)?'running':['archived','sent','pending'].includes(task.status)?'healthy':'pending'; - items.push({id:task.id,owner:connections.find(c=>c.id===task.connectionId)?.owner,name:redact(task.processName||'订单执行任务'),status,checkedAt:timestamp(task.updatedAt),detail:redact(task.error||task.reason||task.blockedReason||'任务进度已持久保存,请在分类规则查看。'),...this.remember('execution',task.id,{successAt:status==='healthy'?task.updatedAt:null,failureAt:status==='error'?task.updatedAt:null})});} + items.push({id:task.id,owner:connections.find(c=>c.id===task.connectionId)?.owner,name:redact(task.processName||'订单执行任务'),status,checkedAt:timestamp(task.updatedAt),detail:redact(task.error||task.reason||task.blockedReason||'任务进度已持久保存,请在订单通知管理查看。'),...this.remember('execution',task.id,{successAt:status==='healthy'?task.updatedAt:null,failureAt:status==='error'?task.updatedAt:null})});} return items; }); return groups; diff --git a/tests/app/execution-contract-ui.test.cjs b/tests/app/execution-contract-ui.test.cjs index aa0f196..40a8193 100644 --- a/tests/app/execution-contract-ui.test.cjs +++ b/tests/app/execution-contract-ui.test.cjs @@ -5,6 +5,15 @@ test('real captured sample uses server evidence id and uncertain batch verificat const dir=await fs.mkdtemp(path.join(os.tmpdir(),'execution-contract-ui-')),runtime=await startTestDashboard({stateDir:dir}),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(async()=>{await browser.close();await runtime.close();await fs.rm(dir,{recursive:true,force:true});});const page=await browser.newPage();page.setDefaultTimeout(5000);const writes=[]; let captured=false;await page.route('**/api/order-rules/fields',route=>route.fulfill({json:{samples:captured?[{id:'capture-1',processName:'备损订单更改评审',processVersion:'1.4',sample:{demo:false,processName:'备损订单更改评审',processVersion:'1.4',fields:{'OFR_BS_Applicant.OrderNum':'REAL-1'},title:'订单号:REAL-1'},fields:[{path:'OFR_BS_Applicant.OrderNum',label:'订单号',value:'REAL-1'}]}]:[],adapters:[]}})); await page.route('**/api/order-rules/preview',route=>{writes.push(route.request().postDataJSON());return route.fulfill({json:{valid:true,issues:[]}});}); - await page.goto('http://127.0.0.1:'+runtime.server.address().port+'/#order-rules');await login(page);await page.locator('#order-rule-refresh').waitFor();captured=true;await page.getByRole('button',{name:'通知规则',exact:true}).click();await page.locator('[data-rule-id="bs-change"]').click();await page.getByLabel('表单样本',{exact:true}).selectOption('capture:capture-1');assert.equal(await page.locator('#order-rule-sample').getAttribute('readonly'),'');await page.getByRole('button',{name:'校验已保存规则',exact:true}).click();await page.locator('#order-rule-preview-result .alert-success').waitFor();assert.deepEqual(writes[0],{sampleId:'capture-1'}); - const snapshot=runtime.orderRules.snapshot();snapshot.batches=[{id:'unknown-1',version:7,status:'unknown',subject:'待核验批次',to:['orders@example.test'],orderIds:[],text:'冻结内容'}];await page.route('**/api/order-rules',route=>route.fulfill({json:snapshot}));await page.route('**/api/order-rules/batches/unknown-1/resolve',route=>{writes.push(route.request().postDataJSON());return route.fulfill({json:{status:'failed'}});});await page.getByRole('button',{name:'发送记录',exact:true}).click();await page.getByLabel('核验依据',{exact:true}).fill('已核实SMTP服务器未接受');await page.getByRole('button',{name:'保存核验结论',exact:true}).click();await page.getByText('核验结论已保存。',{exact:true}).waitFor();assert.equal(writes[1].version,7);assert.ok(writes[1].idempotencyKey);assert.equal(writes[1].note,'已核实SMTP服务器未接受'); + await page.goto('http://127.0.0.1:'+runtime.server.address().port+'/#order-rules');await login(page);await page.locator('#order-rule-refresh').waitFor();captured=true;await page.locator('#order-rule-refresh').click();await page.locator('[data-rule-id="bs-change"]').click();await page.getByLabel('表单样本',{exact:true}).selectOption('capture:capture-1');assert.equal(await page.locator('#order-rule-sample').getAttribute('readonly'),'');await page.getByRole('button',{name:'校验已保存规则',exact:true}).click();await page.locator('#order-rule-preview-result .alert-success').waitFor();assert.deepEqual(writes[0],{sampleId:'capture-1'}); + const snapshot=runtime.orderRules.snapshot();snapshot.batches=[{id:'unknown-1',version:7,status:'unknown',subject:'待核验批次',to:['orders@example.test'],orderIds:[],text:'冻结内容'}];await page.route('**/api/order-rules',route=>route.fulfill({json:snapshot}));await page.route('**/api/order-rules/batches/unknown-1/resolve',route=>{writes.push(route.request().postDataJSON());return route.fulfill({json:{status:'failed'}});});await openRuleRoute(page,'notification-history');await page.getByLabel('核验依据',{exact:true}).fill('已核实SMTP服务器未接受');await page.getByRole('button',{name:'保存核验结论',exact:true}).click();await page.getByText('核验结论已保存。',{exact:true}).waitFor();assert.equal(writes[1].version,7);assert.ok(writes[1].idempotencyKey);assert.equal(writes[1].note,'已核实SMTP服务器未接受'); }); + +async function openRuleRoute(page,hash){ + if(!await page.locator('a[href="#'+hash+'"]').count()){ + const business=['order-rules','rule-fields'].includes(hash); + await page.locator('a[href="#'+(business?'business-settings':'order-notifications')+'"]').first().click(); + if(hash==='notification-settings')await page.locator('a[href="#schedule"]').first().click(); + } + await page.locator('a[href="#'+hash+'"]').first().click(); +} diff --git a/tests/app/navigation-ui.test.cjs b/tests/app/navigation-ui.test.cjs index ca0c134..e7251e7 100644 --- a/tests/app/navigation-ui.test.cjs +++ b/tests/app/navigation-ui.test.cjs @@ -9,13 +9,13 @@ test('compact navigation groups settings, retains deep links and role boundaries for(const role of ['admin','viewer']){ const context=await browser.newContext({viewport:{width:1440,height:1000}}),page=await context.newPage();page.on('pageerror',e=>errors.push(e.message)); await page.goto(base+'/#system-settings');await page.getByLabel('账号',{exact:true}).fill(role);await page.getByLabel('密码',{exact:true}).fill(password);await page.getByRole('button',{name:'登录',exact:true}).click(); - await page.getByRole('heading',{name:'BPM 连接',exact:true}).first().waitFor();assert.equal(await page.locator('#sidebar-menu [data-view]').count(),6); + await page.getByRole('heading',{name:'BPM 连接',exact:true}).first().waitFor();assert.equal(await page.locator('#sidebar-menu [data-view]').count(),7); assert.equal(await page.locator('#settings-tabs a[href="#users"]').count(),role==='admin'?1:0); - await page.getByRole('link',{name:'业务设置',exact:true}).click();await page.getByRole('link',{name:'发送计划',exact:true}).click();await page.locator('#schedule-form').waitFor(); - assert.equal(await page.locator('#sidebar-menu [aria-current="page"]').getAttribute('href'),'#business-settings'); - await page.getByRole('link',{name:'分类通知规则',exact:true}).first().click();await page.getByRole('heading',{name:'分类通知规则',exact:true}).waitFor(); + await page.getByRole('link',{name:'订单通知管理',exact:true}).click();await page.getByRole('link',{name:'通知配置',exact:true}).click();await page.locator('#schedule-form').waitFor(); + assert.equal(await page.locator('#sidebar-menu [aria-current="page"]').getAttribute('href'),'#order-notifications'); + await page.getByRole('link',{name:'业务设置',exact:true}).click();await page.getByRole('heading',{name:'分类通知规则',exact:true}).waitFor(); await page.goto(base+'/#users');await page.getByRole('heading',{name:role==='admin'?'团队账号':'工作总览',exact:true}).first().waitFor(); - await page.goto(base+'/#calendar');await page.getByRole('heading',{name:'业务日历',exact:true}).waitFor();assert.equal(await page.locator('#sidebar-menu [aria-current="page"]').getAttribute('href'),'#business-settings'); + await page.goto(base+'/#calendar');await page.getByRole('heading',{name:'业务日历',exact:true}).waitFor();assert.equal(await page.locator('#sidebar-menu [aria-current="page"]').getAttribute('href'),'#order-notifications'); await page.goto(base+'/#system-settings');await page.setViewportSize({width:390,height:844});await page.getByRole('button',{name:'展开菜单',exact:true}).click(); await page.locator('#sidebar-menu').getByRole('link',{name:'业务设置',exact:true}).click();await page.getByRole('heading',{name:'分类通知规则',exact:true}).waitFor(); await page.waitForFunction(()=>!document.querySelector('#sidebar-menu').classList.contains('collapsing'));assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);assert.equal(await page.locator('#sidebar-menu').evaluate(el=>el.classList.contains('show')),false);assert.equal(await page.getByRole('button',{name:'展开菜单',exact:true}).getAttribute('aria-expanded'),'false'); diff --git a/tests/app/notification-navigation.test.cjs b/tests/app/notification-navigation.test.cjs new file mode 100644 index 0000000..c87eb71 --- /dev/null +++ b/tests/app/notification-navigation.test.cjs @@ -0,0 +1,117 @@ +'use strict'; +const {test}=require('node:test'); +const assert=require('node:assert/strict'); +const fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path'); +const {startTestDashboard,login}=require('../fixtures/dashboard-runtime.cjs'); +const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs'); + +async function fixture(t){ + const dir=await fs.mkdtemp(path.join(os.tmpdir(),'notification-navigation-')); + const runtime=await startTestDashboard({stateDir:dir,mailHistory:true}); + const browser=await loadPlaywright().chromium.launch(browserOptions()); + t.after(async()=>{await browser.close();await runtime.close();await fs.rm(dir,{recursive:true,force:true});}); + return {runtime,browser,base:'http://127.0.0.1:'+runtime.server.address().port}; +} + +test('notification operations have addressable navigation while rules remain in business settings',{timeout:90000},async t=>{ + const {runtime,browser,base}=await fixture(t),page=await browser.newPage({viewport:{width:1440,height:1000}}); + page.setDefaultTimeout(7000);const errors=[],writes=[]; + page.on('pageerror',error=>errors.push(error.message));page.on('request',req=>{if(req.method()==='POST'&&!req.url().endsWith('/login'))writes.push(req.url());}); + await page.goto(base+'/#order-notifications');await login(page); + await page.getByRole('heading',{name:'通知总览',exact:true}).waitFor(); + assert.equal(await page.locator('#sidebar-menu [data-view]').count(),7); + const routeCases=[['notification-execution','订单执行'],['notification-orders','通知订单'],['notification-batches','待发批次'],['notification-history','发送记录'],['schedule','发送计划'],['calendar','业务日历'],['templates','邮件模板'],['notification-settings','发送设置']]; + for(const [route,title] of routeCases){ + await page.goto(base+'/#'+route);await page.locator('#view-title').filter({hasText:title}).waitFor(); + assert.equal(await page.locator('#sidebar-menu [aria-current="page"]').getAttribute('href'),'#order-notifications'); + assert.equal(await page.locator('#settings-tabs .active').getAttribute('href'),['schedule','calendar','templates','notification-settings'].includes(route)?'#schedule':'#'+route); + if(['schedule','calendar','templates','notification-settings'].includes(route))assert.equal(await page.locator('#notification-config-tabs [aria-current="page"]').getAttribute('href'),'#'+route); + } + await page.goto(base+'/#business-settings');await page.getByRole('heading',{name:'分类通知规则',exact:true}).waitFor(); + assert.deepEqual(await page.locator('#settings-tabs a').allTextContents(),['分类通知规则','字段映射']); + await page.locator('#settings-tabs a[href="#rule-fields"]').click();await page.getByRole('heading',{name:'字段映射',exact:true}).first().waitFor(); + await page.reload();assert.equal(await page.locator('#sidebar-menu [aria-current="page"]').getAttribute('href'),'#business-settings'); + await page.goBack();await page.getByRole('heading',{name:'分类通知规则',exact:true}).waitFor(); + await page.goForward();await page.getByRole('heading',{name:'字段映射',exact:true}).first().waitFor(); + assert.equal(runtime.orderRules.snapshot().settings.enabled,false);assert.deepEqual(writes,[]);assert.deepEqual(errors,[]); +}); + +test('status reflects persisted notification settings, read failures and late responses',{timeout:60000},async t=>{ + const {browser,base}=await fixture(t),page=await browser.newPage();page.setDefaultTimeout(7000); + await page.goto(base+'/#overview');await login(page);await page.getByText('自动通知已暂停',{exact:true}).waitFor(); + const original=await (await page.request.get(base+'/api/order-rules')).json(); + const overview=await (await page.request.get(base+'/api/overview')).json(); + await page.route('**/api/overview',route=>route.fulfill({json:{...overview,automation:{enabled:true,ready:true,reason:'隔离测试:实际检查通过'}}})); + await page.route('**/api/order-rules',route=>route.fulfill({json:{...original,settings:{...original.settings,enabled:true},capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true}}})); + await page.getByRole('button',{name:'刷新数据',exact:true}).click();await page.getByText('自动通知已启用',{exact:true}).waitFor(); + assert.match(await page.locator('#workspace-automation').innerText(),/已启用/); + await page.route('**/api/order-rules',route=>route.fulfill({status:503,json:{error:'隔离测试:状态查询失败'}})); + await page.getByRole('button',{name:'刷新数据',exact:true}).click();await page.getByText('通知状态待确认',{exact:true}).waitFor(); + assert.match(await page.locator('#automation-status').getAttribute('title'),/状态查询失败/); + let release,received; + const held=new Promise(resolve=>{received=resolve;}); + await page.route('**/api/order-rules',async route=>{release=()=>route.fulfill({json:{...original,settings:{...original.settings,enabled:true},capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true}}});received();}); + await page.getByRole('button',{name:'刷新数据',exact:true}).click();await held; + await page.route('**/api/order-rules',route=>route.fulfill({status:503,json:{error:'新页面状态仍待核实'}})); + await page.locator('#sidebar-menu a[href="#system-settings"]').click();await page.getByRole('heading',{name:'BPM 连接',exact:true}).first().waitFor(); + await page.waitForFunction(()=>document.querySelector('#automation-status')?.title.includes('新页面状态仍待核实')); + const completed=page.waitForResponse(response=>response.url().endsWith('/api/order-rules')&&response.status()===200); + await release();await completed;await page.evaluate(()=>new Promise(requestAnimationFrame)); + assert.equal(await page.locator('#automation-status').innerText(),'通知状态待确认'); +}); + +test('notification and configuration navigation retain dirty guards and fit mobile for each role',{timeout:90000},async t=>{ + const {runtime,browser,base}=await fixture(t); + for(const role of ['operator','viewer'])runtime.store.addUser({username:role,password:'Test-password-123',role},'admin'); + for(const role of ['admin','operator','viewer']){ + const context=await browser.newContext({viewport:{width:390,height:844}}),page=await context.newPage();page.setDefaultTimeout(7000); + await page.goto(base+'/#notification-settings');await page.getByLabel('账号',{exact:true}).fill(role);await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click(); + await page.getByRole('heading',{name:'发送设置',exact:true}).first().waitFor();await page.locator('#order-rule-max-size').waitFor(); + assert.equal(await page.locator('#order-rule-max-size').isDisabled(),role!=='admin'); + assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true); + assert.equal(await page.locator('#settings-tabs .active').evaluate(el=>{const r=el.getBoundingClientRect(),p=el.parentElement.getBoundingClientRect();return r.left>=p.left-1&&r.right<=p.right+1;}),true); + if(role==='admin'){ + await page.locator('#order-rule-max-size').fill('19');await page.locator('#notification-config-tabs a[href="#calendar"]').click(); + await page.getByRole('button',{name:'留在此页',exact:true}).click();assert.equal(await page.locator('#order-rule-max-size').inputValue(),'19'); + await page.locator('#notification-config-tabs a[href="#calendar"]').click();await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.getByRole('heading',{name:'业务日历',exact:true}).waitFor(); + await page.setViewportSize({width:1440,height:1000});await page.evaluate(()=>new Promise(requestAnimationFrame)); + await page.setViewportSize({width:390,height:844});await page.evaluate(()=>new Promise(requestAnimationFrame)); + assert.equal(await page.locator('#settings-tabs .active').evaluate(el=>{const r=el.getBoundingClientRect(),p=el.parentElement.getBoundingClientRect();return r.left>=p.left-1&&r.right<=p.right+1;}),true,'active notification configuration remains visible after resizing'); + } + await page.goto(base+'/#system-settings');await page.getByRole('heading',{name:'BPM 连接',exact:true}).first().waitFor(); + assert.equal(await page.locator('#settings-tabs a[href="#users"]').count(),role==='admin'?1:0); + assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true); + await context.close(); + } + assert.equal(runtime.orderRules.snapshot().settings.enabled,false); +}); + +test('older overview polls cannot replace a newer persisted notification state',{timeout:60000},async t=>{ + const {browser,base}=await fixture(t),page=await browser.newPage();page.setDefaultTimeout(7000); + await page.clock.install();await page.goto(base+'/#overview');await login(page);await page.locator('#workspace-automation').waitFor(); + const snapshot=await (await page.request.get(base+'/api/overview')).json(),pending=[];let firstSeen,secondSeen; + const first=new Promise(resolve=>{firstSeen=resolve;}),second=new Promise(resolve=>{secondSeen=resolve;}); + await page.route('**/api/overview',route=>{pending.push(route);if(pending.length===1)firstSeen();if(pending.length===2)secondSeen();}); + await page.clock.fastForward(15001);await first; + assert.equal(pending.length,1); + await page.clock.fastForward(15001);await second; + assert.equal(pending.length,2); + await pending[1].fulfill({json:{...snapshot,automation:{enabled:true,ready:true,reason:'较新服务端状态'}}}); + await page.locator('#workspace-automation').getByText('较新服务端状态',{exact:true}).waitFor(); + const completed=page.waitForResponse(response=>response.url().endsWith('/api/overview')&&response.status()===200); + await pending[0].fulfill({json:{...snapshot,automation:{enabled:false,ready:false,reason:'较旧服务端状态'}}});await completed; + await page.evaluate(()=>new Promise(requestAnimationFrame)); + assert.match(await page.locator('#workspace-automation').innerText(),/较新服务端状态/); +}); + +test('a failed initial overview read cannot replace a later successful poll',{timeout:60000},async t=>{ + const {browser,base}=await fixture(t),page=await browser.newPage();page.setDefaultTimeout(7000);await page.clock.install(); + let initial,received,snapshot;const held=new Promise(resolve=>{received=resolve;}); + await page.route('**/api/overview',route=>{if(!initial){initial=route;received();return;}return route.fulfill({json:{...snapshot,automation:{enabled:false,ready:false,reason:'最新读取成功'}}});}); + await page.goto(base+'/#overview');await login(page);await held; + snapshot=await (await page.request.get(base+'/api/overview')).json(); + await page.clock.fastForward(15001);await page.locator('#workspace-automation').getByText('最新读取成功',{exact:true}).waitFor(); + const completed=page.waitForResponse(response=>response.url().endsWith('/api/overview')&&response.status()===503); + await initial.fulfill({status:503,json:{error:'已过期的读取错误'}});await completed;await page.evaluate(()=>new Promise(requestAnimationFrame)); + assert.match(await page.locator('#content').innerText(),/最新读取成功/); +}); diff --git a/tests/app/web-closure-review-ui.test.cjs b/tests/app/web-closure-review-ui.test.cjs index fd09942..9c1d2fe 100644 --- a/tests/app/web-closure-review-ui.test.cjs +++ b/tests/app/web-closure-review-ui.test.cjs @@ -3,24 +3,33 @@ const {test}=require('node:test'),assert=require('node:assert/strict'),fs=requir const {startTestDashboard,login}=require('../fixtures/dashboard-runtime.cjs'),{loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs'); async function fixture(t,hash='schedule'){const dir=await fs.mkdtemp(path.join(os.tmpdir(),'closure-review-')),runtime=await startTestDashboard({stateDir:dir}),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(async()=>{await browser.close();await runtime.close();await fs.rm(dir,{recursive:true,force:true});});const page=await browser.newPage({viewport:{width:1440,height:1000}});page.setDefaultTimeout(6000);await page.goto('http://127.0.0.1:'+runtime.server.address().port+'/#'+hash);await login(page);return {page,runtime};} test('a successful delayed save commits only submitted inputs and later edits remain dirty',{timeout:45000},async t=>{const {page}=await fixture(t);await page.locator('#schedule-form').waitFor();let release,arrive;const arrived=new Promise(r=>arrive=r),gate=new Promise(r=>release=r);await page.route('**/api/settings',async route=>{if(route.request().method()==='GET')return route.continue();const response=await route.fetch();arrive();await gate;return route.fulfill({response});});await page.locator('#time-first').fill('09:11');await page.getByRole('button',{name:'保存发送计划',exact:true}).click();await arrived;await page.locator('#time-first').fill('09:12');release();await page.getByText('发送计划已保存。',{exact:true}).waitFor();assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),true);await page.getByRole('link',{name:'业务日历',exact:true}).first().click();await page.getByRole('dialog',{name:'未保存的修改'}).waitFor();assert.equal(await page.locator('#time-first').inputValue(),'09:12');}); -for(const destination of ['internal','route'])test('Save and Continue preserves currentTarget for rule settings: '+destination,{timeout:45000},async t=>{const {page}=await fixture(t,'order-rules');await page.getByRole('button',{name:'设置',exact:true}).click();await page.locator('#order-rule-settings').waitFor();const input=page.locator('#order-rule-settings [name=maxSize]');await input.fill('12');const posts=[];await page.route('**/api/order-rules/settings',async route=>{posts.push(route.request().postDataJSON());return route.continue();});if(destination==='internal')await page.getByRole('button',{name:'工作台',exact:true}).click();else await page.getByRole('link',{name:'发送计划',exact:true}).first().click();await page.getByRole('button',{name:'保存并继续',exact:true}).click();if(destination==='internal')await page.getByRole('heading',{name:'本时段范围',exact:true}).waitFor();else await page.locator('#schedule-form').waitFor();assert.equal(posts.length,1);assert.equal(posts[0].maxMessageBytes,12582912);}); +for(const destination of ['internal','route'])test('Save and Continue preserves currentTarget for rule settings: '+destination,{timeout:45000},async t=>{const {page}=await fixture(t,'order-rules');await openRuleRoute(page,'notification-settings');await page.locator('#order-rule-settings').waitFor();const input=page.locator('#order-rule-settings [name=maxSize]');await input.fill('12');const posts=[];await page.route('**/api/order-rules/settings',async route=>{posts.push(route.request().postDataJSON());return route.continue();});if(destination==='internal')await openRuleRoute(page,'order-notifications');else await page.getByRole('link',{name:'发送计划',exact:true}).first().click();await page.getByRole('button',{name:'保存并继续',exact:true}).click();if(destination==='internal')await page.getByRole('heading',{name:'本时段范围',exact:true}).waitFor();else await page.locator('#schedule-form').waitFor();assert.equal(posts.length,1);assert.equal(posts[0].maxMessageBytes,12582912);}); async function mailFixture(page){const drafts=['t1','t2'].map((id,i)=>({id,version:1,status:'pending',subject:'模板'+(i+1),scope:'',channelId:'mail1',sender:'fixture@example.test',attachmentCount:0,attachments:[],text:'正文'}));await page.route('**/api/mail',route=>route.fulfill({json:{channels:[],templates:drafts,receipts:[],sends:[]}}));await page.route('**/api/mail/templates/categories',route=>route.fulfill({json:{categories:[],bindings:[]}}));await page.route(/\/api\/mail\/templates\/t[12]$/,route=>route.fulfill({json:drafts.find(d=>route.request().url().endsWith('/'+d.id))}));await page.route('**/api/mail/templates/*/preview',route=>route.fulfill({contentType:'text/html',body:'

正文

'}));return drafts;} test('switching a dirty template supports stay discard and save before selecting another',{timeout:45000},async t=>{const {page}=await fixture(t);const drafts=await mailFixture(page);let saved;await page.route('**/api/mail/templates/t1/confirm',route=>{saved=route.request().postDataJSON();drafts[0].status='active';drafts[0].subject=saved.subject;return route.fulfill({json:{ok:true}});});await page.getByRole('link',{name:'邮件模板',exact:true}).click();await page.locator('[data-template=t1]').click();await page.locator('#template-subject').fill('未保存模板一');await page.locator('[data-template=t2]').click();await page.getByRole('button',{name:'留在此页',exact:true}).click();assert.equal(await page.locator('#template-subject').inputValue(),'未保存模板一');await page.locator('[data-template=t2]').click();await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.waitForFunction(()=>document.querySelector('#template-subject')?.value==='模板2');await page.locator('[data-template=t1]').click();await page.locator('#template-subject').fill('保存模板一');await page.locator('[data-template=t2]').click();await page.getByRole('button',{name:'保存并继续',exact:true}).click();await page.waitForFunction(()=>document.querySelector('#template-subject')?.value==='模板2');assert.equal(saved.subject,'保存模板一');}); test('failed uncertain-result readback stays uncertain and never claims state was queried',{timeout:45000},async t=>{const {page}=await fixture(t);await page.locator('#schedule-form').waitFor();let posts=0,reads=0;await page.route('**/api/settings',route=>{if(route.request().method()==='POST'){posts++;return route.abort('timedout');}reads++;return route.fulfill({status:503,json:{error:'State unavailable'}});});await page.locator('#time-first').fill('10:01');await page.getByRole('button',{name:'保存发送计划',exact:true}).click();await page.waitForFunction(()=>document.querySelector('#operation-uncertain')?.textContent.includes('查询失败'));const text=await page.locator('#operation-uncertain').innerText();assert.match(text,/结果待核实/);assert.doesNotMatch(text,/已查询最新状态/);assert.equal(posts,1);assert.equal(reads,1);}); test('delayed readback cannot notify after leaving its originating page',{timeout:45000},async t=>{const {page}=await fixture(t);await page.locator('#schedule-form').waitFor();let release,arrive;const gate=new Promise(r=>release=r),arrived=new Promise(r=>arrive=r);await page.route('**/api/settings',async route=>{if(route.request().method()==='POST')return route.abort('timedout');arrive();await gate;return route.fulfill({json:{version:2,schedule:{times:['09:00','17:00']}}});});await page.locator('#time-first').fill('10:02');await page.getByRole('button',{name:'保存发送计划',exact:true}).click();await arrived;await page.getByRole('link',{name:'系统设置',exact:true}).click();await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.getByRole('heading',{name:'BPM 连接',exact:true}).first().waitFor();await page.evaluate(()=>document.querySelector('#flash')?.remove());release();await page.waitForTimeout(250);assert.equal(await page.locator('#flash').count(),0);assert.equal(await page.locator('#operation-uncertain').count(),0);}); -test('execution refreshes after actions and on visible refresh while retaining other task notes',{timeout:45000},async t=>{const {page}=await fixture(t,'order-rules');let tasks=[{id:'t1',connectionId:'c1',status:'failed',version:1,error:'失败一'},{id:'t2',connectionId:'c1',status:'failed',version:1,error:'失败二'}],gets=0;const retried=[];await page.route('**/api/order-execution',route=>{gets++;return route.fulfill({json:{tasks,capabilities:{},fields:{samples:[],adapters:[]}}});});await page.route('**/api/order-execution/tasks/t1/retry',route=>{retried.push(route.request().postDataJSON());tasks[0]={...tasks[0],version:2,error:'再次失败'};return route.fulfill({json:{ok:true}});});await page.route('**/api/order-execution/scan',route=>{tasks.push({id:'new1',status:'archived',version:1,title:'新扫描任务'});return route.fulfill({json:{ok:true}});});await page.getByRole('button',{name:'订单执行',exact:true}).click();await page.locator('[data-execution-retry=t2] textarea').fill('保留另一任务的处理依据');await page.locator('[data-execution-retry=t1] textarea').fill('核实恢复后再次尝试');await page.locator('[data-execution-retry=t1] button').click();await page.getByText('再次失败',{exact:true}).waitFor();assert.equal(await page.locator('[data-execution-retry=t2] textarea').inputValue(),'保留另一任务的处理依据');await page.locator('[data-execution-retry=t1] textarea').fill('核实恢复后第二次尝试');await page.locator('[data-execution-retry=t1] button').click();await page.getByText('重试请求已提交,请核对任务状态。',{exact:true}).waitFor();assert.deepEqual(retried.map(r=>r.version),[1,2]);await page.getByLabel('扫描连接',{exact:true}).selectOption('c1');await page.getByRole('button',{name:'扫描待办',exact:true}).click();await page.locator('[data-execution-task=new1]').waitFor();assert.match(await page.locator('[data-execution-task=new1]').innerText(),/新扫描任务/);tasks[0]={...tasks[0],version:3,status:'archived',error:''};await page.getByRole('button',{name:'刷新时段与状态',exact:true}).click();await page.waitForFunction(()=>!document.querySelector('[data-execution-retry=t1]'));assert.equal(await page.locator('[data-execution-retry=t2] textarea').inputValue(),'保留另一任务的处理依据');assert.ok(gets>=5);}); -test('rerendering rule saves lock editable fields until the saved response has replaced the form',{timeout:45000},async t=>{const {page}=await fixture(t,'order-rules');await page.getByRole('button',{name:'通知规则',exact:true}).click();let release,arrive;const gate=new Promise(r=>release=r),arrived=new Promise(r=>arrive=r);await page.route('**/api/order-rules/rules',async route=>{const response=await route.fetch();arrive();await gate;return route.fulfill({response});});await page.getByLabel('规则名称',{exact:true}).fill('提交中的草稿');await page.getByRole('button',{name:'保存草稿',exact:true}).click();await arrived;assert.equal(await page.getByLabel('规则名称',{exact:true}).isDisabled(),true);release();await page.getByText('规则草稿已保存。',{exact:true}).waitFor();assert.equal(await page.getByLabel('规则名称',{exact:true}).isDisabled(),false);assert.equal(await page.getByLabel('规则名称',{exact:true}).inputValue(),'提交中的草稿');assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),false);}); +test('execution refreshes after actions and on visible refresh while retaining other task notes',{timeout:45000},async t=>{const {page}=await fixture(t,'order-rules');let tasks=[{id:'t1',connectionId:'c1',status:'failed',version:1,error:'失败一'},{id:'t2',connectionId:'c1',status:'failed',version:1,error:'失败二'}],gets=0;const retried=[];await page.route('**/api/order-execution',route=>{gets++;return route.fulfill({json:{tasks,capabilities:{},fields:{samples:[],adapters:[]}}});});await page.route('**/api/order-execution/tasks/t1/retry',route=>{retried.push(route.request().postDataJSON());tasks[0]={...tasks[0],version:2,error:'再次失败'};return route.fulfill({json:{ok:true}});});await page.route('**/api/order-execution/scan',route=>{tasks.push({id:'new1',status:'archived',version:1,title:'新扫描任务'});return route.fulfill({json:{ok:true}});});await openRuleRoute(page,'notification-execution');await page.locator('[data-execution-retry=t2] textarea').fill('保留另一任务的处理依据');await page.locator('[data-execution-retry=t1] textarea').fill('核实恢复后再次尝试');await page.locator('[data-execution-retry=t1] button').click();await page.getByText('再次失败',{exact:true}).waitFor();assert.equal(await page.locator('[data-execution-retry=t2] textarea').inputValue(),'保留另一任务的处理依据');await page.locator('[data-execution-retry=t1] textarea').fill('核实恢复后第二次尝试');await page.locator('[data-execution-retry=t1] button').click();await page.getByText('重试请求已提交,请核对任务状态。',{exact:true}).waitFor();assert.deepEqual(retried.map(r=>r.version),[1,2]);await page.getByLabel('扫描连接',{exact:true}).selectOption('c1');await page.getByRole('button',{name:'扫描待办',exact:true}).click();await page.locator('[data-execution-task=new1]').waitFor();assert.match(await page.locator('[data-execution-task=new1]').innerText(),/新扫描任务/);tasks[0]={...tasks[0],version:3,status:'archived',error:''};await page.getByRole('button',{name:'刷新时段与状态',exact:true}).click();await page.waitForFunction(()=>!document.querySelector('[data-execution-retry=t1]'));assert.equal(await page.locator('[data-execution-retry=t2] textarea').inputValue(),'保留另一任务的处理依据');assert.ok(gets>=5);}); +test('rerendering rule saves lock editable fields until the saved response has replaced the form',{timeout:45000},async t=>{const {page}=await fixture(t,'order-rules');await openRuleRoute(page,'order-rules');let release,arrive;const gate=new Promise(r=>release=r),arrived=new Promise(r=>arrive=r);await page.route('**/api/order-rules/rules',async route=>{const response=await route.fetch();arrive();await gate;return route.fulfill({response});});await page.getByLabel('规则名称',{exact:true}).fill('提交中的草稿');await page.getByRole('button',{name:'保存草稿',exact:true}).click();await arrived;assert.equal(await page.getByLabel('规则名称',{exact:true}).isDisabled(),true);release();await page.getByText('规则草稿已保存。',{exact:true}).waitFor();assert.equal(await page.getByLabel('规则名称',{exact:true}).isDisabled(),false);assert.equal(await page.getByLabel('规则名称',{exact:true}).inputValue(),'提交中的草稿');assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),false);}); test('invalid readback payload is rejected even when HTTP succeeds',{timeout:45000},async t=>{const {page}=await fixture(t);await page.locator('#schedule-form').waitFor();await page.route('**/api/settings',route=>route.request().method()==='POST'?route.abort('timedout'):route.fulfill({json:{schedule:'not a schedule'}}));await page.locator('#time-first').fill('10:03');await page.getByRole('button',{name:'保存发送计划',exact:true}).click();await page.waitForFunction(()=>document.querySelector('#operation-uncertain')?.textContent.includes('查询失败'));assert.doesNotMatch(await page.locator('#operation-uncertain').innerText(),/已查询最新状态/);}); test('uncertain calendar write reads its workspace calendar rather than overview',{timeout:45000},async t=>{const {page}=await fixture(t,'calendar');await page.locator('#day-note').waitFor();let reads=0;await page.route('**/api/calendar',route=>route.abort('timedout'));await page.route('**/api/workspace',route=>{reads++;return route.fulfill({json:{calendar:{version:8,overrides:[]}}});});await page.locator('#day-note').fill('隔离测试日历安排');await page.getByRole('button',{name:'应用到此日期',exact:true}).click();await page.getByRole('button',{name:'保存日历',exact:true}).click();await page.waitForFunction(()=>document.querySelector('#operation-uncertain')?.textContent.includes('配置版本 8'));assert.equal(reads,1);}); -test('rule durable save survives refresh failure, retains version and permits Save and Continue',{timeout:45000},async t=>{const {page}=await fixture(t,'order-rules');await page.getByRole('button',{name:'通知规则',exact:true}).click();let failRead=false;const versions=[];await page.route('**/api/order-rules',route=>failRead?route.fulfill({status:503,json:{error:'refresh unavailable'}}):route.continue());await page.route('**/api/order-rules/rules',async route=>{versions.push(route.request().postDataJSON().version);const response=await route.fetch();failRead=true;return route.fulfill({response});});await page.getByLabel('规则名称',{exact:true}).fill('首次持久保存');await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText(/已保存.*刷新失败/).waitFor();assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),false);await page.getByLabel('规则名称',{exact:true}).fill('再次持久保存');await page.getByRole('link',{name:'发送计划',exact:true}).first().click();await page.getByRole('button',{name:'保存并继续',exact:true}).click();await page.locator('#schedule-form').waitFor();assert.deepEqual(versions,[1,2]);}); +test('rule durable save survives refresh failure, retains version and permits Save and Continue',{timeout:45000},async t=>{const {page}=await fixture(t,'order-rules');await openRuleRoute(page,'order-rules');let failRead=false;const versions=[];await page.route('**/api/order-rules',route=>failRead?route.fulfill({status:503,json:{error:'refresh unavailable'}}):route.continue());await page.route('**/api/order-rules/rules',async route=>{versions.push(route.request().postDataJSON().version);const response=await route.fetch();failRead=true;return route.fulfill({response});});await page.getByLabel('规则名称',{exact:true}).fill('首次持久保存');await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText(/已保存.*刷新失败/).waitFor();assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),false);await page.getByLabel('规则名称',{exact:true}).fill('再次持久保存');await page.locator('a[href="#system-settings"]').first().click();await page.getByRole('button',{name:'保存并继续',exact:true}).click();await page.getByRole('heading',{name:'BPM 连接',exact:true}).first().waitFor();assert.deepEqual(versions,[1,2]);}); -test('field adapter save retains returned version after followup GET fails',{timeout:45000},async t=>{const {page}=await fixture(t,'order-rules');let saved=false;const versions=[];await page.route('**/api/order-rules/fields',route=>saved?route.fulfill({status:503,json:{error:'fields unavailable'}}):route.fulfill({json:{samples:[{id:'s1',processName:'测试流程',processVersion:'1',fields:[{path:'order',label:'订单号',value:'A1'},{path:'brief',label:'摘要',value:'摘要'}]}],adapters:[]}}));await page.route('**/api/order-rules/adapters',route=>{const input=route.request().postDataJSON();versions.push(input.version);saved=true;return route.fulfill({json:{...input,id:'a1',version:versions.length}});});await page.getByRole('button',{name:'字段目录',exact:true}).click();await page.locator('#field-sample').selectOption('s1');await page.locator('#field-orderNo').selectOption('order');await page.locator('#field-brief').selectOption('brief');await page.getByRole('button',{name:'保存字段对应',exact:true}).click();await page.getByText(/已保存.*刷新失败/).waitFor();assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),false);await page.locator('#field-customer').selectOption('brief');await page.getByRole('link',{name:'发送计划',exact:true}).first().click();await page.getByRole('button',{name:'保存并继续',exact:true}).click();await page.locator('#schedule-form').waitFor();assert.deepEqual(versions,[undefined,1]);}); +test('field adapter save retains returned version after followup GET fails',{timeout:45000},async t=>{const {page}=await fixture(t,'order-rules');let saved=false;const versions=[];await page.route('**/api/order-rules/fields',route=>saved?route.fulfill({status:503,json:{error:'fields unavailable'}}):route.fulfill({json:{samples:[{id:'s1',processName:'测试流程',processVersion:'1',fields:[{path:'order',label:'订单号',value:'A1'},{path:'brief',label:'摘要',value:'摘要'}]}],adapters:[]}}));await page.route('**/api/order-rules/adapters',route=>{const input=route.request().postDataJSON();versions.push(input.version);saved=true;return route.fulfill({json:{...input,id:'a1',version:versions.length}});});await openRuleRoute(page,'rule-fields');await page.locator('#field-sample').selectOption('s1');await page.locator('#field-orderNo').selectOption('order');await page.locator('#field-brief').selectOption('brief');await page.getByRole('button',{name:'保存字段对应',exact:true}).click();await page.getByText(/已保存.*刷新失败/).waitFor();assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),false);await page.locator('#field-customer').selectOption('brief');await page.locator('a[href="#order-notifications"]').first().click();await page.getByRole('button',{name:'保存并继续',exact:true}).click();await page.getByRole('heading',{name:'本时段范围',exact:true}).waitFor();assert.deepEqual(versions,[undefined,1]);}); test('category binding save retains response version without repeating committed mutation',{timeout:45000},async t=>{const {page}=await fixture(t);await mailFixture(page);let saved=false;const versions=[];await page.route('**/api/mail/templates/categories',route=>{if(route.request().method()==='GET')return saved?route.fulfill({status:503,json:{error:'bindings unavailable'}}):route.fulfill({json:{categories:[{id:'r1',name:'测试类别'}],bindings:[]}});const input=route.request().postDataJSON();versions.push(input.version);saved=true;return route.fulfill({json:{...input,version:versions.length}});});await page.getByRole('link',{name:'邮件模板',exact:true}).click();await page.locator('[data-category=r1] button').click();await page.getByText(/已保存.*刷新失败/).waitFor();await page.locator('[data-category=r1] button').click();await page.waitForFunction(()=>document.querySelector('[data-category=r1]')?.getAttribute('aria-busy')===null);assert.deepEqual(versions,[0,1]);}); -test('owner retry and persisted scan progress refresh together without replacing recovery notes',{timeout:45000},async t=>{const {page}=await fixture(t,'order-rules');await page.evaluate(async()=>{currentUser={username:'owner',role:'operator'};OrderRuleViews.configure({api,esc,formatDate,notify,user:currentUser});await renderView();});await page.route('**/api/workspace',route=>route.fulfill({json:{connections:[{id:'c1',owner:'owner',name:'owned'}]}}));let query={status:'scanning',startedAt:'2026-10-19T03:00:00Z',rowCount:2,targetCount:2,processedCount:0},blockers=['扫描尚未完成'];let tasks=[{id:'t1',status:'failed',canRetry:true,version:1,connectionId:'c1'},{id:'unknown',status:'unknown',canRetry:false},{id:'conflict',status:'blocked',conflict:true,canRetry:false}];await page.route('**/api/order-execution',route=>route.fulfill({json:{tasks,query,blockers,capabilities:{liveTodo:true}}}));await page.getByRole('button',{name:'订单执行',exact:true}).click();await page.locator('[data-execution-retry=t1]').waitFor();await page.locator('[data-execution-retry=t1] textarea').fill('保留负责人的恢复依据');assert.equal(await page.locator('[data-execution-retry]').count(),1);await page.locator('#execution-query').getByText(/扫描中/).waitFor();tasks=[];query={status:'failed',error:'zero-row provider failure',targetCount:0,rowCount:0,finishedAt:'2026-10-19T03:00:10Z'};blockers=['扫描失败,冻结受阻'];await page.locator('#order-rule-refresh').click();await page.locator('#execution-query').getByText(/zero-row provider failure/).waitFor();assert.equal(await page.locator('[data-execution-retry=t1] textarea').inputValue(),'保留负责人的恢复依据');assert.match(await page.locator('#execution-capabilities').innerText(),/冻结受阻/);}); +test('owner retry and persisted scan progress refresh together without replacing recovery notes',{timeout:45000},async t=>{const {page}=await fixture(t,'order-rules');await page.evaluate(async()=>{currentUser={username:'owner',role:'operator'};OrderRuleViews.configure({api,esc,formatDate,notify,user:currentUser});await renderView();});await page.route('**/api/workspace',route=>route.fulfill({json:{connections:[{id:'c1',owner:'owner',name:'owned'}]}}));let query={status:'scanning',startedAt:'2026-10-19T03:00:00Z',rowCount:2,targetCount:2,processedCount:0},blockers=['扫描尚未完成'];let tasks=[{id:'t1',status:'failed',canRetry:true,version:1,connectionId:'c1'},{id:'unknown',status:'unknown',canRetry:false},{id:'conflict',status:'blocked',conflict:true,canRetry:false}];await page.route('**/api/order-execution',route=>route.fulfill({json:{tasks,query,blockers,capabilities:{liveTodo:true}}}));await openRuleRoute(page,'notification-execution');await page.locator('[data-execution-retry=t1]').waitFor();await page.locator('[data-execution-retry=t1] textarea').fill('保留负责人的恢复依据');assert.equal(await page.locator('[data-execution-retry]').count(),1);await page.locator('#execution-query').getByText(/扫描中/).waitFor();tasks=[];query={status:'failed',error:'zero-row provider failure',targetCount:0,rowCount:0,finishedAt:'2026-10-19T03:00:10Z'};blockers=['扫描失败,冻结受阻'];await page.locator('#order-rule-refresh').click();await page.locator('#execution-query').getByText(/zero-row provider failure/).waitFor();assert.equal(await page.locator('[data-execution-retry=t1] textarea').inputValue(),'保留负责人的恢复依据');assert.match(await page.locator('#execution-capabilities').innerText(),/冻结受阻/);}); test('confirmed template and created user stay committed when list refresh fails',{timeout:45000},async t=>{const {page}=await fixture(t);await mailFixture(page);await page.route('**/api/mail/templates/t1/confirm',route=>route.fulfill({json:{id:'t1',status:'active',version:2}}));await page.getByRole('link',{name:'邮件模板',exact:true}).click();await page.locator('[data-template=t1]').click();await page.route('**/api/mail',route=>route.fulfill({status:503,json:{error:'mail list unavailable'}}));await page.getByRole('button',{name:'确认生效',exact:true}).click();await page.getByText(/模板已确认生效.*刷新失败/).waitFor();assert.equal(await page.getByRole('button',{name:'确认生效',exact:true}).count(),0);await page.getByRole('link',{name:'系统设置',exact:true}).click();await page.getByRole('link',{name:'团队账号',exact:true}).click();await page.locator('#new-username').fill('isolated-new');await page.locator('#new-password').fill('Fixture-password-123');await page.route('**/api/users',route=>route.request().method()==='POST'?route.fulfill({json:{id:'new-user'}}):route.fulfill({status:503,json:{error:'users unavailable'}}));await page.getByRole('button',{name:'创建账号',exact:true}).click();await page.getByText(/账号已创建.*刷新失败/).waitFor();assert.equal(await page.locator('#new-password').inputValue(),'');}); test('assistant settings retain persisted version after refresh failure',{timeout:45000},async t=>{const {page}=await fixture(t);await page.route('**/api/assistant',route=>route.fulfill({json:{settings:{version:1,runtimePath:'',apiBase:'',model:'',timeoutSeconds:30,dailyLimit:10}}}));await page.getByRole('link',{name:'系统设置',exact:true}).click();await page.getByRole('link',{name:'助手设置',exact:true}).click();await page.locator('#assistant-model').waitFor();const versions=[];await page.route('**/api/assistant/settings',async route=>{versions.push(route.request().postDataJSON().version);return route.fulfill({json:{version:versions.at(-1)+1}});});await page.route('**/api/assistant',route=>route.fulfill({status:503,json:{error:'assistant refresh unavailable'}}));await page.locator('#assistant-model').fill('fixture-model-one');await page.getByRole('button',{name:'保存助手设置',exact:true}).click();await page.getByText(/助手设置已保存.*刷新失败/).waitFor();await page.locator('#assistant-model').fill('fixture-model-two');await page.getByRole('button',{name:'保存助手设置',exact:true}).click();await page.waitForFunction(()=>!document.querySelector('#assistant-settings-form')?.hasAttribute('aria-busy'));assert.equal(versions[1],versions[0]+1);}); + +async function openRuleRoute(page,hash){ + if(!await page.locator('a[href="#'+hash+'"]').count()){ + const business=['order-rules','rule-fields'].includes(hash); + await page.locator('a[href="#'+(business?'business-settings':'order-notifications')+'"]').first().click(); + if(hash==='notification-settings')await page.locator('a[href="#schedule"]').first().click(); + } + await page.locator('a[href="#'+hash+'"]').first().click(); +} diff --git a/tests/app/web-closure-ui.test.cjs b/tests/app/web-closure-ui.test.cjs index 77c22ea..d1af39a 100644 --- a/tests/app/web-closure-ui.test.cjs +++ b/tests/app/web-closure-ui.test.cjs @@ -3,16 +3,25 @@ const {test}=require('node:test'),assert=require('node:assert/strict'),fs=requir const {startTestDashboard,login}=require('../fixtures/dashboard-runtime.cjs'); const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs'); async function fixture(t,hash='schedule') {const dir=await fs.mkdtemp(path.join(os.tmpdir(),'web-closure-'));const runtime=await startTestDashboard({stateDir:dir});const browser=await loadPlaywright().chromium.launch(browserOptions());t.after(async()=>{await browser.close();await runtime.close();await fs.rm(dir,{recursive:true,force:true});});const page=await browser.newPage({viewport:{width:1440,height:1000}});page.setDefaultTimeout(5000);await page.goto('http://127.0.0.1:'+runtime.server.address().port+'/#'+hash);await login(page);return {page,runtime};} -test('settings open directly with horizontal tabs, retired hashes redirect, and mobile stays inside viewport',{timeout:45000},async t=>{const {page}=await fixture(t,'business-settings');await page.locator('#order-rules-panel').waitFor();assert.equal(await page.locator('#settings-tabs a').count(),4);await page.getByRole('link',{name:'发送计划',exact:true}).click();await page.locator('#schedule-form').waitFor();assert.equal(await page.locator('#send-mode').count(),0);await page.goBack();await page.locator('#order-rules-panel').waitFor();for(const [hash,title] of [['supervisor','系统健康'],['connections','系统健康'],['notifications','分类通知规则']]){await page.evaluate(h=>location.hash=h,hash);await page.getByRole('heading',{name:title,exact:true}).first().waitFor();}await page.evaluate(()=>location.hash='system-settings');await page.getByRole('heading',{name:'BPM 连接',exact:true}).first().waitFor();assert.equal(await page.locator('#settings-tabs a').count(),7);await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);assert.equal(await page.locator('#settings-tabs').evaluate(e=>getComputedStyle(e).overflowX),'auto');}); +test('settings open directly with horizontal tabs, retired hashes redirect, and mobile stays inside viewport',{timeout:45000},async t=>{const {page}=await fixture(t,'business-settings');await page.locator('#order-rules-panel').waitFor();assert.equal(await page.locator('#settings-tabs a').count(),2);await openRuleRoute(page,'schedule');await page.locator('#schedule-form').waitFor();assert.equal(await page.locator('#send-mode').count(),0);await page.goBack();await page.goBack();await page.locator('#order-rules-panel').waitFor();for(const [hash,title] of [['supervisor','系统健康'],['connections','系统健康'],['notifications','分类通知规则']]){await page.evaluate(h=>location.hash=h,hash);await page.getByRole('heading',{name:title,exact:true}).first().waitFor();}await page.evaluate(()=>location.hash='system-settings');await page.getByRole('heading',{name:'BPM 连接',exact:true}).first().waitFor();assert.equal(await page.locator('#settings-tabs a').count(),7);await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);assert.equal(await page.locator('#settings-tabs').evaluate(e=>getComputedStyle(e).overflowX),'auto');}); test('dirty navigation offers stay discard save, suppresses duplicate saves and preserves failed inputs',{timeout:45000},async t=>{const {page}=await fixture(t);await page.locator('#schedule-form').waitFor();await page.locator('#time-first').fill('09:11');await page.getByRole('link',{name:'业务日历',exact:true}).first().click();await page.getByRole('dialog',{name:'未保存的修改'}).waitFor();await page.getByRole('button',{name:'留在此页',exact:true}).click();assert.equal(await page.locator('#time-first').inputValue(),'09:11');await page.getByRole('link',{name:'业务日历',exact:true}).first().click();await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.locator('#day-form').waitFor();await page.getByRole('link',{name:'发送计划',exact:true}).first().click();await page.locator('#time-first').fill('09:12');let requests=0;await page.route('**/api/settings',async route=>{if(route.request().method()==='GET')return route.continue();requests++;await new Promise(r=>setTimeout(r,100));await route.fulfill({status:409,json:{error:'版本已更新,请核对'}});});await page.getByRole('button',{name:'保存发送计划',exact:true}).dblclick();await page.getByRole('alert').getByText('版本已更新,请核对',{exact:true}).waitFor();assert.equal(requests,1);assert.equal(await page.locator('#time-first').inputValue(),'09:12');await page.unroute('**/api/settings');await page.getByRole('link',{name:'业务日历',exact:true}).first().click();await page.getByRole('button',{name:'保存并继续',exact:true}).click();await page.locator('#day-form').waitFor();await page.getByRole('link',{name:'发送计划',exact:true}).first().click();assert.equal(await page.locator('#time-first').inputValue(),'09:12');}); test('password creation is discard-only and assistant settings have a distinct route',{timeout:45000},async t=>{const {page}=await fixture(t,'account');await page.route('**/api/assistant',route=>route.fulfill({json:{settings:{version:1,runtimePath:'',apiBase:'',model:'',timeoutSeconds:60,dailyLimit:30,enabled:false,allowActions:false},conversations:[],usage:{calls:0,limit:30}}}));await page.locator('#account-current').fill('unsaved-test-secret');await page.getByRole('link',{name:'系统设置',exact:true}).click();await page.getByRole('dialog',{name:'未保存的修改'}).waitFor();assert.equal(await page.getByRole('button',{name:'保存并继续',exact:true}).count(),0);await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.getByRole('link',{name:'助手设置',exact:true}).click();await page.locator('#assistant-settings-form').waitFor();await page.getByRole('link',{name:'ZCode 助手',exact:true}).click();await page.locator('#assistant-compose').waitFor();assert.equal(await page.locator('#assistant-settings-form').count(),0);}); -test('execution scan, evidence-only field binding and frozen-batch resend emit versioned contracts',{timeout:45000},async t=>{const {page}=await fixture(t,'order-rules');const writes=[];await page.route('**/api/order-execution**',async route=>{if(route.request().method()==='POST'){writes.push({url:route.request().url(),body:route.request().postDataJSON()});return route.fulfill({json:{ok:true}});}return route.fulfill({json:{tasks:[{id:'task1',version:4,status:'failed',error:'归档失败',connectionId:'connection1'}],capabilities:{liveTodo:false,pdfExport:false,automaticArchive:false},fields:{samples:[],adapters:[]}}});});await page.route('**/api/order-rules/fields',route=>route.fulfill({json:{samples:[{id:'sample1',processName:'订单流程',processVersion:'v7',fields:[{path:'Order.Number',label:'订单编号',value:'A123'},{path:'Order.Text',label:'正文',value:'通知'}]}],adapters:[]}}));await page.route('**/api/order-rules/adapters',route=>{writes.push({url:route.request().url(),body:route.request().postDataJSON()});return route.fulfill({json:{ok:true}});});await page.getByRole('button',{name:'订单执行',exact:true}).click();await page.getByText('归档失败',{exact:true}).waitFor();await page.getByLabel('扫描连接',{exact:true}).selectOption('connection1');await page.evaluate(()=>{crypto.randomUUID=undefined;});await page.getByRole('button',{name:'扫描待办',exact:true}).click();await page.getByText('扫描请求已提交,请核对任务状态。',{exact:true}).waitFor();assert.equal(writes[0].body.connectionId,'connection1');assert.match(writes[0].body.idempotencyKey,/^[a-z0-9-]+$/i);await page.getByLabel('任务重试依据',{exact:true}).fill('已恢复隔离归档目录');await page.getByRole('button',{name:'重试失败任务',exact:true}).click();await page.getByText('重试请求已提交,请核对任务状态。',{exact:true}).waitFor();assert.equal(writes[1].body.version,4);await page.getByRole('button',{name:'字段目录',exact:true}).click();await page.getByLabel('真实采集样本',{exact:true}).selectOption('sample1');await page.getByLabel('订单号来源',{exact:true}).selectOption('Order.Number');await page.getByLabel('简要说明来源',{exact:true}).selectOption('Order.Text');assert.equal(await page.locator('#adapter-fields input[type=text]').count(),0);await page.getByRole('button',{name:'保存字段对应',exact:true}).click();await page.getByText('字段对应已保存。',{exact:true}).waitFor();assert.deepEqual(writes[2].body,{sampleId:'sample1',processName:'订单流程',processVersion:'v7',fields:{orderNo:'Order.Number',brief:'Order.Text'}});}); -test('calendar staged changes save through navigation and rule tab changes use the same guard',{timeout:45000},async t=>{const {page,runtime}=await fixture(t,'calendar');await page.getByLabel('安排说明',{exact:true}).fill('隔离测试调休日');await page.getByRole('button',{name:'应用到此日期',exact:true}).click();await page.getByRole('link',{name:'发送计划',exact:true}).first().click();await page.getByRole('button',{name:'保存并继续',exact:true}).click();await page.locator('#schedule-form').waitFor();assert.equal(runtime.workspace.snapshot().calendar.overrides[0].note,'隔离测试调休日');await page.getByRole('link',{name:'分类通知规则',exact:true}).first().click();await page.getByRole('button',{name:'通知规则',exact:true}).click();await page.getByLabel('规则名称',{exact:true}).fill('尚未保存规则');await page.getByRole('button',{name:'待发批次',exact:true}).click();await page.getByRole('button',{name:'留在此页',exact:true}).click();assert.equal(await page.getByLabel('规则名称',{exact:true}).inputValue(),'尚未保存规则');assert.equal(await page.evaluate(()=>{const e=new Event('beforeunload',{cancelable:true});window.dispatchEvent(e);return e.defaultPrevented;}),true);await page.getByRole('button',{name:'待发批次',exact:true}).click();await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.getByText('暂无待发批次',{exact:true}).waitFor();}); -test('manual resend is only offered for failed batches and sends frozen identity with version and reason',{timeout:45000},async t=>{const {page}=await fixture(t,'order-rules');const original=await page.request.get(new URL('/api/order-rules',page.url()).href);const snapshot=await original.json();snapshot.batches=[{id:'failed1',version:8,status:'failed',categoryId:'test',subject:'隔离失败批次',to:['frozen@example.test'],orderNos:['A1']},{id:'unknown1',version:1,status:'unknown',categoryId:'test',subject:'待核验批次',to:[],orderNos:[]}];let body;await page.route('**/api/order-rules',route=>route.fulfill({json:snapshot}));await page.route('**/api/order-rules/batches/failed1/resend',route=>{body=route.request().postDataJSON();return route.fulfill({json:{ok:true}});});await page.getByRole('button',{name:'发送记录',exact:true}).click();await page.locator('[data-rule-resend]').waitFor();assert.equal(await page.locator('[data-rule-resend]').count(),1);await page.getByLabel('人工补发依据',{exact:true}).fill('已确认原发送明确失败');await page.getByRole('button',{name:'人工补发此失败批次',exact:true}).click();await page.getByText('人工补发请求已提交,请核对发送记录。',{exact:true}).waitFor();assert.equal(body.version,8);assert.equal(body.note,'已确认原发送明确失败');assert.equal(typeof body.idempotencyKey,'string');assert.equal(Object.hasOwn(body,'to'),false);}); +test('execution scan, evidence-only field binding and frozen-batch resend emit versioned contracts',{timeout:45000},async t=>{const {page}=await fixture(t,'order-rules');const writes=[];await page.route('**/api/order-execution**',async route=>{if(route.request().method()==='POST'){writes.push({url:route.request().url(),body:route.request().postDataJSON()});return route.fulfill({json:{ok:true}});}return route.fulfill({json:{tasks:[{id:'task1',version:4,status:'failed',error:'归档失败',connectionId:'connection1'}],capabilities:{liveTodo:false,pdfExport:false,automaticArchive:false},fields:{samples:[],adapters:[]}}});});await page.route('**/api/order-rules/fields',route=>route.fulfill({json:{samples:[{id:'sample1',processName:'订单流程',processVersion:'v7',fields:[{path:'Order.Number',label:'订单编号',value:'A123'},{path:'Order.Text',label:'正文',value:'通知'}]}],adapters:[]}}));await page.route('**/api/order-rules/adapters',route=>{writes.push({url:route.request().url(),body:route.request().postDataJSON()});return route.fulfill({json:{ok:true}});});await openRuleRoute(page,'notification-execution');await page.getByText('归档失败',{exact:true}).waitFor();await page.getByLabel('扫描连接',{exact:true}).selectOption('connection1');await page.evaluate(()=>{crypto.randomUUID=undefined;});await page.getByRole('button',{name:'扫描待办',exact:true}).click();await page.getByText('扫描请求已提交,请核对任务状态。',{exact:true}).waitFor();assert.equal(writes[0].body.connectionId,'connection1');assert.match(writes[0].body.idempotencyKey,/^[a-z0-9-]+$/i);await page.getByLabel('任务重试依据',{exact:true}).fill('已恢复隔离归档目录');await page.getByRole('button',{name:'重试失败任务',exact:true}).click();await page.getByText('重试请求已提交,请核对任务状态。',{exact:true}).waitFor();assert.equal(writes[1].body.version,4);await openRuleRoute(page,'rule-fields');await page.getByLabel('真实采集样本',{exact:true}).selectOption('sample1');await page.getByLabel('订单号来源',{exact:true}).selectOption('Order.Number');await page.getByLabel('简要说明来源',{exact:true}).selectOption('Order.Text');assert.equal(await page.locator('#adapter-fields input[type=text]').count(),0);await page.getByRole('button',{name:'保存字段对应',exact:true}).click();await page.getByText('字段对应已保存。',{exact:true}).waitFor();assert.deepEqual(writes[2].body,{sampleId:'sample1',processName:'订单流程',processVersion:'v7',fields:{orderNo:'Order.Number',brief:'Order.Text'}});}); +test('calendar staged changes save through navigation and rule tab changes use the same guard',{timeout:45000},async t=>{const {page,runtime}=await fixture(t,'calendar');await page.route('**/api/order-rules/fields',route=>route.fulfill({json:{samples:[],adapters:[]}}));await page.getByLabel('安排说明',{exact:true}).fill('隔离测试调休日');await page.getByRole('button',{name:'应用到此日期',exact:true}).click();await page.getByRole('link',{name:'发送计划',exact:true}).first().click();await page.getByRole('button',{name:'保存并继续',exact:true}).click();await page.locator('#schedule-form').waitFor();assert.equal(runtime.workspace.snapshot().calendar.overrides[0].note,'隔离测试调休日');await openRuleRoute(page,'order-rules');await page.getByLabel('规则名称',{exact:true}).fill('尚未保存规则');await openRuleRoute(page,'rule-fields');await page.getByRole('button',{name:'留在此页',exact:true}).click();assert.equal(await page.getByLabel('规则名称',{exact:true}).inputValue(),'尚未保存规则');assert.equal(await page.evaluate(()=>{const e=new Event('beforeunload',{cancelable:true});window.dispatchEvent(e);return e.defaultPrevented;}),true);await openRuleRoute(page,'rule-fields');await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.waitForFunction(()=>location.hash==='#rule-fields');await page.locator('#field-sample').waitFor();}); +test('manual resend is only offered for failed batches and sends frozen identity with version and reason',{timeout:45000},async t=>{const {page}=await fixture(t,'order-rules');const original=await page.request.get(new URL('/api/order-rules',page.url()).href);const snapshot=await original.json();snapshot.batches=[{id:'failed1',version:8,status:'failed',categoryId:'test',subject:'隔离失败批次',to:['frozen@example.test'],orderNos:['A1']},{id:'unknown1',version:1,status:'unknown',categoryId:'test',subject:'待核验批次',to:[],orderNos:[]}];let body;await page.route('**/api/order-rules',route=>route.fulfill({json:snapshot}));await page.route('**/api/order-rules/batches/failed1/resend',route=>{body=route.request().postDataJSON();return route.fulfill({json:{ok:true}});});await openRuleRoute(page,'notification-history');await page.locator('[data-rule-resend]').waitFor();assert.equal(await page.locator('[data-rule-resend]').count(),1);await page.getByLabel('人工补发依据',{exact:true}).fill('已确认原发送明确失败');await page.getByRole('button',{name:'人工补发此失败批次',exact:true}).click();await page.getByText('人工补发请求已提交,请核对发送记录。',{exact:true}).waitFor();assert.equal(body.version,8);assert.equal(body.note,'已确认原发送明确失败');assert.equal(typeof body.idempotencyKey,'string');assert.equal(Object.hasOwn(body,'to'),false);}); test('late page responses cannot overwrite new form and dirty browser history keeps current inputs',{timeout:45000},async t=>{const {page}=await fixture(t,'calendar');await page.locator('#day-form').waitFor();let release;const gate=new Promise(r=>release=r);await page.route('**/api/settings',async route=>{if(route.request().method()!=='GET')return route.continue();await gate;return route.continue();});await page.getByRole('link',{name:'发送计划',exact:true}).first().click();await page.getByRole('link',{name:'业务日历',exact:true}).first().click();release();await page.locator('#day-form').waitFor();assert.equal(await page.locator('#schedule-form').count(),0);await page.unroute('**/api/settings');await page.getByRole('link',{name:'发送计划',exact:true}).first().click();await page.locator('#time-first').fill('10:13');await page.goBack();await page.getByRole('button',{name:'留在此页',exact:true}).click();assert.match(page.url(),/#schedule$/);assert.equal(await page.locator('#time-first').inputValue(),'10:13');}); test('write timeout queries state without resubmission and retains uncertain inputs',{timeout:45000},async t=>{const {page}=await fixture(t,'schedule');await page.locator('#schedule-form').waitFor();await page.clock.install();let posts=0,gets=0;await page.route('**/api/settings',async route=>{if(route.request().method()==='GET'){gets++;return route.continue();}posts++;await route.abort('timedout');});await page.locator('#time-first').fill('10:14');await page.getByRole('button',{name:'保存发送计划',exact:true}).click();await page.locator('#operation-uncertain').waitFor();assert.equal(posts,1);await page.waitForFunction(()=>document.querySelector('#flash')?.textContent.includes('已查询最新状态'));assert.equal(gets,1);assert.equal(await page.locator('#time-first').inputValue(),'10:14');}); test('record history opens legacy notifications read-only after retired address redirects',{timeout:45000},async t=>{const {page}=await fixture(t,'notifications');await page.getByRole('heading',{name:'分类通知规则',exact:true}).waitFor();assert.equal(await page.locator('#notification-settings').count(),0);await page.route('**/api/notifications',route=>route.fulfill({json:{items:[{sourceId:'OLD1',industry:'原分类',subject:'历史通知',brief:'原正文',status:'sent'}],batches:[{id:'old-batch',industry:'原分类',subject:'历史批次',status:'sent',to:['old@example.test']}]}}));await page.getByRole('link',{name:'订单与导出记录',exact:true}).click();await page.getByRole('button',{name:'查看旧通知历史(只读)',exact:true}).click();await page.getByText('历史通知',{exact:true}).waitFor();assert.equal(await page.locator('#legacy-notification-history form').count(),0);}); -test('a delayed execution response cannot replace the selected field directory',{timeout:45000},async t=>{const {page}=await fixture(t,'order-rules');let release;const gate=new Promise(r=>release=r);await page.route('**/api/order-execution',async route=>{await gate;return route.fulfill({json:{tasks:[],capabilities:{},fields:{samples:[],adapters:[]}}});});await page.route('**/api/order-rules/fields',route=>route.fulfill({json:{samples:[],adapters:[]}}));await page.getByRole('button',{name:'订单执行',exact:true}).click();await page.getByRole('button',{name:'字段目录',exact:true}).click();await page.locator('#field-sample').waitFor();release();await page.waitForTimeout(300);assert.equal(await page.locator('#field-sample').count(),1);assert.equal(await page.locator('#execution-scan').count(),0);}); -test('operator scans but cannot configure fields or resend, viewer has no scan action',{timeout:45000},async t=>{const {page,runtime}=await fixture(t,'order-rules');const base=new URL(page.url()).origin;for(const role of ['operator','viewer'])runtime.store.addUser({username:role,password:'Test-password-123',role},'admin');for(const role of ['operator','viewer']){const context=await page.context().browser().newContext(),member=await context.newPage();member.setDefaultTimeout(5000);await member.route('**/api/order-execution',route=>route.fulfill({json:{tasks:[{id:'x',version:1,status:'failed'}],capabilities:{},fields:{samples:[],adapters:[]}}}));await member.route('**/api/order-rules/fields',route=>route.fulfill({json:{samples:[],adapters:[]}}));await member.goto(base+'/#order-rules');await member.getByLabel('账号',{exact:true}).fill(role);await member.getByLabel('密码',{exact:true}).fill('Test-password-123');await member.getByRole('button',{name:'登录',exact:true}).click();await member.getByRole('button',{name:'订单执行',exact:true}).click();await member.getByRole('heading',{name:'持久执行任务',exact:true}).waitFor();assert.equal(await member.getByRole('button',{name:'扫描待办',exact:true}).count(),role==='operator'?1:0);assert.equal(await member.getByRole('button',{name:'重试失败任务',exact:true}).count(),0);await member.getByRole('button',{name:'字段目录',exact:true}).click();await member.getByLabel('真实采集样本',{exact:true}).waitFor();assert.equal(await member.getByRole('button',{name:'保存字段对应',exact:true}).count(),0);await context.close();}}); +test('a delayed execution response cannot replace the selected field directory',{timeout:45000},async t=>{const {page}=await fixture(t,'order-rules');let release;const gate=new Promise(r=>release=r);await page.route('**/api/order-execution',async route=>{await gate;return route.fulfill({json:{tasks:[],capabilities:{},fields:{samples:[],adapters:[]}}});});await page.route('**/api/order-rules/fields',route=>route.fulfill({json:{samples:[],adapters:[]}}));await openRuleRoute(page,'notification-execution');await openRuleRoute(page,'rule-fields');await page.locator('#field-sample').waitFor();release();await page.waitForTimeout(300);assert.equal(await page.locator('#field-sample').count(),1);assert.equal(await page.locator('#execution-scan').count(),0);}); +test('operator scans but cannot configure fields or resend, viewer has no scan action',{timeout:45000},async t=>{const {page,runtime}=await fixture(t,'order-rules');const base=new URL(page.url()).origin;for(const role of ['operator','viewer'])runtime.store.addUser({username:role,password:'Test-password-123',role},'admin');for(const role of ['operator','viewer']){const context=await page.context().browser().newContext(),member=await context.newPage();member.setDefaultTimeout(5000);await member.route('**/api/order-execution',route=>route.fulfill({json:{tasks:[{id:'x',version:1,status:'failed'}],capabilities:{},fields:{samples:[],adapters:[]}}}));await member.route('**/api/order-rules/fields',route=>route.fulfill({json:{samples:[],adapters:[]}}));await member.goto(base+'/#order-rules');await member.getByLabel('账号',{exact:true}).fill(role);await member.getByLabel('密码',{exact:true}).fill('Test-password-123');await member.getByRole('button',{name:'登录',exact:true}).click();await openRuleRoute(member,'notification-execution');await member.getByRole('heading',{name:'持久执行任务',exact:true}).waitFor();assert.equal(await member.getByRole('button',{name:'扫描待办',exact:true}).count(),role==='operator'?1:0);assert.equal(await member.getByRole('button',{name:'重试失败任务',exact:true}).count(),0);await openRuleRoute(member,'rule-fields');await member.getByLabel('真实采集样本',{exact:true}).waitFor();assert.equal(await member.getByRole('button',{name:'保存字段对应',exact:true}).count(),0);await context.close();}}); test('staying after browser Back preserves history so a second Back can discard to its original page',{timeout:45000},async t=>{const {page}=await fixture(t,'calendar');await page.locator('#day-form').waitFor();await page.getByRole('link',{name:'发送计划',exact:true}).first().click();await page.locator('#time-first').fill('11:17');await page.goBack();await page.getByRole('button',{name:'留在此页',exact:true}).click();await page.goBack();await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.locator('#day-form').waitFor();await page.goForward();await page.locator('#schedule-form').waitFor();}); test('template categories use explicit versioned bindings and keep recipient editing in rules',{timeout:45000},async t=>{const {page}=await fixture(t,'schedule');const bindings=[];let saved;await page.route('**/api/mail',route=>route.fulfill({json:{channels:[],templates:[{id:'t1',status:'active',subject:'已确认模板',scope:'原产品线',attachmentCount:0}],receipts:[],sends:[]}}));await page.route('**/api/mail/templates/categories',route=>{if(route.request().method()==='POST'){saved=route.request().postDataJSON();bindings.push({...saved,version:1});return route.fulfill({json:{ok:true}});}return route.fulfill({json:{categories:[{id:'cat1',name:'Excel 分类一'}],bindings}});});await page.getByRole('link',{name:'邮件模板',exact:true}).click();await page.getByLabel('Excel 分类一',{exact:true}).selectOption('t1');assert.equal(await page.locator('#group-editor,#save-groups').count(),0);await page.getByRole('button',{name:'保存关联',exact:true}).click();await page.getByText('类别模板关联已保存。',{exact:true}).waitFor();assert.deepEqual(saved,{categoryId:'cat1',templateId:'t1',version:0});await page.getByLabel('Excel 分类一',{exact:true}).selectOption('');await page.getByRole('button',{name:'保存关联',exact:true}).click();await page.getByText('类别模板关联已保存。',{exact:true}).waitFor();assert.equal(saved.templateId,'');assert.equal(saved.version,1);}); + +async function openRuleRoute(page,hash){ + if(!await page.locator('a[href="#'+hash+'"]').count()){ + const business=['order-rules','rule-fields'].includes(hash); + await page.locator('a[href="#'+(business?'business-settings':'order-notifications')+'"]').first().click(); + if(hash==='notification-settings')await page.locator('a[href="#schedule"]').first().click(); + } + await page.locator('a[href="#'+hash+'"]').first().click(); +} diff --git a/tests/bpm/bpm-ui.test.cjs b/tests/bpm/bpm-ui.test.cjs index 1a3d9b5..a3d506c 100644 --- a/tests/bpm/bpm-ui.test.cjs +++ b/tests/bpm/bpm-ui.test.cjs @@ -258,7 +258,7 @@ test('narrow screens keep the frame inside the page and native typing forwards t test('refresh and logout release BPM control before rendering or dropping authentication',async()=>{ const vm=require('node:vm'),events=[],elements=new Map(); const element=id=>{if(!elements.has(id))elements.set(id,{innerHTML:'',textContent:'',classList:{remove(){}},querySelector(){return {disabled:false};}});return elements.get(id);}; - const context=vm.createContext({Intl,setTimeout,clearInterval,location:{hash:'#overview'},history:{replaceState(){}},document:{querySelector:element,querySelectorAll:()=>[],addEventListener(){}},window:{addEventListener(){},PageLifecycle:{guard:fn=>fn(),dispose:async()=>{},attach(){},bind(){}},AppNavigation:{primary:[],resolve:id=>id,sectionFor:()=>null,renderTabs(){}},BpmLogin:{dispose:async()=>events.push('release')},WorkspaceViews:{overview:async()=>events.push('render')}}}); + const context=vm.createContext({Intl,setTimeout,clearInterval,location:{hash:'#overview'},history:{replaceState(){}},document:{querySelector:element,querySelectorAll:()=>[],addEventListener(){}},window:{addEventListener(){},PageLifecycle:{guard:fn=>fn(),dispose:async()=>{},attach(){},bind(){}},AppNavigation:{primary:[],resolve:id=>id,sectionFor:()=>null,renderTabs(){},isConfiguration:()=>false},BpmLogin:{dispose:async()=>events.push('release')},WorkspaceViews:{overview:async()=>events.push('render')}}}); const source=fs.readFileSync(path.join(__dirname,'../../web/app.js'),'utf8').replace(/boot\(\)\.catch[\s\S]*$/,''); vm.runInContext(source,context); await vm.runInContext("currentUser={username:'alice',role:'admin'};renderView()",context); diff --git a/tests/mail/mail-ui.test.cjs b/tests/mail/mail-ui.test.cjs index f2e408b..f8331a5 100644 --- a/tests/mail/mail-ui.test.cjs +++ b/tests/mail/mail-ui.test.cjs @@ -3,6 +3,6 @@ test('mail management saves a real config, previews template under CSP and confi const dir=fs.mkdtempSync(path.join(os.tmpdir(),'mail-ui-')),store=new Store(path.join(dir,'users'));store.bootstrap('admin','Test-password-123');const mailStore=new MailStore(path.join(dir,'mail')),mail=new MailService({store:mailStore});const server=createDashboard({store,mail,outputDir:dir});let browser; t.after(async()=>{await browser?.close();await mail.stop();await new Promise(r=>server.close(r));mailStore.close();fs.rmSync(dir,{recursive:true,force:true});});await new Promise(r=>server.listen(0,'127.0.0.1',r));const base='http://127.0.0.1:'+server.address().port;browser=await loadPlaywright().chromium.launch(browserOptions());const page=await browser.newPage({viewport:{width:1360,height:950}});const errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto(base+'/#mail');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('button',{name:'添加邮箱',exact:true}).click({timeout:5000}); await page.getByLabel('邮箱名称',{exact:true}).fill('通知邮箱');await page.getByLabel('邮箱地址',{exact:true}).fill('orders@company.test');for(const type of ['SMTP','IMAP']){await page.getByLabel(type+' 服务器',{exact:true}).fill(type.toLowerCase()+'.company.test');await page.getByLabel(type+' 登录账号',{exact:true}).fill('orders');await page.getByLabel(type+' 密码 / 授权码',{exact:true}).fill('Secret-mail-123');}await page.getByLabel('允许提交模板的发件人',{exact:true}).fill('author@company.test');await page.getByRole('button',{name:'保存邮箱',exact:true}).click();await page.getByText('通知邮箱',{exact:true}).waitFor();assert.equal(mailStore.channels().length,1); - const c=mailStore.channels()[0],raw=Buffer.from('From: author@company.test\r\nTo: orders@company.test\r\nSubject: [模板]Notice\r\nMIME-Version: 1.0\r\nContent-Type: text/html\r\n\r\n
Template body
');const draft=mailStore.ingest(c.id,'1',1,await parseTemplate(raw,c),raw,1);await page.getByRole('link',{name:'业务设置',exact:true}).click();await page.getByRole('link',{name:'邮件模板',exact:true}).click();await page.getByRole('button',{name:'预览并确认',exact:true}).click();await page.frameLocator('iframe[title="邮件正文预览"]').getByText('Template body',{exact:true}).waitFor();assert.equal(mailStore.template(draft.id).status,'pending');await page.getByLabel('发信标题',{exact:true}).fill('Confirmed notice');await page.getByRole('button',{name:'确认生效',exact:true}).click();await page.getByText('模板已确认生效。',{exact:true}).waitFor();assert.equal(mailStore.template(draft.id).status,'active'); + const c=mailStore.channels()[0],raw=Buffer.from('From: author@company.test\r\nTo: orders@company.test\r\nSubject: [模板]Notice\r\nMIME-Version: 1.0\r\nContent-Type: text/html\r\n\r\n
Template body
');const draft=mailStore.ingest(c.id,'1',1,await parseTemplate(raw,c),raw,1);await page.getByRole('link',{name:'订单通知管理',exact:true}).click();await page.getByRole('link',{name:'通知配置',exact:true}).click();await page.locator('#notification-config-tabs').getByRole('link',{name:'邮件模板',exact:true}).click();await page.getByRole('button',{name:'预览并确认',exact:true}).click();await page.frameLocator('iframe[title="邮件正文预览"]').getByText('Template body',{exact:true}).waitFor();assert.equal(mailStore.template(draft.id).status,'pending');await page.getByLabel('发信标题',{exact:true}).fill('Confirmed notice');await page.getByRole('button',{name:'确认生效',exact:true}).click();await page.getByText('模板已确认生效。',{exact:true}).waitFor();assert.equal(mailStore.template(draft.id).status,'active'); await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);assert.deepEqual(errors,[]); }); diff --git a/tests/order-rules/section-ui.test.cjs b/tests/order-rules/section-ui.test.cjs new file mode 100644 index 0000000..2ae7675 --- /dev/null +++ b/tests/order-rules/section-ui.test.cjs @@ -0,0 +1,18 @@ +'use strict'; +const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),path=require('node:path'); +const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs'); +async function setup(t,section,owner='OrderNotificationViews',mailFailure=false){ + const browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage();await page.setContent('
'); + for(const file of ['order-notifications/shared.js','order-rules/view.js','order-notifications/view.js'])await page.addScriptTag({content:await fs.readFile(path.resolve('web/modules',file),'utf8')}); + await page.evaluate(async({section,owner,mailFailure})=>{window.calls=[];window.active=true;window.PageLifecycle={requestKey:()=> 'key',dirty:()=>false,onDispose:()=>{},afterSave:async reload=>reload(),guard:fn=>fn()};window.OrderExecutionViews={fields:async panel=>{panel.textContent='字段映射';},execution:async panel=>{panel.textContent='订单执行';return {refresh:async()=>{}};}};const snapshot={rules:[],orders:[{id:'o1',orderNo:'ORDER-1',status:'blocked',batchId:'BATCH-1',ruleSnapshot:{version:4},archive:{path:'archive/ORDER-1.pdf'},reason:'缺少归档证据'}],batches:[],audit:[],adapters:[],settings:{enabled:false},capabilities:{},window:{available:true,start:'2026-10-19T00:00:00Z',end:'2026-10-19T11:00:00Z'}};window[owner].configure(window.viewHelpers={api:async url=>{window.calls.push(url);if(url==='/mail'&&mailFailure)throw Error('SMTP目录暂不可读');return url==='/overview'?{nextSlots:['2026-10-20T03:00:00Z']}:url==='/mail'?{channels:[]}:url.endsWith('/fields')?{samples:[]}:snapshot;},esc:value=>String(value??'').replaceAll('&','&').replaceAll('<','<'),formatDate:v=>v||'—',user:{role:'admin'}});await window[owner].render(document.querySelector('#root'),()=>window.active,section);},{section,owner,mailFailure});return page; +} +test('notification orders expose batch and archive evidence without reading mailbox or field catalogs',async t=>{const page=await setup(t,'orders');await page.locator('summary').click();assert.match(await page.locator('main').innerText(),/BATCH-1/);assert.match(await page.locator('main').innerText(),/archive\/ORDER-1.pdf/);assert.equal(await page.locator('a[href="#notification-batches"]').count(),1);assert.equal(await page.locator('a[href="#records"]').count(),1);assert.equal(await page.locator('[data-rule-tab]').count(),0);assert.deepEqual(await page.evaluate(()=>calls),['/order-rules']);}); +test('fields route delegates fields lifecycle and never reads notification mailbox or runtime snapshot',async t=>{const page=await setup(t,'fields','OrderRuleViews');await page.getByText('字段映射',{exact:true}).waitFor();assert.deepEqual(await page.evaluate(()=>calls),[]);assert.equal(await page.locator('[data-rule-tab]').count(),0);}); +test('workbench shows server next slot and concrete capability remediation links',async t=>{const page=await setup(t,'workbench');assert.match(await page.locator('main').innerText(),/2026-10-20T03:00:00Z/);for(const hash of ['#rule-fields','#bpm','#storage','#notification-orders'])assert.ok(await page.locator('a[href="'+hash+'"]').count());assert.deepEqual(await page.evaluate(()=>calls),['/order-rules','/overview']);}); + +test('settings mailbox read failure is visible and does not present an empty catalog as confirmed',async t=>{const page=await setup(t,'settings','OrderNotificationViews',true);assert.match(await page.locator('main').innerText(),/SMTP目录暂不可读/);assert.match(await page.locator('main').innerText(),/邮箱.*读取失败/);}); + +test('a late notification action after departure starts no readback and emits no saved feedback',async t=>{ + const page=await setup(t,'pending');await page.evaluate(()=>{const prior=window.viewHelpers.api;window.OrderNotificationViews.configure({...window.viewHelpers,api:async(url,body)=>{if(url==='/order-rules/prepare')return new Promise(resolve=>window.releaseAction=()=>resolve({version:2}));return prior(url,body);}});}); + await page.locator('#order-rule-prepare button[type=submit]').click();await page.waitForFunction(()=>typeof window.releaseAction==='function');await page.evaluate(()=>{window.active=false;window.releaseAction();});await page.waitForFunction(()=>!document.querySelector('#order-rule-prepare button[type=submit]').disabled);assert.deepEqual(await page.evaluate(()=>calls),['/order-rules']);assert.equal(await page.locator('#order-rules-feedback').textContent(),''); +}); diff --git a/tests/order-rules/web.test.cjs b/tests/order-rules/web.test.cjs index 62055ae..aebcc61 100644 --- a/tests/order-rules/web.test.cjs +++ b/tests/order-rules/web.test.cjs @@ -21,25 +21,25 @@ test('category editor saves/reloads drafts, previews readable evidence without i const writes=[];browser=await loadPlaywright().chromium.launch(browserOptions());const page=await browser.newPage({viewport:{width:1440,height:1000}});page.setDefaultTimeout(7000);const errors=[];page.on('pageerror',e=>errors.push(e.message));await page.clock.install(); await page.route('**/api/order-rules**',async route=>{const req=route.request(),url=new URL(req.url());let result=data;if(req.method()==='POST'){const body=req.postDataJSON();writes.push({path:url.pathname,body});if(url.pathname.endsWith('/rules')){data.rules[0]={...data.rules[0],...body,version:data.rules[0].version+1};result=data.rules[0];}else if(url.pathname.endsWith('/preview'))result={valid:true,ruleId:'category-1',checks:[{label:'数量',ok:true,detail:'零数量合法'}],issues:[],explanation:'按类别汇总一封邮件',fieldTrace:[{key:'quantity',label:'数量',path:'订单.数量',value:0}],event:{orderNo:'SAMPLE-1',quantity:0}};else if(url.pathname.endsWith('/publish')){await route.fulfill({status:409,json:{error:'实时待办接入待联调,暂不可发布'}});return;}}await route.fulfill({json:result});}); await page.goto('http://127.0.0.1:'+server.address().port+'/#order-rules');await page.getByLabel('账号',{exact:true}).waitFor();assert.equal(await page.getByRole('button',{name:'进入演示空间',exact:true}).count(),0);await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click(); - await page.getByRole('button',{name:'通知规则',exact:true}).click();await page.getByLabel('规则名称',{exact:true}).fill('订单类别更新');await page.getByLabel('收件人',{exact:true}).fill('recipient@example.test');await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText('规则草稿已保存。',{exact:true}).waitFor(); + await openRuleRoute(page,'order-rules');await page.getByLabel('规则名称',{exact:true}).fill('订单类别更新');await page.getByLabel('收件人',{exact:true}).fill('recipient@example.test');await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText('规则草稿已保存。',{exact:true}).waitFor(); assert.equal(data.rules[0].name,'订单类别更新');assert.deepEqual(data.rules[0].to,['recipient@example.test']);assert.deepEqual(writes[0].body.processNames,['订单流程']); - await page.reload();await page.getByRole('button',{name:'通知规则',exact:true}).click();assert.equal(await page.getByLabel('规则名称',{exact:true}).inputValue(),'订单类别更新'); + await page.reload();await openRuleRoute(page,'order-rules');assert.equal(await page.getByLabel('规则名称',{exact:true}).inputValue(),'订单类别更新'); await page.getByLabel('BPM 原始标题',{exact:true}).fill('客户等级:C订单号:148396机芯号:X毛利:绿标订单号:HA148396总数量:5000');await page.getByRole('button',{name:'校验已保存规则',exact:true}).click();await page.locator('#order-rule-preview-result').getByText('零数量合法',{exact:true}).waitFor();assert.match(await page.locator('#order-rule-preview-result').innerText(),/订单.数量/);assert.match(await page.locator('#order-rule-preview-result').innerText(),/0/);assert.equal(data.orders.length,0);assert.equal(writes.some(x=>x.path.endsWith('/events')),false);assert.equal(writes.find(x=>x.path.endsWith('/preview')).body.sample.title,'客户等级:C订单号:148396机芯号:X毛利:绿标订单号:HA148396总数量:5000'); await page.getByRole('button',{name:'发布此版本',exact:true}).click();await page.getByText('实时待办接入待联调,暂不可发布',{exact:true}).waitFor(); - await page.getByRole('button',{name:'设置',exact:true}).click();assert.equal(await page.getByLabel('启用自动分类通知',{exact:true}).isDisabled(),true);assert.match(await page.locator('#order-rules-panel').innerText(),/待联调/); + await openRuleRoute(page,'notification-settings');assert.equal(await page.getByLabel('启用自动分类通知',{exact:true}).isDisabled(),true);assert.match(await page.locator('#order-rules-panel').innerText(),/待联调/); data.orders=[{id:'old',orderNo:'HISTORICAL-ORDER',categoryId:'category-1',status:'pending',receivedAt:'2026-10-19T09:00:00+08:00'},{id:'current',orderNo:'CURRENT-ORDER',categoryId:'category-1',status:'pending',receivedAt:'2026-10-20T09:00:00+08:00'},{id:'future',orderNo:'FUTURE-ORDER',categoryId:'category-1',status:'pending',receivedAt:'2026-10-20T15:00:00+08:00'}]; - await page.reload();await page.getByRole('button',{name:'待发批次',exact:true}).click();await page.getByText('暂无待发批次',{exact:true}).waitFor(); + await page.reload();await openRuleRoute(page,'notification-batches');await page.getByText('暂无待发批次',{exact:true}).waitFor(); assert.equal(await page.getByLabel('本批截止时间(北京时间)',{exact:true}).count(),0);assert.match(await page.locator('#order-rules-panel').innerText(),/工作日第一时段/);assert.match(await page.locator('#order-rules-panel').innerText(),/CURRENT-ORDER/);assert.doesNotMatch(await page.locator('#order-rules-panel').innerText(),/HISTORICAL-ORDER|FUTURE-ORDER/); await page.getByRole('button',{name:'整理本时段批次',exact:true}).click();assert.deepEqual(writes.find(x=>x.path.endsWith('/prepare')).body,{cutoff:data.window.end}); await page.locator('[data-rule-recheck="current"]').locator('..').locator('summary').click();await page.getByLabel('重新核对依据',{exact:true}).fill('已核实更新后的业务分类');await page.getByRole('button',{name:'重新核对此订单',exact:true}).click();await page.getByText('此订单已重新核对,请检查新匹配结果及归档状态。',{exact:true}).waitFor();assert.deepEqual(writes.find(x=>x.path.endsWith('/recheck')).body,{note:'已核实更新后的业务分类'}); - data.window.available=false;await page.reload();await page.getByRole('button',{name:'待发批次',exact:true}).click();assert.equal(await page.getByRole('button',{name:'整理本时段批次',exact:true}).isDisabled(),true);assert.match(await page.locator('#order-rules-panel').innerText(),/当前只预览/); + data.window.available=false;await page.reload();await openRuleRoute(page,'notification-batches');assert.equal(await page.getByRole('button',{name:'整理本时段批次',exact:true}).isDisabled(),true);assert.match(await page.locator('#order-rules-panel').innerText(),/当前只预览/); data.window.available=true;data.batches=[{id:'fresh-batch',categoryId:'category-1',subject:'自动刷新后的本时段批次',status:'prepared',windowStart:data.window.start,windowEnd:data.window.end,to:[],orderIds:[]}];await page.clock.fastForward(15001);await page.getByText('自动刷新后的本时段批次',{exact:true}).waitFor();assert.equal(await page.getByRole('button',{name:'整理本时段批次',exact:true}).isDisabled(),false); - await page.getByRole('button',{name:'通知规则',exact:true}).click();await page.locator('#order-rule-advanced summary').click();const typedSample='{"custom":"保留尚未运行的样本"}';await page.getByLabel('待校验 JSON 样本',{exact:true}).fill(typedSample);await page.clock.fastForward(15001);assert.equal(await page.getByLabel('待校验 JSON 样本',{exact:true}).inputValue(),typedSample);await page.getByLabel('规则名称',{exact:true}).fill('保留尚未保存的规则');await page.clock.fastForward(15001);assert.equal(await page.getByLabel('规则名称',{exact:true}).inputValue(),'保留尚未保存的规则');assert.equal(await page.getByLabel('待校验 JSON 样本',{exact:true}).inputValue(),typedSample); + await openRuleRoute(page,'order-rules');await page.locator('#order-rule-advanced summary').click();const typedSample='{"custom":"保留尚未运行的样本"}';await page.getByLabel('待校验 JSON 样本',{exact:true}).fill(typedSample);await page.clock.fastForward(15001);assert.equal(await page.getByLabel('待校验 JSON 样本',{exact:true}).inputValue(),typedSample);await page.getByLabel('规则名称',{exact:true}).fill('保留尚未保存的规则');await page.clock.fastForward(15001);assert.equal(await page.getByLabel('规则名称',{exact:true}).inputValue(),'保留尚未保存的规则');assert.equal(await page.getByLabel('待校验 JSON 样本',{exact:true}).inputValue(),typedSample); await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);assert.deepEqual(errors,[]); }); test('ordinary admin login opens all category rules without a demo entry',{timeout:60000},async t=>{ - const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-rules-preview-web-'));const runtime=await startTestDashboard({stateDir:dir});let browser;t.after(async()=>{await browser?.close();runtime.server.closeAllConnections();await runtime.close();await fs.rm(dir,{recursive:true,force:true});});browser=await loadPlaywright().chromium.launch(browserOptions());const page=await browser.newPage();await page.goto('http://127.0.0.1:'+runtime.server.address().port+'/#order-rules');assert.equal(await page.getByRole('button',{name:'进入演示空间',exact:true}).count(),0);await login(page);await page.getByRole('button',{name:'通知规则',exact:true}).click();await page.getByText('Excel 分类 · 15',{exact:true}).waitFor();assert.equal(runtime.orderRules.snapshot().orders.length,0);assert.equal(await page.getByLabel('规则名称',{exact:true}).isEnabled(),true); + const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-rules-preview-web-'));const runtime=await startTestDashboard({stateDir:dir});let browser;t.after(async()=>{await browser?.close();runtime.server.closeAllConnections();await runtime.close();await fs.rm(dir,{recursive:true,force:true});});browser=await loadPlaywright().chromium.launch(browserOptions());const page=await browser.newPage();await page.goto('http://127.0.0.1:'+runtime.server.address().port+'/#order-rules');assert.equal(await page.getByRole('button',{name:'进入演示空间',exact:true}).count(),0);await login(page);await openRuleRoute(page,'order-rules');await page.getByText('Excel 分类 · 15',{exact:true}).waitFor();assert.equal(runtime.orderRules.snapshot().orders.length,0);assert.equal(await page.getByLabel('规则名称',{exact:true}).isEnabled(),true); }); test('real catalog workflow publishes a saved and sampled draft while roles and production gates remain enforced',{timeout:90000},async t=>{ @@ -48,9 +48,9 @@ test('real catalog workflow publishes a saved and sampled draft while roles and const orderRules=new RuleStore(path.join(dir,'rules')),server=createDashboard({store,orderRules,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));let browser; t.after(async()=>{await browser?.close();server.closeAllConnections();await new Promise(r=>server.close(r));orderRules.close();await fs.rm(dir,{recursive:true,force:true});}); browser=await loadPlaywright().chromium.launch(browserOptions());const base='http://127.0.0.1:'+server.address().port; - async function open(role){const page=await browser.newPage({viewport:{width:1440,height:1000}});page.setDefaultTimeout(7000);await page.goto(base+'/#order-rules');await page.getByLabel('账号',{exact:true}).fill(role);await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('button',{name:'通知规则',exact:true}).click();return page;} + async function open(role){const page=await browser.newPage({viewport:{width:1440,height:1000}});page.setDefaultTimeout(7000);await page.goto(base+'/#order-rules');await page.getByLabel('账号',{exact:true}).fill(role);await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await openRuleRoute(page,'order-rules');return page;} const page=await open('admin');await page.locator('[data-rule-id="bs-change"]').click();await page.getByLabel('规则名称',{exact:true}).fill('备损更改通知测试');await page.getByLabel('归档目录',{exact:true}).fill('\\\\fixture-server\\orders\\changes');await page.getByLabel('文件名日期依据',{exact:true}).selectOption('appDate');await page.getByLabel('收件人',{exact:true}).fill('recipient@example.test');await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText('规则草稿已保存。',{exact:true}).waitFor(); - await page.reload();await page.getByRole('button',{name:'通知规则',exact:true}).click();await page.locator('[data-rule-id="bs-change"]').click();assert.equal(await page.getByLabel('规则名称',{exact:true}).inputValue(),'备损更改通知测试'); + await page.reload();await openRuleRoute(page,'order-rules');await page.locator('[data-rule-id="bs-change"]').click();assert.equal(await page.getByLabel('规则名称',{exact:true}).inputValue(),'备损更改通知测试'); await page.locator('#order-rule-advanced summary').click();const realSample=JSON.parse(await page.getByLabel('待校验 JSON 样本',{exact:true}).inputValue());realSample.demo=false;await page.getByLabel('待校验 JSON 样本',{exact:true}).fill(JSON.stringify(realSample));await page.getByRole('button',{name:'校验已保存规则',exact:true}).click();await page.locator('#order-rule-preview-result .alert').getByText(/样本校验通过/).waitFor();assert.match(await page.locator('#order-rule-preview-result').innerText(),/OFR_BS_Applicant.OrderNum/);await page.getByRole('button',{name:'发布此版本',exact:true}).click();await page.getByText('发布前必须选择服务端真实采集样本完成试运行。',{exact:true}).waitFor(); const captured=orderRules.recordCapture({sample:realSample,snapshot:{processVersion:realSample.processVersion,html:'

isolated provider fixture

',fields:Object.entries(realSample.fields).map(([path,value])=>({path,label:path,value}))},taskId:'isolated-provider-fixture'}); const trial=await page.request.post(base+'/api/order-rules/preview',{headers:{Origin:base},data:{sampleId:captured.id}});assert.equal(trial.status(),200);assert.equal((await trial.json()).valid,true); @@ -61,3 +61,12 @@ test('real catalog workflow publishes a saved and sampled draft while roles and const operator=await open('operator');assert.equal(await operator.getByLabel('规则名称',{exact:true}).isDisabled(),true);assert.equal(await operator.getByRole('button',{name:'保存草稿',exact:true}).count(),0);assert.equal(await operator.getByRole('button',{name:'校验已保存规则',exact:true}).count(),1); const viewer=await open('viewer');assert.equal(await viewer.getByLabel('规则名称',{exact:true}).isDisabled(),true);assert.equal(await viewer.getByRole('button',{name:'校验已保存规则',exact:true}).count(),0); }); + +async function openRuleRoute(page,hash){ + if(!await page.locator('a[href="#'+hash+'"]').count()){ + const business=['order-rules','rule-fields'].includes(hash); + await page.locator('a[href="#'+(business?'business-settings':'order-notifications')+'"]').first().click(); + if(hash==='notification-settings')await page.locator('a[href="#schedule"]').first().click(); + } + await page.locator('a[href="#'+hash+'"]').first().click(); +} diff --git a/web/app.css b/web/app.css index 9f27fef..0534ebe 100644 --- a/web/app.css +++ b/web/app.css @@ -22,10 +22,22 @@ @media(max-width:767px){.assistant-layout{grid-template-columns:minmax(0,1fr)}.assistant-sidebar{max-height:230px}.assistant-messages{min-height:340px;padding:1rem}.assistant-user{margin-left:5%}.assistant-welcome{padding:2rem .25rem}.assistant-chat .card-footer{padding:1rem}.assistant-chat .btn-list{gap:.4rem}} .health-check-item+.health-check-item{border-top:1px solid var(--tblr-border-color,#dce1e7);padding-top:1rem;margin-top:1rem}.health-check-times{display:grid;grid-template-columns:5rem minmax(0,1fr);gap:.4rem .6rem}.health-check-times dt{font-weight:400;color:var(--tblr-secondary,#6c7a91)}.health-check-times dd{margin:0;overflow-wrap:anywhere}#health-runtime .card,#health-groups .card{min-width:0} -.order-rule-tabs{display:flex;gap:.5rem;flex-wrap:wrap}.order-rule-tabs .btn{flex:0 0 auto}.order-rules-layout{display:grid;grid-template-columns:240px minmax(0,1fr);gap:1.25rem;align-items:start}.order-rule-main,.order-rule-list,.order-rules .card,.order-rules .card-body{min-width:0}.order-rule-list .list-group-item{text-align:left;padding:1rem;white-space:normal;overflow-wrap:anywhere}.order-rule-list .list-group-item.active{background:#eef6f1;color:#254c3a;border-color:#dce9df;box-shadow:inset 3px 0 #28745b}.order-rule-list strong{font-size:.86rem;font-weight:550}.order-rule-capabilities{display:flex;flex-wrap:wrap;gap:1rem 1.8rem}.order-rule-capabilities>div{display:flex;align-items:center;gap:.65rem;font-size:.82rem}.order-rule-explanation{background:#f0f6f2;border:1px solid #dce9df;border-radius:8px;padding:1rem;line-height:1.85;font-size:.85rem;overflow-wrap:anywhere}.order-rule-record{white-space:pre-wrap;overflow-wrap:anywhere;line-height:1.8}.order-rules-empty{padding:2rem 1rem;text-align:center;font-size:.85rem}.order-rules-table td{min-width:140px;max-width:560px;overflow-wrap:anywhere}.order-rules-table th{white-space:nowrap}.order-rule-fields td{vertical-align:top;max-width:240px;overflow-wrap:anywhere}.order-rule-fields code{white-space:normal;overflow-wrap:anywhere}.order-rule-fields th{white-space:nowrap}.order-rule-cutoff{max-width:260px}.order-rules summary{cursor:pointer}.order-rules select[multiple]{min-height:115px}.order-rules #order-rules-feedback:empty{display:none} -@media(max-width:991px){.order-rules-layout{grid-template-columns:minmax(0,1fr)}.order-rule-list .list-group{max-height:240px;overflow:auto}}@media(max-width:767px){.order-rule-capabilities{gap:.8rem;flex-direction:column}.order-rule-tabs{gap:.35rem}.order-rule-tabs .btn{padding:.5rem .65rem;font-size:.8rem}.order-rules select[multiple]{width:100%;min-width:0}.order-rule-fields{font-size:.76rem}.order-rule-explanation{padding:.8rem}.order-rules-table td{max-width:300px}} +.order-rules-layout{display:grid;grid-template-columns:240px minmax(0,1fr);gap:1.25rem;align-items:start}.order-rule-main,.order-rule-list,.order-rules .card,.order-rules .card-body{min-width:0}.order-rule-list .list-group-item{text-align:left;padding:1rem;white-space:normal;overflow-wrap:anywhere}.order-rule-list .list-group-item.active{background:#eef6f1;color:#254c3a;border-color:#dce9df;box-shadow:inset 3px 0 #28745b}.order-rule-list strong{font-size:.86rem;font-weight:550}.order-rule-capabilities{display:flex;flex-wrap:wrap;gap:1rem 1.8rem}.order-rule-capabilities>div{display:flex;align-items:center;gap:.65rem;font-size:.82rem}.order-rule-explanation{background:#f0f6f2;border:1px solid #dce9df;border-radius:8px;padding:1rem;line-height:1.85;font-size:.85rem;overflow-wrap:anywhere}.order-rule-record{white-space:pre-wrap;overflow-wrap:anywhere;line-height:1.8}.order-rules-empty{padding:2rem 1rem;text-align:center;font-size:.85rem}.order-rules-table td{min-width:140px;max-width:560px;overflow-wrap:anywhere}.order-rules-table th{white-space:nowrap}.order-rule-fields td{vertical-align:top;max-width:240px;overflow-wrap:anywhere}.order-rule-fields code{white-space:normal;overflow-wrap:anywhere}.order-rule-fields th{white-space:nowrap}.order-rule-cutoff{max-width:260px}.order-rules summary{cursor:pointer}.order-rules select[multiple]{min-height:115px}.order-rules #order-rules-feedback:empty{display:none} +@media(max-width:991px){.order-rules-layout{grid-template-columns:minmax(0,1fr)}.order-rule-list .list-group{max-height:240px;overflow:auto}}@media(max-width:767px){.order-rule-capabilities{gap:.8rem;flex-direction:column}.order-rules select[multiple]{width:100%;min-width:0}.order-rule-fields{font-size:.76rem}.order-rule-explanation{padding:.8rem}.order-rules-table td{max-width:300px}} .settings-entry{color:inherit;text-decoration:none;transition:border-color .15s,box-shadow .15s}.settings-entry:hover,.settings-entry:focus-visible{border-color:var(--tblr-primary);box-shadow:0 2px 10px #0000000a}.settings-entry .flex-fill{min-width:0}.settings-entry .small{overflow-wrap:anywhere}#view-breadcrumb{font-size:.8rem} -.settings-tabs{display:flex;flex-wrap:nowrap;overflow-x:auto;gap:4px;max-width:100%;border-bottom:1px solid var(--tblr-border-color,#ddd);margin-bottom:20px;scrollbar-width:thin}.settings-tab{white-space:nowrap;display:block;padding:12px 16px;color:var(--tblr-body-color);border-bottom:3px solid transparent;text-decoration:none}.settings-tab.active{color:var(--tblr-primary);border-color:var(--tblr-primary);font-weight:600}.page-leave-dialog{border:1px solid #ccc;border-radius:10px;padding:24px;max-width:min(520px,calc(100vw - 32px))}.page-leave-dialog::backdrop{background:rgba(0,0,0,.35)}.page-leave-dialog .btn-list{flex-wrap:wrap} +/* Tabler nav-segmented remains the component; these rules adapt route navigation to scrolling. */ +.settings-tabs.nav-segmented{--nav-bg:#eef1f5;--nav-active-bg:#fff;display:flex;flex-wrap:nowrap;gap:4px;width:fit-content;max-width:100%;overflow-x:auto;overflow-y:hidden;padding:5px;margin-bottom:22px;border-radius:12px;scrollbar-width:thin;scroll-padding-inline:5px;overscroll-behavior-x:contain} +.settings-tabs.nav-segmented .nav-link{flex:0 0 auto;gap:8px;height:40px;padding:9px 15px;border-radius:8px;color:#667486;font-weight:500;text-decoration:none;white-space:nowrap} +.settings-tabs.nav-segmented .nav-link:hover{color:#26364a;background:#ffffff70} +.settings-tabs.nav-segmented .nav-link.active{background:#fff;color:#26364a;border-color:#dfe4eb;box-shadow:0 1px 3px #1426410d;font-weight:600} +.settings-tabs .nav-link:focus-visible{outline:2px solid var(--tblr-primary);outline-offset:-2px} +.navigation-icon{flex:none;display:block}.notification-configuration{min-width:0}.notification-configuration>.card-header{min-width:0;padding:16px 20px;border-bottom:1px solid var(--tblr-border-color)} +.notification-configuration .configuration-tabs{margin-bottom:0}.notification-configuration>.card-body{min-width:0;padding:20px}.notification-configuration .settings-width{max-width:100%} +#automation-status{max-width:100%;white-space:normal;line-height:1.5}.page-wrapper,.page-body>.container-xl,#content{min-width:0} +@media(max-width:767px){.settings-tabs.nav-segmented{margin-bottom:16px;border-radius:10px}.settings-tabs.nav-segmented .nav-link{height:38px;padding:8px 12px;gap:6px;font-size:.82rem}.notification-configuration>.card-header,.notification-configuration>.card-body{padding:12px}.settings-tabs .navigation-icon{width:16px;height:16px}} +.page-leave-dialog{border:1px solid #ccc;border-radius:10px;padding:24px;max-width:min(520px,calc(100vw - 32px))}.page-leave-dialog::backdrop{background:rgba(0,0,0,.35)}.page-leave-dialog .btn-list{flex-wrap:wrap} .settings-tabs[hidden]{display:none} + +.notification-timing{display:grid;grid-template-columns:minmax(0,1.2fr) minmax(0,1fr);gap:1rem}.notification-timing>.card{min-width:0}.notification-timing .card-header{flex-wrap:wrap;gap:.5rem}.notification-timing .card-header>.ms-auto{margin-left:0!important}.notification-timing .card-body{overflow-wrap:anywhere}@media(max-width:767px){.notification-timing{grid-template-columns:minmax(0,1fr);gap:0}} diff --git a/web/app.js b/web/app.js index bcd8db9..2780ca2 100644 --- a/web/app.js +++ b/web/app.js @@ -4,8 +4,8 @@ const esc=value=>String(value??'').replace(/[&<>"']/g,c=>({'&':'&','<':'< const formatDate=value=>{const date=new Date(value);return value&&!Number.isNaN(date.getTime())?new Intl.DateTimeFormat('zh-CN',{timeZone:'Asia/Shanghai',dateStyle:'short',timeStyle:'medium',hour12:false}).format(date):'—';}; const roles={admin:'管理员',operator:'操作员',viewer:'只读成员'}; const statusMap={running:['处理中','blue'],success:['已完成','green'],error:['失败','red'],interrupted:['已中断','orange']}; -let currentUser=null,settings=null,currentView='overview',overview=null,refreshTimer=null,viewGeneration=0,historyIndex=0,historyTransition=null; -const views={'assistant-settings':['助手设置','配置 ZCode 运行包、模型与受控操作权限'],'business-settings':['业务设置','集中维护订单分类、发送时间和收件规则'],'system-settings':['系统设置','集中管理服务连接、运行维护和团队权限'],account:['个人账号','维护自己的登录密码与访问安全'],'order-rules':['分类通知规则','按 Excel 类别配置匹配、归档与邮件,查看订单和批次状态'],health:['系统健康','查看服务守护、登录自启和各模块最近检查结果'],assistant:['ZCode 助手','对话查询运行状态、分析异常与执行受控恢复'],storage:['存储服务器','配置 SMB 共享目录、检查连接与管理 PDF 归档'],notifications:['兼容业务通知','原来源映射、产业接口人与通知队列'],overview:['工作总览','团队工作一目了然,每一次协作都有记录'],calendar:['业务日历','按公司实际安排设置工作日、休息日与暂停日期'],exceptions:['异常待办','认领、转交和跟进异常'],bpm:['BPM 连接','管理连接及负责人'],supervisor:['运行监管','配置负责人、通知方式与重试上限'],records:['订单与导出记录','查询已经采集的订单,下载已完成的 PDF'],rules:['分类通知规则','按 Excel 类别配置匹配、归档与邮件,查看订单和批次状态'],schedule:['发送计划','设置每日两个发送时间及周末安排'],templates:['邮件模板','管理模板及 Excel 类别关联;收件名单在分类规则维护'],mail:['邮箱管理','维护托管邮箱、模板收信与连接状态'],connections:['服务接入','查看各个环节的接入情况'],users:['团队账号','为局域网内的同事分配访问权限'],audit:['操作记录','查看配置变更和导出任务的处理记录']}; +let currentUser=null,settings=null,currentView='overview',overview=null,refreshTimer=null,viewGeneration=0,historyIndex=0,historyTransition=null,automationRevision=0,overviewRevision=0; +const views={'order-notifications':['通知总览','查看当前发送时段、待发订单及接入阻塞'],'notification-execution':['订单执行','扫描真实待办,查看归档进度与受控恢复'],'notification-orders':['通知订单','查看订单分类、归档证据及所属邮件批次'],'notification-batches':['待发批次','按发送时段检查分类汇总和冻结内容'],'notification-history':['发送记录','核对发送结果、冻结内容和人工恢复记录'],'notification-settings':['发送设置','维护发件邮箱、邮件限制与自动通知开关'],'rule-fields':['字段映射','从真实 BPM 样本选择字段,按表单版本保存对应关系'],'assistant-settings':['助手设置','配置 ZCode 运行包、模型与受控操作权限'],'business-settings':['业务设置','维护 Excel 分类规则、收件人和真实字段对应'],'system-settings':['系统设置','集中管理服务连接、运行维护和团队权限'],account:['个人账号','维护自己的登录密码与访问安全'],'order-rules':['分类通知规则','按 Excel 类别维护匹配、归档、收件人与通知正文'],health:['系统健康','查看服务守护、登录自启和各模块最近检查结果'],assistant:['ZCode 助手','对话查询运行状态、分析异常与执行受控恢复'],storage:['存储服务器','配置 SMB 共享目录、检查连接与管理 PDF 归档'],notifications:['兼容业务通知','原来源映射、产业接口人与通知队列'],overview:['工作总览','团队工作一目了然,每一次协作都有记录'],calendar:['业务日历','按公司实际安排设置工作日、休息日与暂停日期'],exceptions:['异常待办','认领、转交和跟进异常'],bpm:['BPM 连接','管理连接及负责人'],supervisor:['运行监管','配置负责人、通知方式与重试上限'],records:['订单与导出记录','查询已经采集的订单,下载已完成的 PDF'],rules:['分类通知规则','按 Excel 类别维护匹配、归档、收件人与通知正文'],schedule:['发送计划','设置每日两个发送时间及周末安排'],templates:['邮件模板','管理模板及 Excel 类别关联;收件名单在分类规则维护'],mail:['邮箱管理','维护托管邮箱、模板收信与连接状态'],connections:['服务接入','查看各个环节的接入情况'],users:['团队账号','为局域网内的同事分配访问权限'],audit:['操作记录','查看配置变更和导出任务的处理记录']}; const pendingWrites=new Map(); async function api(route,body,{signal,ownerCheck}={}) { const originGeneration=viewGeneration,originUser=currentUser,originRevision=window.PageLifecycle?.revision;const originActive=()=>viewGeneration===originGeneration&¤tUser===originUser&&window.PageLifecycle?.revision===originRevision;const submission=window.PageLifecycle?.submission,write=body!==undefined,key=originGeneration+':'+originRevision+':'+route+':'+JSON.stringify(body);const pending=pendingWrites.get(key);if(write&&pending?.user===originUser)return pending.work; @@ -30,9 +30,9 @@ function notify(message,type='success') { const flash=document.createElement('div');flash.id='flash';flash.className='alert alert-'+type+' shadow';flash.setAttribute('role','alert');flash.textContent=message;document.body.append(flash);setTimeout(()=>flash.remove(),6500); } function badge(status){const [label,color]=statusMap[status] || ['待处理','secondary'];return `${label}`;} -function navItem(id,symbol){return ``;} +function navItem(id,symbol){return ``;} function shell() { - root.innerHTML=`
订单通知中心 · 局域网工作台
UI 基于 Tabler · MIT
`; + root.innerHTML=`
订单通知中心 · 局域网工作台
UI 基于 Tabler · MIT
`; document.querySelector('#logout').onclick=()=>window.PageLifecycle.guard(async()=>{++viewGeneration;await window.BpmLogin?.dispose();await api('/logout',{});currentUser=null;clearInterval(refreshTimer);await window.PageLifecycle.dispose();await boot();}); document.querySelector('#refresh').onclick=()=>window.PageLifecycle.guard(()=>renderView()).catch(error=>notify(error.message,'danger')); document.querySelectorAll('[data-view]').forEach(link=>link.onclick=()=>{const menu=document.querySelector('#sidebar-menu');menu.classList.remove('show');if(menu.classList.contains('collapsing'))menu.addEventListener('shown.bs.collapse',()=>menu.classList.remove('show'),{once:true});document.querySelector('.navbar-toggler').setAttribute('aria-expanded','false');}); @@ -42,12 +42,15 @@ function readOnlyNote(){return currentUser.role==='admin'?'':`
${esc(job.metadata?.order || '未记录订单号')}
${esc(job.metadata?.serial || '')}
${esc(job.metadata?.project || '—')}
${esc(job.metadata?.model || '')}
${badge(job.status)}${job.error?`
${esc(job.error)}
`:''}${formatDate(job.updatedAt)}${job.downloadable?`下载 PDF`:'—'}`).join('');} function jobTable(jobs){return `
${jobRows(jobs)}
订单 / 通知书编号项目 / 型号状态更新时间
`;} async function viewOverview(container,isActive=()=>true) { - if(window.WorkspaceViews)return window.WorkspaceViews.overview(container,isActive); - await api('/workspace');if(!isActive())return; - container.innerHTML=empty('工作台模块未加载','请刷新页面后重试。'); + const revision=++overviewRevision,ownsResponse=()=>revision===overviewRevision&&isActive(); + try{ + if(window.WorkspaceViews)return await window.WorkspaceViews.overview(container,ownsResponse); + await api('/workspace');if(!ownsResponse())return; + container.innerHTML=empty('工作台模块未加载','请刷新页面后重试。'); + }catch(error){if(ownsResponse())throw error;} } async function viewRecords(container,isActive=()=>true) { - await window.OrderViews.records(container,isActive,viewPdfRecords);if(!isActive())return;const history=document.createElement('section');history.className='mt-3';history.innerHTML='
';container.append(history);history.querySelector('button').onclick=async event=>{const button=event.currentTarget;button.disabled=true;try{await window.NotificationViews.history(history.querySelector('#legacy-notification-history'),isActive);}catch(error){if(isActive())notify(error.message,'danger');}finally{if(button.isConnected)button.disabled=false;}}; + await window.OrderViews.records(container,isActive,viewPdfRecords);if(!isActive())return;const notice=document.createElement('div');notice.className='alert alert-info';notice.innerHTML='此处查询采集与 PDF 导出记录;分类和邮件批次请到 通知订单 查看。';container.prepend(notice);const history=document.createElement('section');history.className='mt-3';history.innerHTML='
';container.append(history);history.querySelector('button').onclick=async event=>{const button=event.currentTarget;button.disabled=true;try{await window.NotificationViews.history(history.querySelector('#legacy-notification-history'),isActive);}catch(error){if(isActive())notify(error.message,'danger');}finally{if(button.isConnected)button.disabled=false;}}; } async function viewPdfRecords(container,isActive=()=>true) { const {jobs}=await api('/jobs');if(!isActive())return; @@ -58,7 +61,7 @@ async function viewPdfRecords(container,isActive=()=>true) { } async function viewSchedule(container,isActive=()=>true) { const loaded=await api('/settings');if(!isActive())return;let draft=loaded;const s=draft.schedule;const disabled=currentUser.role!=='admin'?'disabled':''; - container.innerHTML=`
${readOnlyNote()}
新分类通知在 分类通知规则 配置,按本时段内 Excel 类别汇总,更早历史不补发。按北京时间执行;不自动追补更早历史。

每日两次通知

北京时间
关闭后仅在周一至周五发送;公司调休与暂停安排可在 业务日历 中按日期覆盖。
`; + container.innerHTML=`
${readOnlyNote()}
收件人及类别要求在 分类通知规则 维护。按北京时间和业务日历生成发送时段,更早历史不自动补发。

每日两次通知

北京时间
关闭后仅在周一至周五发送;公司调休与暂停安排可在 业务日历 中按日期覆盖。
`; document.querySelector('#schedule-form').onsubmit=async event=>{event.preventDefault();try{const updated=await api('/settings',{version:draft.version,schedule:{...draft.schedule,times:[document.querySelector('#time-first').value,document.querySelector('#time-second').value],timezone:'Asia/Shanghai',weekends:document.querySelector('#weekends').checked}});if(!isActive())return;draft=updated;notify('发送计划已保存。');}catch(error){if(isActive())notify(error.message,'danger');}}; } async function viewTemplates(container,isActive=()=>true) { @@ -69,7 +72,24 @@ async function viewTemplates(container,isActive=()=>true) { host.querySelectorAll('form').forEach(form=>form.onsubmit=async event=>{event.preventDefault();const binding=catalog.bindings.find(b=>b.categoryId===form.dataset.category);try{const result=await api('/mail/templates/categories',{categoryId:form.dataset.category,templateId:form.elements.templateId.value,version:binding?.version??0});if(!isActive())return;catalog.bindings=catalog.bindings.filter(b=>b.categoryId!==result.categoryId).concat(result);form.querySelector('[role="alert"]').textContent='';await window.PageLifecycle.afterSave(async()=>{const fresh=await api('/mail/templates/categories');if(isActive())catalog.bindings=fresh.bindings;},'类别模板关联已保存。',notify,isActive);}catch(error){if(isActive())form.querySelector('[role="alert"]').textContent=error.message;}}); } async function viewAudit(container,isActive=()=>true){const [legacy,workspace]=await Promise.all([api('/audit'),api('/workspace')]);if(!isActive())return;const audit=[...legacy.audit,...workspace.audit].sort((a,b)=>new Date(b.at)-new Date(a.at));container.innerHTML=`

最近操作记录

按时间展示最近 200 条
${audit.length?`
${audit.slice(0,200).map(item=>``).join('')}
时间(北京时间)操作人操作详情
${formatDate(item.at)}${esc(item.actor)}${esc(window.WorkspaceViews.activityText(item.action))}${esc(item.detail)}
`:empty('暂无操作记录','保存设置或导出订单后,可在这里查看。')}
`;} -function viewRules(container,isActive){return window.OrderRuleViews.render(container,isActive);} +function viewRules(container,isActive){return window.OrderRuleViews.render(container,isActive,'rules');} +async function updateAutomationStatus(isActive){ + const request=++automationRevision,node=document.querySelector('#automation-status');if(!node||!isActive())return; + const apply=(label,color,detail)=>{if(!isActive()||request!==automationRevision||!node.isConnected)return;node.textContent=label;node.className='badge bg-'+color+'-lt text-decoration-none';node.title=detail;}; + try{ + const data=await api('/order-rules',undefined,{ownerCheck:isActive});if(!isActive())return; + if(typeof data?.settings?.enabled!=='boolean')throw Error('服务端未返回有效通知开关'); + const missing=Object.entries({liveTodo:'实时待办接入',pdfExport:'PDF 导出',automaticArchive:'自动归档'}).filter(([key])=>data.capabilities?.[key]!==true).map(([,label])=>label); + if(!data.settings.enabled)apply('自动通知已暂停','secondary','自动发信保持暂停;请完成类别字段、目录、邮箱与预览核验。'+(missing.length?' 待检查:'+missing.join('、'):' 点击查看发送设置。')); + else if(missing.length)apply('自动通知受阻','yellow','未通过实际检查:'+missing.join('、')+'。点击查看发送设置。'); + else apply('自动通知已启用','green','通知开关已启用;实际任务、类别及批次仍按各自检查结果执行。'); + }catch(error){apply('通知状态待确认','yellow',error.message+';请刷新重试。');} +} +function configurationHost(container){ + container.innerHTML='
'; + window.AppNavigation.renderConfiguration(container.querySelector('#notification-config-tabs'),{id:currentView,views,esc}); + return container.querySelector('#notification-config-content'); +} async function renderView() { if(!currentUser)return; const generation=++viewGeneration;const isActive=()=>generation===viewGeneration && !!currentUser; @@ -81,12 +101,15 @@ async function renderView() { const section=window.AppNavigation.sectionFor(currentView); window.AppNavigation.renderTabs(document.querySelector('#settings-tabs'),{id:currentView,user:currentUser,views,esc}); document.querySelectorAll('[data-view]').forEach(link=>{const active=link.dataset.view===(section||currentView);link.classList.toggle('active',active);if(active)link.setAttribute('aria-current','page');else link.removeAttribute('aria-current');}); - const breadcrumb=document.querySelector('#view-breadcrumb');breadcrumb.hidden=!section||section===currentView;breadcrumb.innerHTML=breadcrumb.hidden?'':`← ${views[section][0]} / ${esc(views[currentView][0])}`; + const sectionTitle=section==='order-notifications'?'订单通知管理':views[section]?.[0]; + const breadcrumb=document.querySelector('#view-breadcrumb');breadcrumb.hidden=!section||section===currentView;breadcrumb.innerHTML=breadcrumb.hidden?'':`← ${sectionTitle} / ${esc(views[currentView][0])}`; document.querySelector('#view-title').textContent=views[currentView][0];document.querySelector('#view-description').textContent=views[currentView][1]; const container=document.querySelector('#content');container.innerHTML='
正在加载…
'; - const fn={'assistant-settings':window.AssistantViews?.settings,account:window.AccountViews?.account,'order-rules':window.OrderRuleViews?.render,health:window.HealthViews?.render,assistant:window.AssistantViews?.render,storage:window.StorageViews?.render,overview:viewOverview,calendar:window.WorkspaceViews?.calendar,exceptions:window.WorkspaceViews?.exceptions,bpm:window.WorkspaceViews?.bpm,records:viewRecords,schedule:viewSchedule,templates:viewTemplates,mail:window.MailViews?.accounts,users:window.AccountViews?.users,audit:viewAudit,rules:viewRules}[currentView]; - try{window.PageLifecycle?.attach(container);await fn(container,isActive);if(isActive())window.PageLifecycle?.bind();}catch(error){if(isActive())container.innerHTML=`
${esc(error.message)}
`;} + const notificationSections={'order-notifications':'workbench','notification-execution':'execution','notification-orders':'orders','notification-batches':'pending','notification-history':'history','notification-settings':'settings'}; + const fn={'rule-fields':(host,active)=>window.OrderRuleViews.render(host,active,'fields'),...Object.fromEntries(Object.entries(notificationSections).map(([route,section])=>[route,(host,active)=>window.OrderNotificationViews.render(host,active,section)])),'assistant-settings':window.AssistantViews?.settings,account:window.AccountViews?.account,'order-rules':window.OrderRuleViews?.render,health:window.HealthViews?.render,assistant:window.AssistantViews?.render,storage:window.StorageViews?.render,overview:viewOverview,calendar:window.WorkspaceViews?.calendar,exceptions:window.WorkspaceViews?.exceptions,bpm:window.WorkspaceViews?.bpm,records:viewRecords,schedule:viewSchedule,templates:viewTemplates,mail:window.MailViews?.accounts,users:window.AccountViews?.users,audit:viewAudit,rules:viewRules}[currentView]; + void updateAutomationStatus(isActive); + try{window.PageLifecycle?.attach(container);const host=window.AppNavigation.isConfiguration(currentView)?configurationHost(container):container;await fn(host,isActive);if(isActive())window.PageLifecycle?.bind();}catch(error){if(isActive())container.innerHTML=`
${esc(error.message)}
`;} } async function authScreen() { const setup=await api('/bootstrap/status');const initialize=setup.required && setup.canSetup; @@ -95,7 +118,7 @@ async function authScreen() { } async function passwordChanged(actorId){if(currentUser&¤tUser.id!==actorId)return false;currentUser=null;++viewGeneration;clearInterval(refreshTimer);await window.PageLifecycle?.dispose();await window.BpmLogin?.dispose().catch(()=>{});await boot();return true;} -function enter(){window.AccountViews?.configure({api,esc,formatDate,notify,user:currentUser,onPasswordChanged:passwordChanged});window.OrderRuleViews?.configure({api,esc,formatDate,notify,user:currentUser});window.HealthViews?.configure({api,esc,formatDate});window.AssistantViews?.configure({api,esc,formatDate,notify,user:currentUser});window.StorageViews?.configure({api,esc,formatDate,notify,user:currentUser});window.NotificationViews?.configure({api,esc,formatDate,notify,user:currentUser});window.OrderViews?.configure({api,esc,formatDate,notify,user:currentUser});window.MailViews?.configure({api,esc,formatDate,notify,user:currentUser});window.WorkspaceViews?.configure({api,esc,formatDate,notify,user:currentUser});shell();renderView();clearInterval(refreshTimer);refreshTimer=setInterval(()=>{if(currentUser && currentView==='overview' && !document.hidden){const generation=++viewGeneration;viewOverview(document.querySelector('#content'),()=>generation===viewGeneration && !!currentUser && currentView==='overview').catch(()=>{});}},15000);} +function enter(){window.AccountViews?.configure({api,esc,formatDate,notify,user:currentUser,onPasswordChanged:passwordChanged});window.OrderRuleViews?.configure({api,esc,formatDate,notify,user:currentUser});window.OrderNotificationViews?.configure({api,esc,formatDate,notify,user:currentUser});window.HealthViews?.configure({api,esc,formatDate});window.AssistantViews?.configure({api,esc,formatDate,notify,user:currentUser});window.StorageViews?.configure({api,esc,formatDate,notify,user:currentUser});window.NotificationViews?.configure({api,esc,formatDate,notify,user:currentUser});window.OrderViews?.configure({api,esc,formatDate,notify,user:currentUser});window.MailViews?.configure({api,esc,formatDate,notify,user:currentUser});window.WorkspaceViews?.configure({api,esc,formatDate,notify,user:currentUser});shell();renderView();clearInterval(refreshTimer);refreshTimer=setInterval(()=>{if(currentUser&&!document.hidden){const statusGeneration=viewGeneration,statusUser=currentUser;void updateAutomationStatus(()=>statusGeneration===viewGeneration&&statusUser===currentUser);}if(currentUser && currentView==='overview' && !document.hidden){const generation=viewGeneration;viewOverview(document.querySelector('#content'),()=>generation===viewGeneration && !!currentUser && currentView==='overview').catch(()=>{});}},15000);} async function boot(){try{const setup=await api('/bootstrap/status');currentUser=(await api('/me')).user;enter();}catch{await authScreen();}} window.addEventListener('page-operation-error',event=>notify(event.detail.message,'danger')); window.addEventListener('pagehide',()=>{window.BpmLogin?.dispose({unload:true});}); diff --git a/web/index.html b/web/index.html index 50e8d4c..9892eb5 100644 --- a/web/index.html +++ b/web/index.html @@ -1,3 +1,3 @@ 订单通知中心 -
正在连接订单通知中心…
+
正在连接订单通知中心…
diff --git a/web/modules/navigation/view.js b/web/modules/navigation/view.js index 7bb6304..6abb401 100644 --- a/web/modules/navigation/view.js +++ b/web/modules/navigation/view.js @@ -1,10 +1,50 @@ 'use strict'; window.AppNavigation=(()=>{ - const primary=[['overview','▦'],['records','≡'],['exceptions','☷'],['assistant','Z'],['business-settings','▤'],['system-settings','⚙']]; - const groups={'business-settings':['order-rules','schedule','calendar','templates'],'system-settings':['bpm','mail','storage','assistant-settings','health','users','audit']}; + const primary=[['overview','overview'],['order-notifications','mail'],['records','file'],['exceptions','alert'],['assistant','spark'],['business-settings','rules'],['system-settings','settings']]; + const groups={ + 'order-notifications':['order-notifications','notification-execution','notification-orders','notification-batches','notification-history','schedule'], + 'business-settings':['order-rules','rule-fields'], + 'system-settings':['bpm','mail','storage','assistant-settings','health','users','audit'] + }; + const configuration=['schedule','calendar','templates','notification-settings']; const aliases={'business-settings':'order-rules','system-settings':'bpm',rules:'order-rules',notifications:'order-rules',supervisor:'health',connections:'health'}; + const icons={ + overview:'M4 4h6v6H4z M14 4h6v6h-6z M4 14h6v6H4z M14 14h6v6h-6z', + mail:'M4 5h16v14H4z M4 6l8 6 8-6', + file:'M14 3H6v18h12V7z M14 3v5h4 M9 12h6 M9 16h6', + alert:'M12 3L2 21h20z M12 9v4 M12 17v.01', + spark:'M12 3l2.5 6.5L21 12l-6.5 2.5L12 21l-2.5-6.5L3 12l6.5-2.5z', + rules:'M9 6h11 M9 12h11 M9 18h11 M4 6h.01 M4 12h.01 M4 18h.01', + settings:'M4 7h16 M4 17h16 M8 4v6 M16 14v6', + play:'M8 4l12 8-12 8z', + fields:'M4 4h16v16H4z M4 10h16 M10 4v16', + batches:'M4 7l8-4 8 4-8 4z M4 12l8 4 8-4 M4 17l8 4 8-4', + history:'M3 11a9 9 0 1 1 3 8 M3 4v7h7 M12 7v5l3 2', + calendar:'M4 5h16v16H4z M8 3v4 M16 3v4 M4 11h16', + link:'M10 13a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-2 2 M14 11a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l2-2', + users:'M8 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8z M2 21v-3a6 6 0 0 1 12 0v3 M17 3a4 4 0 0 1 0 8 M18 15a5 5 0 0 1 4 5' + }; + const routeIcons={'order-notifications':'overview','notification-execution':'play','notification-orders':'file','notification-batches':'batches','notification-history':'history',schedule:'calendar',calendar:'calendar',templates:'mail','notification-settings':'settings','order-rules':'rules','rule-fields':'fields',bpm:'link',mail:'mail',storage:'batches','assistant-settings':'spark',health:'alert',users:'users',audit:'history'}; const resolve=id=>aliases[id]||id; - function sectionFor(id){id=resolve(id);return Object.keys(groups).find(section=>groups[section].includes(id))||null;} - function renderTabs(container,{id,user,views,esc}){const section=sectionFor(id);container.hidden=!section;container.innerHTML=section?groups[section].filter(item=>item!=='users'||user.role==='admin').map(item=>`${esc(views[item][0])}`).join(''):'';} - return {primary,groups,resolve,sectionFor,renderTabs}; + const isConfiguration=id=>configuration.includes(resolve(id)); + function sectionFor(id){id=resolve(id);if(isConfiguration(id))return 'order-notifications';return Object.keys(groups).find(section=>groups[section].includes(id))||null;} + function icon(name){return ``;} + function reveal(container){ + const active=container.querySelector('.active');if(!active)return; + const box=container.getBoundingClientRect(),item=active.getBoundingClientRect(); + if(item.leftbox.right-5)container.scrollLeft+=item.right-box.right+5; + } + function links(ids,active,{views,esc},labels={}){return ids.map(id=>`${icon(routeIcons[id])}${esc(labels[id]||views[id][0])}`).join('');} + function renderTabs(container,{id,user,views,esc}){ + const section=sectionFor(id);container.hidden=!section; + container.className='nav nav-segmented settings-tabs';container.setAttribute('aria-label',section==='order-notifications'?'订单通知管理导航':section==='business-settings'?'业务设置导航':'系统设置导航'); + container.innerHTML=section?links(groups[section].filter(item=>item!=='users'||user.role==='admin'),isConfiguration(id)?'schedule':id,{views,esc},{schedule:'通知配置'}):''; + reveal(container); + } + function renderConfiguration(container,{id,views,esc}){ + container.innerHTML=links(configuration,id,{views,esc});reveal(container); + } + window.addEventListener('resize',()=>document.querySelectorAll('.settings-tabs').forEach(reveal),{passive:true}); + return {primary,groups,configuration,resolve,sectionFor,renderTabs,renderConfiguration,isConfiguration,icon}; })(); diff --git a/web/modules/order-notifications/shared.js b/web/modules/order-notifications/shared.js new file mode 100644 index 0000000..6e89ea4 --- /dev/null +++ b/web/modules/order-notifications/shared.js @@ -0,0 +1,21 @@ +(() => { + 'use strict'; + window.OrderNotificationShared={create({esc}){ + const statuses={draft:'草稿',enabled:'已发布',paused:'已暂停',identified:'已识别',preparing:'准备中',archived:'已归档',pending:'待发',batched:'已编入批次',blocked:'受阻',prepared:'已准备',sending:'发送中',sent:'已提交邮件服务器',failed:'失败',unknown:'结果待核实',cancelled:'已取消',ignored:'更早历史,不补发'}; + const status=s=>`${esc(statuses[s]||s||'未记录')}`; + const empty=text=>`
${esc(text)}
`; + const table=(heads,rows,none)=>`
${heads.map(h=>``).join('')}${rows.join('')||``}
${h}
${empty(none)}
`; + const list=v=>(v||[]).join('、')||'未配置'; + const operationKey=(form,body)=>{const signature=JSON.stringify(body);if(form.dataset.requestSignature!==signature){form.dataset.requestSignature=signature;form.dataset.requestKey=window.PageLifecycle.requestKey();}return form.dataset.requestKey;}; + const capabilityNames={liveTodo:'实时待办接入',pdfExport:'通知书 PDF 导出',automaticArchive:'自动归档'}; + const ready=c=>Object.keys(capabilityNames).every(k=>c[k]===true); + function capabilities(c){return `
${Object.entries(capabilityNames).map(([key,label])=>`
${c[key]===true?'已就绪':'待联调'}${label}
`).join('')}
`;} + + function capabilityBlockers(c){ + const checks=[['liveTodo','实时待办接入尚未验证,不能自动采集订单。','#bpm','检查 BPM 连接'],['pdfExport','通知书 PDF 导出尚未验证,不能提供附件证据。','#rule-fields','核实真实字段'],['automaticArchive','自动归档尚未验证,不能确认文件已安全归档。','#storage','检查存储服务器']]; + const missing=checks.filter(([key])=>c[key]!==true); + return missing.length?`
自动执行受阻${missing.map(([,reason,href,label])=>`
${esc(reason)} ${label}
`).join('')}
`:''; + } + return {capabilityBlockers,status,empty,table,list,operationKey,capabilities,ready}; + }}; +})(); diff --git a/web/modules/order-notifications/view.js b/web/modules/order-notifications/view.js new file mode 100644 index 0000000..999ac80 --- /dev/null +++ b/web/modules/order-notifications/view.js @@ -0,0 +1,52 @@ +(() => { + 'use strict'; + let api,esc,formatDate,notify,user; + const helpers=()=>window.OrderNotificationShared.create({esc}); + async function render(container,isActive=()=>true,section='workbench'){ + const {status,empty,table,list,operationKey,capabilities,capabilityBlockers,ready}=helpers(); + const tab=['workbench','execution','orders','pending','history','settings'].includes(section)?section:'workbench'; + const [snapshot,mail,overview]=await Promise.all([api('/order-rules'),tab==='settings'?api('/mail').catch(error=>({channels:[],error:error.message})):Promise.resolve({channels:[]}),tab==='workbench'?api('/overview').catch(()=>({nextSlots:[]})):Promise.resolve({nextSlots:[]})]);if(!isActive())return; + const data={rules:[],adapters:[],orders:[],batches:[],audit:[],settings:{},capabilities:{},...snapshot},admin=user.role==='admin',operator=user.role!=='viewer'; + let dirty=false,refreshing=false,timer,panelRevision=0,executionController=null; + container.innerHTML=`
分类通知${data.settings.enabled?'已启用':'自动执行已暂停'}。按 Excel 类别汇总,本时段内同类别订单合并一封,更早历史不补发;通知与更改单独归类,BPM 节点由人工办理。
时段与运行状态每 15 秒刷新
`; + const panel=container.querySelector('#order-rules-panel'); + const feedback=(message,type='success')=>{if(!isActive())return;const node=container.querySelector('#order-rules-feedback');node.textContent=message;node.className='alert alert-'+type;}; + async function action(button,work){if(button)button.disabled=true;try{await work();}catch(error){feedback(error.message,'danger');}finally{if(button?.isConnected)button.disabled=false;}} + async function saved(message){if(!isActive())return false;dirty=false;return window.PageLifecycle.afterSave(reload,message,feedback,isActive);} + async function reload(){if(!isActive())return false;const [fresh,freshMail]=await Promise.all([api('/order-rules'),tab==='settings'?api('/mail').catch(error=>({channels:[],error:error.message})):Promise.resolve(null)]);if(!isActive())return false;Object.assign(data,fresh);if(freshMail){delete mail.error;Object.assign(mail,freshMail);}syncState();dirty=false;draw();return true;} + function syncState(){const node=container.querySelector('#order-rule-state');node.className='alert alert-'+(data.settings.enabled?'success':'info');node.textContent='分类通知'+(data.settings.enabled?'已启用':'自动执行已暂停')+'。按 Excel 类别汇总,本时段内同类别订单合并一封,更早历史不补发;通知与更改单独归类,BPM 节点由人工办理。';} + function keepInputs(){return window.PageLifecycle?.dirty()||tab==='execution'||dirty||tab==='settings'||[...panel.querySelectorAll('textarea')].some(input=>input.value.trim());} + async function refreshStatus(){if(refreshing)return;refreshing=true;try{const [fresh,nextOverview]=await Promise.all([api('/order-rules'),tab==='workbench'?api('/overview').catch(error=>({nextSlots:[],error:error.message})):Promise.resolve(null)]);if(!isActive())return;Object.assign(data,fresh);if(nextOverview)Object.assign(overview,nextOverview);syncState();container.querySelector('#order-rule-updated').textContent='时段与状态更新于 '+formatDate(new Date().toISOString());if(tab==='execution'&&executionController)await executionController.refresh();if(!keepInputs())draw();}finally{refreshing=false;}} + function ordersTable(orders){return table(['订单 / 类别','状态与原因','接收时间'],orders.map(o=>`${esc(o.orderNo||o.event?.orderNo||'订单号未提供')}
${esc(data.rules.find(r=>r.categoryId===o.categoryId)?.name||o.categoryId||'未分类')}
查看订单信息
流程:${esc(o.processName||o.event?.processName||'—')}
节点:${esc(o.nodeName||o.event?.nodeName||'—')}
流程实例:${esc(o.instanceId||o.event?.instanceId||'—')}
任务:${esc(o.taskId||o.event?.taskId||'—')}
来源版本:${esc(o.revision||o.event?.revision||'—')}
批次:${esc(o.batchId||'未编入批次')}
规则版本:${esc(o.ruleVersion??o.ruleSnapshot?.publishedVersion??o.ruleSnapshot?.version??'—')}
归档证据:${esc(o.archiveEvidence?JSON.stringify(o.archiveEvidence):o.archive?JSON.stringify(o.archive):'未记录')}
查看待发批次 · 查看导出记录
数量:${esc(o.quantity??o.event?.quantity??'—')}
${esc(o.brief||o.event?.brief||'')}
${status(o.status)}${o.error||o.reason?`
${esc(o.error||o.reason)}
`:''}${admin&&!o.batchId&&['pending','blocked'].includes(o.status)?`
按当前发布规则重新核对

重新匹配会清除原归档证据,需重新校验和归档;更早历史仍不补发。

`:''}${formatDate(o.receivedAt||o.event?.receivedAt||o.createdAt)}`),'暂无订单记录。样本预览不会创建订单。');} + function batchesTable(batches,pending){return table(['类别 / 主题','订单与收件人','状态'],batches.map(b=>`${esc(b.subject||b.categoryId)}
${esc(b.categoryId)} · ${formatDate(b.createdAt)}
查看冻结内容
业务时段:${formatDate(b.windowStart)} 至 ${formatDate(b.windowEnd||b.cutoff)}
收件人:${esc(list(b.to))}
抄送:${esc(list(b.cc))}
附件:${esc((b.attachments||[]).map(a=>a.name||a.filename).join('、')||'无')}
${esc(b.text||'')}
${esc(list(b.orderNos||b.orderIds))}
${esc(list(b.to))}
${status(b.status)}${b.error?`
${esc(b.error)}
`:''}${b.status==='failed'&&admin?`

人工补发沿用原冻结内容和收件人。

`:''}${b.status==='unknown'&&admin?`
`:''}`),pending?'暂无待发批次':'暂无发送记录');} + function windowInfo(){const w=data.window;return w&&Number.isFinite(Date.parse(w.start))&&Number.isFinite(Date.parse(w.end))&&Date.parse(w.start)=Date.parse(w.start)&&at

本时段范围

${w?`${esc(w.label||'配置发送时段')}`:''}
${w?`${formatDate(w.start)} 至 ${formatDate(w.end)}
以订单接收时间归入时段。本时段内同类别订单合并一封,更早历史不补发。
`:`
${esc(data.window?.error||'当前没有已确认的发送时段。请先确认发送计划及工作日规则。')}
`}${prepare&&admin?`
${w&&w.available!==true?'未到配置发送时点,当前只预览。':''}按服务器确定的时段整理已接入订单并冻结规则和附件,不发送邮件。缺少归档证据时将阻塞该类别。
`:''}
`;} + function windowOrders(){const groups=new Map();for(const order of data.orders.filter(o=>inWindow(o)&&['pending','blocked','archived','preparing','identified'].includes(o.status))){const id=order.categoryId||'未分类';if(!groups.has(id))groups.set(id,[]);groups.get(id).push(order);}return `

本时段订单 · 按类别预览

${groups.size?[...groups.entries()].map(([id,orders])=>`
${esc(data.rules.find(r=>r.categoryId===id)?.name||id)}${orders.length} 单
${ordersTable(orders)}
`).join(''):empty('本时段暂无待整理订单;更早历史不计入。')}
`;} + function drawWorkbench(){ + panel.innerHTML=`
${windowCard()}

下一发送时点

${(overview.nextSlots||[]).map(slot=>`
${formatDate(slot)}
`).join('')||empty('服务器未提供下一发送时点,请检查发送计划与业务日历。')}发送计划 · 业务日历
${[['已发布规则',data.rules.filter(r=>r.publishedVersion||r.status==='enabled').length],['本时段待发订单',data.orders.filter(o=>inWindow(o)&&['pending','batched'].includes(o.status)).length],['本时段受阻订单',data.orders.filter(o=>inWindow(o)&&o.status==='blocked').length],['结果待核实',data.batches.filter(b=>b.status==='unknown').length]].map(([label,count])=>`
${label}
${count}项
`).join('')}

接入状态

${capabilities(data.capabilities)}${capabilityBlockers(data.capabilities)}订单执行 · 通知订单 · 待发批次 · 通知设置

规则草稿和样本试运行可独立配置;自动执行需全部接入就绪并由管理员启用。样本结构核验不等于实时接口验证。

本时段受阻订单

${ordersTable(data.orders.filter(o=>inWindow(o)&&o.status==='blocked'))}
`; + } + function drawSettings(){ + const config=data.settings,canEnable=ready(data.capabilities)&&!mail.error,disabled=admin?'':'disabled'; + panel.innerHTML=`

分类通知设置

${capabilities(data.capabilities)}${capabilityBlockers(data.capabilities)}${mail.error?`
邮箱目录读取失败:${esc(mail.error)}。检查邮箱连接
`:''}${!canEnable?'
自动执行待联调。可保存邮箱与附件大小限制;全部接入验证通过后才可启用。
':''}

发送时段与工作日可在 发送计划、业务日历 配置。分类通知按配置时段内的 Excel 类别汇总,更早历史不补发;旧通用通知调度已停用,收件人统一在分类规则维护。

${admin?'':''}
`; + if(admin)panel.querySelector('form').onsubmit=e=>{e.preventDefault();const form=e.currentTarget;return action(e.submitter,async()=>{const result=await api('/order-rules/settings',{version:config.version,channelId:form.elements.channelId.value,maxMessageBytes:Math.round(Number(form.elements.maxSize.value)*1048576),enabled:canEnable&&form.elements.enabled.checked});if(!isActive())return;Object.assign(config,result);await saved('分类通知设置已保存。');});}; + } + function draw(){ + if(!isActive())return;const drawnRevision=++panelRevision,drawnTab=tab;executionController=null; + if(tab==='workbench')drawWorkbench();else if(tab==='settings')drawSettings();else if(tab==='execution'){panel.innerHTML=empty('正在加载…');window.OrderExecutionViews[tab](panel,{api,esc,formatDate,user,isActive:()=>isActive()&&panelRevision===drawnRevision&&tab===drawnTab,feedback}).then(controller=>{if(isActive()&&panelRevision===drawnRevision)executionController=controller;}).catch(error=>{if(!isActive()||panelRevision!==drawnRevision)return;panel.innerHTML=empty('数据加载未完成,请刷新重试。');feedback(error.message,'danger');});} + else if(tab==='orders')panel.innerHTML=`

订单记录 · ${data.orders.length}

${ordersTable(data.orders)}
`; + else if(tab==='pending')panel.innerHTML=`${windowCard(true)}${windowOrders()}

本时段待发批次

${batchesTable(data.batches.filter(b=>{const w=windowInfo();return w&&['prepared','sending','unknown','failed'].includes(b.status)&&Date.parse(b.windowStart)===Date.parse(w.start)&&Date.parse(b.windowEnd||b.cutoff)===Date.parse(w.end);}),true)}
`; + else if(tab==='history')panel.innerHTML=`
“已提交邮件服务器”表示 SMTP 接受,不代表最终送达。结果不明的批次须人工核实。

发送记录

${batchesTable(data.batches.filter(b=>['sent','cancelled','failed','unknown'].includes(b.status)),false)}

规则与执行操作记录

${table(['时间','操作人 / 操作','说明'],data.audit.map(a=>`${formatDate(a.at||a.createdAt)}${esc(a.actor?.username||a.actor||'系统')}
${esc(a.action)}
${esc(typeof a.detail==='object'?JSON.stringify(a.detail):a.detail||a.note||'')}`),'暂无操作记录')}
`; + const prepare=panel.querySelector('#order-rule-prepare');if(prepare)prepare.onsubmit=e=>{e.preventDefault();const w=windowInfo();if(!w||w.available!==true)return;return action(e.submitter,async()=>{await api('/order-rules/prepare',{cutoff:w.end});await saved('本时段批次整理已完成,请查看实际批次与受阻原因。');});}; + panel.querySelectorAll('[data-rule-recheck]').forEach(form=>form.onsubmit=e=>{e.preventDefault();return action(e.submitter,async()=>{await api('/order-rules/orders/'+encodeURIComponent(form.dataset.ruleRecheck)+'/recheck',{note:form.elements.note.value});await saved('此订单已重新核对,请检查新匹配结果及归档状态。');});}); + panel.querySelectorAll('[data-rule-resend]').forEach(form=>form.onsubmit=e=>{e.preventDefault();const batch=data.batches.find(b=>b.id===form.dataset.ruleResend);return action(e.submitter,async()=>{await api('/order-rules/batches/'+encodeURIComponent(batch.id)+'/resend',{version:batch.version,idempotencyKey:operationKey(form,{version:batch.version,note:form.elements.note.value}),note:form.elements.note.value});await saved('人工补发请求已提交,请核对发送记录。');});}); + panel.querySelectorAll('[data-rule-resolve]').forEach(form=>form.onsubmit=e=>{e.preventDefault();return action(e.submitter,async()=>{await api('/order-rules/batches/'+encodeURIComponent(form.dataset.ruleResolve)+'/resolve',{version:data.batches.find(b=>b.id===form.dataset.ruleResolve).version,idempotencyKey:operationKey(form,{version:data.batches.find(b=>b.id===form.dataset.ruleResolve).version,resolution:form.elements.resolution.value,note:form.elements.note.value}),resolution:form.elements.resolution.value,note:form.elements.note.value});await saved('核验结论已保存。');});}); + } + container.querySelector('#order-rule-refresh').onclick=e=>{const button=e.currentTarget;return tab==='settings'?window.PageLifecycle.guard(()=>action(button,reload)):action(button,refreshStatus);}; + const stopRefresh=()=>{clearInterval(timer);panelRevision++;executionController?.dispose?.();window.removeEventListener('pagehide',stopRefresh);}; + timer=setInterval(()=>{if(!isActive()){stopRefresh();return;}if(!dirty&&!document.hidden)refreshStatus().catch(error=>feedback(error.message,'danger'));},15000); + window.addEventListener('pagehide',stopRefresh,{once:true});window.PageLifecycle?.onDispose(stopRefresh); + draw(); + } + window.OrderNotificationViews={configure:helpers=>({api,esc,formatDate,notify,user}=helpers),render}; +})(); diff --git a/web/modules/order-rules/view.js b/web/modules/order-rules/view.js index 878e3e4..3477033 100644 --- a/web/modules/order-rules/view.js +++ b/web/modules/order-rules/view.js @@ -1,37 +1,18 @@ (() => { 'use strict'; let api,esc,formatDate,notify,user; - const tabs={workbench:'工作台',execution:'订单执行',fields:'字段目录',rules:'通知规则',pending:'待发批次',orders:'订单记录',history:'发送记录',settings:'设置'}; - const statuses={draft:'草稿',enabled:'已发布',paused:'已暂停',identified:'已识别',preparing:'准备中',archived:'已归档',pending:'待发',batched:'已编入批次',blocked:'受阻',prepared:'已准备',sending:'发送中',sent:'已提交邮件服务器',failed:'失败',unknown:'结果待核实',cancelled:'已取消',ignored:'更早历史,不补发'}; - const status=s=>`${esc(statuses[s]||s||'未记录')}`; - const empty=text=>`
${esc(text)}
`; - const table=(heads,rows,none)=>`
${heads.map(h=>``).join('')}${rows.join('')||``}
${h}
${empty(none)}
`; - const list=v=>(v||[]).join('、')||'未配置'; - const operationKey=(form,body)=>{const signature=JSON.stringify(body);if(form.dataset.requestSignature!==signature){form.dataset.requestSignature=signature;form.dataset.requestKey=window.PageLifecycle.requestKey();}return form.dataset.requestKey;}; - const capabilityNames={liveTodo:'实时待办接入',pdfExport:'通知书 PDF 导出',automaticArchive:'自动归档'}; - const ready=c=>Object.keys(capabilityNames).every(k=>c[k]===true); - function capabilities(c){return `
${Object.entries(capabilityNames).map(([key,label])=>`
${c[key]===true?'已就绪':'待联调'}${label}
`).join('')}
`;} - async function render(container,isActive=()=>true){ - const [snapshot,mail,fieldCatalog]=await Promise.all([api('/order-rules'),api('/mail').catch(()=>({channels:[]})),api('/order-rules/fields').catch(()=>({samples:[]}))]);if(!isActive())return; - const data={samples:fieldCatalog.samples||[],rules:[],adapters:[],orders:[],batches:[],audit:[],settings:{},capabilities:{},...snapshot},admin=user.role==='admin',operator=user.role!=='viewer'; - let tab='workbench',selectedId=data.rules[0]?.id,dirty=false,refreshing=false,timer,panelRevision=0,tabRevision=0,executionController=null; - container.innerHTML=`
分类通知${data.settings.enabled?'已启用':'自动执行已暂停'}。按 Excel 类别汇总,本时段内同类别订单合并一封,更早历史不补发;通知与更改单独归类,BPM 节点由人工办理。
${Object.entries(tabs).map(([id,label])=>``).join('')}
时段与运行状态每 15 秒刷新
`; - const panel=container.querySelector('#order-rules-panel'); + async function render(container,isActive=()=>true,section='rules'){ + const tab=['rules','fields'].includes(section)?section:'rules'; + const {status,empty}=window.OrderNotificationShared.create({esc}); + container.innerHTML='
规则与字段配置
'; + const panel=container.querySelector('#order-rules-panel'),admin=user.role==='admin',operator=user.role!=='viewer'; + let data={rules:[],adapters:[],samples:[]},selectedId,dirty=false,revision=0,controller; const feedback=(message,type='success')=>{if(!isActive())return;const node=container.querySelector('#order-rules-feedback');node.textContent=message;node.className='alert alert-'+type;}; async function action(button,work){if(button)button.disabled=true;try{await work();}catch(error){feedback(error.message,'danger');}finally{if(button?.isConnected)button.disabled=false;}} - async function saved(message){dirty=false;return window.PageLifecycle.afterSave(reload,message,feedback,isActive);} - async function reload(){const [fresh,fields]=await Promise.all([api('/order-rules'),api('/order-rules/fields').catch(()=>({samples:data.samples}))]);if(!isActive())return false;Object.assign(data,fresh,{samples:fields.samples||[]});syncState();dirty=false;draw();return true;} - function syncState(){const node=container.querySelector('#order-rule-state');node.className='alert alert-'+(data.settings.enabled?'success':'info');node.textContent='分类通知'+(data.settings.enabled?'已启用':'自动执行已暂停')+'。按 Excel 类别汇总,本时段内同类别订单合并一封,更早历史不补发;通知与更改单独归类,BPM 节点由人工办理。';} - function keepInputs(){return window.PageLifecycle?.dirty()||['fields','execution'].includes(tab)||dirty||tab==='rules'||tab==='settings'||[...panel.querySelectorAll('textarea')].some(input=>input.value.trim());} - async function refreshStatus(){if(refreshing)return;refreshing=true;try{const fresh=await api('/order-rules');if(!isActive())return;Object.assign(data,fresh);syncState();container.querySelector('#order-rule-updated').textContent='时段与状态更新于 '+formatDate(new Date().toISOString());if(tab==='execution'&&executionController)await executionController.refresh();if(!keepInputs())draw();}finally{refreshing=false;}} - function ordersTable(orders){return table(['订单 / 类别','状态与原因','接收时间'],orders.map(o=>`${esc(o.orderNo||o.event?.orderNo||'订单号未提供')}
${esc(data.rules.find(r=>r.categoryId===o.categoryId)?.name||o.categoryId||'未分类')}
查看订单信息
流程:${esc(o.processName||o.event?.processName||'—')}
节点:${esc(o.nodeName||o.event?.nodeName||'—')}
流程实例:${esc(o.instanceId||o.event?.instanceId||'—')}
任务:${esc(o.taskId||o.event?.taskId||'—')}
来源版本:${esc(o.revision||o.event?.revision||'—')}
规则版本:${esc(o.ruleVersion??'—')}
数量:${esc(o.quantity??o.event?.quantity??'—')}
${esc(o.brief||o.event?.brief||'')}
${status(o.status)}${o.error||o.reason?`
${esc(o.error||o.reason)}
`:''}${admin&&!o.batchId&&['pending','blocked'].includes(o.status)?`
按当前发布规则重新核对

重新匹配会清除原归档证据,需重新校验和归档;更早历史仍不补发。

`:''}${formatDate(o.receivedAt||o.event?.receivedAt||o.createdAt)}`),'暂无订单记录。样本预览不会创建订单。');} - function batchesTable(batches,pending){return table(['类别 / 主题','订单与收件人','状态'],batches.map(b=>`${esc(b.subject||b.categoryId)}
${esc(b.categoryId)} · ${formatDate(b.createdAt)}
查看冻结内容
业务时段:${formatDate(b.windowStart)} 至 ${formatDate(b.windowEnd||b.cutoff)}
收件人:${esc(list(b.to))}
抄送:${esc(list(b.cc))}
附件:${esc((b.attachments||[]).map(a=>a.name||a.filename).join('、')||'无')}
${esc(b.text||'')}
${esc(list(b.orderNos||b.orderIds))}
${esc(list(b.to))}
${status(b.status)}${b.error?`
${esc(b.error)}
`:''}${b.status==='failed'&&admin?`

人工补发沿用原冻结内容和收件人。

`:''}${b.status==='unknown'&&admin?`
`:''}`),pending?'暂无待发批次':'暂无发送记录');} - function windowInfo(){const w=data.window;return w&&Number.isFinite(Date.parse(w.start))&&Number.isFinite(Date.parse(w.end))&&Date.parse(w.start)=Date.parse(w.start)&&at

本时段范围

${w?`${esc(w.label||'配置发送时段')}`:''}
${w?`${formatDate(w.start)} 至 ${formatDate(w.end)}
以订单接收时间归入时段。本时段内同类别订单合并一封,更早历史不补发。
`:`
${esc(data.window?.error||'当前没有已确认的发送时段。请先确认发送计划及工作日规则。')}
`}${prepare&&admin?`
${w&&w.available!==true?'未到配置发送时点,当前只预览。':''}按服务器确定的时段整理已接入订单并冻结规则和附件,不发送邮件。缺少归档证据时将阻塞该类别。
`:''}
`;} - function windowOrders(){const groups=new Map();for(const order of data.orders.filter(o=>inWindow(o)&&['pending','blocked','archived','preparing','identified'].includes(o.status))){const id=order.categoryId||'未分类';if(!groups.has(id))groups.set(id,[]);groups.get(id).push(order);}return `

本时段订单 · 按类别预览

${groups.size?[...groups.entries()].map(([id,orders])=>`
${esc(data.rules.find(r=>r.categoryId===id)?.name||id)}${orders.length} 单
${ordersTable(orders)}
`).join(''):empty('本时段暂无待整理订单;更早历史不计入。')}
`;} - function drawWorkbench(){ - panel.innerHTML=`${windowCard()}
${[['已发布规则',data.rules.filter(r=>r.publishedVersion||r.status==='enabled').length],['本时段待发订单',data.orders.filter(o=>inWindow(o)&&['pending','batched'].includes(o.status)).length],['本时段受阻订单',data.orders.filter(o=>inWindow(o)&&o.status==='blocked').length],['结果待核实',data.batches.filter(b=>b.status==='unknown').length]].map(([label,count])=>`
${label}
${count}项
`).join('')}

接入状态

${capabilities(data.capabilities)}

规则草稿和样本试运行可独立配置;自动执行需全部接入就绪并由管理员启用。样本结构核验不等于实时接口验证。

本时段受阻订单

${ordersTable(data.orders.filter(o=>inWindow(o)&&o.status==='blocked'))}
`; + async function saved(message){if(!isActive())return false;dirty=false;return window.PageLifecycle.afterSave(reload,message,feedback,isActive);} + async function reload(){if(!isActive())return false;const request=++revision;if(tab==='fields'){controller?.dispose?.();const next=await window.OrderExecutionViews.fields(panel,{api,esc,formatDate,user,isActive:()=>isActive()&&request===revision,feedback});if(isActive()&&request===revision)controller=next;return true;} + const [snapshot,catalog]=await Promise.all([api('/order-rules'),api('/order-rules/fields').catch(()=>({samples:[]}))]);if(!isActive()||request!==revision)return false; + data={rules:snapshot.rules||[],adapters:snapshot.adapters||[],samples:catalog.samples||[]};dirty=false;drawRules();return true; } function drawRules(){ if(!data.rules.length){panel.innerHTML=`
${empty('暂无分类规则,请先导入经确认的 Excel 分类。')}
`;return;} @@ -50,28 +31,10 @@ function choose(){const a=sources.find(a=>a.id===source.value);panel.querySelector('#order-rule-adapter').innerHTML=window.OrderRulePreview.adapter(a,{esc});const input=panel.querySelector('#order-rule-sample');if(input){input.value=a?.sample?JSON.stringify(a.sample,null,2):'';input.readOnly=!!a?.sampleId;}const title=panel.querySelector('#order-rule-title');if(title){title.value=a?.sampleId?a.sample?.title||'':'';title.readOnly=!!a?.sampleId;}panel.querySelector('#order-rule-preview-result').innerHTML='';}source.onchange=choose;choose(); if(operator)panel.querySelector('#order-rule-preview').onclick=e=>action(e.currentTarget,async()=>{let sample;try{sample=JSON.parse(panel.querySelector('#order-rule-sample').value);}catch{throw Error('请选择样本,或在高级选项中提供有效的 JSON 对象。');}if(!sample||typeof sample!=='object'||Array.isArray(sample))throw Error('样本必须是 JSON 对象。');const title=panel.querySelector('#order-rule-title').value;if(title.trim())sample.title=title;const evidence=sources.find(a=>a.id===source.value);const result=await api('/order-rules/preview',evidence?.sampleId?{sampleId:evidence.sampleId}:{sample});if(!isActive()||tab!=='rules'||selectedId!==rule.id||panel.querySelector('#order-rule-editor')!==form)return;panel.querySelector('#order-rule-preview-result').innerHTML=window.OrderRulePreview.result(result,{esc,demo:sample.demo===true});}); } - function drawSettings(){ - const config=data.settings,canEnable=ready(data.capabilities),disabled=admin?'':'disabled'; - panel.innerHTML=`

分类通知设置

${capabilities(data.capabilities)}${!canEnable?'
自动执行待联调。可保存邮箱与附件大小限制;全部接入验证通过后才可启用。
':''}

发送时段与工作日可在 发送计划、业务日历 配置。本规则中心按配置时段内的 Excel 类别汇总,更早历史不补发;旧通用通知调度已停用,收件人统一在分类规则维护。

${admin?'':''}
`; - if(admin)panel.querySelector('form').onsubmit=e=>{e.preventDefault();const form=e.currentTarget;return action(e.submitter,async()=>{const result=await api('/order-rules/settings',{version:config.version,channelId:form.elements.channelId.value,maxMessageBytes:Math.round(Number(form.elements.maxSize.value)*1048576),enabled:canEnable&&form.elements.enabled.checked});if(!isActive())return;Object.assign(config,result);await saved('分类通知设置已保存。');});}; - } - function draw(){ - if(!isActive())return;const drawnRevision=++panelRevision,drawnTab=tab;executionController=null; - if(tab==='workbench')drawWorkbench();else if(tab==='rules')drawRules();else if(tab==='settings')drawSettings();else if(tab==='execution'||tab==='fields'){panel.innerHTML=empty('正在加载…');window.OrderExecutionViews[tab](panel,{api,esc,formatDate,user,isActive:()=>isActive()&&panelRevision===drawnRevision&&tab===drawnTab,feedback}).then(controller=>{if(isActive()&&panelRevision===drawnRevision)executionController=controller;}).catch(error=>{if(!isActive()||panelRevision!==drawnRevision)return;panel.innerHTML=empty('数据加载未完成,请刷新重试。');feedback(error.message,'danger');});} - else if(tab==='orders')panel.innerHTML=`

订单记录 · ${data.orders.length}

${ordersTable(data.orders)}
`; - else if(tab==='pending')panel.innerHTML=`${windowCard(true)}${windowOrders()}

本时段待发批次

${batchesTable(data.batches.filter(b=>{const w=windowInfo();return w&&['prepared','sending','unknown','failed'].includes(b.status)&&Date.parse(b.windowStart)===Date.parse(w.start)&&Date.parse(b.windowEnd||b.cutoff)===Date.parse(w.end);}),true)}
`; - else if(tab==='history')panel.innerHTML=`
“已提交邮件服务器”表示 SMTP 接受,不代表最终送达。结果不明的批次须人工核实。

发送记录

${batchesTable(data.batches.filter(b=>['sent','cancelled','failed','unknown'].includes(b.status)),false)}

规则与执行操作记录

${table(['时间','操作人 / 操作','说明'],data.audit.map(a=>`${formatDate(a.at||a.createdAt)}${esc(a.actor?.username||a.actor||'系统')}
${esc(a.action)}
${esc(typeof a.detail==='object'?JSON.stringify(a.detail):a.detail||a.note||'')}`),'暂无操作记录')}
`; - const prepare=panel.querySelector('#order-rule-prepare');if(prepare)prepare.onsubmit=e=>{e.preventDefault();const w=windowInfo();if(!w||w.available!==true)return;return action(e.submitter,async()=>{await api('/order-rules/prepare',{cutoff:w.end});await saved('本时段批次整理已完成,请查看实际批次与受阻原因。');});}; - panel.querySelectorAll('[data-rule-recheck]').forEach(form=>form.onsubmit=e=>{e.preventDefault();return action(e.submitter,async()=>{await api('/order-rules/orders/'+encodeURIComponent(form.dataset.ruleRecheck)+'/recheck',{note:form.elements.note.value});await saved('此订单已重新核对,请检查新匹配结果及归档状态。');});}); - panel.querySelectorAll('[data-rule-resend]').forEach(form=>form.onsubmit=e=>{e.preventDefault();const batch=data.batches.find(b=>b.id===form.dataset.ruleResend);return action(e.submitter,async()=>{await api('/order-rules/batches/'+encodeURIComponent(batch.id)+'/resend',{version:batch.version,idempotencyKey:operationKey(form,{version:batch.version,note:form.elements.note.value}),note:form.elements.note.value});await saved('人工补发请求已提交,请核对发送记录。');});}); - panel.querySelectorAll('[data-rule-resolve]').forEach(form=>form.onsubmit=e=>{e.preventDefault();return action(e.submitter,async()=>{await api('/order-rules/batches/'+encodeURIComponent(form.dataset.ruleResolve)+'/resolve',{version:data.batches.find(b=>b.id===form.dataset.ruleResolve).version,idempotencyKey:operationKey(form,{version:data.batches.find(b=>b.id===form.dataset.ruleResolve).version,resolution:form.elements.resolution.value,note:form.elements.note.value}),resolution:form.elements.resolution.value,note:form.elements.note.value});await saved('核验结论已保存。');});}); - } - container.querySelectorAll('[data-rule-tab]').forEach(button=>button.onclick=()=>window.PageLifecycle.guard(()=>{const request=++tabRevision;return action(button,async()=>{dirty=false;const [fresh,fields]=await Promise.all([api('/order-rules'),api('/order-rules/fields').catch(()=>({samples:data.samples}))]);if(!isActive()||request!==tabRevision)return;Object.assign(data,fresh,{samples:fields.samples||[]});syncState();tab=button.dataset.ruleTab;container.querySelectorAll('[data-rule-tab]').forEach(b=>b.classList.toggle('btn-primary',b===button));draw();});})); - container.querySelector('#order-rule-refresh').onclick=e=>{const button=e.currentTarget;return ['rules','settings','fields'].includes(tab)?window.PageLifecycle.guard(()=>action(button,reload)):action(button,refreshStatus);}; - const stopRefresh=()=>{clearInterval(timer);window.removeEventListener('pagehide',stopRefresh);}; - timer=setInterval(()=>{if(!isActive()){stopRefresh();return;}if(!dirty&&!document.hidden)refreshStatus().catch(error=>feedback(error.message,'danger'));},15000); - window.addEventListener('pagehide',stopRefresh,{once:true});window.PageLifecycle?.onDispose(stopRefresh); - draw(); + + container.querySelector('#order-rule-refresh').onclick=e=>window.PageLifecycle.guard(()=>action(e.currentTarget,reload)); + window.PageLifecycle?.onDispose(()=>{revision++;controller?.dispose?.();}); + await reload(); } window.OrderRuleViews={configure:helpers=>({api,esc,formatDate,notify,user}=helpers),render}; })(); diff --git a/web/modules/workspace/view.js b/web/modules/workspace/view.js index 34b2338..f8e2768 100644 --- a/web/modules/workspace/view.js +++ b/web/modules/workspace/view.js @@ -24,9 +24,10 @@ window.WorkspaceViews=(()=>{ const exceptions=data.exceptions||[],connections=data.connections||[],active=exceptions.filter(e=>e.status!=='resolved'),mine=active.filter(e=>e.owner===user.username); const day=policy(today(),settings.schedule,data.calendar.overrides); const activity=(data.audit||[]).slice(0,5); + const automation=pdf.automation,automationLabel=typeof automation?.enabled!=='boolean'?'状态待确认':!automation.enabled?'已暂停':automation.ready?'已启用':'受阻',automationColor=!automation?.enabled?'secondary':automation.ready?'green':'yellow'; container.innerHTML=`${pdf.scan?`
扫描${pdf.scan.config.enabled?'已开启':'已暂停'}BPM 流程到达记录已收录 ${pdf.scan.total} 条 · 按到达日期查看查看记录 →
`:''}
WORKSPACE / 团队协作

让每一项工作,都有清晰的去向。

安排业务日期、协同处理异常,逐步准备订单通知流程。

查看异常待办
-

需要关注

全部异常 →
${active.length?``:empty('当前没有待处理异常','遇到流程或文件问题时,可建立异常并交给团队处理。')}

业务自动处理

未启用
团队工作台
日历、异常协作与操作留痕已可用
自动处理未启用
服务连接
查看连接状态

最近活动

操作记录 →
${activity.length?`
${activity.map(a=>`
${esc(activityText(actions[a.action]||a.action))}

${esc(activityText(typeof a.detail==='object'?JSON.stringify(a.detail):a.detail||a.note||''))}

${esc(a.actor)} · ${formatDate(a.at)}
`).join('')}
`:empty('工作台已就绪','团队保存日历或处理异常后,活动会显示在这里。')}
下一步

从安排工作日开始

设置公司调休与暂停日期,再为异常指定负责人。

打开业务日历 →
下两个计划发送时段 · 北京时间${(pdf.nextSlots||[]).map(slot=>`
${formatDate(slot)}
`).join('')}

查看现有订单与 PDF 导出记录 →
`; +

需要关注

全部异常 →
${active.length?``:empty('当前没有待处理异常','遇到流程或文件问题时,可建立异常并交给团队处理。')}

订单自动通知

${automationLabel}

${esc(automation?.reason||'服务端未返回通知状态,请刷新重试。')}

打开订单通知管理 →

最近活动

操作记录 →
${activity.length?`
${activity.map(a=>`
${esc(activityText(actions[a.action]||a.action))}

${esc(activityText(typeof a.detail==='object'?JSON.stringify(a.detail):a.detail||a.note||''))}

${esc(a.actor)} · ${formatDate(a.at)}
`).join('')}
`:empty('工作台已就绪','团队保存日历或处理异常后,活动会显示在这里。')}
下一步

从安排工作日开始

设置公司调休与暂停日期,再为异常指定负责人。

打开业务日历 →
下两个计划发送时段 · 北京时间${(pdf.nextSlots||[]).map(slot=>`
${formatDate(slot)}
`).join('')}

查看现有订单与 PDF 导出记录 →
`; } async function calendar(container,isActive=()=>true){