merge: preserve main lazy loading and scoped refresh with DSH

This commit is contained in:
abaishu0730 committed 2026-10-29 09:42:00 +08:00
commit fb7a195186
113 files changed
+2675 -212

No files matched your search

+2
View File
@@ -62,6 +62,8 @@
## 服务守护与系统健康
左侧菜单底部显示当前版本,登录后自动检查一次更新,也可点击“检查更新”。有新版本时显示更新标记,并可查看发布日期、说明及远端发行页面。尚无 Release、已是最新版本和检查暂不可用会分别显示;检查失败不会阻塞业务。当前功能提供更新提示,由部署管理员根据发行说明安排更新。发行流程见[版本发布与更新检查](docs/system-updates.md)。
双击 **启动工具.cmd** 或运行 `npm start`,工作台由独立守护程序在后台运行;启动窗口关闭后服务继续运行,重复启动会复用现有实例。打开 **系统健康**(`/#health`)查看本次启动时间、连续运行时长、守护心跳、恢复次数、最近事件及 Windows 登录自启状态。
守护通过两个本机端口的私有心跳确认业务进程身份。启动宽限 120 秒,之后每 10 秒检查,连续 4 次失败才终止本工具启动的进程树并恢复。退出重试采用 2/5/10/30/60 秒退避,15 分钟内达到 8 次恢复尝试后冷却 5 分钟,避免反复启动。人工停止不会触发恢复,不会结束未知的占用端口进程。自动恢复仍遵守原有任务规则,邮件结果不明时保留待核实状态。
+30
View File
@@ -1,11 +1,41 @@
# 开发交接(2026-10-23)
## 2026-10-28 路由按需加载与 Windows 启动资源优化
- 在 `codex/system-update` 延续前轮性能改动,首页按路由加载可选脚本。清单由服务端计算实际内容指纹,延迟资源保留长期缓存与 SRI;并行预加载、按各路由顺序执行,旧慢页面不阻塞未加载的新页面,失败可重试或重新加载。18 个页面入口、冷切换、完整性拒绝与重试均有浏览器覆盖。
- 与 `73773f9` 同一隔离 HTTP/合成首页比较、各 3 次中位:冷静态请求 44→13,压缩正文 299130→169652 B,首页就绪约 590→399 ms;重复刷新仍为 0 个静态网络请求。含 3000 个合成文件的跨进程 ACL 检查中位约 1142→587 ms;不是生产 SLA。
- Windows ACL 先检查原始 DACL 与 SID 规则,完全符合原有私有目录策略才复用,任何额外对象/回调/不透明 ACE 均不复用;真实目录验证不重写合规 ACL,并能修复放宽后的策略。DPAPI、路径身份核验和原超时保护保持。监督器连续三次未通过首次健康检查即退出时冷却,持久化安全启动诊断;成功健康检查或人工重试重置连续计数。
- 原目标 `codex/smb-storage` 已合入 `main` 并删除,旧请求 #2 已关闭;本轮纳入 `main` 的邮件期限/隔离发送、修复验证器和监督器异常退出清理修复,合并保留两边全部 70 个测试入口。新请求目标为 `main`,不操作 `dsh`。
- 最终 `npm test` 429/429 通过,0 失败、0 跳过,未再出现保护超时日志。集成安全与服务专项 20/20 通过;早期因 Windows 初始化超时失败的业务切片重跑 12/12 通过,保留原始失败日志。独立审查提出的三项 P2 均补回归并复核,提交内容/依赖/语法/差异检查通过;未运行历史 `test:full`。
- 未部署运行服务,未发送真实邮件、办理 BPM 或改动运行配置。实现、基准和限制见 [启动稳定性与首屏加载](startup-stability-2026-10-28.md),原始聚合收据留在忽略目录 `output/lazy-startup-20261028/`。未声称消除所有 Windows 超时或证明完整服务启动已经加速。
## 2026-10-27 PR #1 合并前审查修复
- 修复旧模板测试邮件旁路:固定隔离QQ、空Cc、无附件,发送前/SMTP验证后复查测试期限与模板版本;未知测试结果禁止重复。样例发送同样接入期限,UI文案与真实信封一致。
- 修复AI验证器关联共享Git目录时的dubious ownership;只为当前验证工作区设置命令级精确信任,不改变全局配置。新增真正执行固定与变更测试的回归。
- Windows守护异常退出的孤儿进程疑点被隔离实测排除,新增PID退出/定时任务停止/端口释放回归;无需修改生产守护行为。
- 审查范围、已修复问题和投产限制见docs/pr-1-review-2026-10-27.md。修复前业务292项、修复后针对性25项通过;最终候选测试单独记录。未手动发信或操作BPM,不更新正式服务机。
## 2026-10-28 缓存刷新收尾与按需区域校验
- 接续 `codex/system-update` 上一轮中断前的静态指纹缓存、后端 revision 与前端区域刷新改动。新增 `GET /api/refresh/revisions?regions=assistant` 等按需校验,旧的无参数八区域响应兼容;校验区域白名单、重复/空参数,保持认证、账号隔离与 `no-store`。助手频繁轮询不再访问订单、BPM、存储或 PDF 台账等无关模块。
- 修复审查复现的手动刷新空操作:取消并等待旧请求后清除消费者的已应用 token,强制本次重读取;定时检查继续跳过未变化区域。并发手动刷新仍合并,草稿、筛选、权限及时间边界保持。
- 合成内存 SQLite、5 万订单、每项 300 次采样:全八区域校验中位 5.44 ms / 635 B / 21 次 SQL,助手单区域 0.135 ms / 104 B / 1 次 SQL;首页加顶栏合计 4.37 ms / 204 B / 11 次 SQL。不是生产 CPU、内存或网络 SLA;夹具与边界见 [缓存与区域刷新](cache-region-refresh-2026-10-28.md)。
- 最新 `npm test` 404/404 通过,无失败或跳过;28 个改动脚本语法检查、依赖树与 `git diff --check` 通过,独立审查发现的手动刷新 P2 已修复复核。未运行历史 `test:full`。测试前基线曾遇一次 Windows ACL 子进程超时,最终完整业务回归未复现;保留原始日志,不降低存储保护。
- 开发与验证使用原目标工作区 `C:/Users/ABS/.codex/worktrees/system-update/Order Notification Automation`,桌面应用直接关联该既有目录时无法核实归属。提交范围仅为源码、测试与文档,诊断日志及基准夹具留在忽略的 `output` 中。未部署服务、修改真实业务配置或调用真实 BPM/SMTP/SMB;主目录 `dsh` 的独立改动保持。
## 2026-10-27 分类规则设置响应优化
- 规则页改用专用configuration读取,只返回编辑元数据和资源摘要;顶栏用轻状态接口。首次进入不再读取业务summary或完整执行/字段快照,样本在第04步点击“读取已采集订单”时按当前流程和连接权限读取。
- 保存、发布、启停使用完整服务端版本回执局部更新,保留当前编辑器与冲突/未保存保护。放弃修改后启停恢复真实保存基线;受限测试暂停/到期回执同步目录与提示;不确定结果核验走轻配置。流程本地搜索取消延迟,避免旧搜索回抢焦点。
- 同一份加密数据种子/固定时钟下各3次受控对比:暖态进入中位数1059→235ms,保存691→103ms;进入GET 8→2,保存后GET 7→0。探测仅使用临时副本和隔离账号,无真实BPM/SMTP/SMB调用,未更新运行服务。
- `npm test`最新323/323通过,另有规则交互5项、普通/惠州试运行1项及规则页兼容3项通过;独立审查问题已修复复核。没有重跑历史全量,上一轮基线33项失败未冒称解决。设计与测量边界见[规则页响应优化](rule-settings-performance-2026-10-27.md)。
## 2026-10-27 系统更新提示(独立分支)
- `codex/system-update` 在菜单左下角显示 `package.json` 版本,登录自动检查一次,支持手动检查、更新标记及含日期/纯文本说明/发行链接的详情框。仅提示正式 Gitea Release,不以分支提交或单独 tag 触发更新。
- 服务端固定公开仓库的 `releases/latest`,使用现有登录权限;5 秒超时、256 KiB 上限、禁止重定向,不读取 Git 凭据或传递业务数据。没有发行版本、当前最新与检查失败分别显示;当前远端无 Release,未创建首个发行版。
- 最终业务回归 304/304 通过,更新专项 12 项通过,独立审查发现的说明文字可读性已修复。历史全量 1312 项中 1278 通过、33 失败、1 跳过;部分旧失败已在基线复现,未核验项仍保留,因此提交草稿请求。
- 发布约定见 [版本发布与更新检查](system-updates.md),完整结果和失败后续状态见 [本次验证记录](verification-system-update-2026-10-27.md)。
## 2026-10-27 业务首页轻量看板
+76
View File
@@ -0,0 +1,76 @@
# 静态缓存与分区域刷新验证
本轮把缓存和动态刷新拆成两个边界:公共静态文件允许长期缓存,业务数据只使用用户隔离的短小 revision 验证。没有把订单、邮件正文、凭据或 BPM 证据放进浏览器缓存,也没有改变业务匹配、发送、冻结、未知结果或权限规则。
## 静态资源
根 HTML 响应在服务端读取自身引用的脚本、样式和公开预览资源,按实际内容生成 SHA-256 指纹并改写为 `?v=<64hex>`。只有指纹与当前文件内容完全一致时,资源才返回:
```text
Cache-Control: public, max-age=31536000, immutable
```
HTML 自身始终使用 ETag 和 `max-age=0, must-revalidate`,因此新版本可以在下一次打开时重新验证并获得新的依赖指纹。没有指纹或指纹错误的资源仍然使用 ETag 重新验证策略。压缩、HEAD、预览隔离 CSP、资源变化检测和并发读取行为保留。
隔离 Chromium 测量(基线为 `f317314`,相同 44 个静态请求):
| 场景 | 基线 | 当前 |
| --- | ---: | ---: |
| 再次加载的静态资源网络请求 | 44 个 304 | 0 个 |
| 再次加载的静态资源响应正文 | 0 B | 0 B |
| HTML | 每次条件验证 | 每次条件验证 |
冷打开静态正文约 297 KiB;当前指纹 HTML 会增加少量首屏计算和文档字节,换取后续刷新不再往返 44 个资源。API 保持请求且 `no-store`。
## 动态区域
`GET /api/refresh/revisions` 返回:
```json
{
"version": 1,
"regions": {
"home": "…",
"orderRules": "…",
"records": "…",
"health": "…",
"bpm": "…",
"assistant": "…",
"storage": "…",
"mail": "…"
}
}
```
每个 token 是服务实例密钥生成的 HMAC,包含账号身份、角色、账号版本和可见连接归属。各 SQLite 数据库通过事务触发器维护按表或按业务类型的计数,外部连接写入、回滚和同一状态内容变更均有测试覆盖;验证接口不读取订单/邮件正文,也不构造完整快照。助手只读取当前账号的会话/操作元数据,存储不存在的可选模块返回稳定的 disabled 标记,已配置但暂时读取失败的区域返回随机 token 和安全错误。
### 后续资源优化:按需计算区域
接口增加可选 `regions` 参数,例如 `GET /api/refresh/revisions?regions=assistant`。只计算并返回指定区域;不传参数仍返回原来的八个区域。允许逗号分隔的已知区域,空值、重复区域、重复参数和未知区域返回 400;认证、账号隔离及 `no-store` 保持。各页面传入自身区域,顶栏请求 `orderRules`,不再让每次助手轮询打开 PDF 台账数据库或访问无关模块。
同时修复上一轮遗留的手动刷新问题:取消并等待旧请求后清除该消费者已应用的 token,再读取当前区域与业务数据。手动刷新不再因 token 相同而被跳过,后续定时检查仍可跳过重读取。
同一实现的全区域旧调用与按需调用对比:内存 SQLite、单个合成连接、五万条每条 512 B 的合成订单;每项预热 30 次、采样 300 次,中位数如下。首页与 PDF 台账项目包含独立顶栏检查,因此每周期是两次接口调用。
| 校验工作负载 | 中位耗时 | 每周期响应正文 | 每周期 SQL 读取 |
| --- | ---: | ---: | ---: |
| 原八区域校验 | 5.44 ms | 635 B | 21 |
| 助手区域 | 0.135 ms | 104 B | 1 |
| 首页与顶栏合计 | 4.37 ms | 204 B | 11 |
| PDF 台账与顶栏合计 | 4.50 ms | 207 B | 11 |
此夹具没有操作审计库;配置该库后助手还需读取其最新事件元数据。SQL 计数不包括应用认证;内存数据库与固定时钟用于隔离选择逻辑,不代表生产 HTTP 延迟、磁盘 I/O、CPU 或内存使用降幅。原始脚本及聚合结果在忽略目录 `output/performance-refresh-20261028/resource-selection-benchmark.*`。
前端区域 poller 在隐藏页面暂停,恢复后先验证 token;token 未变化时跳过重数据请求,变化时读取对应页面数据。手动刷新不因 token 相同跳过重读取;校验失败明确报错并可重试。后台订单/批次列表只显示“有更新”提示,保留当前列表、筛选、草稿和详情;PDF 台账每 60 秒仍会检查文件可用性,避免外部文件变化长期不被发现。写操作会使相关区域失效,旧导航或旧账号的结果不能确认新页面状态。
## 验证
- 区域 revision 单测:10/10;HTTP 权限、`no-store`、跨账号 token:1/1。
- 生命周期/区域 poller VM 测试:11/11。
- 区域浏览器测试:3/3;覆盖 token 未变跳过摘要、token 变化后更新、健康和记录筛选保留、初次 revision 失败仍能打开页面。
- 静态资源、压缩、指纹、HTML 依赖变化、预览和 dashboard HTTP 测试:9/9。
- 区域 revision 隔离基准:8 区域响应约 635 B;空历史中位约 6.5 ms,5 万订单约 5.7 ms,再加 5 万旧助手轮次约 6.8 ms;正文枚举/解密守卫触发 0 次。
这些数据来自本地隔离数据库和浏览器,不能作为生产网络 SLA。revision 只证明本地持久状态或权限相关元数据变化;它不能证明 BPM、SMTP、SMB 或模型服务当前外部连通。
本轮最终 `npm test` 为 404/404 通过,0 失败、0 跳过,包含区域选择 4 项、生命周期区域 poller 8 项、区域浏览器 3 项,以及带区域参数的真实 HTTP 鉴权与错误响应。28 个改动脚本语法检查、依赖树和 `git diff --check` 通过;未运行历史 `test:full`。独立复核已验证手动刷新并发合并、取消等待和校验失败后可重试,没有剩余具体 P1/P2。初次基线 16/17 通过,失败来自 Windows ACL 子进程超时,最终完整业务回归没有该失败;日志保留在忽略目录 `output/performance-refresh-20261028/resource-*.log`。
+1 -1
View File
@@ -25,7 +25,7 @@ Excel 15 类已建立。左侧分类卡片显示流程数、收件人数、待
1. **适用通知**:直接维护完整的“流程+触发节点”配对,任一行精确满足即归入该类。简要显示已生效识别接口状态;来源、候选及版本修复在字段映射页完成。
2. **通知内容**:类别模板、主题、收件人/抄送、PDF附件要求;使用标准正文时可维护引导语及签名。同类别每时段一封,具体时点由通知配置统一维护。
3. **归档要求**:从已配置服务器选择共享内目录和命名日期依据。目录浏览、失败重试及原选择保留不变。
4. **验证与发布**:在单个样本选择框选该流程真实待办,检查当前规则如何分类、归档和生成邮件。调用已生效字段接口,映射草稿不参与此业务验证。历史不提供发布凭据。未保存配置可检查模拟结果,发布仍需保存后重新检查。
4. **验证与发布**:先点击“读取已采集订单”,再在样本选择框选该流程真实待办,检查当前规则如何分类、归档和生成邮件。读取只查看已有采集记录,不会重新采集 BPM。调用已生效字段接口,映射草稿不参与此业务验证。历史不提供发布凭据。未保存配置可检查模拟结果,发布仍需保存后重新检查。
本页不提供字段候选、高级来源、完整字段目录或映射生效操作。字段映射变更后重新进入本页读取规则版本;并发保存冲突保留输入,刷新需经过未保存保护。
@@ -0,0 +1,44 @@
# 分类规则设置响应优化
规则页原来需要等待7个接口才显示表单,顶栏另读一次业务summary;保存一个草稿后又重新加载整套目录,成功提示与控件解锁都被推迟。本次将规则配置与订单业务汇总分开,保存使用服务端版本回执局部更新,真实订单样本改为在第04步按需读取。
## 行为与接口
- `GET /api/order-rules/configuration` 返回规则编辑状态、适配器元数据、流程节点目录和模板/服务器摘要,不读取订单、批次、执行任务、采集样本或审计历史。
- 可选资源不可读取时,返回对应的`null`及局部错误。页面保留已知选项和原模板/目录值;不将读取失败当作空配置。
- 规则页顶栏使用`GET /api/order-rules/status`,只读取有效通知开关和已有能力标记。缺少能力时提示待核验,不以未读取的订单计数推断业务正常或失败。
- 第04步点击“读取已采集订单”,通过`GET /api/order-rules/configuration/samples?process=...`读取本类别的样本元数据。仍按连接权限过滤,只接受服务端非演示、非历史样本,不返回表单字段值或HTML,不重新调用BPM采集。
- 保存、发布、启停回执在既有顶层`id/version`契约上补齐激活、发布、草稿和测试版本状态。前端保留当前编辑器,只更新当前分类及目录状态;测试应用返回受影响规则状态。写入未知时仍需人工核对,查询使用轻量配置。
- 控件在写请求中继续锁定,版本冲突保留输入。保存后按回执更新规范化邮箱、校验提示和dirty基线;放弃修改后启停先恢复已保存模型。受限测试暂停/到期时同步提示与目录标记。
- 本地流程搜索不再延迟执行旧搜索,避免快速选择节点时旧搜索重新打开流程下拉并抢焦点。
业务匹配、发送计划、冻结批次、未知发信保护、实际归档与SMTP校验未作修改。没有新增持久缓存、数据库迁移或依赖包。
## 受控性能对比
基线为`39ece1920a1b21c04d50169c965a47f88380bb10`。同一个探测进程读取真实规则/邮箱数据库的一份一致字节副本,固定时钟;每次试验将临时SQLite恢复为完全相同的加密种子记录。基线模块和页面脚本从Git读入内存,优化版使用本次源码。均使用合成工作台账号、空workspace/storage配置和独立无界面Chromium;没有业务提供器、真实发送或源数据库写入。
进入页面的计时从已登录账号页开始,静态资源已加载;两边都包含100ms稳定等待。每个版本测3次,中位数如下。
| 项目 | 优化前 | 优化后 |
| --- | ---: | ---: |
| 进入规则编辑页 | 1059ms | 235ms |
| 保存到成功提示并解锁 | 691ms | 103ms |
| 首次进入的GET请求 | 8次 | 2次(配置和轻状态) |
| 每次保存后的附加GET | 7次 | 0次 |
三个样本中,进入页面由1043–1149ms降为234–268ms,保存由645–736ms降为102–113ms;保存后dirty均为false。本次不将此前不同采样时段观察到的4.3–7.2秒进入、5.7秒保存与优化结果直接相减,也不将本机隔离探测当作生产网络SLA。
## 正确性验证
新增测试以损坏的加密历史记录作为守卫,验证配置和能力读取不会暗中解密历史;覆盖部分资源失败、样本权限/来源/字段裁剪、非法查询、版本冲突、发布启停以及真实隔离受限测试回执。
界面回归覆盖首次进入不取历史、按需样本读取、连续多主送/抄送保存、保存后不重建表单/不刷新资源、迟到样本不覆盖新类别、放弃修改后启停的基线、暂停测试提示、失败写入轻量核验、原有真实样本试运行与发布门槛。
最新完整业务回归`npm test`为323项全部通过;其中包含新增配置/界面测试及规则工作台回归。另完成交互5项、普通/惠州混合试运行1项及规则页兼容3项验证。独立只读审查发现的放弃修改、全局测试提示和失败读取路径问题已修复并复核;多收件人连续保存也已验证。
本次未重跑历史全量集;该基线的上一轮全量记录为1312项、1278通过、33失败、1跳过,不能据本次专项宣称全量通过。
## 本地复核材料
原始聚合收据、诊断日志和抛弃式探测入口位于忽略目录`output/performance-scan-20261027/`:`rules-comparison.json`、`compare-rules.cjs`、`rules-targeted-final.log`、`rules-interactions.log`及`rules-business.log`。截图使用隔离示例环境,不提交真实订单、规则正文、邮箱凭据、Cookie或密钥。
+46
View File
@@ -0,0 +1,46 @@
# 启动稳定性与首屏加载优化
本轮在 `codex/system-update` 继续处理两类资源问题:首次打开工作台加载过多页面脚本,以及 Windows 启动阶段反复拉起已经确定会失败的业务进程。
## 路由脚本按需加载
`index.html` 只保留 Tabler、导航、生命周期、记录状态、模块加载器和 `app.js`。BPM、邮箱、订单、规则、存储、健康、助手等页面脚本由 `web/modules/navigation/module-loader.js` 在进入对应路由前按组加载,并在同一个工作台文档内复用脚本 Promise。分组及依赖在 `module-manifest.json` 定义;服务端把实际内容指纹写入 HTML 的非执行元数据,延迟资源仍使用原长期缓存。
下载通过带完整性校验的 preload 并行,脚本使用 async 独立执行,每个路由按自己的依赖顺序等待;避免某个未完成的助手脚本阻塞新打开的首页。脚本 SRI 由指纹派生,部署切换后旧页面不能执行与其清单不符的新脚本;加载失败提供重试和重新加载工作台入口。CSS 保持公共加载,避免页面切换时出现布局闪烁;业务 API、权限和数据读取顺序保持。
加载器 VM 与真实 HTTP 测试覆盖分组选择、重复加载去重、依赖顺序、失败重试、核心资源预算和延迟资源的指纹缓存。浏览器专项覆盖 18 个页面入口、冷助手脚本卡住后切到未加载首页、离页旧结果不能挂载、资源字节被替换时不执行及重试恢复。用例只使用隔离账号、合成数据与本机服务。
相同隔离 HTTP 与首页合成响应、Chromium、每个版本 3 个新浏览器上下文,取中位数:
| 场景 | 基线 `73773f9` | 本轮 |
| --- | ---: | ---: |
| 冷首页静态资源网络请求 | 44 | 13 |
| 冷首页静态响应正文(压缩后) | 299130 B | 169652 B |
| 冷首页 HTML 正文(压缩后) | 2267 B | 3056 B |
| 冷首页就绪耗时 | 589.7 ms | 399.0 ms |
| 重复刷新静态请求 / 正文 | 0 / 0 B | 0 / 0 B |
| 重复刷新首页就绪耗时 | 180.7 ms | 183.5 ms |
延迟资源元数据增加了少量 HTML 字节,换取冷打开约 43% 的静态正文减少。重复刷新耗时基本相当,未声称继续加速。上述是本机合成 API 与固定页面的测量,不代表生产网络、CPU、内存或真实 BPM/SMB 的 SLA。脚本及聚合原始结果保存在忽略目录 `output/lazy-startup-20261028/`,未提交业务数据库或凭据。
## 启动失败冷却
监督器把“子进程尚未通过第一次健康检查就退出”记录为 `startupFailure`,本次守护运行内连续 3 次启动失败后进入已有 5 分钟冷却窗口;健康检查成功会清零该计数,人工重启也会清零。子进程通过现有 IPC 传递安全启动诊断,守护进程再次过滤字段,仅持久化阶段、错误代码与耗时,不接受原始消息或堆栈。
普通运行期间的健康超时继续使用原有失败阈值和退避。冷却只减少重复启动和 Windows ACL/DPAPI 超时造成的资源浪费,不跳过端口检查、健康检查或加密目录保护。`restartCount` 是跨守护启动保留的历史累计数,不能据此推断本次启动发生同样次数的故障。
专项监督器测试覆盖启动失败冷却、普通崩溃恢复、健康超时、端口变化和手动停止。旧服务配置与加密数据格式不变。
## 避免重复传播合规 ACL
完整测试过程中定位到共享键目录已有约 2.2 万个文件,且已经具备正确的受保护 ACL。原逻辑在每个新进程中仍重设目录 ACL,可能重新传播到所有继承权限的子文件。现在先以 SID 读取并核验:DACL 受保护、所有者为当前用户、只有一条当前用户的显式 Allow FullControl 规则,且同时继承给文件和子目录、传播标志为 None;全部匹配才跳过重复写入。任何不一致仍按原策略重新保护,读失败仍报错,路径身份前后核验与 DPAPI 格式不变。
先读取原始二进制安全描述符,要求 DACL 中恰有一个普通非回调的 AccessAllowed ACE,且无不透明数据,再检查托管规则字段,避免 `GetAccessRules()` 隐藏额外对象 ACE。真实 Windows/.NET ACL 测试覆盖正确策略、未保护、其他所有者、权限不足、缺少继承、仅继承、Deny、其他用户、额外规则及隐藏对象 ACE;使用真实目录 ctime 确认合规检查没有重写权限,另验证取消保护或插入额外对象 ACE 后会修复。最初因初始化超时失败的 Excel 执行业务切片与该策略测试重跑 12/12 通过,未跳过原断言。
在含 3000 个合成文件的临时目录中,交替执行每项 3 次、取含 PowerShell 启动的跨进程中位耗时:原强制重写 1142 ms,核验后复用 587 ms。临时目录均已删除,原始聚合数据见忽略的 `output/lazy-startup-20261028/acl-benchmark.json`。这证明减少了一类重复权限写入;没有声称已经消除所有 Windows 超时,也未测量真实服务完整启动耗时。
## 最终集成验证
原草稿请求 #2 的目标分支已合入 `main` 并删除,本轮合并 `main` 修复并保留两边全部 70 个测试入口。邮件期限与隔离发送、固定修复验证器以及 Windows 监督器异常退出清理均保留。最终 `npm test` 为 429/429 通过、0 失败、0 跳过,未再出现保护超时日志;集成原生 ACL/存储诊断/邮件策略/修复验证器/服务监督专项 20/20 通过。
最初完整测试的 Windows ACL 初始化超时与失败原始日志保留,不作为最终通过依据。独立复核提出的文档级脚本执行队列阻塞、部署后延迟脚本完整性及隐藏对象 ACE 三项 P2 均已补失败回归并修复复核。语法、依赖、差异和提交内容检查通过,本轮未运行历史 `test:full`。源码和测试在最终回归期间保持不变,未部署真实服务或修改运行配置。
+26
View File
@@ -0,0 +1,26 @@
# 版本发布与更新检查
当前版本来自 `package.json.version`,工作台侧栏与扩展健康接口使用同一个来源。
登录后自动检查一次,用户可在菜单底部手动检查。检查只读访问本仓库 Gitea 的 `GET /api/v1/repos/Skyworth_Digital_Hardware/order-notification-automation/releases/latest`;浏览器通过已登录的同源 `GET /api/update` 读取结果,不直接访问远端,不传递工作台账号、Cookie 或业务数据。
| 结果 | 界面显示 |
| --- | --- |
| 远端没有发行版本(404) | 暂无可用发行版本 |
| 最新稳定版本高于当前版本 | 更新标记、发行日期、说明及发行页面入口 |
| 当前版本等于或高于远端版本 | 已是最新版本 |
| 网络、超时、响应格式错误 | 暂时无法检查更新;当前版本仍可见 |
检查总超时为 5 秒,读取响应最多 256 KiB,不跟随重定向。版本按 SemVer 比较,支持 `v` 前缀与 build metadata,跳过草稿和预发行版。发行说明按纯文本显示,链接只允许本仓库的 HTTPS 发行页面。没有安装器、自动下载、源码覆盖或服务重启行为。
## 发布步骤
1. 在准备发行的提交中同步更新 `package.json` 与 `package-lock.json` 根包版本,例如 `0.2.0`。
2. 执行 `npm ci`、`npm test` 与 `npm run test:full`,检查结果后合并对应变更。
3. 给确切的发行提交创建一致的版本标签,例如 `v0.2.0`,推送标签。
4. 在 Gitea 基于该标签发布正式 Release,填写变更说明、更新与备份要求;仅推送标签不会触发提示,草稿或预发行版也不会作为稳定更新。
5. 部署管理员按说明备份本地状态、停服、更新发行源码和依赖、重新启动并核对版本及健康状态。
远端仓库目前公开可读。若以后改为私有仓库,应另行设计服务端只读认证;本功能不读取 Git 凭据,也不要求前端填写 token。私有仓库返回 404 时与“未发行”无法区分。
本次功能提交不创建首个 Release;首发版本应对应经过确认的发行提交。
+56
View File
@@ -0,0 +1,56 @@
# 全站加载与后台刷新优化
本轮在 `codex/system-update` 继续处理现有页面的加载、切换和后台更新,不调整订单匹配、收件人、发送窗口、冻结/未知结果保护或受限测试期限。测量基线为上一轮规则优化后的 `649a0df`;使用隔离 HTTP、合成账号、内存 SQLite/AES-GCM 与本地文件,不调用真实 BPM、SMTP、IMAP、SMB 或更新仓库,不更新运行服务。
## 页面覆盖
| 界面 | 本轮改动 |
| --- | --- |
| 全站与登录 | 公共 HTML/JS/CSS/WASM 支持 ETag 重新验证、Brotli/gzip、受限内存缓存;保留安全响应头。已登录启动跳过 bootstrap,登录页只读取一次。登录验证改为异步 scrypt,参数不变,4 个执行位、32 个等待位;账号版本在异步验证及会话发放前再次核验。 |
| 全站顶栏 | 所有页面统一读取轻量通知状态,不再为顶栏计算订单/批次摘要。能力未齐时显示“自动通知待核验”;具体业务阻塞仍在首页/通知总览展示。 |
| 首页、通知总览 | 首次及每周期只读一次业务摘要;后台检查仅提示有更新,保留当前显示。隐藏时暂停,重新可见时检查。 |
| 订单中心、邮件批次、发送记录 | 每次同步查询内复用读取结果,建立任务身份多值索引、订单及收集批次反向索引;已发送/禁用/冻结模式先排除,再检查资格。普通与惠州模式分别判断。列表后台检查暂停/恢复,不覆盖筛选草稿或详情。 |
| PDF 台账、到达历史 | 共用列表轮询的可见性、取消、串行检查和页面离开清理。 |
| 分类规则、发送设置、模板 | 保留上一轮局部保存及按需样本;发送设置只取设置与测试状态,列表类别及模板使用情况取轻目录,独立邮箱/目录读取并行。 |
| 字段映射 | 流程节点目录和连接列表并行读取;延续搜索、保存和离开保护。 |
| BPM 连接、远程登录 | 状态及登录画面在隐藏时停止轮询,可见时恢复;扫描后读取新状态,避免复用扫描前请求。 |
| 系统健康 | 直接读取持久任务进度及已有能力,避免构造完整执行/字段证据快照;保留按连接负责人过滤和观测时间语义。页面轮询在离开时清理。 |
| 助手 | 对话更新使用可见性轮询,禁止同一轮询重叠,保留输入和账号/对话代际检查。 |
| 邮箱历史 | 最多 50 个 UID 一次 FETCH,保持降序、文件夹锁、UIDVALIDITY、消失邮件及分段协议响应处理;单封正文仍按需读取。 |
| 存储与文件预览 | 下载及 PDF 预览 Range 下推到同一验证过的文件句柄,IPC 只返回所需字节;检查头部、大小、路径身份和读前后变化。Office/图片仍完整验证,再返回所需片段;文本范围按解码后的 UTF-8 字节计算。 |
| 日历、异常、账号、计划、操作记录等 | 共用静态资源、轻顶栏、请求合并和生命周期改进;原编辑操作及权限保持。 |
## 一致性与刷新约束
GET 仅合并同账号、同页面代际和生命周期内尚未完成的相同请求,不缓存业务响应。调用方各自拥有取消信号和独立结果对象,取消一个调用方不会误取消其他调用方。写入前后清除可合并入口;手动刷新及扫描后的刷新取消旧检查,重新读取。旧导航的 401 不会清除新会话。
服务端只读上下文只活在一次同步调用内,禁止写入,并在公开返回边界复制结果;异步归档读取前后分别创建上下文。移除依赖单连接 `total_changes()` 的跨请求记录缓存,避免漏掉其他连接的更新。旧记录没有 portalSource 时仍视为命名空间重叠,多条匹配仍拒绝自动合并。没有跨请求缓存资格、权限或测试期限。
后台调度仍执行必要的到期处理;普通通知完成后独立惠州通知仍可进入原检查。只在进入昂贵身份读取前排除确实不能到期的历史状态,不缓存写事务内的业务读取。
公共资产缓存与业务数据分开:API、Cookie、订单文件继续 `no-store`;HTML 和无指纹资源使用 `max-age=0, must-revalidate`,安装文件变化后重新发送。预览壳的隔离 CSP 保留。更新检查只合并正在进行的请求,下次手动检查仍访问上游。
## 隔离测量
每项取 3 次中位数。同一查询夹具、固定时钟的 18 个前后比较,完整 JSON 的 SHA-256 及字节数全部一致;健康与邮件列表比较也保持完整输出一致。
| 工作负载 | 修改前 | 修改后 |
| --- | ---: | ---: |
| 300 条已发送历史,订单列表 | 7937 ms | 32 ms |
| 300 条待处理订单,订单列表 | 7824 ms | 69 ms |
| 300 条待处理订单,批次列表 | 12124 ms | 48 ms |
| 300 条待处理订单,业务摘要 | 9293 ms | 41 ms |
| 健康:300 任务及每份 100 KiB 样本 | 226 ms | 35 ms |
| 暂停调度:300 条历史,含到期处理 | 4272 ms | 15 ms |
| 50 封邮件,模拟每条协议命令延时 | 52 命令 / 1627 ms | 3 命令 / 94 ms |
| 8 个同时更新检查 | 8 个上游请求 | 1 个上游请求 |
| 16 MiB 文件,下载请求 64 KiB | 实读 16 MiB | 实读 64 KiB |
| 同上 PDF 预览 | 实读 16 MiB | 实读 64 KiB + 5 字节头部 |
查询耗时是同步函数时间;IMAP 使用模拟延迟,文件使用本地磁盘。上述数据不等同真实订单全流程、办公网络、实际邮箱或 SMB 的 SLA。
## 保留的后续空间
订单和任务仍在一次请求中整体读取一次,尚未引入数据库摘要投影;健康仍线性读取任务。页面仍载入现有脚本集合,尚未进行路由代码拆包。Office/图片因完整校验仍读取全文件。当前隔离 PDF 查看器仍由父页面传入完整 Blob,尚未改为渐进加载;Range 收益适用于实际发出 Range 的客户端,不能描述成当前查看器首屏已经只下载 64 KiB。PDF 浏览器池、渐进预览、异步 Git/修复执行器及数据库进程隔离需要独立的取消、崩溃和恢复设计。当前密码修改/创建账号的低频哈希仍是同步路径,普通登录已经移出主线程。
原始收据与抛弃式入口保存在忽略目录 `output/query-read-performance/` 和 `output/performance-refresh-20261028/`;不提交数据库副本、账号凭据、Cookie、密钥或真实订单内容。
+2
View File
@@ -91,6 +91,8 @@
以 Excel 类别维护精确的流程与触发节点配对,以及类别通知内容、To/Cc、模板、归档位置和验证状态。可搜索类别、导入规则文件、下载当前规则。导入先预览错误和变更,再一次性确认;错误行或并发版本变化会阻止整次提交。保存产生草稿,不会覆盖当前发布版本;真实待办样本检查通过且依赖完整后,管理员才可发布。字段目录须先在字段映射页采集。更新字段映射后,相关类别可能暂停并要求重新检查发布。
第04步先点击“读取已采集订单”,再选择样本并检查识别结果;它只读取已有采集记录,不会重新采集 BPM。刷新规则后如需验证,请重新读取样本。
本页检查一个真实样本不等于全部类别和表单版本都已验收。当前整体自动通知仍按首页及发送设置显示为暂停/待核验;不要把规则存在或发布描述成完整业务闭环。
### 字段映射
@@ -0,0 +1,64 @@
# 系统更新功能验证(2026-10-27)
功能基于开发分支 `codex/smb-storage` 的 `dcea4a0`,工作分支为 `codex/system-update`。未在测试中调用真实 BPM、SMTP 或 SMB 业务连接;新版本响应和截图使用隔离测试数据。
## 验证结果
| 检查 | 结果 |
| --- | --- |
| `npm ci` | 成功,349 个包;审计 0 条已知漏洞 |
| `npm test`(最终业务回归) | 304 通过,0 失败,0 跳过 |
| 更新功能专项 | 12 通过;包含 SemVer、稳定发行、404、网络超时、响应大小、链接、鉴权、详情转义、对比度及手机交互 |
| 更新功能 + 新版首页联合验证 | 21 通过 |
| `npm run test:full` | 1312 项:1278 通过、33 失败、1 跳过;未全绿 |
| 独立只读代码审查 | 说明文字颜色问题已修复并复核,无剩余已报告阻塞 |
| 真实 Gitea 只读检查 | 公开仓库发行列表为空,检查器返回 `none`,当前版本 `0.1.0` |
| 视觉验证 | 已查看桌面侧栏、发行详情和手机菜单截图;修复 Tabler 的浅底浅字问题 |
全量运行中发现的 DOM 最小夹具兼容问题已通过删除一个无用途的属性清理调用修复,原用例复验通过;上述原始全量汇总仍包含该次失败,不能据此宣称全量已通过。全量失败不自动全部归因于旧问题,未完成逐项基线核验的项目按下表保留。
原开发基线的抽样对照:13 项旧账号/界面失败及 BPM 登录、Excel 校验各 1 项同名失败复现;另有邮件历史与 DOM 生命周期用例在基线通过。任务恢复用例的基线复测遇到 Windows 加密调用超时,原因对照未完成。
## 全量运行失败清单
| 位置 | 用例 | 后续核验 |
| --- | --- | --- |
| tests/app/account-password.test.cjs:50:1 | password change closes only the target account BPM login windows | 在 dcea4a0 基线复现同名失败 |
| tests/app/business-records.test.cjs:25:1 | dismissal cancels late details, guards Escape drafts, and sent batch links include history | 在 dcea4a0 基线复现同名失败 |
| tests/app/execution-contract-ui.test.cjs:4:1 | real captured sample uses server evidence id and uncertain batch verification carries version and idempotency | 在 dcea4a0 基线复现同名失败 |
| tests/app/notification-navigation.test.cjs:32:1 | homepage background polling only announces updates and ignores responses after departure | 在 dcea4a0 基线复现同名失败 |
| tests/app/web-closure-review-ui.test.cjs:6:47 | Save and Continue preserves currentTarget for rule settings: internal | 在 dcea4a0 基线复现同名失败 |
| tests/app/web-closure-review-ui.test.cjs:18:1 | execution detail retains recovery notes during explicit list refresh and reopens with current version | 在 dcea4a0 基线复现同名失败 |
| tests/app/web-closure-review-ui.test.cjs:29:1 | field mapping save retains returned version after followup GET fails | 在 dcea4a0 基线复现同名失败 |
| tests/app/web-closure-review-ui.test.cjs:39:1 | unknown and conflicted task details cannot offer ordinary retry | 在 dcea4a0 基线复现同名失败 |
| tests/app/web-closure-ui.test.cjs:9:1 | execution scan, evidence-only field draft and check emit versioned contracts | 在 dcea4a0 基线复现同名失败 |
| tests/app/web-closure-ui.test.cjs:21:1 | calendar staged changes save through navigation and rule tab changes use the same guard | 在 dcea4a0 基线复现同名失败 |
| tests/app/web-closure-ui.test.cjs:22:1 | manual resend uses frozen batch identity and unknown offers verification only | 在 dcea4a0 基线复现同名失败 |
| tests/app/web-closure-ui.test.cjs:30:1 | a delayed execution response cannot replace the selected field directory | 在 dcea4a0 基线复现同名失败 |
| tests/app/web-closure-ui.test.cjs:31:1 | operator scans but cannot configure fields or resend, viewer has no scan action | 在 dcea4a0 基线复现同名失败 |
| tests/bpm/bpm-integration.test.cjs:9:1 | formal dashboard remote screen signs into an isolated BPM fixture under production CSP | 在 dcea4a0 基线复现同名失败 |
| tests/bpm/bpm-ui.test.cjs:264:1 | refresh and logout release BPM control before rendering or dropping authentication | 已移除无效属性清理调用,原用例独立复验通过 |
| tests/mail/history-ui.test.cjs:4:1 | history UI saves IMAP-only credentials locally, explicitly queries sent mail and displays escaped evidence | 全量中加密初始化失败;当前分支独立复跑通过 |
| tests/order-rules/business-config.test.cjs:13:1 | Excel reports unknown and duplicate categories, invalid addresses and stale versions without partial writes | 在 dcea4a0 基线复现同名失败 |
| tests/order-rules/failure-evidence-ui.test.cjs:4:1 | authorized users can explicitly revalidate only the original departed task while viewers cannot | 基线同名用例遇加密调用超时,尚未证实与全量相同原因 |
| tests/order-rules/huizhou-ui.test.cjs:41:1 | viewers can inspect Hui choices but cannot edit rules or confirm template modes | 尚未逐项基线复测 |
| tests/order-rules/huizhou-ui.test.cjs:48:1 | template confirmation sends selected Hui mode and lists mode-specific published usage | 尚未逐项基线复测 |
| tests/order-rules/order-driven-mapping-ui.test.cjs:5:1 | mapping output shows separate mail summary columns including shipping and zero without merging customer text | 尚未逐项基线复测 |
| tests/order-rules/order-driven-mapping-ui.test.cjs:12:1 | selecting an order locates its real version and recognizes zero and HA without configuration writes | 尚未逐项基线复测 |
| tests/order-rules/order-driven-mapping-ui.test.cjs:17:1 | ambiguous candidates edit page only, guard context changes, and an acknowledged lost save is verified before retry | 尚未逐项基线复测 |
| tests/order-rules/order-driven-mapping-ui.test.cjs:22:1 | a late proposal cannot replace a newer order and an expired login retires the page | 尚未逐项基线复测 |
| tests/order-rules/order-driven-mapping-ui.test.cjs:27:1 | operators and viewers only select their own evidence on both pages and never see configuration actions | 尚未逐项基线复测 |
| tests/order-rules/order-driven-mapping-ui.test.cjs:31:1 | an old check cannot confirm a different interrupted check request | 尚未逐项基线复测 |
| tests/order-rules/order-driven-mapping-ui.test.cjs:33:1 | saving a recommendation refreshes its displayed basis and persisted version | 尚未逐项基线复测 |
| tests/order-rules/order-driven-mapping-ui.test.cjs:35:1 | verified lost save, check and activation responses show one confirmed result without a contradictory unknown banner | 尚未逐项基线复测 |
| tests/order-rules/order-driven-mapping-ui.test.cjs:37:1 | a failed read-only proposal never creates an uncertain-write banner or state readback | 尚未逐项基线复测 |
| tests/order-rules/readiness-pending-ui.test.cjs:4:1 | healthy todo without matched orders shows pending verification without loosening capability gates | 全量中 Windows 加密调用超时;304 项业务回归中通过 |
| tests/order-rules/section-ui.test.cjs:11:1 | business homepage uses bounded summary and concrete remediation links | 尚未逐项基线复测 |
| tests/order-rules/test-preparation.test.cjs:26:1 | replacement freezes 15 source rules, preserves old records and holds only unfrozen previous-run orders | 尚未逐项基线复测 |
| tests/order-rules/workbench.test.cjs:40:1 | publication overlap uses paired rows and permits disjoint pairs sharing both columns | 尚未逐项基线复测 |
## 证据位置与范围
原始输出、聚合收据和隔离截图保存在工作区忽略目录 `output/system-update-review/`;不提交模拟发行或真实业务数据。完整命令结果也保留于本机临时目录的 `system-update-*-tests.log`。
当前未发布首个 Release。高版本可用场景通过隔离的 Gitea 响应验证;部署和实际更新仍由管理员按[发行流程](system-updates.md)执行。由于历史全量集未通过,本功能以草稿合并请求交付审查。
+1 -1
View File
@@ -13,7 +13,7 @@
"service:stop": "node scripts/service.cjs stop",
"service:restart": "node scripts/service.cjs restart",
"test": "npm run test:business",
"test:business": "node --test --test-concurrency=1 tests/service/supervisor-crash.test.cjs tests/app/business-home-ui.test.cjs tests/order-rules/home-summary.test.cjs tests/order-rules/carry-forward-core.test.cjs tests/order-rules/carry-forward-integration.test.cjs tests/order-rules/dispatch-unsent-proof.test.cjs tests/order-rules/dismiss-task.test.cjs tests/app/carry-dismiss-ui.test.cjs tests/workspace/business-issues.test.cjs tests/mail/unified-account.test.cjs tests/mail/unified-account-ui.test.cjs tests/assistant/workspace-events.test.cjs tests/assistant/dsh-events.test.cjs tests/assistant/workspace-http.test.cjs tests/assistant/events-client.test.cjs tests/assistant/diagnostic-workspace-ui.test.cjs tests/assistant/providers.test.cjs tests/assistant/providers-runtime.test.cjs tests/assistant/provider-http.test.cjs tests/assistant/providers-ui.test.cjs tests/assistant/action-results-ui.test.cjs tests/assistant/native-schedules.test.cjs tests/assistant/schedule-manager.test.cjs tests/assistant/schedules-http.test.cjs tests/assistant/schedule-proposals.test.cjs tests/assistant/schedules-ui.test.cjs tests/assistant/management.test.cjs tests/assistant/configuration.test.cjs tests/assistant/configuration-approval.test.cjs tests/assistant/configuration-ui.test.cjs tests/assistant/attachments.test.cjs tests/assistant/attachments-http.test.cjs tests/assistant/attachments-ui.test.cjs tests/assistant/model-capabilities.test.cjs tests/assistant/image-attachments.test.cjs tests/assistant/image-http.test.cjs tests/assistant/image-ui.test.cjs tests/assistant/toolbar-sidebar-ui.test.cjs tests/assistant/vision-transport.test.cjs tests/assistant/vision-runtime.test.cjs tests/assistant/conversation-trash.test.cjs tests/assistant/conversation-trash-ui.test.cjs tests/assistant/assistant-restore.test.cjs tests/assistant/assistant.test.cjs tests/assistant/assistant-http-ui.test.cjs tests/assistant/controlled-operations.test.cjs tests/assistant/dsh-runtime.test.cjs tests/assistant/dsh-runtime-installer.test.cjs tests/assistant/repair-validator.test.cjs tests/assistant/repair-runner.test.cjs tests/app/automatic-pdf-ledger.test.cjs tests/app/job-records.test.cjs tests/order-rules/version-compatibility.test.cjs tests/bpm-display-policy.test.cjs tests/bpm-dynamicarea.test.cjs tests/bpm-readonly-form.test.cjs tests/bpm-form-contracts.test.cjs tests/bpm-obsolete-display-fields.test.cjs tests/order-rules/snapshot-read-context.test.cjs tests/order-rules/summary.test.cjs tests/order-rules/execution-single-flight.test.cjs tests/order-rules/execution-responsiveness.test.cjs tests/order-rules/readiness-pending-ui.test.cjs tests/dependency-compatibility.test.cjs tests/order-rules/slow-cutoff.test.cjs tests/order-rules/removed-discovery-barrier.test.cjs tests/mail/template-test-policy.test.cjs tests/mail/sample-send.test.cjs tests/mail/template-editing.test.cjs tests/mail/template-editor-ui.test.cjs tests/order-rules/scope-catalog.test.cjs tests/order-rules/field-mapping-ui.test.cjs tests/order-rules/scope-search-ui.test.cjs tests/order-rules/excel-import-contract.test.cjs tests/order-rules/excel-execution-bridge.test.cjs tests/order-rules/excel-import-flow-ui.test.cjs tests/order-rules/collecting-batches.test.cjs tests/order-rules/collecting-batches-ui.test.cjs tests/order-rules/query.test.cjs tests/order-rules/scheduled-mail-policy.test.cjs",
"test:business": "node --test --test-concurrency=1 tests/service/supervisor-crash.test.cjs tests/app/business-home-ui.test.cjs tests/order-rules/home-summary.test.cjs tests/order-rules/carry-forward-core.test.cjs tests/order-rules/carry-forward-integration.test.cjs tests/order-rules/dispatch-unsent-proof.test.cjs tests/order-rules/dismiss-task.test.cjs tests/app/carry-dismiss-ui.test.cjs tests/workspace/business-issues.test.cjs tests/mail/unified-account.test.cjs tests/mail/unified-account-ui.test.cjs tests/assistant/assistant.test.cjs tests/assistant/assistant-http-ui.test.cjs tests/assistant/controlled-operations.test.cjs tests/assistant/dsh-runtime.test.cjs tests/assistant/dsh-runtime-installer.test.cjs tests/assistant/repair-validator.test.cjs tests/assistant/repair-runner.test.cjs tests/app/automatic-pdf-ledger.test.cjs tests/app/job-records.test.cjs tests/order-rules/version-compatibility.test.cjs tests/bpm-display-policy.test.cjs tests/bpm-dynamicarea.test.cjs tests/bpm-readonly-form.test.cjs tests/bpm-form-contracts.test.cjs tests/bpm-obsolete-display-fields.test.cjs tests/order-rules/snapshot-read-context.test.cjs tests/order-rules/summary.test.cjs tests/order-rules/execution-single-flight.test.cjs tests/order-rules/execution-responsiveness.test.cjs tests/order-rules/readiness-pending-ui.test.cjs tests/dependency-compatibility.test.cjs tests/order-rules/slow-cutoff.test.cjs tests/order-rules/removed-discovery-barrier.test.cjs tests/mail/template-test-policy.test.cjs tests/mail/sample-send.test.cjs tests/mail/template-editing.test.cjs tests/mail/template-editor-ui.test.cjs tests/order-rules/scope-catalog.test.cjs tests/order-rules/field-mapping-ui.test.cjs tests/order-rules/scope-search-ui.test.cjs tests/order-rules/excel-import-contract.test.cjs tests/order-rules/excel-execution-bridge.test.cjs tests/order-rules/excel-import-flow-ui.test.cjs tests/order-rules/collecting-batches.test.cjs tests/order-rules/collecting-batches-ui.test.cjs tests/order-rules/query.test.cjs tests/order-rules/scheduled-mail-policy.test.cjs tests/system-update/checker.test.cjs tests/system-update/system-update.test.cjs tests/order-rules/configuration.test.cjs tests/order-rules/configuration-ui.test.cjs tests/order-rules/workbench-ui.test.cjs tests/app/asset-delivery.test.cjs tests/app/authentication-responsiveness.test.cjs tests/app/backend-refresh-performance.test.cjs tests/app/read-refresh-performance.test.cjs tests/app/polling-performance-ui.test.cjs tests/order-rules/query-read-performance.test.cjs tests/mail/history.test.cjs tests/storage/storage-range.test.cjs tests/app/region-revisions.test.cjs tests/app/region-revisions-http.test.cjs tests/app/region-refresh.test.cjs tests/app/region-refresh-ui.test.cjs tests/app/region-selection.test.cjs tests/app/module-loader.test.cjs tests/app/module-loader-ui.test.cjs tests/service/service-supervisor.test.cjs tests/bpm/windows-directory.test.cjs tests/assistant/workspace-events.test.cjs tests/assistant/dsh-events.test.cjs tests/assistant/workspace-http.test.cjs tests/assistant/events-client.test.cjs tests/assistant/diagnostic-workspace-ui.test.cjs tests/assistant/providers.test.cjs tests/assistant/providers-runtime.test.cjs tests/assistant/provider-http.test.cjs tests/assistant/providers-ui.test.cjs tests/assistant/action-results-ui.test.cjs tests/assistant/native-schedules.test.cjs tests/assistant/schedule-manager.test.cjs tests/assistant/schedules-http.test.cjs tests/assistant/schedule-proposals.test.cjs tests/assistant/schedules-ui.test.cjs tests/assistant/management.test.cjs tests/assistant/configuration.test.cjs tests/assistant/configuration-approval.test.cjs tests/assistant/configuration-ui.test.cjs tests/assistant/attachments.test.cjs tests/assistant/attachments-http.test.cjs tests/assistant/attachments-ui.test.cjs tests/assistant/model-capabilities.test.cjs tests/assistant/image-attachments.test.cjs tests/assistant/image-http.test.cjs tests/assistant/image-ui.test.cjs tests/assistant/toolbar-sidebar-ui.test.cjs tests/assistant/vision-transport.test.cjs tests/assistant/vision-runtime.test.cjs tests/assistant/conversation-trash.test.cjs tests/assistant/conversation-trash-ui.test.cjs tests/assistant/assistant-restore.test.cjs tests/assistant/main-integration.test.cjs",
"test:full": "node --test --test-concurrency=2 \"tests/**/*.test.cjs\"",
"test:assistant": "node --test --test-concurrency=1 \"tests/assistant/*.test.cjs\"",
"format:assistant": "prettier --write \"src/modules/assistant/**/*.cjs\" \"web/modules/assistant/**/*.js\" \"tests/assistant/**/*.cjs\" \"tests/fixtures/isolated-vault-key.cjs\" \"tests/fixtures/provider-streams.cjs\"",
+3 -1
View File
@@ -28,6 +28,8 @@ const { OrderRuleDispatcher } = require('../modules/order-rules/dispatcher.cjs')
const { BpmOrderProvider } = require('../modules/bpm/order-provider.cjs');
const { OrderArchiveProvider } = require('../modules/storage/order-archive.cjs');
const { OrderExecutionCoordinator } = require('../modules/order-execution/coordinator.cjs');
const { createUpdateChecker } = require('../modules/system-update/checker.cjs');
const appVersion=require('../../package.json').version;
async function closeServer(server){
if(!server)return;
@@ -106,7 +108,7 @@ async function main(options = {}) {
await bpmSessions.migrateAccounts(workspace.snapshot().connections);
workspace.markSessionChecksPending();
server=await startService({token,port,outputDir,scale:config.scale,installedExtension,extensionSourceDir:path.join(root,'extension'),store,storage,watchdog,renderSnapshot:options.renderSnapshot});
dashboard=createDashboard({store,workspace,outputDir,bpmSessions,bpmMonitor,mail,scanner,storage,notifications,orderRules,orderExecution,orderDispatcher,assistant,health,watchdog,trustedProxy:dashboardConfig.trustedProxy===true});
dashboard=createDashboard({store,workspace,outputDir,bpmSessions,bpmMonitor,mail,scanner,storage,notifications,orderRules,orderExecution,orderDispatcher,assistant,health,watchdog,trustedProxy:dashboardConfig.trustedProxy===true,updateChecker:createUpdateChecker({currentVersion:appVersion})});
await new Promise((resolve,reject)=>{dashboard.once('error',reject);dashboard.listen(dashboardPort,dashboardHost,resolve);});store.recoverJobs();mailStore.recoverSends();custodian.start();mail.start();bpmMonitor.start();
health.start();
orderExecution.start();
+65
View File
@@ -0,0 +1,65 @@
'use strict';
const fs=require('node:fs/promises'),crypto=require('node:crypto'),zlib=require('node:zlib'),{promisify}=require('node:util');
const brotli=promisify(zlib.brotliCompress),gzip=promisify(zlib.gzip);
function encodingFor(header=''){
const weights=new Map(String(header).toLowerCase().split(',').map(value=>{const [name,...options]=value.trim().split(';');const q=options.find(item=>item.trim().startsWith('q='));return [name,q?Number(q.trim().slice(2)):1];}));
const weight=name=>{const value=weights.get(name)??(name==='identity'?(weights.get('*')===0?0:1):weights.get('*')??0);return Number.isFinite(value)&&value>=0&&value<=1?value:0;};
const choices=['br','gzip'].map(name=>({name,q:weight(name)})).filter(item=>item.q>0).sort((a,b)=>b.q-a.q);
if(weights.has('identity')&&weight('identity')>(choices[0]?.q||0))return 'identity';
return choices[0]?.name||(weight('identity')>0?'identity':null);
}
function requestedFingerprint(request){
try {
const url=new URL(request.url||'http://localhost/','http://localhost');
const values=url.searchParams.getAll('v');
return values.length===1&&/^[0-9a-f]{64}$/.test(values[0])?values[0]:null;
}catch{return null;}
}
// Only public assets from createAssets enter this bounded cache; APIs and managed
// files retain no-store. Stat validation allows an edited installation to update.
function createAssetDelivery({maxBytes=32*1024*1024,resolveAsset,moduleManifest}={}){
const cache=new Map(),pending=new Map();let size=0;
let documentValue=null,documentKey=null;
const valueFor=(bytes,version)=>{const fingerprint=crypto.createHash('sha256').update(bytes).digest('hex');return {version,bytes,fingerprint,etag:'W/"'+fingerprint+'"',encodings:new Map()};};
async function load(asset){
const stat=await fs.stat(asset.path),version=[stat.size,stat.mtimeMs,stat.ctimeMs].join(':'),saved=cache.get(asset.path);
if(saved?.version===version){cache.delete(asset.path);cache.set(asset.path,saved);return saved;}
const key=asset.path+':'+version;if(pending.has(key))return pending.get(key);
const work=(async()=>{
const bytes=await fs.readFile(asset.path),value=valueFor(bytes,version);
if(bytes.length<=maxBytes/2){const current=cache.get(asset.path);if(current){size-=current.size;cache.delete(asset.path);}value.size=bytes.length;cache.set(asset.path,value);size+=value.size;trim();}
return value;
})();pending.set(key,work);try{return await work;}finally{pending.delete(key);}
}
async function documentWithVersions(asset,value){
if(asset.type!=='text/html'||asset.preview||!resolveAsset)return value;
const source=value.bytes.toString('utf8'),modules=moduleManifest&&source.includes('<meta name="app-modules" content="">')?moduleManifest:null;
const urls=[...new Set([...Array.from(source.matchAll(/(?:src|href)="(\/(?!\/)[^"#]+)"/g),match=>match[1]),...Object.values(modules||{}).flat().filter(route=>!route.startsWith('$')).map(route=>'/'+route)])];
const versions=await Promise.all(urls.map(async route=>{const url=new URL(route,'http://localhost'),dependency=resolveAsset(url.pathname);if(!dependency||dependency.type==='text/html')return [route,route];const content=await load(dependency);url.searchParams.set('v',content.fingerprint);return [route,url.pathname+url.search];}));
const key=JSON.stringify([asset.path,value.fingerprint,versions,modules]);if(key===documentKey)return documentValue;
const replacements=new Map(versions);let html=source.replace(/((?:src|href)=")(\/(?!\/)[^"#]+)(")/g,(_,prefix,route,suffix)=>prefix+(replacements.get(route)||route)+suffix);
if(modules){const data=JSON.stringify({groups:modules,urls:Object.fromEntries(versions)}).replaceAll('&','&amp;').replaceAll('"','&quot;').replaceAll('<','&lt;').replaceAll('>','&gt;');html=html.replace('<meta name="app-modules" content="">',()=>'<meta name="app-modules" content="'+data+'">');}
const bytes=Buffer.from(html);
documentKey=key;documentValue=valueFor(bytes,key);return documentValue;
}
function trim(){while(size>maxBytes&&cache.size){const [key,value]=cache.entries().next().value;size-=value.size;cache.delete(key);}}
async function compressed(asset,value,encoding){
if(!value.encodings.has(encoding))value.encodings.set(encoding,(async()=>{
const bytes=encoding==='br'?await brotli(value.bytes,{params:{[zlib.constants.BROTLI_PARAM_QUALITY]:4}}):await gzip(value.bytes);
if(cache.get(asset.path)===value){value.size+=bytes.length;size+=bytes.length;trim();}return bytes;
})().catch(error=>{value.encodings.delete(encoding);throw error;}));
return value.encodings.get(encoding);
}
return async function deliver(request,response,asset){
const value=await documentWithVersions(asset,await load(asset)),encoding=encodingFor(request.headers['accept-encoding']);
const immutable=asset.type!=='text/html'&&requestedFingerprint(request)===value.fingerprint;
response.setHeader('Cache-Control',immutable?'public, max-age=31536000, immutable':'public, max-age=0, must-revalidate');response.setHeader('ETag',value.etag);response.setHeader('X-Asset-Version',value.fingerprint);response.setHeader('Vary','Accept-Encoding');
if(!encoding){response.writeHead(406);response.end();return;}
const tags=String(request.headers['if-none-match']||'').split(',').map(tag=>tag.trim().replace(/^W\//,''));
if(tags.includes('*')||tags.includes(value.etag.replace(/^W\//,''))){response.writeHead(304);response.end();return;}
const bytes=encoding==='identity'?value.bytes:await compressed(asset,value,encoding);
if(encoding!=='identity')response.setHeader('Content-Encoding',encoding);
response.writeHead(200,{'Content-Type':asset.type+(asset.binary?'':'; charset=utf-8'),'Content-Length':bytes.length});response.end(request.method==='HEAD'?undefined:bytes);
};
}
module.exports={createAssetDelivery};
+1
View File
@@ -7,6 +7,7 @@ function createAssets(){
'/app.js':{path:path.join(webRoot,'app.js'),type:'text/javascript'},
'/account.js':{path:path.join(webRoot,'modules/account/view.js'),type:'text/javascript'},
'/page-lifecycle.js':{path:path.join(webRoot,'modules/navigation/lifecycle.js'),type:'text/javascript'},
'/modules/navigation/module-loader.js':{path:path.join(webRoot,'modules/navigation/module-loader.js'),type:'text/javascript'},
'/navigation.js':{path:path.join(webRoot,'modules/navigation/view.js'),type:'text/javascript'},
'/workspace.js':{path:path.join(webRoot,'modules/workspace/view.js'),type:'text/javascript'},
'/bpm-sync-settings.js':{path:path.join(webRoot,'modules/bpm/sync-settings.js'),type:'text/javascript'},
+1 -1
View File
@@ -27,7 +27,7 @@ function createServer(options) {
const supplied = Buffer.from(String(request.headers['x-order-token'] || ''));
const expected = Buffer.from(options.token);
if (supplied.length !== expected.length || !crypto.timingSafeEqual(supplied, expected)) return reply(401, {error:'配对失效,请重新加载扩展。'});
if (request.method === 'GET' && request.url === '/health') return reply(200, {ok:true,version:'0.1.0',busy});
if (request.method === 'GET' && request.url === '/health') return reply(200, {ok:true,version:require('../../package.json').version,busy});
const jobRoute = /^\/jobs\/([a-f0-9]{32})$/.exec(request.url);
if (request.method === 'GET' && jobRoute) return jobs.has(jobRoute[1]) ? reply(200,jobs.get(jobRoute[1])) : reply(404,{error:'任务已过期,请检查输出目录后重试。'});
if (request.method !== 'POST' || request.url !== '/export') return reply(404, {error:'未知操作。'});
+15 -5
View File
@@ -1,4 +1,4 @@
const http=require('node:http');const fs=require('node:fs');
const http=require('node:http');
const {dashboardApi}=require('../modules/dashboard/api.cjs');
const {workspaceApi}=require('../modules/workspace/api.cjs');
const {bpmApi}=require('../modules/bpm/api.cjs');
@@ -8,19 +8,24 @@ const {storageApi}=require('../modules/storage/api.cjs');
const {notificationApi}=require('../modules/notifications/api.cjs');
const {orderRuleApi}=require('../modules/order-rules/api.cjs');
const {orderRuleQueryApi}=require('../modules/order-rules/query-api.cjs');
const {orderRuleConfigurationApi}=require('../modules/order-rules/configuration.cjs');
const {orderExecutionApi}=require('../modules/order-execution/api.cjs');
const {assistantApi}=require('../modules/assistant/api.cjs');
const {respondToPing}=require('../platform/service/ping.cjs');
const {createAssets,PREVIEW_CSP}=require('./assets.cjs');
const {createAssetDelivery}=require('./asset-delivery.cjs');
const {createRegionRevisions}=require('./region-revisions.cjs');
const {createAuth}=require('../modules/dashboard/auth.cjs');
const {prepareRequest,readBody}=require('./request.cjs');
const {BpmConnectionLifecycle}=require('../modules/bpm/connection-lifecycle.cjs');
function createDashboard({store,outputDir,workspace,bpmSessions,bpmMonitor,mail,scanner,storage,notifications,orderRules,orderExecution,orderDispatcher,assistant,health,watchdog,trustedProxy=false}) {
function createDashboard({store,outputDir,workspace,bpmSessions,bpmMonitor,mail,scanner,storage,notifications,orderRules,orderExecution,orderDispatcher,assistant,health,watchdog,trustedProxy=false,updateChecker}) {
const bpmLifecycle=workspace?new BpmConnectionLifecycle({workspace,manager:bpmSessions,monitor:bpmMonitor}):null;
const auth=createAuth({store,workspace,bpmSessions,bpmMonitor,bpmLifecycle});
const streams=assistant?new(require('../modules/assistant/event-stream.cjs').AssistantStreams)({store:assistant.store}):null;
let assetFor;try{assetFor=createAssets();}catch(error){auth.close();throw error;}
const deliverAsset=createAssetDelivery({resolveAsset:assetFor,moduleManifest:require('../../web/modules/navigation/module-manifest.json')});
const regionRevisions=createRegionRevisions({store,workspace,bpmSessions,bpmMonitor,mail,scanner,storage,orderRules,orderExecution,assistant,health});
const server=http.createServer(async(request,response)=>{
if(respondToPing(request,response,watchdog))return;
const {encryptedTransport,reply,fail}=prepareRequest(request,response,trustedProxy);
@@ -28,15 +33,19 @@ function createDashboard({store,outputDir,workspace,bpmSessions,bpmMonitor,mail,
const url=new URL(request.url,'http://localhost');const route=url.pathname;
const asset=assetFor(route);
if(/^\/vendor\/(embedpdf|photoswipe|docx|jszip|exceljs)\//.test(route)&&!asset)fail(404,'资源不存在。');
if(request.method==='GET' && asset) {
let bytes;try{bytes=await fs.promises.readFile(asset.path);}catch(error){if(error.code==='ENOENT')fail(404,'资源不存在。');throw error;}
if(['GET','HEAD'].includes(request.method) && asset) {
if(asset.preview){response.setHeader('Content-Security-Policy',PREVIEW_CSP);response.setHeader('Access-Control-Allow-Origin','*');}
response.writeHead(200,{'Content-Type':asset.type+(asset.binary?'':'; charset=utf-8')});response.end(bytes);return;
try{await deliverAsset(request,response,asset);}catch(error){if(error.code==='ENOENT')fail(404,'资源不存在。');throw error;}return;
}
const body=await readBody(request,fail);
const authResult=await auth.authenticate({request,response,route,body,reply,fail,encryptedTransport});
if(authResult.handled)return;
const {user,token}=authResult;
if(regionRevisions.api({route,url,method:request.method,user,response,reply}))return;
if(route==='/api/update' && request.method==='GET') {
const result=await (updateChecker|| (async()=>({status:'unavailable',currentVersion:require('../../package.json').version,latest:null})))();
return reply(200,result);
}
if(route==='/api/health' && request.method==='GET'){if(!health)fail(503,'健康状态服务未启动。');return reply(200,health.snapshot(user));}
if(await require('../modules/dashboard/maintenance.cjs').maintenanceApi({store,outputDir,user,route,method:request.method,reply,response}))return;
if(route==='/api/order-rules'&&request.method==='GET'&&url.searchParams.get('view')==='summary')workspace?.syncBusinessIssues?.(orderRules?.all('business-issues')||[],store.users());
@@ -45,6 +54,7 @@ function createDashboard({store,outputDir,workspace,bpmSessions,bpmMonitor,mail,
if(await bpmScanApi({scanner,workspace,bpmMonitor,orderRules,user,sessionId:token,url,route,method:request.method,body,reply}))return;
if(await storageApi({storage,workspace,user,url,route,method:request.method,body,request,response,reply,trustedProxy}))return;
if(await notificationApi({notifications,workspace,user,route,method:request.method,body,reply}))return;
if(orderRuleConfigurationApi({orderRules,mail,storage,workspace,user,url,route,method:request.method,reply}))return;
if(await orderRuleQueryApi({orderRules,execution:orderExecution,workspace,user,url,route,method:request.method,reply,response}))return;
if(await orderExecutionApi({execution:orderExecution,orderRules,dispatcher:orderDispatcher,workspace,user,sessionId:token,url,route,method:request.method,body,reply}))return;
if(await orderRuleApi({orderRules,mail,workspace,user,url,route,method:request.method,body,reply,response}))return;
+76
View File
@@ -0,0 +1,76 @@
'use strict';
const crypto=require('node:crypto');
const {readRevisions}=require('../shared/refresh-revisions.cjs');
const {upcomingWindow}=require('../modules/order-rules/window.cjs');
const {connectionSnapshot}=require('../modules/bpm/connection-status.cjs');
const REGION_NAMES=Object.freeze(['home','orderRules','records','health','bpm','assistant','storage','mail']);
const fail=()=>{throw Object.assign(Error('请先登录。'),{status:401});};
function createRegionRevisions(context){
// A new server always invalidates browser validators, including restored DBs.
// These are change validators only: a changed token requests a fresh bounded
// resource read; it never authorizes a write or claims that an external BPM,
// SMB, SMTP, or model provider is reachable. External side effects are folded
// in only through their persisted local observation/revision metadata.
const key=crypto.randomBytes(32);
const token=value=>crypto.createHmac('sha256',key).update(JSON.stringify(value)).digest('hex');
function snapshot(user,selection=REGION_NAMES){
if(!user||!user.id||!user.username||!['admin','operator','viewer'].includes(user.role)||user.enabled===false)fail();
if(!Array.isArray(selection)||!selection.length||selection.length>REGION_NAMES.length||new Set(selection).size!==selection.length||selection.some(name=>!REGION_NAMES.includes(name)))throw Object.assign(Error('刷新区域无效。'),{status:400});
const identity=[user.id,user.username,user.role,user.version||0,user.enabled!==false],now=new Date(context.clock?context.clock():Date.now()),memo=new Map();
const once=(name,read)=>{if(!memo.has(name)){try{memo.set(name,{value:read()});}catch(error){memo.set(name,{error});}}const result=memo.get(name);if(result.error)throw result.error;return result.value;};
const database=(name,store,scopes)=>once(name,()=>{if(!store)return {disabled:true};if(!store.db)throw Error('Revision source unavailable');return readRevisions(store.db,scopes);});
const workspace=scopes=>database('workspace:'+scopes.join(','),context.workspace,scopes);
const ownership=()=>once('ownership',()=>{
if(!context.workspace)return [];const db=context.workspace.db;if(!db)throw Error('Ownership source unavailable');
return db.prepare("SELECT id,json_extract(value,'$.owner') AS owner,'current' AS status,json_extract(value,'$.status')!='disabled' AS enabled FROM connections WHERE ?='admin' OR json_extract(value,'$.owner')=? UNION ALL SELECT id,json_extract(value,'$.owner') AS owner,'archived' AS status,0 AS enabled FROM connection_archives WHERE ?='admin' OR json_extract(value,'$.owner')=? ORDER BY id").all(user.role,user.username,user.role,user.username).map(c=>[c.id,c.owner,c.status,c.enabled]);
});
const rules=()=>database('rules',context.orderRules);
const configuration=()=>once('configuration',()=>Object.fromEntries(Object.entries(rules()).filter(([scope])=>!['orders','batches','execution-tasks','business-issues','audit'].some(kind=>scope==='records:'+kind)&&!scope.endsWith('-history'))));
const dashboard=()=>once('dashboard',()=>{if(!context.store?.database)throw Error('Export revision source unavailable');return context.store.database(db=>readRevisions(db,['pdf_jobs']));});
const mail=scopes=>database('mail:'+scopes.join(','),context.mail?.store,scopes);
const storage=scopes=>database('storage:'+scopes.join(','),context.storage?.store,scopes);
const scan=scopes=>database('scan:'+scopes.join(','),context.scanner?.store,scopes);
const timing=()=>once('timing',()=>{
if(!context.orderRules)return {disabled:true};
const schedule=context.store.settings().schedule,calendar=context.workspace?context.workspace.meta('calendar'):{version:0,overrides:[]},settings=context.orderRules.get('settings','main'),test=context.orderRules.get('stability-test','main');
const window=upcomingWindow(now,schedule,calendar.overrides),started=Date.parse(test?.startedAt),end=Date.parse(test?.endsAt),expired=test?.enabled===true&&(!Number.isFinite(started)||!Number.isFinite(end)||end<=started||+now>=end);
return {settingsVersion:settings?.version,schedule,calendarVersion:calendar.version,window,collection:window?(+now<Date.parse(window.collectionStart)?'before':+now<Date.parse(window.collectionEnd)?'open':'closed'):null,expired,day:new Date(+now+28800000).toISOString().slice(0,10)};
});
const bpm=()=>once('bpm',()=>{
if(!context.workspace)return [];
const ids=new Set(ownership().map(row=>row[0]));
const connections=context.workspace.db.prepare('SELECT value FROM connections ORDER BY id').all().map(row=>JSON.parse(row.value)).filter(c=>ids.has(c.id));
const config=context.scanner?context.scanner.store.config():{};
return connections.map(c=>connectionSnapshot(c,{manager:context.bpmSessions,monitor:context.bpmMonitor,config,now:+now}));
});
const readers={
home:()=>[rules(),ownership(),workspace(['connections','connection_archives','exceptions','metadata:calendar']),mail(['channels','templates']),storage(['servers','settings']),scan(['config','runs']),context.orderRules?.capabilities,timing()],
orderRules:()=>[configuration(),ownership(),workspace(['connections','connection_archives','metadata:calendar']),mail(['channels','templates','meta']),storage(['servers','settings']),context.orderRules?.capabilities,timing()],
records:()=>[rules(),ownership(),workspace(['connections','connection_archives']),dashboard(),scan(['arrivals','runs','config']),storage(['archives','servers']),mail(['channels','templates','meta']),timing()],
// Health contains uptime/event-loop/supervisor observations without a revision
// API. Its ten-second bucket preserves the existing maximum polling interval.
health:()=>context.health?[rules(),ownership(),workspace(['connections','exceptions']),mail(['channels']),storage(['servers','archives']),scan(['config','runs','execution_deliveries']),bpm(),context.health.instanceId,context.health.startedAt,Math.floor(+now/10000)]:['disabled'],
bpm:()=>[ownership(),workspace(['connections','connection_archives','exceptions']),scan(['config','runs','execution_deliveries']),bpm()],
assistant:()=>{
if(!context.assistant)return ['disabled'];const db=context.assistant.store?.db;if(!db)throw Error('Assistant revision source unavailable');
const day=new Date(+now+28800000).toISOString().slice(0,10);
const journal=context.assistant.journal?.db,operations=journal?journal.prepare('SELECT MAX(id) AS latest FROM operation_events'+(user.role==='admin'?'':' WHERE actor=?')).get(...(user.role==='admin'?[]:[user.id])).latest:null;
return [database('assistant',context.assistant.store,['config','owner:'+user.id,'usage:'+day]),day,operations];
},
storage:()=>[storage(['servers','settings','archives'])],
mail:()=>[mail(['channels','templates','receipts','sends','meta'])]
};
const regions={},errors={};
for(const name of selection){try{regions[name]=token([1,name,identity,readers[name]()]);}catch{regions[name]=crypto.randomBytes(32).toString('hex');errors[name]='暂时无法核实此区域是否更新,请重新读取并核对。';}}
return {version:1,regions,...(Object.keys(errors).length?{errors}:{})};
}
function api({route,url,method,user,response,reply}){
if(route!=='/api/refresh/revisions'||method!=='GET')return false;
response?.setHeader?.('Cache-Control','no-store');
const selections=url?.searchParams.getAll('regions')||[];
if(selections.length>1)throw Object.assign(Error('刷新区域无效。'),{status:400});
reply(200,snapshot(user,selections.length?selections[0].split(','):undefined));return true;
}
return {snapshot,api};
}
module.exports={createRegionRevisions,REGION_NAMES};
@@ -96,6 +96,10 @@ class NativeSchedules {
this.store.db.exec(
"CREATE TABLE IF NOT EXISTS assistant_schedule_tasks(id TEXT PRIMARY KEY,conversation_id TEXT NOT NULL,owner TEXT NOT NULL,payload BLOB NOT NULL,last_error TEXT NOT NULL DEFAULT '');CREATE TABLE IF NOT EXISTS assistant_schedule_inbox(id TEXT PRIMARY KEY,conversation_id TEXT NOT NULL,owner TEXT NOT NULL,task_id TEXT NOT NULL,status TEXT NOT NULL,turn_id TEXT,payload BLOB NOT NULL,created_at TEXT NOT NULL);CREATE INDEX IF NOT EXISTS schedule_inbox_owner ON assistant_schedule_inbox(owner,created_at);UPDATE assistant_schedule_inbox SET status='queued' WHERE status='running';",
);
require('../../shared/refresh-revisions.cjs').installRevisionTracking(this.store.db, [
['assistant_schedule_tasks', "'owner:' || $row.owner"],
['assistant_schedule_inbox', "'owner:' || $row.owner"],
]);
const schema = this.module.scheduleDomain.tables.tasks.valueSchema;
for (const row of this.store.db.prepare('SELECT * FROM assistant_schedule_tasks').all()) {
const value = schema.parse(this.store.decode('schedule-task:' + row.id, row.payload));
+9
View File
@@ -48,6 +48,15 @@ class AssistantStore {
.run(this.encode('config', { ...raw, apiKey: '' }));
}
});
require('../../shared/refresh-revisions.cjs').installRevisionTracking(this.db, [
'config',
['conversations', "'owner:' || $row.owner"],
['turns', "'owner:' || (SELECT owner FROM conversations WHERE id=$row.conversation_id)"],
['turns', "'usage:' || $row.day", 'OLD.day IS NOT NEW.day'],
['assistant_usage', "'usage:' || $row.day"],
['assistant_providers', "'config'"],
['assistant_provider_defaults', "'config'"],
]);
} catch (error) {
try {
this.db?.close();
+1
View File
@@ -14,6 +14,7 @@ class BpmScanStore{
UPDATE runs SET status='error',message='服务重启,扫描未完成。',finished_at=CURRENT_TIMESTAMP WHERE status='running';`);
if(!this.db.prepare('PRAGMA table_info(runs)').all().some(c=>c.name==='kind'))this.db.exec("ALTER TABLE runs ADD COLUMN kind TEXT NOT NULL DEFAULT 'inform'");
this.deliveries=new ScanDeliveries({db:this.db,dir});
require('../../shared/refresh-revisions.cjs').installRevisionTracking(this.db,['config','arrivals','runs','execution_deliveries']);
} catch(error) {
try { this.db?.close(); } catch {}
throw error;
+7 -3
View File
@@ -3,7 +3,7 @@ const {SessionStore,SESSION_MS}=require('./sessions.cjs');
const {isLoopback}=require('../../app/request.cjs');
const {validateChange}=require('./passwords.cjs');
function createAuth({store,workspace,bpmSessions,bpmMonitor,bpmLifecycle}){
const sessions=new SessionStore(path.dirname(store.file));const failures=new Map(),passwordFailures=new Map();
const sessions=new SessionStore(path.dirname(store.file));const failures=new Map(),passwordFailures=new Map(),pendingLogins=new Map();
const cleanup=require('./pending-cleanup.cjs').accessCleanup({store,workspace,bpmSessions,bpmMonitor,bpmLifecycle,sessions});
const sessionCookieName='order_session';
const sessionCookiePattern=new RegExp('(?:^|;\\s*)'+sessionCookieName+'=([a-f0-9]{64})(?:;|$)');
@@ -24,8 +24,12 @@ const handled=(...args)=>{reply(...args);return {handled:true};};
if(route==='/api/login' && request.method==='POST') {
const address=request.socket.remoteAddress;const now=Date.now();
for(const [key,value] of failures)if(now-value.since>900000)failures.delete(key);
if(failures.get(address)?.count>=10)fail(429,'登录失败次数过多,请 15 分钟后重试。');
const user=store.authenticate(body.username,body.password);
if((failures.get(address)?.count||0)+(pendingLogins.get(address)||0)>=10)fail(429,'登录失败次数过多,请 15 分钟后重试。');
const candidate=typeof body.username==='string'?store.users().find(member=>member.username.toLowerCase()===body.username.toLowerCase()):null;
const passwordVersion=candidate?store.passwordVersion(candidate.id):null;
pendingLogins.set(address,(pendingLogins.get(address)||0)+1);
let user;try{user=await store.authenticateAsync(body.username,body.password);}finally{const pending=(pendingLogins.get(address)||1)-1;if(pending)pendingLogins.set(address,pending);else pendingLogins.delete(address);}
if(user&&(!candidate||user.id!==candidate.id||store.passwordVersion(user.id)!==passwordVersion||store.user(user.id)?.enabled===false))user=null;
if(!user){if(failures.size>1000)failures.clear();const previous=failures.get(address);failures.set(address,{since:previous?.since || now,count:(previous?.count || 0)+1});fail(401,'账号或密码不正确。');}
failures.delete(address);return handled(200,{user:signIn(user)});
}
+15 -1
View File
@@ -1,5 +1,14 @@
'use strict';
const crypto=require('node:crypto');
const {promisify}=require('node:util');
const scrypt=promisify(crypto.scrypt),passwordQueue=[];let active=0;
function schedulePassword(work){
if(active>=4&&passwordQueue.length>=32)return Promise.reject(Object.assign(Error('登录验证繁忙,请稍后重试。'),{status:429}));
return new Promise((resolve,reject)=>{
const start=()=>{active++;Promise.resolve().then(work).then(resolve,reject).finally(()=>{active--;passwordQueue.shift()?.();});};
if(active<4)start();else passwordQueue.push(start);
});
}
const fail=message=>{throw Object.assign(new Error(message),{status:400});};
function validatePassword(password){if(typeof password!=='string'||password.length<12||password.length>128)fail('密码长度需为 12–128 位。');}
function hashPassword(password){validatePassword(password);const salt=crypto.randomBytes(16).toString('hex');return salt+':'+crypto.scryptSync(password,salt,32).toString('hex');}
@@ -9,10 +18,15 @@ function matchesPassword(password,encoded){
const actual=crypto.scryptSync(password,salt,32),expected=Buffer.from(hash||'','hex');
return expected.length===actual.length&&crypto.timingSafeEqual(actual,expected);
}
async function matchesPasswordAsync(password,encoded){
if(typeof password!=='string'||password.length>128)return false;
const [salt,hash]=(encoded||'00000000000000000000000000000000:'+ '0'.repeat(64)).split(':');
return schedulePassword(async()=>{const actual=await scrypt(password,salt,32),expected=Buffer.from(hash||'','hex');return expected.length===actual.length&&crypto.timingSafeEqual(actual,expected);});
}
function validateChange(body){
if(!body||Object.keys(body).some(key=>!['currentPassword','newPassword','confirmPassword'].includes(key)))fail('密码修改内容不正确。');
if(typeof body.currentPassword!=='string'||!body.currentPassword||body.currentPassword.length>128)fail('请填写当前密码。');
validatePassword(body.newPassword);
if(body.confirmPassword!==body.newPassword)fail('两次输入的新密码不一致。');
}
module.exports={validatePassword,hashPassword,matchesPassword,validateChange};
module.exports={validatePassword,hashPassword,matchesPassword,matchesPasswordAsync,validateChange};
+12 -1
View File
@@ -2,7 +2,7 @@ const fs=require('node:fs');
const path=require('node:path');
const crypto=require('node:crypto');
const {DatabaseSync}=require('node:sqlite');
const {validatePassword,hashPassword,matchesPassword}=require('./passwords.cjs');
const {validatePassword,hashPassword,matchesPassword,matchesPasswordAsync}=require('./passwords.cjs');
const {JobStore}=require('./job-store.cjs');
const copy=value=>structuredClone(value);
const safeUser=({id,username,role,createdAt,enabled=true,version=1})=>({id,username,role,createdAt,enabled,version});
@@ -43,6 +43,7 @@ class Store {
return JSON.parse(db.prepare('SELECT value FROM dashboard_state WHERE id=1').get().value);
});
this.jobStore=new JobStore(this);
this.database(db=>require('../../shared/refresh-revisions.cjs').installRevisionTracking(db,['pdf_jobs','dashboard_state']));
}
database(work){
const db=new DatabaseSync(this.file);
@@ -93,6 +94,16 @@ class Store {
return safeUser(user);
}
passwordVersion(id){return this.data.users.find(user=>user.id===id)?.passwordVersion||0;}
async authenticateAsync(username,password){
if(typeof username!=='string'||typeof password!=='string'||password.length>128)return null;
const prior=this.data.users.find(user=>user.username.toLowerCase()===username.toLowerCase());
const passwordHash=prior?.passwordHash,version=prior?.passwordVersion||0;
const matches=await matchesPasswordAsync(password,passwordHash);
// Password/role changes can commit while the worker pool verifies the hash.
const current=prior&&this.data.users.find(user=>user.id===prior.id);
if(!matches||!current||current.enabled===false||current.passwordHash!==passwordHash||(current.passwordVersion||0)!==version)return null;
return safeUser(current);
}
validateUserChange(id,input,actor){
if(actor?.role!=='admin')fail('仅管理员可以调整账号。',403);
const target=this.user(id);if(!target)fail('账号不存在。',404);
+1 -1
View File
@@ -60,7 +60,7 @@ class RuntimeHealth {
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','分类订单执行','#notification-execution',()=>{
const data=this.sources.execution.snapshot(),names={liveTodo:'真实待办',pdfExport:'PDF 导出',automaticArchive:'归档校验'};
const execution=this.sources.execution,data=typeof execution.healthSnapshot==='function'?execution.healthSnapshot():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?'实际检查已通过;各类别仍需现场核验。':'尚未通过实际接入检查,请在订单通知管理的订单执行查看阻塞原因。'}));
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})});}
+7 -5
View File
@@ -25,11 +25,13 @@ async function readHistory(client,input={}){
try{
const uidValidity=String(client.mailbox.uidValidity);
if(input.action==='search'){
const found=await client.search(query,{uid:true}),uids=(found||[]).filter(Number.isSafeInteger).sort((a,b)=>b-a),messages=[];
for(const uid of uids.slice(0,limit)){
const info=await client.fetchOne(uid,{envelope:true,size:true},{uid:true});if(!info)continue;
messages.push({uid,subject:info.envelope?.subject||'',date:info.envelope?.date?.toISOString()||null,to:addresses(info.envelope?.to),cc:addresses(info.envelope?.cc),size:info.size});
}
const found=await client.search(query,{uid:true}),uids=(found||[]).filter(uid=>Number.isSafeInteger(uid)&&uid>0).sort((a,b)=>b-a),selected=uids.slice(0,limit),envelopes=new Map();
// FETCH emits mailbox sequence order; retain the selected UID order even when
// messages disappear between SEARCH and FETCH. An empty set must never mean '*'.
if(selected.length)for await(const info of client.fetch(selected.join(','),{uid:true,envelope:true,size:true},{uid:true}))if(selected.includes(info.uid))envelopes.set(info.uid,{...envelopes.get(info.uid),...info});
const messages=selected.flatMap(uid=>{
const info=envelopes.get(uid);return info?[{uid,subject:info.envelope?.subject||'',date:info.envelope?.date?.toISOString()||null,to:addresses(info.envelope?.to),cc:addresses(info.envelope?.cc),size:info.size}]:[];
});
return {folder:input.folder,uidValidity,messages,truncated:uids.length>limit};
}
if(!Number.isSafeInteger(input.uid)||input.uid<=0)fail('邮件标识无效。');
+1
View File
@@ -20,6 +20,7 @@ class MailStore{
if(columns!=='channel_id,scope,notification_mode')this.db.exec("DROP INDEX IF EXISTS active_template; CREATE UNIQUE INDEX active_template ON templates(channel_id,scope,notification_mode) WHERE status='active'");
});
for(const r of this.db.prepare("SELECT id,payload FROM templates WHERE summary='{}'").all()){const p=this.decode(r.id,r.payload);this.db.prepare('UPDATE templates SET summary=? WHERE id=?').run(this.summary(p),r.id);}
require('../../shared/refresh-revisions.cjs').installRevisionTracking(this.db,['channels','templates','receipts','sends','meta']);
} catch(error) {
try { this.db?.close(); } catch {}
try { this.vault?.destroy(); } catch {}
@@ -141,6 +141,17 @@ class OrderExecutionCoordinator{
try{this.connection(task.connectionId,principal);return true;}
catch{return false;}
}
healthSnapshot(){
// Health consumes persisted progress, never captured fields or discovery views.
const tasks=this.store.all('execution-tasks').map(task=>{
const order=task.orderId&&this.store.get('orders',task.orderId);
const activeStatus=['failed','unknown','blocked','capturing','archiving'].includes(task.status);
return {id:task.id,connectionId:task.connectionId,processName:task.row?.processName,
status:activeStatus?task.status:order?.status||task.status,updatedAt:task.updatedAt,
error:task.error||order?.error||null,reason:task.reason,blockedReason:task.blockedReason};
}).reverse();
return {tasks,capabilities:clone(this.store.capabilities)};
}
snapshot(principal,{includeFieldEvidence=false}={}){
const allowed=id=>!principal||require('../order-rules/access.cjs').canReadConnection(this.workspace,principal.user,id);
const fields=this.store.fields();
+4 -3
View File
@@ -1,6 +1,7 @@
'use strict';
const {fail,validateRule}=require('./validation.cjs');
const {checkTemplates}=require('./template-validation.cjs');
const {ruleReceipt,restrictedReceipt}=require('./configuration.cjs');
async function orderRuleApi({orderRules,mail,workspace,user,url,route,method,body,reply,response}){
if(route!=='/api/order-rules'&&!route.startsWith('/api/order-rules/'))return false;
if(!orderRules)fail('分类通知规则服务未启动。',503);
@@ -39,12 +40,12 @@ async function orderRuleApi({orderRules,mail,workspace,user,url,route,method,bod
else if(route==='/api/order-rules/import/commit')result=require('./import.cjs').commitImport(orderRules,body,actor,{mail,user});
else if(route==='/api/order-rules/restricted-test/apply'){
for(const item of Array.isArray(body?.rules)?body.rules:[]){const record=orderRules.get('rules',item?.id);if(record)checkTemplates(mail,record.draft);}
result=orderRules.applyRestrictedDrafts(body,user);
result=restrictedReceipt(orderRules,orderRules.applyRestrictedDrafts(body,user));
}
else if(route==='/api/order-rules/rules'){
const old=orderRules.get('rules',body?.id)?.draft;
if(old)checkTemplates(mail,validateRule(body,old));
result=orderRules.saveRule(body,actor);
result=ruleReceipt(orderRules,orderRules.saveRule(body,actor));
}
else if(route==='/api/order-rules/settings'){
if(body?.enabled){if(!mail)fail('发件邮箱服务未启动。',409);const channel=mail.store.publicChannel(body.channelId);if(!channel.state.smtp)fail('请先验证发件邮箱 SMTP。',409);}
@@ -60,7 +61,7 @@ async function orderRuleApi({orderRules,mail,workspace,user,url,route,method,bod
const recheck=/^\/api\/order-rules\/orders\/([\w-]+)\/recheck$/.exec(route);
if(rule){if(!body||Object.keys(body).some(k=>!['version','publishedVersion','activationVersion'].includes(k)))fail('请提供当前规则和启停版本。');const record=orderRules.get('rules',rule[1]);if(rule[2]==='publish'){if(!record?.trialSampleId||!orderRules.get('capture-samples',record.trialSampleId))fail('发布前必须选择服务端真实采集样本完成试运行。',409);}
if(rule[2]!=='pause'){const selected=rule[2]==='resume'?record?.published:record?.draft;checkTemplates(mail,selected);}
result=orderRules[rule[2]](rule[1],body,actor);}
result=ruleReceipt(orderRules,orderRules[rule[2]](rule[1],body,actor));}
else if(batch){if(!body||Object.keys(body).some(k=>!['version','idempotencyKey','resolution','note'].includes(k)))fail('核验内容无效。');result=orderRules.resolve(batch[1],body,actor,{controlled:true});}
else if(recheck){if(!body||Object.keys(body).some(k=>k!=='note'))fail('重新识别内容无效。');result=orderRules.recheck(recheck[1],body,actor);}
else fail('没有找到此规则操作。',404);
+10 -3
View File
@@ -11,7 +11,7 @@ function associated(store,order,mode){return store.all('batches').filter(b=>mode
function safeHistory(batches){return batches.every(b=>proof(b)&&(b.status==='failed'||b.status==='cancelled'&&b.resolution?.resolution==='carry_forward'));}
function qualified(store,order,{active=true}={}){
if(!order||order.removedAt||!order.categoryId||!order.sample||!receipt(order.archive)||!order.ruleSnapshot)return null;
const tasks=store.all('execution-tasks').filter(t=>t.orderId===order.id);if(tasks.length!==1)return null;const task=tasks[0];
const tasks=require('./read-context.cjs').byOrder(store,'execution-tasks',order.id);if(tasks.length!==1)return null;const task=tasks[0];
if(task.removedAt||task.supersededBy||task.revisionIgnored||task.conflict||task.blockedByBatchId||!['complete','missed_window'].includes(task.step))return null;
if(!identity.sameTask(task.row,order.sample)||['source','portalSource','taskId','instanceId','revision','processName','nodeName','receivedAt'].some(k=>String(task.row?.[k])!==String(order.sample[k])))return null;
const captured=store.get('capture-samples',task.sampleId||'');if(captured?.provenance!=='server-provider'||captured.taskId!==task.id||typeof captured.snapshot?.html!=='string'||!captured.snapshot.html.trim()||!captured.sample||identity.fingerprint(captured.sample)!==identity.fingerprint(order.sample))return null;
@@ -24,6 +24,11 @@ function qualified(store,order,{active=true}={}){
return {task,original};
}
function windowForOrder(store,value,mode='normal'){
const context=require('./read-context.cjs').state(store);
if(context&&value?.id){const key=JSON.stringify(['carry',value.id,mode]);if(!context.memo.has(key))context.memo.set(key,readWindow(store,value,mode));return context.memo.get(key);}
return readWindow(store,value,mode);
}
function readWindow(store,value,mode){
if(!['normal','huizhou'].includes(mode))return null;
// A Hui projection replaces event/order numbers. Always validate the persisted source.
const order=value?.id&&store.get('orders',value.id),stamp=order?.carryForward?.[mode];if(!stamp||stamp.basisHash!==basis(order)||!qualified(store,order,{active:false}))return null;
@@ -37,11 +42,13 @@ function knownMissed(store,value,original,stamp){
return ['start','end','collectionStart','collectionEnd','collectionLeadMinutes','policyVersion','startInclusive','endInclusive'].every(key=>value[key]===expected[key]);
}
function candidate(store,order,mode){
const q=qualified(store,order),state=delivery(order,mode);if(!q||!state||order.blockedByBatchId||state.blockedByBatchId||!['pending','blocked','archived'].includes(state.status))return null;
const state=delivery(order,mode);if(!state||order.blockedByBatchId||state.blockedByBatchId||!['pending','blocked','archived'].includes(state.status))return null;
if(mode==='huizhou'&&(order.ruleSnapshot?.huizhouEnabled!==true||!state.orderNos?.length||state.issues?.length||!['pending','blocked','archived','batched','sent','unknown'].includes(order.status)))return null;
const q=qualified(store,order);if(!q)return null;
const batches=associated(store,order,mode);if(!safeHistory(batches))return null;
const failed=batches.filter(b=>b.status==='failed');if(state.batchId&&!failed.some(b=>b.id===state.batchId))return null;
if(mode==='normal'&&['unknown','sending','sent','ignored','archiving','capturing','failed'].includes(q.task.status))return null;
if(mode==='huizhou'&&(order.ruleSnapshot.huizhouEnabled!==true||!state.orderNos?.length||state.issues?.length||!['pending','blocked','archived','batched','sent','unknown'].includes(order.status)||q.task.step!=='complete'&&q.task.step!=='missed_window'))return null;
if(mode==='huizhou'&&q.task.step!=='complete'&&q.task.step!=='missed_window')return null;
const stamp=order.carryForward?.[mode];if(stamp&&!windowForOrder(store,order,mode))return null;
if(!knownMissed(store,mode==='normal'?order.missedWindow:state.missedWindow,q.original,stamp)||mode==='normal'&&!knownMissed(store,q.task.missedWindow,q.original,stamp))return null;
return {...q,order,mode,state,stamp,failed,previous:stamp?.targetCutoff||q.original.end};
@@ -14,18 +14,19 @@ function contentFor(store,rule,cutoff,mode,template){
if(template?.attachments?.length)fail('业务通知模板禁止附件,批次编辑不能覆盖此限制。',409);
return {template:{...(template||{}),id:template?.id||rule.bodyTemplateId||id,version:template?.version||rule.version,notificationMode:mode,status:'active',attachments:[],subject:saved.subject,text:saved.text,html:saved.html},edit:{id,version:saved.version,updatedAt:saved.updatedAt,updatedBy:saved.updatedBy}};
}
function list(store,{cutoff}={}){
function list(store,options={}){return structuredClone(readList(require('./read-context.cjs').readStore(store),options));}
function readList(store,{cutoff}={}){
if(typeof store.clock!=='function'||typeof store.schedule!=='function'||typeof store.calendar!=='function')return [];
const window=cutoff?require('./window.cjs').windowForCutoff(cutoff,store.schedule(),store.calendar()):upcomingWindow(store.clock(),store.schedule(),store.calendar());if(!window)return [];
const groups=new Map(),frozen=store.all('batches');
const groups=new Map(),frozen=new Set(store.all('batches').filter(b=>b.cutoff===window.end).map(b=>JSON.stringify([b.categoryId,b.notificationMode||'normal'])));
for(const order of store.all('orders')){
const rule=order.ruleSnapshot;if(order.removedAt||!rule?.id||!rule.categoryId||!require('./scopes.cjs').matchesScope(rule,order.event||{}))continue;
if(order.blockedByBatchId||order.status==='ignored')continue;
for(const mode of ['normal','huizhou']){
const carried=require('./carry-forward.cjs').windowForOrder(store,order,mode);if(order.missedWindow&&!carried||!require('./restricted-test.cjs').orderInWindow(store,order,window,mode))continue;
const notice=delivery(order,mode);if(!notice||notice.batchId||!['identified','preparing','archived','pending','blocked','failed'].includes(notice.status))continue;
if(mode==='huizhou'&&rule.huizhouEnabled!==true)continue;
if(frozen.some(b=>b.categoryId===rule.categoryId&&(b.notificationMode||'normal')===mode&&b.cutoff===window.end))continue;
if(frozen.has(JSON.stringify([rule.categoryId,mode])))continue;
const carried=require('./carry-forward.cjs').windowForOrder(store,order,mode);if(order.missedWindow&&!carried||!require('./restricted-test.cjs').orderInWindow(store,order,window,mode))continue;
const id=idFor(rule,window.end,mode);if(!groups.has(id))groups.set(id,{id,status:'collecting',categoryId:rule.categoryId,notificationMode:mode,cutoff:window.end,window,windowStart:window.start,windowEnd:window.end,rule,orders:[],orderIds:[],attachments:[],createdAt:order.ingestedAt||order.createdAt,...(rule.testRunId?{testRunId:rule.testRunId}:{})});const group=groups.get(id);group.orders.push(order);group.orderIds.push(order.id);
}
}
+55
View File
@@ -0,0 +1,55 @@
'use strict';
const {fail}=require('./validation.cjs');
const {canReadConnection}=require('./access.cjs');
const pick=(value,keys)=>Object.fromEntries(keys.filter(key=>Object.hasOwn(value,key)).map(key=>[key,value[key]]));
const adapterKeys=['id','processName','processVersion','verified','reference','status','label','sampleId'];
const templateKeys=['id','channelId','scope','notificationMode','status','version','createdAt','subject','sender','attachmentCount'];
const serverKeys=['id','version','name','host','share','directory','username','enabled','state','hasPassword','createdAt','updatedAt','address','authMode','passwordless'];
const sampleKeys=['connectionId','source','processVersion','nodeName','serialNum','title','receivedAt'];
function configuration(orderRules,mail,storage){
const snapshot=orderRules.snapshot({includeRecords:false}),errors={};
const resource=(key,read)=>{try{return read();}catch{errors[key]={templates:'邮件模板暂不可读取,请稍后重试。',bindings:'类别模板关联暂不可读取,请稍后重试。',servers:'归档服务器暂不可读取,请稍后重试。'}[key];return null;}};
const bindings=resource('bindings',()=>mail.store.categoryBindings().map(value=>pick(value,['categoryId','templateId','version'])));
const bound=new Set([...(bindings||[]).map(value=>value.templateId),...snapshot.rules.flatMap(rule=>[rule.bodyTemplateId,rule.huizhouTemplateId])].filter(Boolean));
const templates=resource('templates',()=>mail.store.templates().filter(value=>value.status==='active'||bound.has(value.id)).map(value=>pick(value,templateKeys)));
const servers=resource('servers',()=>storage.store.servers().map(value=>pick(value,serverKeys)));
let scopeProcesses=[],scopeCatalog=[],scopeError=null;
try{const directory=require('./scope-catalog.cjs').directory(orderRules);scopeProcesses=directory.processes;scopeCatalog=directory.scopes;}
catch{scopeError='流程节点目录暂不可读取,请稍后重试。';}
return {rules:snapshot.rules.map(rule=>({huizhouEnabled:false,huizhouTemplateId:'',...rule})),adapters:snapshot.adapters.map(value=>pick(value,adapterKeys)),restrictedTest:snapshot.restrictedTest??null,settings:snapshot.settings,capabilities:snapshot.capabilities,window:snapshot.window,scopeProcesses,scopeCatalog,scopeError,resources:{templates,bindings,servers,errors}};
}
function samples(orderRules,workspace,user,params){
const processes=new Set();
for(const [key,value] of params){
if(key!=='process'||!value.trim()||value.length>250||/[\x00-\x1f\x7f-\x9f]/.test(value))fail('请选择有效的样本流程。');
processes.add(value.trim());
}
if(processes.size>100)fail('一次最多读取100个流程的样本。');
if(!processes.size)return {samples:[]};
return {samples:orderRules.all('capture-samples').filter(value=>value.provenance==='server-provider'&&!value.sample?.demo&&value.sample&&value.sample.source!=='history'&&processes.has(value.processName)&&canReadConnection(workspace,user,value.sample.connectionId)).map(value=>({...pick(value,['id','processName','provenance','capturedAt']),sample:pick(value.sample,sampleKeys)}))};
}
function ruleReceipt(orderRules,result){
const snapshot=orderRules.snapshot({includeRecords:false});
return {...result,...snapshot.rules.find(rule=>rule.id===result.id),restrictedTest:snapshot.restrictedTest??null};
}
function restrictedReceipt(orderRules,result){
const snapshot=orderRules.snapshot({includeRecords:false});
return {...result,rules:snapshot.rules,restrictedTest:snapshot.restrictedTest??null};
}
function templateUsage(rules){return rules.map(r=>({categoryId:r.published?.categoryId||r.draft?.categoryId,name:r.draft?.name,templateId:r.published?.bodyTemplateId||'',huizhouEnabled:r.published?.huizhouEnabled===true,huizhouTemplateId:r.published?.huizhouTemplateId||'',legacyBinding:!!r.published&&r.published.bodyTemplateId===undefined,publishedVersion:r.published?.version||null,status:r.published?.status||'draft'}));}
function orderRuleConfigurationApi({orderRules,mail,storage,workspace,user,url,route,method,reply}){
if(method!=='GET'||!['/api/order-rules/configuration','/api/order-rules/configuration/samples','/api/order-rules/status','/api/order-rules/catalog','/api/order-rules/notification-settings'].includes(route))return false;
if(!user)fail('请先登录。',401);
if(!orderRules)fail('分类通知规则服务未启动。',503);
if(route==='/api/order-rules/configuration')reply(200,configuration(orderRules,mail,storage));
else if(route==='/api/order-rules/status')reply(200,{settings:{enabled:orderRules.settings().enabled},capabilities:structuredClone(orderRules.capabilities)});
else if(route==='/api/order-rules/catalog'){const rules=orderRules.all('rules');reply(200,{rules:rules.map(r=>pick(r.draft,['categoryId','name'])),templateUsage:templateUsage(rules)});}
else if(route==='/api/order-rules/notification-settings')reply(200,{settings:orderRules.settings(),restrictedTest:orderRules.restrictedTest()});
else reply(200,samples(orderRules,workspace,user,url.searchParams));
return true;
}
module.exports={orderRuleConfigurationApi,ruleReceipt,restrictedReceipt,templateUsage};
+6 -4
View File
@@ -24,7 +24,9 @@ class OrderRuleDispatcher{
this.attachmentReader=attachmentReader;if(templateResolver)store.templateResolver=templateResolver;if(mail?.store?.signature)store.signatureResolver=id=>mail.store.signature(id);
}
ready(){
const config=this.store.settings(),cap=this.store.snapshot().capabilities;
// Real RuleStore exposes immutable capabilities directly; retain the small
// snapshot fallback for adapters and older test/runtime stores.
const config=this.store.settings(),cap=this.store.capabilities||this.store.snapshot?.().capabilities||{};
return !this.stopped&&config.enabled===true&&this.providersReady()===true&&cap?.liveTodo===true&&cap?.pdfExport===true&&cap?.automaticArchive===true;
}
tick(now=this.clock()){
@@ -35,7 +37,7 @@ class OrderRuleDispatcher{
}
async perform(now){
this.store.expireIntakes?.();
for(const batch of this.store.snapshot().batches||[])if(batch.status==='prepared'&&!batch.manual&&now-Date.parse(batch.cutoff)>1800000)this.store.finishSending(batch.id,'failed','冻结发送队列超过30分钟,请负责人核验后受控补发。',{outcome:'not_submitted',phase:'queue_expired',at:this.clock().toISOString()});
for(const batch of this.store.all('batches').reverse())if(batch.status==='prepared'&&!batch.manual&&now-Date.parse(batch.cutoff)>1800000)this.store.finishSending(batch.id,'failed','冻结发送队列超过30分钟,请负责人核验后受控补发。',{outcome:'not_submitted',phase:'queue_expired',at:this.clock().toISOString()});
if(!this.ready())return;
const config=freeze(structuredClone(this.store.settings())),schedule=this.settings()?.schedule,calendar=this.calendar();
if(!schedule?.times?.length)return;
@@ -43,13 +45,13 @@ class OrderRuleDispatcher{
if(!this.schedule||this.schedule.signature!==signature||now-Date.parse(this.schedule.next)>60000){const current=require('./window.cjs').upcomingWindow(now,schedule,calendar);this.schedule={signature,next:current?.available?current.end:nextSlots(schedule,now,1,calendar)[0]};}
const resumed=this.store.pendingIntakeCutoffs?.().filter(cutoff=>now-Date.parse(cutoff)>60000)||[];
const cutoff=resumed[0]||this.schedule.next,canPrepare=cutoff&&now-Date.parse(cutoff)>=0&&(now-Date.parse(cutoff)<=60000||resumed.includes(cutoff));
const queued=(this.store.snapshot().batches||[]).some(b=>b.status==='prepared'&&!b.manual&&now-Date.parse(b.cutoff)>=0&&now-Date.parse(b.cutoff)<=1800000);
const queued=this.store.all('batches').some(b=>b.status==='prepared'&&!b.manual&&now-Date.parse(b.cutoff)>=0&&now-Date.parse(b.cutoff)<=1800000);
if(!canPrepare&&!queued)return;
try{await this.mail.exclusive(config.channelId,async()=>{
if(!this.ready())return;
if(canPrepare&&!this.store.discoveryBlockers(cutoff).length){const window=windowForCutoff(cutoff,schedule,calendar);this.store.prepare(cutoff,'系统调度',window);}
// A frozen collection is immutable. Queue time is distinct from collection time.
const batches=(this.store.snapshot().batches||[]).filter(b=>b.status==='prepared'&&!b.manual&&now-Date.parse(b.cutoff)>=0&&now-Date.parse(b.cutoff)<=1800000);
const batches=this.store.all('batches').reverse().filter(b=>b.status==='prepared'&&!b.manual&&now-Date.parse(b.cutoff)>=0&&now-Date.parse(b.cutoff)<=1800000);
for(const batch of batches){if(!this.ready())break;
let expected;try{expected=windowForCutoff(batch.cutoff,schedule,calendar);}catch{continue;}
const legacyStart=new Date(Date.parse(batch.cutoff)+8*3600000).toISOString().slice(0,10)+'T00:00:00+08:00';
+9 -8
View File
@@ -3,15 +3,14 @@ const crypto=require('node:crypto');
const {canReadConnection,canReadOrder,canReadBatch}=require('./access.cjs');
const {fail}=require('./validation.cjs');
const {notifications,modeOf}=require('./delivery.cjs');
const cache=new WeakMap();
const {readStore,state:readState}=require('./read-context.cjs');
const orderStates=['candidate','identified','preparing','archived','pending','batched','blocked','unknown','sent','failed','capturing','archiving','queued','ignored'];
const batchStates=['collecting','prepared','sending','unknown','failed','sent','cancelled'];
function records(store){
const revision=store.queryRevision?.();
const saved=cache.get(store);
if(revision!==undefined&&saved?.revision===revision)return saved;
const memo=readState(store)?.memo,saved=memo?.get('records');if(saved)return saved;
const value={revision:revision??Date.now(),orders:store.all('orders'),batches:store.all('batches'),tasks:store.all('execution-tasks'),issues:store.all('business-issues')};
if(revision!==undefined)cache.set(store,value);
memo?.set('records',value);
return value;
}
function filters(input={},kind){
@@ -63,7 +62,8 @@ function visibleOrders(context,user,collectingGroups){
const rows=data.orders.filter(o=>classified(o,tasks.get(o.id))&&canReadOrder(context.workspace,user,o)).map(o=>orderRow(o,tasks.get(o.id)));
for(const task of data.tasks)if(!task.orderId&&!task.supersededBy&&classified(null,task)&&canReadConnection(context.workspace,user,task.connectionId))rows.push(orderRow(null,task));
const collecting=(collectingGroups||require('./collecting-batches.cjs').list(context.orderRules)).filter(b=>canReadBatch(context.workspace,user,b,context.orderRules));
for(const row of rows)row.collectingBatches=collecting.filter(b=>b.orderIds.includes(row.id)).map(b=>({id:b.id,subject:b.subject,cutoff:b.cutoff}));
const membership=new Map();for(const batch of collecting)for(const id of batch.orderIds){if(!membership.has(id))membership.set(id,[]);membership.get(id).push({id:batch.id,subject:batch.subject,cutoff:batch.cutoff});}
for(const row of rows)row.collectingBatches=membership.get(row.id)||[];
return rows;
}
function page(rows,input,revision){
@@ -112,14 +112,14 @@ function batchDetail(context,id,user){
return {...batchRow(context,batch),...pick(batch,['to','cc','text','html','window','sentAt','resolvedAt','resolution','manual','originalBatchId','template','signature','contentEdit','editor','edited','context','editable']),orders:(batch.orderIds||[]).map(id=>context.orderRules.get('orders',id)).filter(Boolean).map(o=>orderRow(o)),attachments:(batch.attachments||[]).map(a=>pick(a,['name','filename','size','sha256']))};
}
async function readOrderFile(context,id,index,user){
orderDetail(context,id,user);
orderDetail({...context,orderRules:readStore(context.orderRules)},id,user);
if(!Number.isSafeInteger(index)||index<0)fail('文件编号无效。');
const file=context.orderRules.get('orders',id)?.archive?.files?.[index];
if(!file||!Number.isSafeInteger(file.size)||!/^[a-f0-9]{64}$/i.test(file.sha256||''))fail('归档文件证据不完整。',409);
if(typeof context.execution?.archive?.read!=='function')fail('归档读取服务暂不可用。',503);
const bytes=await context.execution.archive.read(structuredClone(file));
// Ownership may change while storage performs an asynchronous read.
orderDetail(context,id,user);
orderDetail({...context,orderRules:readStore(context.orderRules)},id,user);
const current=context.orderRules.get('orders',id)?.archive?.files?.[index];
if(!current||current.sha256!==file.sha256||current.path!==file.path||current.size!==file.size)fail('归档证据已变化,请重新读取详情。',409);
if(!Buffer.isBuffer(bytes)||bytes.length!==file.size||bytes.subarray(0,5).toString()!=='%PDF-'||crypto.createHash('sha256').update(bytes).digest('hex')!==file.sha256)fail('归档文件读回校验失败。',409);
@@ -145,4 +145,5 @@ function summary(context,user){
result.revision=crypto.createHash('sha256').update(publicRevision(context,user)+JSON.stringify([result.window,result.issues])).digest('hex').slice(0,24);
return result;
}
module.exports={queryOrders,queryBatches,orderDetail,batchDetail,readOrderFile,summary};
const scoped=fn=>(context,...args)=>structuredClone(fn({...context,orderRules:readStore(context.orderRules)},...args));
module.exports={queryOrders:scoped(queryOrders),queryBatches:scoped(queryBatches),orderDetail:scoped(orderDetail),batchDetail:scoped(batchDetail),readOrderFile,summary:scoped(summary)};
+32
View File
@@ -0,0 +1,32 @@
'use strict';
const contextKey=Symbol('order-rules-read-context');
// This facade lives for one synchronous read only. Cached rows are internal,
// read-only values; public query boundaries copy their result before returning.
function readStore(store){
if(store[contextKey])return store;
const rows=new Map(),values=new Map(),indexes=new Map(),memo=new Map(),view=Object.create(store);
const state={memo,index(name,build){if(!indexes.has(name))indexes.set(name,build());return indexes.get(name);}};
Object.defineProperty(view,contextKey,{value:state});
view.all=function(kind){
if(!rows.has(kind)){
const result=store.all(kind);rows.set(kind,result);
let found=values.get(kind);if(!found)values.set(kind,found=new Map());for(const row of result)found.set(row.id,row);
}
// snapshot callers may reverse/sort the array, never the cached ordering.
return rows.get(kind).slice();
};
view.get=function(kind,id){
let found=values.get(kind);if(!found)values.set(kind,found=new Map());
if(!found.has(id))found.set(id,rows.has(kind)?null:store.get(kind,id));
return found.get(id);
};
for(const method of ['put','audit','transaction'])view[method]=()=>{throw new Error('Read context cannot write.');};
return view;
}
function state(store){return store?.[contextKey];}
function byOrder(store,kind,id){
const context=state(store);if(!context)return store.all(kind).filter(row=>row.orderId===id);
const index=context.index('order:'+kind,()=>{const map=new Map();for(const row of store.all(kind)){if(!map.has(row.orderId))map.set(row.orderId,[]);map.get(row.orderId).push(row);}return map;});
return index.get(id)||[];
}
module.exports={readStore,state,byOrder};
+12 -5
View File
@@ -17,6 +17,7 @@ const digest=value=>crypto.createHash('sha256').update(JSON.stringify(canonical(
const copy=value=>structuredClone(value);
const BASE_CAPABILITIES={liveTodo:false,pdfExport:false,automaticArchive:false};
function validDate(value){return typeof value==='string'&&/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/.test(value)&&Number.isFinite(Date.parse(value));}
function pendingCompanionState(order){const hui=delivery(order,'huizhou');return !!order?.archive&&order.ruleSnapshot?.huizhouEnabled===true&&['batched','sending','sent','unknown'].includes(order.status)&&!!hui&&['pending','blocked'].includes(hui.status)&&!hui.batchId&&!hui.missedWindow;}
class RuleStore{
constructor(dir,{clock=()=>new Date(),capabilities={},seedOverrides=[],schedule=()=>({times:['11:00','17:00'],weekends:false}),calendar=()=>[],desktopRoot=path.join(require('node:os').homedir(),'Desktop')}={}){
this.desktopRoot=desktopRoot;
@@ -45,6 +46,7 @@ class RuleStore{
}
}
});
require('../../shared/refresh-revisions.cjs').installRevisionTracking(this.db,[['records',"'records:' || $row.kind"]]);
}catch(error){try{this.db?.close();}catch{}this.vault?.destroy();throw error;}
}
now(){return this.clock().toISOString();}
@@ -113,13 +115,13 @@ class RuleStore{
if(issues.length)fail(issues.join(';'),409);
record.published={...copy(record.draft),status:'enabled',publishedAt:this.now()};record.mappingIssue=null;record.publicationSampleId=record.trialSampleId;record.publicationAdaptersHash=digest(record.published.adapterIds.map(id=>this.adapters().find(a=>a.id===id)));record.activationVersion=(record.activationVersion||0)+1;this.put('rules',record);
this.put('rule-history',{id:record.id+':'+record.draft.version,rule:copy(record.published),at:this.now(),actor});this.audit(actor,'发布规则',id+' v'+record.draft.version);
return this.snapshot().rules.find(r=>r.id===id);
return this.snapshot({includeRecords:false}).rules.find(r=>r.id===id);
});}
pause(id,input,actor){return this.transaction(()=>{
const record=this.get('rules',id);if(!record)fail('规则不存在。',404);
if(input?.version!==record.draft.version)fail('规则已变化,请刷新。',409);
if(input.activationVersion!==undefined&&input.activationVersion!==(record.activationVersion||0))fail('启停状态已变化,请刷新。',409);
if(record.published)record.published.status='paused';record.activationVersion=(record.activationVersion||0)+1;this.put('rules',record);this.audit(actor,'暂停规则',id);return this.snapshot().rules.find(r=>r.id===id);
if(record.published)record.published.status='paused';record.activationVersion=(record.activationVersion||0)+1;this.put('rules',record);this.audit(actor,'暂停规则',id);return this.snapshot({includeRecords:false}).rules.find(r=>r.id===id);
});}
resume(id,input,actor){return this.transaction(()=>{
const record=this.get('rules',id);if(!record?.published)fail('此分类尚未发布,请先保存并检查真实订单,再发布启用。',409);
@@ -132,7 +134,7 @@ class RuleStore{
const overlaps=this.all('rules').filter(r=>r.id!==id&&r.published?.status==='enabled'&&scopesOverlap(r.published,record.published));
if(overlaps.length)issues.push('与其他启用分类的流程节点冲突');
if(issues.length)fail(issues.join(';'),409);
record.published.status='enabled';record.activationVersion=(record.activationVersion||0)+1;this.put('rules',record);this.audit(actor,'启用已发布规则',id+' v'+record.published.version);return this.snapshot().rules.find(r=>r.id===id);
record.published.status='enabled';record.activationVersion=(record.activationVersion||0)+1;this.put('rules',record);this.audit(actor,'启用已发布规则',id+' v'+record.published.version);return this.snapshot({includeRecords:false}).rules.find(r=>r.id===id);
});}
matchingPublications(sample){
const rules=this.all('rules').map(r=>this.executionRule(r)).filter(Boolean);
@@ -158,12 +160,17 @@ class RuleStore{
return [...new Set(cutoffs.filter(cutoff=>cutoff&&now>=Date.parse(cutoff)&&now<=Date.parse(cutoff)+1800000))].sort();
}
pendingCompanion(order){
const hui=delivery(order,'huizhou'),normal=order?.batchId&&this.get('batches',order.batchId);
return !!order?.archive&&order.ruleSnapshot?.huizhouEnabled===true&&['batched','sending','sent','unknown'].includes(order.status)&&!!hui&&['pending','blocked'].includes(hui.status)&&!hui.batchId&&!hui.missedWindow&&normal?.huizhouPlanned===true&&modeOf(normal)==='normal'&&normal.orderIds?.includes(order.id)&&normal.cutoff===this.intakeWindow(order.sample||order.event,{includeExpired:true})?.end;
if(!pendingCompanionState(order))return false;
const normal=order.batchId&&this.get('batches',order.batchId);
return normal?.huizhouPlanned===true&&modeOf(normal)==='normal'&&normal.orderIds?.includes(order.id)&&normal.cutoff===this.intakeWindow(order.sample||order.event,{includeExpired:true})?.end;
}
expireIntakes(){return this.transaction(()=>{
const carry=require('./carry-forward.cjs');carry.advance(this);
for(const order of this.all('orders')){
// Only uncompleted normal work or an independent Hui companion can expire.
// Do this before intakeWindow's task lookup; keep carry advancement above
// and the persisted evidence checks below on the ordinary writable store.
if(!(['identified','preparing','archived','pending','blocked'].includes(order.status)&&!order.batchId&&!order.missedWindow)&&!pendingCompanionState(order))continue;
const window=this.intakeWindow(order.sample||order.event,{includeExpired:true});
if(!window||+this.clock()<=Date.parse(window.end)+1800000)continue;
if(this.pendingCompanion(order)&&!carry.hasCarry(this,order,'huizhou')){
+9 -1
View File
@@ -9,7 +9,15 @@ function taskIdentity(value){const item=identity(value);if(!item.source||!item.t
// A legacy row with no native portal source is ambiguous. Treat it as an
// overlapping namespace, never guess v4/v8 and create a second notification.
function sameTask(a,b){a=identity(a);b=identity(b);return !!a.source&&!!a.taskId&&a.source===b.source&&a.taskId===b.taskId&&(!a.portalSource||!b.portalSource||a.portalSource===b.portalSource);}
function records(store,kind,value){return store.all(kind).filter(row=>sameTask(row,value));}
function records(store,kind,value){
const context=require('./read-context.cjs').state(store);if(!context)return store.all(kind).filter(row=>sameTask(row,value));
const key=item=>JSON.stringify([item.source,item.taskId]),index=context.index('task:'+kind,()=>{
const groups=new Map();for(const row of store.all(kind)){const item=identity(row);if(!item.source||!item.taskId)continue;const k=key(item);if(!groups.has(k))groups.set(k,[]);groups.get(k).push(row);}return groups;
});
// Keep all portal variants: a legacy row without portalSource overlaps every
// native namespace, and lookup must still reject multiple matching records.
return (index.get(key(identity(value)))||[]).filter(row=>sameTask(row,value));
}
function lookup(store,kind,value){const rows=records(store,kind,value);if(rows.length>1)fail('同一通知任务存在多条旧记录,须人工核验,禁止新建或自动合并。',409);return rows[0]||null;}
function normalize(value){const row=structuredClone(value);for(const key of ['connectionId','source','portalSource','instanceId','taskId','revision'])if(row[key]!==undefined&&row[key]!==null)row[key]=text(row[key]);if(!text(row.revision))delete row.revision;return row;}
function fingerprint(value){const row=normalize(value);delete row.connectionId;return digest(row);}
+7 -7
View File
@@ -1,5 +1,6 @@
'use strict';
const {secureBpmTransport}=require('../bpm/api.cjs');
const {byteRange}=require('./files.cjs');
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
function payload(body,keys){if(!body||Object.keys(body).some(k=>!keys.includes(k)))fail('存储操作参数无效。');}
async function storageApi({storage,workspace,user,url,route,method,body,request,response,reply,trustedProxy}){
@@ -25,14 +26,13 @@ async function storageApi({storage,workspace,user,url,route,method,body,request,
if(action==='archive'&&method==='POST'){payload(body,['jobId','directory']);const result=await storage.archive(id,body.jobId,body.directory??'',user.username);audit('PDF 归档完成',result.relativePath);reply(200,result);return true;}
if(action==='preview-info'&&method==='GET'){reply(200,await storage.previewInfo(id,url.searchParams.get('path')||''));return true;}
if((action==='file'||action==='content')&&method==='GET'){
const preview=action==='content',file=await storage[preview?'readPreview':'readFile'](id,url.searchParams.get('path')||''),total=file.bytes.length;
const preview=action==='content',range=request.headers.range,file=await storage[preview?'readPreview':'readFile'](id,url.searchParams.get('path')||'',range===undefined?{}:{range}),total=file.total??file.bytes.length;
response.setHeader('Content-Type',preview?file.contentType:'application/octet-stream');response.setHeader('Content-Disposition',(preview?'inline':'attachment')+"; filename*=UTF-8''"+encodeURIComponent(file.filename));response.setHeader('Content-Security-Policy',"default-src 'none'; sandbox");response.setHeader('Cross-Origin-Resource-Policy','same-origin');response.setHeader('Accept-Ranges','bytes');
let start=0,end=total-1,status=200;
if(request.headers.range){const range=/^bytes=(\d*)-(\d*)$/.exec(request.headers.range);if(!range||(!range[1]&&!range[2])){response.setHeader('Content-Range','bytes */'+total);response.writeHead(416);response.end();return true;}
if(range[1]){start=Number(range[1]);if(range[2])end=Math.min(Number(range[2]),end);}else start=Math.max(0,total-Number(range[2]));
if(!Number.isSafeInteger(start)||!Number.isSafeInteger(end)||start>end||start>=total){response.setHeader('Content-Range','bytes */'+total);response.writeHead(416);response.end();return true;}status=206;response.setHeader('Content-Range',`bytes ${start}-${end}/${total}`);
}
const bytes=file.bytes.subarray(start,end+1);response.setHeader('Content-Length',bytes.length);response.writeHead(status);response.end(bytes);return true;
const {start,end,status}=byteRange(range,total);
if(file.total!==undefined&&(file.start!==start||file.end!==end||file.status!==status||file.bytes.length!==(status===416?0:end-start+1)))fail('存储分段响应无效。',502);
if(status===416){response.setHeader('Content-Range','bytes */'+total);response.writeHead(416);response.end();return true;}
if(status===206)response.setHeader('Content-Range',`bytes ${start}-${end}/${total}`);
const bytes=file.total===undefined?file.bytes.subarray(start,end+1):file.bytes;response.setHeader('Content-Length',bytes.length);response.writeHead(status);response.end(bytes);return true;
}
}
fail('没有找到此存储操作。',404);
+34 -8
View File
@@ -15,6 +15,22 @@ function segments(relative=''){
}
function inside(root,file){const rel=path.relative(root,file);return !path.isAbsolute(rel)&&rel!=='..'&&!rel.startsWith('..'+path.sep);}
function digest(bytes){return crypto.createHash('sha256').update(bytes).digest('hex');}
function byteRange(value,total){
if(!Number.isSafeInteger(total)||total<0)throw fail('存储文件大小无效。',502);
const invalid={status:416,start:0,end:-1};
if(value===undefined)return {status:200,start:0,end:total-1};
const match=typeof value==='string'&&/^bytes=(\d*)-(\d*)$/.exec(value);if(!match||!total||(!match[1]&&!match[2]))return invalid;
const first=match[1]?Number(match[1]):null,last=match[2]?Number(match[2]):null;
if(first!==null&&!Number.isSafeInteger(first)||last!==null&&!Number.isSafeInteger(last))return invalid;
const start=first===null?Math.max(0,total-last):first,end=first===null||last===null?total-1:Math.min(last,total-1);
return start<0||start>end||start>=total?invalid:{status:206,start,end};
}
async function readExact(handle,start,length){
const buffer=Buffer.alloc(length);let offset=0;
while(offset<length){const result=await handle.read(buffer,offset,length-offset,start+offset);if(!result.bytesRead)throw fail('文件正在更新,请稍后重试。',409);offset+=result.bytesRead;}
return buffer;
}
const unchanged=(a,b)=>['dev','ino','size','mtimeNs','ctimeNs'].every(key=>a[key]===b[key]);
async function pdf(file){const info=await fs.stat(file);if(!info.isFile()||info.size>MAX_FILE)throw fail('PDF 必须为不超过 64 MiB 的文件。');const bytes=await fs.readFile(file);if(bytes.length>MAX_FILE||bytes.subarray(0,5).toString()!=='%PDF-')throw fail('文件不是有效的 PDF。');return bytes;}
class FileArea{
constructor(root,{boundary=root}={}){this.root=path.resolve(root);this.boundary=path.resolve(boundary);if(!inside(this.boundary,this.root))throw fail('归档根目录超出共享目录。');}
@@ -45,16 +61,26 @@ class FileArea{
}
async readPdf(relative){if(path.extname(relative).toLowerCase()!=='.pdf')throw fail('仅支持下载归档 PDF。');const file=await this.resolve(relative);return {bytes:await pdf(file),filename:path.basename(file)};}
async previewInfo(relative){const file=await this.resolve(relative),stat=await fs.stat(file);if(!stat.isFile())throw fail('请选择文件进行预览。');return describePreview(path.basename(file),stat.size);}
async readFile(relative,limit=MAX_FILE){
async readFile(relative,limit=MAX_FILE,{range,previewPdf=false}={}){
const file=await this.resolve(relative),handle=await fs.open(file,'r');
try{const stat=await handle.stat();if(!stat.isFile())throw fail('请选择要读取的文件。');if(stat.size>limit)throw fail('文件超过工作台读取上限。',413);
const buffer=Buffer.alloc(stat.size+1);let length=0;
while(length<buffer.length){const result=await handle.read(buffer,length,buffer.length-length,null);if(!result.bytesRead)break;length+=result.bytesRead;}
if(length>stat.size)throw fail('文件正在更新,请稍后重试。',409);
return {filename:path.basename(file),bytes:buffer.subarray(0,length)};
try{const stat=await handle.stat({bigint:true}),total=Number(stat.size),filename=path.basename(file);if(!stat.isFile())throw fail('请选择要读取的文件。');if(!Number.isSafeInteger(total)||total>limit)throw fail('文件超过工作台读取上限。',413);
if(previewPdf){const info=describePreview(filename,total);if(info.kind!=='pdf')throw fail('此格式不支持 PDF 分段预览。',415);await validatePreview(info,await readExact(handle,0,Math.min(5,total)));}
const selected=byteRange(range,total),bytes=selected.status===416?Buffer.alloc(0):await readExact(handle,selected.start,selected.end-selected.start+1);
// Validate both the opened file and its path after reading. Ranges and PDF
// headers use this same handle, and no successful short/growing read escapes.
const after=await handle.stat({bigint:true});await this.resolve(relative);const current=await fs.lstat(file,{bigint:true});
if(current.isSymbolicLink()||!unchanged(stat,after)||!unchanged(stat,current))throw fail('文件正在更新,请稍后重试。',409);
return {filename,bytes,total,...selected};
}finally{await handle.close();}
}
async readPreview(relative){const info=await this.previewInfo(relative);if(!info.canPreview)throw fail(info.reason,info.kind==='unsupported'?415:413);const file=await this.readFile(relative,info.limit);return {...info,bytes:await validatePreview({...info,bytes:file.bytes.length,canPreview:file.bytes.length<=info.limit},file.bytes)};}
async readPreview(relative,{range}={}){
if(range!==undefined&&path.extname(relative).toLowerCase()==='.pdf'){
const file=await this.readFile(relative,MAX_FILE,{range,previewPdf:true});return {...describePreview(file.filename,file.total),...file};
}
const info=await this.previewInfo(relative);if(!info.canPreview)throw fail(info.reason,info.kind==='unsupported'?415:413);
const file=await this.readFile(relative,info.limit),bytes=await validatePreview({...info,bytes:file.bytes.length,canPreview:file.bytes.length<=info.limit},file.bytes),selected=byteRange(range,bytes.length);
return {...info,total:bytes.length,...selected,bytes:selected.status===416?Buffer.alloc(0):bytes.subarray(selected.start,selected.end+1)};
}
async archive(source,filename,relative=''){
if(segments(filename).length!==1||path.extname(filename).toLowerCase()!=='.pdf')throw fail('归档文件名必须为 PDF 文件名。');
const bytes=await pdf(source),sha256=digest(bytes),directory=await this.resolve(relative,true);
@@ -79,4 +105,4 @@ class SmbClient{
async browse(server,options){return require('./smb-probe.cjs').probe(server,options);}
async area(server){if(server.authMode!=='windows')await native.connect(server);const boundary=path.win32.join('\\\\'+server.host,server.share),root=path.win32.join(boundary,...segments(server.directory));return new FileArea(root,{boundary});}
}
module.exports={FileArea,SmbClient,segments,inside,MAX_FILE};
module.exports={FileArea,SmbClient,segments,inside,MAX_FILE,byteRange};
+3 -3
View File
@@ -1,6 +1,6 @@
'use strict';
const fs=require('node:fs/promises');const path=require('node:path');
const {SmbClient,segments,inside}=require('./files.cjs');
const {SmbClient,segments,inside,MAX_FILE}=require('./files.cjs');
const {orderFolder}=require('./order.cjs');
const fail=(message,status=400)=>Object.assign(new Error(message),{status});
const safe=e=>e.status?e:fail(({ENOENT:'找不到文件或归档目录,请检查路径。',EACCES:'没有共享目录访问权限。',EPERM:'没有共享目录操作权限。',ENOSPC:'存储服务器空间不足。',ENOTDIR:'指定路径不是目录。'})[e.code]||'存储操作未完成,请检查服务器与网络。',502);
@@ -71,8 +71,8 @@ class StorageService{
mkdir(id,relative){return this.run(id,async (server,signal)=>this.operation(server,'mkdir',[relative],signal));}
readPdf(id,relative){return this.run(id,async (server,signal)=>this.operation(server,'readPdf',[relative],signal));}
previewInfo(id,relative){return this.run(id,async (server,signal)=>this.operation(server,'previewInfo',[relative],signal));}
readPreview(id,relative){return this.run(id,async (server,signal)=>this.operation(server,'readPreview',[relative],signal));}
readFile(id,relative){return this.run(id,async (server,signal)=>this.operation(server,'readFile',[relative],signal));}
readPreview(id,relative,options={}){return this.run(id,async (server,signal)=>this.operation(server,'readPreview',[relative,options],signal));}
readFile(id,relative,options={}){return this.run(id,async (server,signal)=>this.operation(server,'readFile',[relative,MAX_FILE,options],signal));}
archive(id,jobId,directory='',actor='自动归档'){
return this.run(id,async (server,signal)=>{
segments(directory);if(typeof jobId!=='string'||!jobId||jobId.length>200)throw fail('请选择已完成的 PDF 导出任务。');
+7
View File
@@ -17,6 +17,13 @@ function validate(operation,value){
visit(value);
if(!value||typeof value!=='object'||Array.isArray(value))throw fail('存储响应无效。',502);
if(['readPdf','readPreview','readFile'].includes(operation)&&!Buffer.isBuffer(value.bytes))throw fail('存储文件响应无效。',502);
if(['readPreview','readFile'].includes(operation)&&value.total!==undefined){
const {total,start,end,status,bytes}=value,valid=Number.isSafeInteger(total)&&total>=0&&total<=MAX_FILE&&Number.isSafeInteger(start)&&Number.isSafeInteger(end);
const layout=status===416?start===0&&end===-1&&bytes.length===0:
status===200?start===0&&end===total-1&&bytes.length===total:
status===206&&total>0&&start>=0&&start<=end&&end<total&&bytes.length===end-start+1;
if(!valid||!layout)throw fail('存储分段响应无效。',502);
}
if(operation==='list'&&(!Array.isArray(value.entries)||value.entries.length>500||typeof value.path!=='string'||typeof value.truncated!=='boolean'||value.entries.some(e=>!e||typeof e.name!=='string'||!['directory','file','blocked'].includes(e.type))))throw fail('存储目录响应无效。',502);
if(operation==='check'&&(value.readable!==true||value.writable!==true))throw fail('存储检查响应无效。',502);
if(operation==='archive'&&(!Number.isSafeInteger(value.bytes)||value.bytes<0||value.bytes>MAX_FILE||!/^[a-f0-9]{64}$/.test(value.sha256)||typeof value.filename!=='string'||typeof value.relativePath!=='string'))throw fail('归档响应无效。',502);
+1
View File
@@ -18,6 +18,7 @@ class StorageStore{
INSERT OR IGNORE INTO settings VALUES(1,'{"serverId":"","enabled":false,"since":null}');
CREATE TABLE IF NOT EXISTS archives(id TEXT PRIMARY KEY,server_id TEXT NOT NULL,job_id TEXT NOT NULL,status TEXT NOT NULL,value TEXT NOT NULL,UNIQUE(server_id,job_id));
UPDATE archives SET status='interrupted' WHERE status='running';`);
require('../../shared/refresh-revisions.cjs').installRevisionTracking(this.db,['servers','settings','archives']);
} catch(error) {
try { this.db?.close(); } catch {}
try { this.vault?.destroy(); } catch {}
+87
View File
@@ -0,0 +1,87 @@
'use strict';
const REPOSITORY_URL='https://git.simgreek.com/Skyworth_Digital_Hardware/order-notification-automation';
const RELEASES_API_URL='https://git.simgreek.com/api/v1/repos/Skyworth_Digital_Hardware/order-notification-automation/releases/latest';
const VERSION_PATTERN=/^[vV]?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
const MAX_RESPONSE_BYTES=256*1024;
function versionParts(value){
const match=typeof value==='string'&&value.length<=200&&VERSION_PATTERN.exec(value.trim());
if(!match)return null;
const pre=match[4]?match[4].split('.'):[];
if(pre.some(part=>/^0\d+$/.test(part)))return null;
return {major:BigInt(match[1]),minor:BigInt(match[2]),patch:BigInt(match[3]),pre};
}
function compareIdentifiers(a,b){
const an=/^\d+$/.test(a),bn=/^\d+$/.test(b);
if(an&&bn)return BigInt(a)>BigInt(b)?1:BigInt(a)<BigInt(b)?-1:0;
if(an!==bn)return an?-1:1;
return a>b?1:a<b?-1:0;
}
function compareVersions(left,right){
const a=versionParts(left),b=versionParts(right);
if(!a||!b)throw new Error('版本必须是 x.y.z 格式。');
for(const key of ['major','minor','patch'])if(a[key]!==b[key])return a[key]>b[key]?1:-1;
if(!a.pre.length&&!b.pre.length)return 0;
if(!a.pre.length)return 1;
if(!b.pre.length)return -1;
for(let i=0;i<Math.max(a.pre.length,b.pre.length);i++){
if(i>=a.pre.length)return -1;
if(i>=b.pre.length)return 1;
const result=compareIdentifiers(a.pre[i],b.pre[i]);
if(result)return result>0?1:-1;
}
return 0;
}
function safeReleaseUrl(value,repositoryUrl=REPOSITORY_URL){
try{
const url=new URL(value),base=new URL(repositoryUrl);
if(url.username||url.password||url.origin!==base.origin||!url.pathname.startsWith(base.pathname+'/releases/'))return '';
return url.href;
}catch{return '';}
}
function parseRelease(release,currentVersion,{repositoryUrl=REPOSITORY_URL}={}){
const base={currentVersion,latest:null};
if(!release||typeof release!=='object'||Array.isArray(release)||typeof release.tag_name!=='string')return {...base,status:'unavailable'};
const version=release.tag_name.trim().replace(/^v/i,''),parts=versionParts(version);
if(!parts)return {...base,status:'unavailable'};
if(release.draft===true||release.prerelease===true||parts.pre.length)return {...base,status:'none'};
if(compareVersions(version,currentVersion)<=0)return {...base,status:'current'};
const publishedAt=release.published_at?new Date(release.published_at):null;
return {status:'update-available',currentVersion,latest:{version,name:String(release.name||release.tag_name||version).slice(0,200),notes:String(release.body||'').slice(0,20000),url:safeReleaseUrl(release.html_url,repositoryUrl),publishedAt:publishedAt&&!Number.isNaN(publishedAt.getTime())?publishedAt.toISOString():null}};
}
async function readRelease(response){
const reader=response.body?.getReader();
if(!reader)throw Error('发行版本响应为空。');
const chunks=[];let bytes=0;
try{
while(true){
const {value,done}=await reader.read();if(done)break;
bytes+=value.byteLength;if(bytes>MAX_RESPONSE_BYTES)throw Error('发行版本响应过大。');
chunks.push(Buffer.from(value));
}
return JSON.parse(Buffer.concat(chunks,bytes).toString('utf8'));
}catch(error){await reader.cancel().catch(()=>{});throw error;}
finally{reader.releaseLock();}
}
function createUpdateChecker({currentVersion,fetchImpl=globalThis.fetch,apiUrl=RELEASES_API_URL,repositoryUrl=REPOSITORY_URL,timeoutMs=5000}={}){
if(!versionParts(currentVersion))throw new Error('当前版本必须是 x.y.z 格式。');
let inFlight=null;
async function readUpdate(){
const base={currentVersion,latest:null};
if(typeof fetchImpl!=='function')return {...base,status:'unavailable'};
const controller=new AbortController(),timer=setTimeout(()=>controller.abort(),timeoutMs);
try{
const response=await fetchImpl(apiUrl,{headers:{Accept:'application/json'},redirect:'error',credentials:'omit',signal:controller.signal});
if(!response.ok){await response.body?.cancel();return {...base,status:response.status===404?'none':'unavailable'};}
return parseRelease(await readRelease(response),currentVersion,{repositoryUrl});
}catch{return {...base,status:'unavailable'};}
finally{clearTimeout(timer);}
}
return async function checkForUpdate(){
// Share only work still in progress; a later manual check always revalidates.
if(!inFlight)inFlight=readUpdate().finally(()=>{inFlight=null;});
return structuredClone(await inFlight);
};
}
module.exports={REPOSITORY_URL,RELEASES_API_URL,compareVersions,parseRelease,createUpdateChecker};
+1
View File
@@ -24,6 +24,7 @@ class WorkspaceStore {
delete item.detailUrl;if(item.checks)delete item.checks.detail;if(item.status==='partial')item.status='unchecked';
this.db.prepare('UPDATE connections SET value=? WHERE id=?').run(JSON.stringify(item),row.id);
}});
require('../../shared/refresh-revisions.cjs').installRevisionTracking(this.db,['connections','connection_archives','exceptions',['metadata',"'metadata:' || $row.key"]]);
} catch(error) {
try { this.db?.close(); } catch {}
throw error;
+2 -1
View File
@@ -5,6 +5,7 @@ const path = require('node:path');
const crypto = require('node:crypto');
const { execFileSync } = require('node:child_process');
const { DatabaseSync } = require('node:sqlite');
const {secureDirectoryScript}=require('./windows-directory.cjs');
const fail = (cause,stage) => cause?.code==='STORAGE_UNAVAILABLE'&&!stage?cause:Object.assign(new Error('加密存储暂时不可用,请查看系统诊断。',cause?{cause}:undefined), { status: 503,code:'STORAGE_UNAVAILABLE',stage:stage||'db_read' });
const duplicate = () => Object.assign(new Error('该 BPM 账号已开启自动续登,请使用已有连接或先解除原账号托管。'), { status: 409, code: 'BPM_ACCOUNT_DUPLICATE' });
const digest = value => crypto.createHash('sha256').update(value).digest('hex');
@@ -29,7 +30,7 @@ function secureDirectory(dir) {
if (process.platform === 'win32') {
const key=path.resolve(dir).toLowerCase(),identity=directoryIdentity(dir);
if(securedDirectories.get(key)===identity)return;
powershell('$ErrorActionPreference="Stop"; $p=[Console]::In.ReadToEnd(); $s=[System.Security.Principal.WindowsIdentity]::GetCurrent().User; $a=New-Object System.Security.AccessControl.DirectorySecurity; $a.SetAccessRuleProtection($true,$false); $a.SetOwner($s); $r=New-Object System.Security.AccessControl.FileSystemAccessRule($s,"FullControl","ContainerInherit,ObjectInherit","None","Allow"); $a.AddAccessRule($r); [System.IO.Directory]::SetAccessControl($p,$a)', dir);
powershell(secureDirectoryScript, dir);
if(directoryIdentity(dir)!==identity)throw Object.assign(Error('Storage directory changed during protection'),{code:'ESTORAGECHANGED'});
securedDirectories.set(key,identity);if(securedDirectories.size>512)securedDirectories.delete(securedDirectories.keys().next().value);
} else fs.chmodSync(dir, 0o700);
@@ -0,0 +1,30 @@
'use strict';
// Read SIDs directly: do not resolve account names or weaken an existing policy.
const privateDirectoryAcl=String.raw`
function Test-PrivateDirectoryAcl($acl,$sid) {
if(-not $acl.AreAccessRulesProtected -or -not $acl.GetOwner([System.Security.Principal.SecurityIdentifier]).Equals($sid)){return $false}
$raw=New-Object System.Security.AccessControl.RawSecurityDescriptor($acl.GetSecurityDescriptorBinaryForm(),0)
if($null -eq $raw.DiscretionaryAcl -or $raw.DiscretionaryAcl.Count -ne 1){return $false}
$ace=$raw.DiscretionaryAcl[0]
if($ace -isnot [System.Security.AccessControl.CommonAce] -or $ace.AceType -ne [System.Security.AccessControl.AceType]::AccessAllowed -or $ace.IsCallback -or $ace.OpaqueLength -ne 0){return $false}
$rules=$acl.GetAccessRules($true,$true,[System.Security.Principal.SecurityIdentifier])
if($rules.Count -ne 1){return $false}
$rule=$rules[0]
return (-not $rule.IsInherited -and $rule.IdentityReference.Equals($sid) -and $rule.FileSystemRights -eq [System.Security.AccessControl.FileSystemRights]::FullControl -and $rule.AccessControlType -eq [System.Security.AccessControl.AccessControlType]::Allow -and $rule.InheritanceFlags -eq [System.Security.AccessControl.InheritanceFlags]'ContainerInherit,ObjectInherit' -and $rule.PropagationFlags -eq [System.Security.AccessControl.PropagationFlags]::None)
}
`;
const secureDirectoryScript=privateDirectoryAcl+String.raw`
$ErrorActionPreference="Stop"
$p=[Console]::In.ReadToEnd()
$s=[System.Security.Principal.WindowsIdentity]::GetCurrent().User
$current=[System.IO.Directory]::GetAccessControl($p)
if(-not (Test-PrivateDirectoryAcl $current $s)){
$a=New-Object System.Security.AccessControl.DirectorySecurity
$a.SetAccessRuleProtection($true,$false)
$a.SetOwner($s)
$r=New-Object System.Security.AccessControl.FileSystemAccessRule($s,"FullControl","ContainerInherit,ObjectInherit","None","Allow")
$a.AddAccessRule($r)
[System.IO.Directory]::SetAccessControl($p,$a)
}
`;
module.exports={privateDirectoryAcl,secureDirectoryScript};
+18 -11
View File
@@ -1,11 +1,12 @@
'use strict';
const fs=require('node:fs'),path=require('node:path'),net=require('node:net'),crypto=require('node:crypto'),{spawn,execFile}=require('node:child_process'),{promisify}=require('node:util');
const {SupervisorStore}=require('./store.cjs'),{controlAddress}=require('./control.cjs'),{checkPing,sameToken}=require('./ping.cjs');
const execFileAsync=promisify(execFile),DEFAULTS={intervalMs:10000,pingTimeoutMs:5000,startupGraceMs:120000,failureThreshold:4,stopGraceMs:15000,backoffMs:[2000,5000,10000,30000,60000],windowMs:900000,maxRestarts:8,cooldownMs:300000};
function restartPlan({failures=0,recent=0,...options}={}){const t={...DEFAULTS,...options},cooldown=recent>=t.maxRestarts;return {cooldown,delayMs:cooldown?t.cooldownMs:t.backoffMs[Math.min(failures,t.backoffMs.length-1)]};}
const {safeDiagnostic}=require('../../shared/diagnostics.cjs');
const execFileAsync=promisify(execFile),DEFAULTS={intervalMs:10000,pingTimeoutMs:5000,startupGraceMs:120000,failureThreshold:4,stopGraceMs:15000,backoffMs:[2000,5000,10000,30000,60000],windowMs:900000,maxRestarts:8,cooldownMs:300000,startupFailureThreshold:3};
function restartPlan({failures=0,recent=0,startupFailures=0,...options}={}){const t={...DEFAULTS,...options},cooldown=recent>=t.maxRestarts||startupFailures>=t.startupFailureThreshold;return {cooldown,delayMs:cooldown?t.cooldownMs:t.backoffMs[Math.min(failures,t.backoffMs.length-1)]};}
async function portsAvailable(ports){for(const port of ports){const server=net.createServer();await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(port,'127.0.0.1',resolve);});await new Promise(r=>server.close(r));}}
class ServiceSupervisor {
constructor({stateDir,entry=path.join(require('../../shared/paths.cjs').PROJECT_ROOT,'src/server.cjs'),ports=[18765,18766],portsProvider,env={},timing={}}){Object.assign(this,{stateDir:path.resolve(stateDir),entry:path.resolve(entry),ports,portsProvider,env});this.timing={...DEFAULTS,...timing};this.state={};this.restarts=[];this.failures=0;this.stopping=false;this.started=false;}
constructor({stateDir,entry=path.join(require('../../shared/paths.cjs').PROJECT_ROOT,'src/server.cjs'),ports=[18765,18766],portsProvider,env={},timing={}}){Object.assign(this,{stateDir:path.resolve(stateDir),entry:path.resolve(entry),ports,portsProvider,env});this.timing={...DEFAULTS,...timing};this.state={};this.restarts=[];this.failures=0;this.startupFailures=0;this.ready=false;this.stopping=false;this.started=false;}
snapshot(){return {...this.state};}
update(patch){Object.assign(this.state,patch,{updatedAt:new Date().toISOString()});this.store.set('state',this.state);}
async start(){
@@ -43,18 +44,24 @@ class ServiceSupervisor {
await portsAvailable(ports);if(this.stopping)return;this.ports=[...ports];this.misses=0;this.spawnedAt=Date.now();const instanceId=crypto.randomUUID(),heartbeatToken=crypto.randomBytes(32).toString('hex'),logFile=path.join(this.store.dir,'service.log');this.rotateLog();
const fd=fs.openSync(logFile,'a',0o600);let child;
try{child=spawn(process.execPath,[this.entry],{cwd:require('../../shared/paths.cjs').PROJECT_ROOT,env:{...process.env,...this.env,ORDER_SUPERVISOR_TOKEN:heartbeatToken,ORDER_SUPERVISOR_INSTANCE:instanceId},windowsHide:true,shell:false,stdio:['ignore',fd,fd,'ipc']});}finally{fs.closeSync(fd);}
this.child=child;this.instanceId=instanceId;this.heartbeatToken=heartbeatToken;this.childClosed=new Promise(resolve=>{this.resolveClosed=resolve;});
this.update({status:'starting',childPid:child.pid||null,childInstanceId:instanceId,childStartedAt:new Date().toISOString(),heartbeatAt:null,nextRestartAt:null});
this.child=child;this.instanceId=instanceId;this.heartbeatToken=heartbeatToken;this.ready=false;this.startupError=null;this.childClosed=new Promise(resolve=>{this.resolveClosed=resolve;});
this.update({status:'starting',childPid:child.pid||null,childInstanceId:instanceId,childStartedAt:new Date().toISOString(),heartbeatAt:null,nextRestartAt:null,startupError:null,consecutiveStartupFailures:this.startupFailures});
child.on('message',message=>{
if(this.child!==child||this.ready||message?.type!=='order:startup-failed'||!message.diagnostic||typeof message.diagnostic!=='object'||Array.isArray(message.diagnostic))return;
const d=message.diagnostic;this.startupError=safeDiagnostic({name:d.type,stage:d.stage,code:d.code,cause:{code:d.causeCode}},{durationMs:d.durationMs});
this.update({startupError:this.startupError});this.store.event('startup_failed',this.startupError);
});
child.on('error',()=>{this.store?.event('spawn_failed');});
child.once('close',(code,signal)=>{const resolve=this.resolveClosed;resolve?.();if(this.child!==child)return;this.child=null;
if(this.stopping||this.manualRestart)return;
this.store.event('child_exit',{code,signal:signal||null});this.update({childPid:null,lastExitAt:new Date().toISOString(),lastExitCode:code,reason:this.exitReason||'unexpected_exit'});this.exitReason=null;this.scheduleRestart();
const startupFailure=!this.ready;this.store.event('child_exit',{code,signal:signal||null,startupFailure});this.update({childPid:null,lastExitAt:new Date().toISOString(),lastExitCode:code,reason:this.exitReason||(this.startupError?'startup_failed':'unexpected_exit'),startupFailure});this.exitReason=null;this.scheduleRestart({startupFailure});
});
}
scheduleRestart(){
scheduleRestart({startupFailure=false}={}){
if(this.stopping)return;clearTimeout(this.restartTimer);const now=Date.now();this.restarts=this.restarts.filter(t=>now-t<this.timing.windowMs);
const plan=restartPlan({...this.timing,failures:this.failures++,recent:this.restarts.length});
this.update({status:plan.cooldown?'cooldown':'backoff',nextRestartAt:new Date(now+plan.delayMs).toISOString()});this.store.event(plan.cooldown?'cooldown':'restarting',{delayMs:plan.delayMs,reason:this.state.reason});
if(startupFailure)this.startupFailures++;
const plan=restartPlan({...this.timing,failures:this.failures++,startupFailures:this.startupFailures,recent:this.restarts.length});
this.update({status:plan.cooldown?'cooldown':'backoff',nextRestartAt:new Date(now+plan.delayMs).toISOString(),consecutiveStartupFailures:this.startupFailures});this.store.event(plan.cooldown?'cooldown':'restarting',{delayMs:plan.delayMs,reason:this.state.reason,consecutiveStartupFailures:this.startupFailures});
this.restartTimer=setTimeout(()=>{if(this.stopping)return;this.restarts.push(Date.now());this.update({restartCount:this.state.restartCount+1});this.launch().catch(()=>{this.update({reason:'spawn_failed'});this.scheduleRestart();});},plan.delayMs);
}
async tick(){
@@ -64,7 +71,7 @@ class ServiceSupervisor {
const child=this.child,instanceId=this.instanceId,token=this.heartbeatToken;
const results=await Promise.allSettled(this.ports.map(port=>checkPing(port,{token,instanceId,timeout:this.timing.pingTimeoutMs})));
if(this.stopping||this.child!==child||this.manualRestart)return;
if(results.every(r=>r.status==='fulfilled')){this.misses=0;if(Date.now()-this.spawnedAt>300000)this.failures=0;this.update({status:'running',heartbeatAt:new Date().toISOString(),reason:'healthy'});return;}
if(results.every(r=>r.status==='fulfilled')){this.misses=0;this.ready=true;this.startupFailures=0;this.startupError=null;if(Date.now()-this.spawnedAt>300000)this.failures=0;this.update({status:'running',heartbeatAt:new Date().toISOString(),reason:'healthy',startupFailure:false,startupError:null,consecutiveStartupFailures:0});return;}
this.update({});if(this.state.status==='starting'&&Date.now()-this.spawnedAt<this.timing.startupGraceMs)return;
if(++this.misses<this.timing.failureThreshold)return;
this.exitReason='health_timeout';this.store.event('unresponsive');await this.endChild(false);
@@ -79,7 +86,7 @@ class ServiceSupervisor {
}
async restart(){
if(this.stopping||this.manualRestart)return;this.manualRestart=true;clearTimeout(this.restartTimer);this.update({status:'starting',reason:'manual_restart',nextRestartAt:null});this.store.event('manual_restart');
try{await this.endChild();this.child=null;this.update({restartCount:this.state.restartCount+1,reason:'manual_restart'});this.failures=0;this.restarts=[];await this.launch();}
try{await this.endChild();this.child=null;this.update({restartCount:this.state.restartCount+1,reason:'manual_restart'});this.failures=0;this.startupFailures=0;this.restarts=[];await this.launch();}
catch(cause){this.update({status:'failed',childPid:this.child?.pid||null,nextRestartAt:null,reason:cause.code==='EADDRINUSE'?'port_conflict':cause.code==='EINVALIDPORTS'?'config_invalid':'restart_failed'});this.store.event('restart_failed',{reason:this.state.reason});throw cause;}
finally{this.manualRestart=false;}
}
+1 -1
View File
@@ -7,5 +7,5 @@ if (require.main === module) main().then(app=>{
process.once('SIGINT',stop);process.once('SIGTERM',stop);
process.on('message',message=>{if(message==='order:shutdown')stop();});
console.info('启动耗时(ms):'+Math.round(performance.now()-startupAt));
}).catch(error => { console.error('启动失败:'+JSON.stringify(safeDiagnostic(error,{durationMs:performance.now()-startupAt}))); process.exitCode=1; });
}).catch(error => { const diagnostic=safeDiagnostic(error,{durationMs:performance.now()-startupAt});console.error('启动失败:'+JSON.stringify(diagnostic));if(process.connected)try{process.send({type:'order:startup-failed',diagnostic},()=>{});}catch{}process.exitCode=1; });
module.exports = { createServer, startService, main };
+21
View File
@@ -0,0 +1,21 @@
'use strict';
const crypto=require('node:crypto');
// Transactional metadata only: triggers never copy/decrypt a business payload.
// Existing rows start at zero; the HTTP validator has a fresh key per server.
function installRevisionTracking(db,specs){
db.exec('CREATE TABLE IF NOT EXISTS refresh_revisions(scope TEXT PRIMARY KEY,revision INTEGER NOT NULL)');
for(const spec of specs){
const [table,expression,updateWhen]=Array.isArray(spec)?spec:[spec,"'"+spec+"'"];
if(!/^[a-z_]+$/.test(table))throw Error('Invalid revision table');
const scope=row=>expression.replaceAll('$row',row),bump=value=>`INSERT INTO refresh_revisions(scope,revision) SELECT ${value},1 WHERE ${value} IS NOT NULL ON CONFLICT(scope) DO UPDATE SET revision=revision+1;`;
const name=table+'_'+crypto.createHash('sha256').update(expression+(updateWhen||'')).digest('hex').slice(0,12);
db.exec(`CREATE TRIGGER IF NOT EXISTS refresh_${name}_insert AFTER INSERT ON ${table} BEGIN ${bump(scope('NEW'))} END;
CREATE TRIGGER IF NOT EXISTS refresh_${name}_update AFTER UPDATE ON ${table}${updateWhen?' WHEN '+updateWhen:''} BEGIN ${bump(scope('OLD'))} ${bump(scope('NEW'))} END;
CREATE TRIGGER IF NOT EXISTS refresh_${name}_delete AFTER DELETE ON ${table} BEGIN ${bump(scope('OLD'))} END;`);
}
}
function readRevisions(db,scopes){
const rows=scopes?db.prepare('SELECT scope,revision FROM refresh_revisions WHERE scope IN (SELECT value FROM json_each(?)) ORDER BY scope').all(JSON.stringify(scopes)):db.prepare('SELECT scope,revision FROM refresh_revisions ORDER BY scope').all();
return {...Object.fromEntries((scopes||[]).map(scope=>[scope,0])),...Object.fromEntries(rows.map(row=>[row.scope,Number(row.revision)]))};
}
module.exports={installRevisionTracking,readRevisions};
+1 -1
View File
@@ -50,7 +50,7 @@ test('password version rejects old sessions even if eager session cleanup fails'
test('password change closes only the target account BPM login windows',async t=>{
const crypto=require('node:crypto'),{BpmSessionManager}=require('../../src/modules/bpm/session-manager.cjs');
const f=await fixture(t),first=await f.login('viewer'),second=await f.login('viewer'),admin=await f.login();
const cookies=[first,second,admin],manager={revokedSessionHashes:new Set(),sessions:new Map(cookies.map((cookie,i)=>[String(i),{id:String(i),sessionId:cookie.split('=')[1]}])),run:async(id,work)=>work(),async closeLease(id){this.sessions.delete(id);}};
const cookies=[first,second,admin],manager={sessionState:new (require('../../src/modules/bpm/session-state.cjs').SessionState)(),revokedSessionHashes:new Set(),sessions:new Map(cookies.map((cookie,i)=>[String(i),{id:String(i),sessionId:cookie.split('=')[1]}])),run:async(id,work)=>work(),async closeLease(id){this.sessions.delete(id);}};
const hashes=new SessionStore(f.dir);const targetHashes=hashes.userSessionHashes(f.viewer.id);hashes.close();
assert.equal(targetHashes.length,2);await BpmSessionManager.prototype.releaseSessionHashes.call(manager,targetHashes);assert.deepEqual([...manager.sessions.keys()],['2']);
assert.equal(targetHashes.includes(crypto.createHash('sha256').update(admin.split('=')[1]).digest('hex')),false);
+81
View File
@@ -0,0 +1,81 @@
'use strict';
const {test}=require('node:test'),assert=require('node:assert/strict');
const fs=require('node:fs'),os=require('node:os'),path=require('node:path'),http=require('node:http'),zlib=require('node:zlib');
const {Store}=require('../../src/modules/dashboard/store.cjs');
const {createDashboard}=require('../../src/app/dashboard.cjs');
const {createAssetDelivery}=require('../../src/app/asset-delivery.cjs');
async function fixture(t){
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'asset-delivery-')),store=new Store(dir),server=createDashboard({store,outputDir:dir});
await new Promise(r=>server.listen(0,'127.0.0.1',r));
t.after(async()=>{server.closeAllConnections();await new Promise(r=>server.close(r));fs.rmSync(dir,{recursive:true,force:true});});
return (route,headers={},method='GET')=>new Promise((resolve,reject)=>{const request=http.request({hostname:'127.0.0.1',port:server.address().port,path:route,headers,method},response=>{const parts=[];response.on('data',part=>parts.push(part));response.on('end',()=>resolve({status:response.statusCode,headers:response.headers,bytes:Buffer.concat(parts)}));});request.on('error',reject);request.end();});
}
test('public assets compress losslessly and conditional reload sends no body while APIs stay private',async t=>{
const get=await fixture(t),plain=await get('/app.js'),compressed=await get('/app.js',{'Accept-Encoding':'br, gzip'});
assert.equal(compressed.status,200);assert.equal(compressed.headers['content-encoding'],'br');
assert.deepEqual(zlib.brotliDecompressSync(compressed.bytes),plain.bytes);assert.ok(compressed.bytes.length<plain.bytes.length/2);
assert.match(compressed.headers.vary,/Accept-Encoding/i);assert.ok(plain.headers.etag);assert.match(plain.headers['cache-control'],/must-revalidate/);
const unchanged=await get('/app.js',{'If-None-Match':plain.headers.etag,'Accept-Encoding':'gzip'});
assert.equal(unchanged.status,304);assert.equal(unchanged.bytes.length,0);
const api=await get('/api/me',{'Accept-Encoding':'br'});assert.equal(api.status,401);assert.equal(api.headers['cache-control'],'no-store');assert.equal(api.headers.etag,undefined);
const html=await get('/');assert.match(html.headers['cache-control'],/must-revalidate/);assert.ok(html.bytes.includes(Buffer.from('<!doctype html>')));
});
test('asset encoding negotiation honors q=0 and HEAD returns metadata without payload',async t=>{
const get=await fixture(t),gzip=await get('/app.css',{'Accept-Encoding':'br;q=0, gzip;q=0.7'});
assert.equal(gzip.headers['content-encoding'],'gzip');assert.ok(zlib.gunzipSync(gzip.bytes).length>gzip.bytes.length);
const plain=await get('/app.css',{'Accept-Encoding':'br;q=0, gzip;q=0'});assert.equal(plain.headers['content-encoding'],undefined);
const preferred=await get('/app.css',{'Accept-Encoding':'gzip;q=0.1, identity;q=1'});assert.equal(preferred.headers['content-encoding'],undefined);
const head=await get('/app.css',{'Accept-Encoding':'gzip'},'HEAD');assert.equal(head.status,200);assert.equal(head.bytes.length,0);assert.equal(Number(head.headers['content-length']),gzip.bytes.length);
const none=await get('/app.css',{'Accept-Encoding':'br;q=0,gzip;q=0,identity;q=0,*;q=0'});assert.equal(none.status,406);
const preview=await get('/storage-preview.js',{'Accept-Encoding':'gzip'});assert.match(preview.headers['content-security-policy'],/frame-ancestors 'self'/);assert.equal(preview.headers['access-control-allow-origin'],'*');
});
test('public asset cache revalidates changed files and concurrent reloads agree',async t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'asset-edit-')),file=path.join(dir,'app.js'),deliver=createAssetDelivery({maxBytes:4096});fs.writeFileSync(file,'old application');t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
async function get(etag){const headers={};let status,bytes;await deliver({method:'GET',headers:{'if-none-match':etag}},{setHeader:(key,value)=>headers[key]=value,writeHead:value=>status=value,end:value=>bytes=value},{path:file,type:'text/javascript'});return {headers,status,bytes};}
const first=await get();fs.writeFileSync(file,'new application with changed size');
const results=await Promise.all(Array.from({length:8},()=>get(first.headers.ETag)));
for(const result of results){assert.equal(result.status,200);assert.equal(result.bytes.toString(),'new application with changed size');assert.notEqual(result.headers.ETag,first.headers.ETag);}
assert.equal((await get(results[0].headers.ETag)).status,304);
});
test('asset URLs become immutable only when their content fingerprint is verified',async t=>{
const get=await fixture(t),plain=await get('/app.js');
const fingerprint=plain.headers['x-asset-version'];
assert.match(fingerprint,/^[0-9a-f]{64}$/);
assert.equal(plain.headers['cache-control'],'public, max-age=0, must-revalidate');
const versioned=await get('/app.js?v='+fingerprint);
assert.equal(versioned.status,200);
assert.equal(versioned.headers['x-asset-version'],fingerprint);
assert.equal(versioned.headers['cache-control'],'public, max-age=31536000, immutable');
const untrusted=await get('/app.js?v=not-the-content-fingerprint');
assert.equal(untrusted.status,200);
assert.equal(untrusted.headers['cache-control'],'public, max-age=0, must-revalidate');
});
test('HTML uses actual fingerprint URLs while the document itself always revalidates',async t=>{
const get=await fixture(t),page=await get('/'),html=page.bytes.toString();
const urls=[...html.matchAll(/(?:src|href)="(\/[^"#]+)"/g)].map(match=>match[1]);assert.ok(urls.length>0&&urls.length<20,'core shell stays below twenty eager assets');
for(const url of urls){assert.match(url,/\?v=[a-f0-9]{64}$/);const asset=await get(url);assert.equal(asset.status,200);assert.match(asset.headers['cache-control'],/immutable/);assert.equal(new URL(url,'http://local').searchParams.get('v'),asset.headers['x-asset-version']);}
const versioned=await get('/?v='+page.headers['x-asset-version']);assert.match(versioned.headers['cache-control'],/must-revalidate/);assert.doesNotMatch(versioned.headers['cache-control'],/immutable/);
});
test('HTML publishes fingerprint URLs for lazy modules without eagerly loading optional pages',async t=>{
const get=await fixture(t),page=await get('/'),html=page.bytes.toString();
const encoded=/<meta name="app-modules" content="([^"]+)"/.exec(html)?.[1];assert.ok(encoded,'lazy module manifest must be available in the document');
const manifest=JSON.parse(encoded.replaceAll('&quot;','"').replaceAll('&lt;','<').replaceAll('&gt;','>').replaceAll('&amp;','&'));
for(const route of ['/assistant.js','/business-home.js','/order-rules.js']){
assert.ok(manifest.urls[route]);assert.equal(html.includes('<script src="'+manifest.urls[route]+'"'),false);
const asset=await get(manifest.urls[route]);assert.equal(asset.status,200);assert.match(asset.headers['cache-control'],/immutable/);assert.equal(new URL(manifest.urls[route],'http://local').searchParams.get('v'),asset.headers['x-asset-version']);
}
});
test('changing one dependency changes its URL and HTML ETag without invalidating other assets',async t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'asset-dependency-'));t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
const documentPath=path.join(dir,'index.html'),one=path.join(dir,'one.js'),two=path.join(dir,'two.css');fs.writeFileSync(documentPath,'<!doctype html><link href="/two.css" rel="stylesheet"><script src="/one.js" defer></script>');fs.writeFileSync(one,'old()');fs.writeFileSync(two,'body{}');
const assets={'/one.js':{path:one,type:'text/javascript'},'/two.css':{path:two,type:'text/css'}},deliver=createAssetDelivery({resolveAsset:url=>assets[url]});
async function get(tag){const headers={};let bytes,status;await deliver({url:'/',method:'GET',headers:{'if-none-match':tag}},{setHeader:(key,value)=>headers[key]=value,writeHead:value=>status=value,end:value=>bytes=value},{path:documentPath,type:'text/html'});return {headers,status,bytes};}
const first=await get();fs.writeFileSync(one,'updated()');const second=await get(first.headers.ETag);assert.equal(second.status,200);assert.notEqual(second.headers.ETag,first.headers.ETag);
const refs=value=>[...value.bytes.toString().matchAll(/(?:src|href)="([^"]+)"/g)].map(match=>match[1]);const a=refs(first),b=refs(second);assert.equal(a[0],b[0]);assert.notEqual(a[1],b[1]);assert.equal((await get(second.headers.ETag)).status,304);
});
@@ -0,0 +1,26 @@
'use strict';
const {test}=require('node:test'),assert=require('node:assert/strict'),crypto=require('node:crypto'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {Store}=require('../../src/modules/dashboard/store.cjs'),{createDashboard}=require('../../src/app/dashboard.cjs');
function fixture(t,cleanup=true){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'async-auth-')),store=new Store(dir),admin=store.bootstrap('admin','Test-password-123');if(cleanup)t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));return {store,dir,admin};}
test('HTTP login validates real stored credentials without synchronous password hashing',async t=>{
const {store,dir}=fixture(t,false),server=createDashboard({store,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(async()=>{server.closeAllConnections();await new Promise(r=>server.close(r));fs.rmSync(dir,{recursive:true,force:true});});
const base='http://127.0.0.1:'+server.address().port;
const call=async(username,password)=>{const response=await fetch(base+'/api/login',{method:'POST',headers:{Origin:base,'Content-Type':'application/json'},body:JSON.stringify({username,password})});return {status:response.status,body:await response.json(),cookie:response.headers.get('set-cookie')};};
t.mock.method(crypto,'scryptSync',()=>{throw Error('synchronous password computation blocks other pages');});
const good=await call('ADMIN','Test-password-123');assert.equal(good.status,200);assert.equal(good.body.user.username,'admin');assert.ok(good.cookie);
assert.equal((await call('missing','Test-password-123')).status,401);assert.equal((await call('admin','Wrong-password-123')).status,401);
const authenticate=store.authenticateAsync.bind(store);store.authenticateAsync=async(...args)=>{const user=await authenticate(...args);store.updateUser(user.id,{version:user.version,enabled:true,role:user.role},user);return user;};
const stale=await call('admin','Test-password-123');assert.equal(stale.status,401,'account revocation between validation and session issuance must win');assert.equal(stale.cookie,null);
});
test('a disabled or changed account cannot complete a queued asynchronous login',async t=>{
const {store,admin}=fixture(t),worker=store.addUser({username:'worker',password:'Test-password-123',role:'operator'},'admin');
assert.equal(typeof store.authenticateAsync,'function');
const pending=store.authenticateAsync('worker','Test-password-123');store.updateUser(worker.id,{version:1,enabled:false,role:'operator'},admin);assert.equal(await pending,null);
const reset=store.authenticateAsync('admin','Test-password-123');store.updatePassword(admin.id,'New-password-456',admin);assert.equal(await reset,null);
});
test('asynchronous password jobs yield to the event loop and reject excessive queued work',async t=>{
const {store}=fixture(t);assert.equal(typeof store.authenticateAsync,'function');
let completed=0;const jobs=Array.from({length:60},()=>store.authenticateAsync('admin','Test-password-123').finally(()=>completed++));
const settled=Promise.allSettled(jobs);await new Promise(r=>setImmediate(r));assert.ok(completed<60,'HTTP/event loop must run while scrypt works');
const results=await settled;assert.ok(results.some(item=>item.status==='fulfilled'&&item.value?.username==='admin'));assert.ok(results.some(item=>item.status==='rejected'&&item.reason.status===429));
});
@@ -0,0 +1,48 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {RuntimeHealth}=require('../../src/modules/health/runtime-health.cjs');
const {OrderExecutionCoordinator}=require('../../src/modules/order-execution/coordinator.cjs');
const {OrderRuleDispatcher}=require('../../src/modules/order-rules/dispatcher.cjs');
test('health reads execution progress without field evidence, candidates, scans or provider probes',t=>{
const stateDir=fs.mkdtempSync(path.join(os.tmpdir(),'lean-health-'));
const tasks=[
{id:'blocked',connectionId:'mine',row:{processName:'Current process'},status:'blocked',orderId:'o1',error:'Capture blocked',updatedAt:'2026-10-27T01:00:00Z'},
{id:'complete',connectionId:'mine',row:{processName:'Completed process'},status:'archived',orderId:'o2',reason:'Archived progress',updatedAt:'2026-10-27T02:00:00Z'},
{id:'private',connectionId:'other',row:{processName:'PRIVATE_OTHER'},status:'failed',updatedAt:'2026-10-27T03:00:00Z'}
];
const execution=Object.create(OrderExecutionCoordinator.prototype);
execution.store={capabilities:{liveTodo:true,pdfExport:false,automaticArchive:true},
all(kind){assert.equal(kind,'execution-tasks','health must only enumerate execution tasks');return structuredClone(tasks);},
get(kind,id){assert.equal(kind,'orders');return {status:id==='o1'?'pending':'sent',error:'Order detail'};},
fields(){assert.fail('health must not decrypt captured fields');}
};
execution.snapshot=()=>assert.fail('full execution snapshot is not a health read');
execution.provider={capabilities:()=>assert.fail('must not probe')};
const health=new RuntimeHealth({stateDir,execution,workspace:{snapshot:()=>({connections:[{id:'mine',owner:'worker'},{id:'other',owner:'other'}]})}});
t.after(()=>{health.close();fs.rmSync(stateDir,{recursive:true,force:true});});
const group=health.snapshot({username:'worker',role:'operator'}).groups.find(group=>group.key==='execution');
assert.equal(group.status,'error');
assert.deepEqual(group.items.filter(item=>!item.global).map(item=>[item.id,item.status,item.detail]),[['complete','healthy','Order detail'],['blocked','error','Capture blocked']]);
assert.doesNotMatch(JSON.stringify(group),/PRIVATE_OTHER/);
const first=execution.healthSnapshot();first.capabilities.liveTodo=false;first.tasks.find(task=>task.id==='complete').status='unknown';
assert.equal(execution.healthSnapshot().capabilities.liveTodo,true);
assert.equal(execution.healthSnapshot().tasks.find(task=>task.id==='complete').status,'sent');
});
test('paused dispatcher expires prepared automatic queues without assembling rules or execution snapshots',async()=>{
const now=new Date('2026-10-27T04:00:00Z'),finished=[],batches=[
{id:'expired',status:'prepared',cutoff:'2026-10-27T03:00:00Z'},
{id:'boundary',status:'prepared',cutoff:'2026-10-27T03:30:00Z'},
{id:'manual',status:'prepared',manual:true,cutoff:'2026-10-27T03:00:00Z'},
{id:'unknown',status:'unknown',cutoff:'2026-10-27T03:00:00Z'}
];let intakeChecks=0;
const dispatcher=new OrderRuleDispatcher({clock:()=>now,store:{
capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true},settings:()=>({enabled:false}),
expireIntakes(){intakeChecks++;},all(kind){assert.equal(kind,'batches');return structuredClone(batches);},
snapshot(){assert.fail('polling must not assemble a full rule snapshot');},finishSending(...args){finished.push(args);}
},mail:{exclusive:()=>assert.fail('paused dispatcher must not send')},providersReady:()=>true});
await dispatcher.tick();
assert.equal(intakeChecks,1);assert.equal(finished.length,1);assert.equal(finished[0][0],'expired');assert.equal(finished[0][1],'failed');
assert.deepEqual(finished[0][3],{outcome:'not_submitted',phase:'queue_expired',at:'2026-10-27T04:00:00.000Z'});
});
+1 -1
View File
@@ -5,4 +5,4 @@ async function setup(t){const f=await orderDrivenUI(t,'#overview'),data=summary(
test('business home presents actual next window and deduplicated work, keeps mobile layout and reduced motion',{timeout:60000},async t=>{const {page}=await setup(t);await page.locator('[data-business-home]').waitFor();assert.equal(await page.locator('[data-home-metric="pending"]').innerText(),'7');assert.equal(await page.locator('[data-home-next-send]').innerText(),'17:00');assert.match(await page.locator('[data-home-cutoff]').innerText(),/16:55/);assert.equal(await page.locator('[data-home-batch]').count(),2);assert.match(await page.locator('[data-home-batch]').first().innerText(),/6.*顺延/s);assert.equal(await page.getByRole('link',{name:'查看全部批次',exact:true}).getAttribute('href'),'#notification-batches');await require('node:fs/promises').mkdir('output/business-flow-test/home-visual',{recursive:true});await page.screenshot({path:'output/business-flow-test/home-visual/desktop.png',fullPage:true});await page.setViewportSize({width:674,height:1000});await page.screenshot({path:'output/business-flow-test/home-visual/compact.png',fullPage:true});await page.emulateMedia({reducedMotion:'reduce'});assert.equal(await page.locator('.home-live .status-dot').evaluate(e=>getComputedStyle(e,'::before').animationName),'none');await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);await page.screenshot({path:'output/business-flow-test/home-visual/mobile.png',fullPage:true});});
test('paused and blocked states remain honest and the clock never claims delivery at the deadline',{timeout:60000},async t=>{const {page,data}=await setup(t);await page.locator('[data-business-home]').waitFor();await page.clock.fastForward(5*3600000+1000);assert.match(await page.locator('[data-home-countdown]').innerText(),/刷新.*发送结果/);data.settings.enabled=false;data.capabilities.liveTodo=false;data.issues=[{id:'i',error:'<img src=x onerror=alert(1)>',status:'open'}];await page.reload();await page.getByText('自动邮件已暂停',{exact:true}).waitFor();assert.equal(await page.locator('.home-live .status-dot-animated').count(),0);assert.equal(await page.locator('.home-issues img').count(),0);assert.match(await page.locator('.home-issues').innerText(),/img src/);});
test('failed summary loading never displays invented zero counts or healthy state',{timeout:60000},async t=>{const {page}=await setup(t);await page.unroute('**/api/order-rules?view=summary');await page.route('**/api/order-rules?view=summary',r=>r.fulfill({status:503,json:{error:'首页数据暂不可用'}}));await page.reload();await page.getByText('首页数据暂不可用',{exact:false}).first().waitFor();assert.equal(await page.locator('[data-business-home]').count(),0);});
test('failed internal refresh retains the last home and offers a working retry',{timeout:60000},async t=>{const {page,data}=await setup(t);await page.locator('[data-business-home]').waitFor();await page.unroute('**/api/order-rules?view=summary');let fail=true;await page.route('**/api/order-rules?view=summary',r=>fail?r.fulfill({status:503,json:{error:'暂时不可用'}}):r.fulfill({json:data}));await page.clock.fastForward(15001);await page.locator('[data-business-updates]').waitFor();await page.getByRole('button',{name:'刷新业务首页',exact:true}).click();await page.getByText('刷新失败:暂时不可用',{exact:false}).waitFor();assert.equal(await page.locator('[data-home-metric="pending"]').innerText(),'7');fail=false;await page.getByRole('button',{name:'刷新业务首页',exact:true}).click();await page.locator('[data-business-updates]').waitFor({state:'hidden'});assert.equal(await page.locator('[data-home-metric="pending"]').innerText(),'7');});
test('failed internal refresh retains the last home and offers a working retry',{timeout:60000},async t=>{const {page,data}=await setup(t);await page.locator('[data-business-home]').waitFor();await page.unroute('**/api/order-rules?view=summary');let fail=true;await page.route('**/api/refresh/revisions*',r=>r.fulfill({json:{regions:{home:'a'.repeat(64),orderRules:'b'.repeat(64)}}}));await page.route('**/api/order-rules?view=summary',r=>fail?r.fulfill({status:503,json:{error:'暂时不可用'}}):r.fulfill({json:data}));await page.clock.fastForward(15001);await page.locator('[data-business-updates]').waitFor();const failedRefresh=page.waitForResponse(response=>response.url().includes('/api/order-rules?view=summary')&&response.status()===503);await page.getByRole('button',{name:'刷新业务首页',exact:true}).click();await failedRefresh;await page.getByText('刷新失败:暂时不可用',{exact:false}).waitFor();await page.waitForFunction(()=>{const button=[...document.querySelectorAll('[data-business-updates] button')].find(item=>item.textContent.includes('刷新业务首页'));return button&&!button.disabled;});assert.equal(await page.locator('[data-home-metric="pending"]').innerText(),'7');fail=false;const successfulRefresh=page.waitForResponse(response=>response.url().includes('/api/order-rules?view=summary')&&response.status()===200);await page.getByRole('button',{name:'刷新业务首页',exact:true}).click();await successfulRefresh;await page.locator('[data-business-updates]').waitFor({state:'hidden'});assert.equal(await page.locator('[data-home-metric="pending"]').innerText(),'7');});
+1 -1
View File
@@ -1,7 +1,7 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),vm=require('node:vm');
const source=fs.readFileSync('web/app.js','utf8');
function fixture(){let resolve,requests=0,disposed=0,booted=0;const context={AbortController,AbortSignal,setTimeout:(fn,ms)=>{const timer=setTimeout(fn,ms);timer.unref();return timer;},clearTimeout,fetch:()=>{requests++;return new Promise(r=>resolve=r);},window:{PageLifecycle:{revision:1,dispose:async()=>{disposed++;},succeeded(){},failed(){}},BpmLogin:{dispose(){}}}};vm.createContext(context);vm.runInContext("let currentUser={username:'old'},viewGeneration=1;const pendingWrites=new Map();async function boot(){booted++;}",context);context.booted=0;vm.runInContext(source.slice(source.indexOf('async function api('),source.indexOf('async function verifyUncertainWrite(')),context);return {context,run:s=>vm.runInContext(s,context),resolve:r=>resolve(r),requests:()=>requests,disposed:()=>disposed};}
function fixture(){let resolve,requests=0,disposed=0,booted=0;const context={AbortController,AbortSignal,structuredClone,DOMException,setTimeout:(fn,ms)=>{const timer=setTimeout(fn,ms);timer.unref();return timer;},clearTimeout,fetch:()=>{requests++;return new Promise(r=>resolve=r);},window:{PageLifecycle:{revision:1,dispose:async()=>{disposed++;},succeeded(){},failed(){}},BpmLogin:{dispose(){}}}};vm.createContext(context);vm.runInContext("let currentUser={username:'old'},viewGeneration=1;async function boot(){booted++;}",context);context.booted=0;vm.runInContext(source.slice(source.indexOf('const pendingWrites='),source.indexOf('async function verifyUncertainWrite(')),context);return {context,run:s=>vm.runInContext(s,context),resolve:r=>resolve(r),requests:()=>requests,disposed:()=>disposed};}
for(const change of ['viewGeneration++;window.PageLifecycle.revision++;','currentUser={username:"new"};viewGeneration++;window.PageLifecycle.revision++;'])test('obsolete 401 has no auth effects after '+change,async()=>{const f=fixture(),request=f.run("api('/old')");f.run(change);f.resolve({ok:false,status:401,json:async()=>({error:'expired'})});await assert.rejects(request,/expired/);assert.equal(f.run('currentUser!==null'),true);assert.equal(f.disposed(),0);assert.equal(f.context.booted,0);});
test('owned session 401 still disposes expired session',async()=>{const f=fixture(),request=f.run("api('/current')");f.resolve({ok:false,status:401,json:async()=>({error:'expired'})});await assert.rejects(request,/expired/);assert.equal(f.run('currentUser'),null);assert.equal(f.disposed(),1);assert.equal(f.context.booted,1);});
test('identical writes from a newer session never join old pending work',async()=>{const f=fixture();f.run("api('/write',{a:1})");f.run('currentUser={username:"new"};viewGeneration++;');const current=f.run("api('/write',{a:1})");assert.equal(f.requests(),2);f.resolve({ok:true,json:async()=>({version:2})});await current;});
+48
View File
@@ -0,0 +1,48 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict');
const {orderDrivenUI}=require('../fixtures/order-driven-ui.cjs');
test('cold home omits optional pages, routes load dependencies on demand and reuse completed scripts',{timeout:120000},async t=>{
const {page}=await orderDrivenUI(t,'#overview'),errors=[];page.on('pageerror',e=>errors.push(e.message));
await page.route('**/api/mail',r=>r.fulfill({json:{channels:[],templates:[],receipts:[],sends:[]}}));
await page.route('**/api/assistant',r=>r.fulfill({json:{settings:{version:1,enabled:false,model:'fixture',runtimePath:'',apiBase:'',timeoutSeconds:90,dailyLimit:100,allowActions:false},conversations:[],skills:[],usage:{calls:0,limit:100}}}));
await page.route('**/api/assistant/providers',r=>r.fulfill({json:{version:1,providers:[],defaultSelection:null,catalog:{protocols:['openai-completions','openai-responses','anthropic-messages'],presets:[]}}}));
await page.route('**/api/assistant/context',r=>r.fulfill({json:{at:'2026-10-29T00:00:00Z',role:'admin',connections:[],runs:[],servers:[],archives:[],jobs:[],exceptions:[],configuration:[],business:{blockers:[]}}}));
await page.route('**/api/assistant/conversations?*',r=>r.fulfill({json:{items:[],total:0,page:1}}));
await page.route('**/api/assistant/operations*',r=>r.fulfill({json:{events:[]}}));
await page.route('**/api/storage',r=>r.fulfill({json:{servers:[],archives:[],settings:{version:1,enabled:false,defaultServerId:''}}}));
await page.route('**/api/health',r=>r.fulfill({json:{runtime:{uptimeSeconds:0,startedAt:'2026-10-28T00:00:00Z',autostart:{enabled:false},guard:{status:'unmanaged',events:[]}},groups:[]}}));
await page.locator('[data-business-home]').waitFor();const reads=[];
page.on('request',r=>{if(r.resourceType()==='script')reads.push(new URL(r.url()).pathname);});
await page.reload();await page.locator('[data-business-home]').waitFor();
for(const route of ['/assistant.js','/bpm.js','/mail.js','/storage.js','/order-rules.js'])assert.equal(reads.includes(route),false,route);
const screens=[['notification-orders','[data-arrival-list]'],['notification-batches','[data-arrival-list]'],['rule-fields','#fm-count'],['order-rules','#order-rules-panel'],['mail','#mail-add'],['assistant','#assistant-input'],['assistant-settings','#assistant-settings-form'],['storage','#storage-add'],['health','#health-refresh'],['records-pdf','[data-pdf-list]'],['records','[data-arrival-list]'],['bpm','[data-bpm-feedback]'],['account','#account-password-form'],['calendar','#day-form'],['exceptions','#exception-new'],['templates','#mail-templates'],['schedule','#schedule-form'],['audit','.audit-detail,.empty-state,.card']];
for(const [route,ready] of screens){await page.evaluate(hash=>location.hash=hash,route);try{await page.locator(ready).first().waitFor({state:'attached'});}catch(e){t.diagnostic(JSON.stringify({route,text:await page.locator('#content').innerText(),errors}));throw e;}assert.equal(await page.locator('[data-module-retry]').count(),0,route+' module load');}
const before=reads.filter(r=>r==='/assistant.js').length;
await page.evaluate(()=>location.hash='assistant');await page.locator('#assistant-input').waitFor();
assert.equal(reads.filter(r=>r==='/assistant.js').length,before);assert.deepEqual(errors,[]);
});
test('failed route scripts offer retry and an abandoned route cannot mount after a slow dependency',{timeout:60000},async t=>{
const {page}=await orderDrivenUI(t,'#overview');await page.locator('[data-business-home]').waitFor();let fail=true;
await page.route('**/health.js?*',route=>fail?route.abort():route.continue());
await page.evaluate(()=>location.hash='health');await page.locator('[data-module-retry]').waitFor();fail=false;
await page.locator('[data-module-retry]').click();await page.locator('#health-refresh').waitFor();
let release;const held=new Promise(resolve=>release=resolve);await page.route('**/assistant.js?*',async route=>{await held;await route.continue();});
try{await page.evaluate(()=>location.hash='assistant');await page.waitForFunction(()=>document.querySelector('#view-title')?.textContent==='DSH 助手');await page.evaluate(()=>location.hash='overview');await page.locator('[data-business-home]').waitFor();}finally{release();}
await page.waitForTimeout(200);assert.equal(await page.locator('[data-business-home]').count(),1);assert.equal(await page.locator('#assistant-input').count(),0);
});
test('an unopened home can execute while a cold assistant script is stalled',{timeout:60000},async t=>{
const {page,base}=await orderDrivenUI(t,'#overview');await page.locator('[data-business-home]').waitFor();
let release;const held=new Promise(resolve=>release=resolve);await page.route('**/assistant.js?*',async route=>{await held;await route.continue();});
try{await page.goto('about:blank');await page.goto(base+'/#assistant',{waitUntil:'domcontentloaded'});await page.waitForFunction(()=>document.querySelector('#view-title')?.textContent==='DSH 助手');await page.evaluate(()=>location.hash='overview');await page.locator('[data-business-home]').waitFor();}finally{release();}
await page.waitForTimeout(100);assert.equal(await page.locator('#assistant-input').count(),0);
});
test('a lazy script whose bytes differ from the document fingerprint cannot execute',{timeout:60000},async t=>{
const {page}=await orderDrivenUI(t,'#overview');await page.locator('[data-business-home]').waitFor();let corrupt=true;
await page.route('**/health.js?*',async route=>{if(!corrupt)return route.continue();const response=await route.fetch();await route.fulfill({response,headers:{...response.headers(),'cache-control':'no-store'},body:(await response.text())+'\nwindow.staleModuleExecuted=true;'});});
await page.evaluate(()=>location.hash='health');await page.locator('[data-module-retry]').waitFor();assert.equal(await page.evaluate(()=>window.staleModuleExecuted),undefined);
corrupt=false;await page.locator('[data-module-retry]').click();await page.locator('#health-refresh').waitFor({state:'attached'});
});
+36
View File
@@ -0,0 +1,36 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),vm=require('node:vm');
function fixture(){
const groups=JSON.parse(fs.readFileSync('web/modules/navigation/module-manifest.json','utf8')),urls=Object.fromEntries(Object.values(groups).flat().filter(file=>!file.startsWith('$')).map(file=>['/'+file,'/'+file+'?v='+'a'.repeat(64)]));
const appended=[],context=vm.createContext({btoa,document:{querySelector:()=>({content:JSON.stringify({groups,urls})}),head:{appendChild(script){if(script.tagName!=='script')return;appended.push(script.src.split('?')[0]);queueMicrotask(()=>script.onload());}},createElement(tagName){return {tagName,remove(){}};}},window:{}});
vm.runInContext(fs.readFileSync('web/modules/navigation/module-loader.js','utf8'),context);
return {context,appended};
}
test('route loader requests only the selected page group and deduplicates dependencies',async()=>{
const f=fixture();
await f.context.window.AppModules.load('overview');
const first=[...f.appended];
assert.ok(first.includes('/order-notifications.js'));
assert.ok(first.includes('/business-home.js'));
assert.equal(first.includes('/assistant.js'),false);
await f.context.window.AppModules.load('overview');
assert.deepEqual(f.appended,first);
});
test('route loader keeps shared modules before route modules and reports script failures',async()=>{
const f=fixture();await f.context.window.AppModules.load('assistant');
const modules=f.appended;
assert.ok(modules.indexOf('/assistant-operations.js')<modules.indexOf('/assistant.js'));
const bad=fixture();bad.context.document.head.appendChild=script=>{if(script.tagName==='script')queueMicrotask(()=>script.onerror(new Error('missing')));};
await assert.rejects(bad.context.window.AppModules.load('assistant'),/无法加载页面资源/);
});
test('failed modules can be retried without executing successful dependencies twice',async()=>{
const f=fixture();let fail=true;
f.context.document.head.appendChild=script=>{if(script.tagName!=='script')return;f.appended.push(script.src.split('?')[0]);queueMicrotask(()=>fail&&script.src.startsWith('/assistant.js')?script.onerror():script.onload());};
await assert.rejects(f.context.window.AppModules.load('assistant'),/无法加载页面资源/);fail=false;
await f.context.window.AppModules.load('assistant');
assert.equal(f.appended.filter(src=>src==='/assistant.js').length,2);assert.equal(f.appended.filter(src=>src==='/assistant-operations.js').length,1);
});
+14
View File
@@ -0,0 +1,14 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict');
const {orderDrivenUI}=require('../fixtures/order-driven-ui.cjs');
async function visibility(page,hidden){await page.evaluate(value=>{Object.defineProperty(document,'hidden',{configurable:true,value});document.dispatchEvent(new Event('visibilitychange'));},hidden);}
test('home opens with one summary and lightweight topbar, validates unchanged tokens and checks once on return',{timeout:60000},async t=>{const {page}=await orderDrivenUI(t,'#overview');await page.locator('[data-business-home]').waitFor();await page.clock.install();const requests=[];page.on('request',r=>{if(r.url().includes('/api/'))requests.push(new URL(r.url()).pathname+new URL(r.url()).search);});await page.reload();await page.locator('[data-business-home]').waitFor();assert.equal(requests.filter(r=>r==='/api/order-rules?view=summary').length,1);assert.equal(requests.filter(r=>r==='/api/order-rules/status').length,1);requests.length=0;await page.clock.fastForward(15001);await new Promise(r=>setTimeout(r,150));assert.equal(requests.filter(r=>r==='/api/order-rules?view=summary').length,0);assert.equal(requests.filter(r=>r==='/api/order-rules/status').length,0);assert.ok(requests.some(r=>r==='/api/refresh/revisions?regions=home'));requests.length=0;await visibility(page,true);await page.clock.fastForward(60001);await page.waitForTimeout(100);assert.deepEqual(requests,[]);const validated=page.waitForResponse(r=>r.url().includes('/api/refresh/revisions?regions=home'));await visibility(page,false);await validated;await page.waitForTimeout(100);assert.equal(requests.filter(r=>r==='/api/order-rules?view=summary').length,0);assert.equal(requests.filter(r=>r==='/api/order-rules/status').length,0);});
test('health, BPM, ledger and business records stop background requests without replacing draft inputs',{timeout:60000},async t=>{const {page}=await orderDrivenUI(t,'#health');await page.clock.install();for(const [route,ready,endpoint] of [['health','#health-refresh','/api/health'],['bpm','[data-bpm-feedback]','/api/workspace'],['records-pdf','[data-pdf-list]','/api/jobs?'],['notification-orders','[data-arrival-list]','/api/order-rules/orders?'],['notification-batches','[data-arrival-list]','/api/order-rules/batches?']]){await visibility(page,false);await page.evaluate(hash=>location.hash=hash,route);await page.locator(ready).waitFor({state:'attached'});await page.waitForTimeout(200);const seen=[];const listen=r=>{if(r.url().includes(endpoint))seen.push(r.url());};const draft=page.locator('[name=q],#record-search').first();if(await draft.count())await draft.fill('未提交过滤词');page.on('request',listen);await visibility(page,true);await page.clock.fastForward(31001);await page.waitForTimeout(100);assert.equal(seen.length,0,route+' should not poll hidden');await visibility(page,false);if(await draft.count())assert.equal(await draft.inputValue(),'未提交过滤词');page.off('request',listen);} });
test('notification settings request only configuration and fetch mailbox in parallel',{timeout:60000},async t=>{const {page}=await orderDrivenUI(t,'#overview');await page.locator('[data-business-home]').waitFor();let release;const held=new Promise(resolve=>release=resolve);let mailRead=false,settingsRead=false,heavy=0;await page.route('**/api/order-rules/notification-settings',async route=>{settingsRead=true;await held;await route.fulfill({json:{settings:{enabled:false,processingEnabled:false,version:1}}});});await page.route('**/api/mail',route=>{mailRead=true;return route.fulfill({json:{channels:[]}});});page.on('request',r=>{if(r.url().endsWith('/api/order-rules?view=summary'))heavy++;});try{await page.evaluate(()=>location.hash='notification-settings');await page.waitForFunction(()=>document.querySelector('#view-title').textContent==='发送设置');await new Promise(r=>setTimeout(r,250));assert.equal(settingsRead,true);assert.equal(mailRead,true);assert.equal(heavy,0);}finally{release();}await page.locator('#order-rule-settings').waitFor();});
test('cold authentication reads bootstrap once and an authenticated reload skips bootstrap',{timeout:60000},async t=>{const {page,browser,base}=await orderDrivenUI(t,'#overview');await page.locator('[data-business-home]').waitFor();const context=await browser.newContext();try{const cold=await context.newPage(),bootstrap=[];cold.on('request',r=>{if(r.url().endsWith('/api/bootstrap/status'))bootstrap.push(r.url());});await cold.goto(base);await cold.locator('#login-form').waitFor();assert.equal(bootstrap.length,1);}finally{await context.close();}let bootstrap=0;page.on('request',r=>{if(r.url().endsWith('/api/bootstrap/status'))bootstrap++;});await page.reload();await page.locator('[data-business-home]').waitFor();assert.equal(bootstrap,0);});
test('field mapping directory starts while the independent connection catalog is still loading',{timeout:60000},async t=>{const {page}=await orderDrivenUI(t,'#overview');await page.locator('[data-business-home]').waitFor();let release;const held=new Promise(resolve=>release=resolve);let fieldRead=false;await page.route('**/api/workspace',async route=>{await held;await route.continue();});await page.route('**/api/order-rules/fields?view=scopes',route=>{fieldRead=true;return route.continue();});try{await page.evaluate(()=>location.hash='rule-fields');await page.waitForFunction(()=>document.querySelector('#view-title').textContent==='字段映射');await new Promise(r=>setTimeout(r,250));assert.equal(fieldRead,true);}finally{release();}await page.locator('#fm-count').waitFor();});
test('running assistant polling pauses hidden and resumes without clearing the next message draft',{timeout:60000},async t=>{const {page}=await orderDrivenUI(t,'#overview');await page.locator('[data-business-home]').waitFor();const conversation={id:'c1',title:'隔离会话',version:1,turns:[{id:'t1',status:'running',text:'只读检查',actions:[]}]};await page.route('**/api/assistant',r=>r.fulfill({json:{settings:{enabled:true,model:'fixture'},conversations:[conversation],usage:{calls:1,limit:30}}}));await page.route('**/api/assistant/conversations?*',r=>r.fulfill({json:{items:[conversation],total:1,page:1}}));await page.route('**/api/assistant/operations*',r=>r.fulfill({json:{events:[]}}));await page.route('**/api/assistant/conversations/c1',r=>r.fulfill({json:conversation}));await page.evaluate(()=>location.hash='assistant');await page.getByRole('button',{name:'停止回复',exact:true}).waitFor();await page.clock.install();await page.locator('#assistant-input').fill('保留下一条草稿');let reads=0;page.on('request',r=>{if(r.url().endsWith('/api/assistant/conversations/c1'))reads++;});await visibility(page,true);await page.clock.fastForward(10001);await new Promise(r=>setTimeout(r,100));assert.equal(reads,0);const response=page.waitForResponse(r=>r.url().endsWith('/api/assistant/conversations/c1'));await visibility(page,false);await response;assert.equal(reads,1);assert.equal(await page.locator('#assistant-input').inputValue(),'保留下一条草稿');});
@@ -0,0 +1,11 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),vm=require('node:vm');
function apiFixture(){const requests=[],context=vm.createContext({document:{querySelector:()=>null},window:{PageLifecycle:{revision:1,succeeded(){},failed(){}}},AbortController,AbortSignal,DOMException,structuredClone,setTimeout,clearTimeout,fetch:(url,options)=>new Promise((resolve,reject)=>{const row={url,options,reply:(data)=>resolve({ok:true,status:200,json:async()=>data})};requests.push(row);options.signal.addEventListener('abort',()=>reject(new DOMException('Aborted','AbortError')),{once:true});})});vm.runInContext(fs.readFileSync('web/app.js','utf8').split('async function verifyUncertainWrite')[0],context);vm.runInContext("currentUser={id:'one'}",context);return {requests,run:code=>vm.runInContext(code,context),context};}
test('same-user in-flight reads share transport but retain independent abort and result objects',async()=>{const f=apiFixture();f.run('globalThis.a=new AbortController();globalThis.b=new AbortController()');const first=f.run("api('/test',undefined,{signal:a.signal})"),second=f.run("api('/test',undefined,{signal:b.signal})");const rejected=assert.rejects(first,{name:'AbortError'});f.run('a.abort()');await rejected;assert.equal(f.requests.length,1);assert.equal(f.requests[0].options.signal.aborted,false);f.requests[0].reply({rows:[1]});assert.deepEqual(await second,{rows:[1]});const third=f.run("api('/next')"),fourth=f.run("api('/next')");f.requests[1].reply({rows:[1]});const [x,y]=await Promise.all([third,fourth]);x.rows.push(2);assert.deepEqual(y,{rows:[1]});});
test('mutations and identity changes prevent joining an older read',async()=>{const f=apiFixture();const old=f.run("api('/test')"),write=f.run("api('/settings',{})");f.requests[1].reply({ok:true});await write;const next=f.run("api('/test')");assert.equal(f.requests.length,3);f.run("currentUser={id:'two'}");const other=f.run("api('/test')");assert.equal(f.requests.length,4);for(const row of f.requests)row.reply({ok:true});await Promise.all([old,next,other]);});
function pollFixture(){const listeners={},timers=new Map();let seq=0;const document={hidden:false,addEventListener:(name,fn)=>listeners[name]=fn,removeEventListener:(name,fn)=>{if(listeners[name]===fn)delete listeners[name];}};const context=vm.createContext({document,window:{addEventListener(){}},crypto,AbortController,DOMException,setTimeout:(fn)=>{timers.set(++seq,fn);return seq;},clearTimeout:id=>timers.delete(id)});vm.runInContext(fs.readFileSync('web/modules/navigation/lifecycle.js','utf8'),context);return {context,document,listeners,timers,run:code=>vm.runInContext(code,context),tick:async()=>{const rows=[...timers.values()];timers.clear();for(const fn of rows)fn();await Promise.resolve();}};}
test('background pollers pause hidden, resume once visible, serialize work and dispose',async()=>{const f=pollFixture();f.run('globalThis.calls=0;globalThis.finish=null;globalThis.poll=window.PageLifecycle.poll(()=>{calls++;return new Promise(resolve=>finish=resolve);},1000)');await f.tick();assert.equal(f.run('calls'),1);f.run('poll.run()');assert.equal(f.run('calls'),1);f.document.hidden=true;f.listeners.visibilitychange();await f.tick();assert.equal(f.run('calls'),1);f.document.hidden=false;f.listeners.visibilitychange();f.run('finish()');await new Promise(r=>setImmediate(r));await f.tick();assert.equal(f.run('calls'),2);f.run('poll.dispose();finish()');await new Promise(r=>setImmediate(r));assert.equal(f.timers.size,0);assert.equal(f.listeners.visibilitychange,undefined);});
test('manual poll refresh cancels an older request and waits for a fresh response',async()=>{const f=pollFixture();f.run("globalThis.calls=0;globalThis.poll=window.PageLifecycle.poll(signal=>{calls++;return new Promise((resolve,reject)=>signal.addEventListener('abort',()=>reject(new DOMException('Aborted','AbortError')),{once:true}));},1000)");await f.tick();assert.equal(f.run('calls'),1);const fresh=f.run('poll.refresh()');await new Promise(r=>setImmediate(r));assert.equal(f.run('calls'),2);f.run('poll.dispose()');await assert.rejects(fresh,{name:'AbortError'});});
test('a new navigation generation cannot join an older page read',async()=>{const f=apiFixture();const old=f.run("api('/test')");f.run('viewGeneration++;window.PageLifecycle.revision++');const fresh=f.run("api('/test')");try{assert.equal(f.requests.length,2);}finally{for(const row of f.requests)row.reply({ok:true});await Promise.all([old,fresh]);}});
+27
View File
@@ -0,0 +1,27 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict');
const {orderDrivenUI}=require('../fixtures/order-driven-ui.cjs');
const regions=()=>({home:'1'.repeat(64),orderRules:'2'.repeat(64),records:'3'.repeat(64),health:'4'.repeat(64),bpm:'5'.repeat(64),assistant:'6'.repeat(64),storage:'7'.repeat(64),mail:'8'.repeat(64)});
test('unchanged home tokens skip heavy reads, changed token offers local apply, validation failure is visible',{timeout:60000},async t=>{
const {page}=await orderDrivenUI(t,'#overview');page.on('pageerror',error=>t.diagnostic(error.message));let tokens=regions(),valid=true,summary=0,status=0,validations=0;
await page.route('**/api/refresh/revisions*',route=>{validations++;return route.fulfill(valid?{json:{regions:tokens}}:{status:503,json:{error:'版本读取暂不可用'}});});
page.on('request',r=>{if(r.url().endsWith('/api/order-rules?view=summary'))summary++;if(r.url().endsWith('/api/order-rules/status'))status++;});
await page.clock.install();await page.reload();await page.locator('[data-business-home]').waitFor();summary=status=validations=0;
await page.clock.fastForward(15001);await page.waitForTimeout(150);assert.ok(validations>0);assert.equal(summary,0);assert.equal(status,0);
tokens={...tokens,home:'a'.repeat(64)};await page.clock.fastForward(15001);await page.waitForTimeout(150);assert.equal(summary,1);
await page.locator('#refresh').click();await page.waitForTimeout(150);assert.equal(summary,2,'manual refresh always rereads the current summary');assert.equal(new URL(page.url()).hash,'#overview');
valid=false;await page.clock.fastForward(15001);await page.getByText(/刷新失败:版本读取暂不可用/).waitFor();assert.equal(summary,2);
});
test('health and record pages validate unchanged tokens while preserving unsubmitted filters',{timeout:60000},async t=>{
const {page}=await orderDrivenUI(t,'#overview');page.on('pageerror',error=>t.diagnostic(error.message));const tokens=regions();await page.route('**/api/refresh/revisions*',r=>r.fulfill({json:{regions:tokens}}));
await page.route('**/api/health',r=>r.fulfill({json:{at:'2026-10-28T01:00:00Z',runtime:{uptimeSeconds:1,startedAt:'2026-10-28T01:00:00Z',autostart:{enabled:false},guard:{status:'unmanaged',events:[]}},groups:[]}}));await page.clock.install();await page.evaluate(()=>location.hash='health');await page.locator('#health-access').waitFor();let health=0,jobs=0;
page.on('request',r=>{if(r.url().endsWith('/api/health'))health++;if(r.url().includes('/api/jobs?'))jobs++;});
await page.clock.fastForward(10001);await page.waitForTimeout(150);assert.equal(health,0);
await page.locator('#health-refresh').click();await page.waitForTimeout(150);assert.equal(health,1,'manual health refresh bypasses an unchanged token');
await page.evaluate(()=>location.hash='records-pdf');await page.locator('[data-pdf-list] table,[data-pdf-list] .empty').waitFor();await page.locator('#record-search').fill('未提交过滤词');jobs=0;
await page.clock.fastForward(10001);await page.waitForTimeout(150);assert.equal(jobs,0);assert.equal(await page.locator('#record-search').inputValue(),'未提交过滤词');
tokens.records='b'.repeat(64);await page.clock.fastForward(10001);await page.waitForTimeout(150);assert.equal(jobs,1);assert.equal(await page.locator('#record-search').inputValue(),'未提交过滤词');
});
test('initial revision failure still loads home data and exposes the failed validation',{timeout:60000},async t=>{
const {page}=await orderDrivenUI(t,'#overview');await page.route('**/api/refresh/revisions*',route=>route.fulfill({status:503,json:{error:'版本服务暂不可用'}}));await page.reload();await page.locator('[data-business-home]').waitFor();await page.getByText(/刷新失败:版本服务暂不可用/).waitFor();assert.equal(await page.locator('[data-business-home]').count(),1);
});
+60
View File
@@ -0,0 +1,60 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),vm=require('node:vm');
function fixture(){
const listeners={},timers=new Map();let sequence=0;
const document={hidden:false,addEventListener:(name,fn)=>{listeners[name]=fn;},removeEventListener:(name,fn)=>{if(listeners[name]===fn)delete listeners[name];}};
const context=vm.createContext({document,window:{addEventListener(){}},AbortController,DOMException,setTimeout:(fn)=>{const id=++sequence;timers.set(id,fn);return id;},clearTimeout:id=>timers.delete(id)});
vm.runInContext(fs.readFileSync('web/modules/navigation/lifecycle.js','utf8'),context);
context.PageLifecycle=context.window.PageLifecycle;
return {context,document,listeners,timers,run:code=>vm.runInContext(code,context),tick:async()=>{const work=[...timers.values()];timers.clear();for(const fn of work)fn();await new Promise(resolve=>setImmediate(resolve));}};
}
const token=letter=>String(letter).repeat(64);function revisions(regions){return {regions:{home:token('a'),orderRules:token('b'),records:token('c'),health:token('d'),bpm:token('e'),assistant:token('f'),storage:token('1'),mail:token('2'),...regions},version:'v1'};}
test('region poll validates revisions before running a heavy read and only reloads after token change',async()=>{
const f=fixture();f.run(`globalThis.revision=${JSON.stringify(revisions())};globalThis.validations=0;globalThis.loads=0;globalThis.poll=PageLifecycle.regionPoll('home',{validate:async()=>{validations++;return revision;},refresh:async()=>{loads++;}},1000)`);
await f.tick();assert.equal(f.run('validations'),1);assert.equal(f.run('loads'),1);
await f.tick();assert.equal(f.run('validations'),2);assert.equal(f.run('loads'),1);
f.run("revision=JSON.parse(JSON.stringify(revision));revision.regions.home='3'.repeat(64)");await f.tick();assert.equal(f.run('validations'),3);assert.equal(f.run('loads'),2);
});
test('manual refresh and mutation invalidation validate immediately without replacing navigation state',async()=>{
const f=fixture();f.run(`globalThis.revision=${JSON.stringify(revisions())};globalThis.loads=0;globalThis.poll=PageLifecycle.regionPoll('orderRules',{validate:async()=>revision,refresh:async()=>{loads++;}},1000)`);await f.tick();
f.run('PageLifecycle.invalidateRegion(\'orderRules\')');const manual=f.run('poll.refresh()');await manual;assert.equal(f.run('loads'),2);
assert.equal(f.run('PageLifecycle.revision'),0);f.run('globalThis.navigation=\'#order-rules\'');assert.equal(f.run('navigation'),'#order-rules');
});
test('an aborted heavy read leaves the token pending and visibility resume retries it',async()=>{
const f=fixture();f.run(`globalThis.revision=${JSON.stringify(revisions())};globalThis.loads=0;globalThis.started=0;globalThis.release=null;globalThis.poll=PageLifecycle.regionPoll('records',{validate:async()=>revision,refresh:signal=>{started++;return new Promise((resolve,reject)=>{release=resolve;signal.addEventListener('abort',()=>reject(new DOMException('Aborted','AbortError')),{once:true});});}},1000)`);
const pending=f.run('poll.run()');await new Promise(resolve=>setImmediate(resolve));assert.equal(f.run('started'),1);f.document.hidden=true;f.listeners.visibilitychange();await assert.rejects(pending,{name:'AbortError'});
f.document.hidden=false;f.listeners.visibilitychange();await new Promise(resolve=>setImmediate(resolve));assert.equal(f.run('started'),2);f.run('release()');await new Promise(resolve=>setImmediate(resolve));
});
test('failed reads, invalid revisions and a mutation during a read cannot acknowledge the region',async()=>{
const f=fixture();f.run(`globalThis.revision=${JSON.stringify(revisions())};globalThis.loads=0;globalThis.errors=0;globalThis.fail=true;globalThis.poll=PageLifecycle.regionPoll('home',{validate:async()=>revision,onError:()=>errors++,refresh:async()=>{loads++;if(fail)throw Error('read failed');PageLifecycle.invalidateRegion('home');}},1000)`);
await assert.rejects(f.run('poll.run()'),/read failed/);f.run('fail=false');await f.run('poll.run()');await f.run('poll.run()');assert.equal(f.run('loads'),3);
f.run('revision.regions.home=null');await assert.rejects(f.run('poll.run()'),/区域版本/);assert.equal(f.run('loads'),3);assert.equal(f.run('errors'),2);
});
test('tokens never carry over between authenticated users',async()=>{
const f=fixture();f.run(`globalThis.user={id:'one'};globalThis.revision=${JSON.stringify(revisions())};globalThis.loads=0;PageLifecycle.configureRegions({read:async()=>revision,user:()=>user});globalThis.poll=PageLifecycle.regionPoll('home',{refresh:async()=>{loads++;}},1000)`);
await f.run('poll.run()');await f.run('poll.run()');assert.equal(f.run('loads'),1);f.run("user={id:'two'}");await f.run('poll.run()');assert.equal(f.run('loads'),2);
});
test('file-backed regions can bound staleness even when database tokens remain unchanged',async()=>{
const f=fixture();f.run(`globalThis.now=0;Date.now=()=>now;globalThis.revision=${JSON.stringify(revisions())};globalThis.loads=0;globalThis.poll=PageLifecycle.regionPoll('records',{validate:async()=>revision,refresh:async()=>{loads++;}},1000,{forceAfter:60000})`);
await f.run('poll.run()');f.run('now=59999');await f.run('poll.run()');assert.equal(f.run('loads'),1);f.run('now=60000');await f.run('poll.run()');assert.equal(f.run('loads'),2);
});
test('each mounted consumer requests only its own region with the original cancellation signal',async()=>{
const f=fixture();f.run(`globalThis.requested=[];globalThis.revision=${JSON.stringify(revisions())};PageLifecycle.configureRegions({read:async(signal,region)=>{requested.push([region,signal instanceof AbortSignal]);return revision;},user:()=>null});globalThis.poll=PageLifecycle.regionPoll('assistant',{refresh:async()=>{}},1200)`);
f.context.AbortSignal=AbortSignal;
await f.run('poll.run()');assert.deepEqual(JSON.parse(f.run('JSON.stringify(requested)')),[['assistant',true]]);
});
test('manual refresh rereads unchanged regions once and periodic checks remain lightweight afterwards',async()=>{
const f=fixture();f.run(`globalThis.revision=${JSON.stringify(revisions())};globalThis.loads=0;globalThis.poll=PageLifecycle.regionPoll('health',{validate:async()=>revision,refresh:async()=>{loads++;}},1000)`);
await f.run('poll.run()');await f.run('poll.run()');assert.equal(f.run('loads'),1);
await f.run('poll.refresh()');assert.equal(f.run('loads'),2);
await f.run('poll.run()');assert.equal(f.run('loads'),2);
});
+14
View File
@@ -0,0 +1,14 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {Store}=require('../../src/modules/dashboard/store.cjs'),{createDashboard}=require('../../src/app/dashboard.cjs');
test('region revision route authenticates every read, keeps tokens private and separates users',async t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'region-http-')),store=new Store(dir);store.bootstrap('admin','Test-password-123');store.addUser({username:'viewer',role:'viewer',password:'Test-password-123'},'admin');
const server=createDashboard({store,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(async()=>{server.closeAllConnections();await new Promise(r=>server.close(r));fs.rmSync(dir,{recursive:true,force:true});});const base='http://127.0.0.1:'+server.address().port;
const get=cookie=>fetch(base+'/api/refresh/revisions',{headers:cookie?{Cookie:cookie}:{}}),login=async username=>{const response=await fetch(base+'/api/login',{method:'POST',headers:{Origin:base,'Content-Type':'application/json'},body:JSON.stringify({username,password:'Test-password-123'})});assert.equal(response.status,200);return response.headers.get('set-cookie').split(';')[0];};
assert.equal((await get()).status,401);const admin=await login('admin'),viewer=await login('viewer'),response=await get(admin);assert.equal(response.status,200);assert.equal(response.headers.get('cache-control'),'no-store');assert.equal(response.headers.get('etag'),null);
const a=await response.json(),b=await(await get(viewer)).json();assert.equal(a.version,1);assert.ok(a.regions.home);assert.notEqual(a.regions.home,b.regions.home);assert.doesNotMatch(JSON.stringify(a),/passwordHash|Test-password|order_session|"admin"/);
const selected=await fetch(base+'/api/refresh/revisions?regions=mail,storage',{headers:{Cookie:admin}});assert.equal(selected.status,200);assert.equal(selected.headers.get('cache-control'),'no-store');assert.deepEqual(await selected.json(),{version:1,regions:{mail:a.regions.mail,storage:a.regions.storage}});
for(const query of ['unknown','','mail&regions=storage','mail,mail','__proto__']){const invalid=await fetch(base+'/api/refresh/revisions?regions='+query,{headers:{Cookie:admin}});assert.equal(invalid.status,400);assert.equal(invalid.headers.get('cache-control'),'no-store');}
assert.equal((await fetch(base+'/api/refresh/revisions?regions=mail')).status,401);
await fetch(base+'/api/logout',{method:'POST',headers:{Origin:base,'Content-Type':'application/json',Cookie:admin},body:'{}'});assert.equal((await get(admin)).status,401);
});
+74
View File
@@ -0,0 +1,74 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),{DatabaseSync}=require('node:sqlite');
let installRevisionTracking,readRevisions,createRegionRevisions;
try{({installRevisionTracking,readRevisions}=require('../../src/shared/refresh-revisions.cjs'));({createRegionRevisions}=require('../../src/app/region-revisions.cjs'));}catch(error){if(error.code!=='MODULE_NOT_FOUND')throw error;}
test('table and kind revision metadata follows committed external writes and rolls back atomically',t=>{
assert.equal(typeof installRevisionTracking,'function');
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'region-counters-')),file=path.join(dir,'state.sqlite'),a=new DatabaseSync(file),b=new DatabaseSync(file);t.after(()=>{a.close();b.close();fs.rmSync(dir,{recursive:true,force:true});});
a.exec('CREATE TABLE records(kind TEXT,id TEXT,payload BLOB,PRIMARY KEY(kind,id)); CREATE TABLE channels(id TEXT)');installRevisionTracking(a,[['records',"'records:' || $row.kind"],'channels']);
const read=()=>readRevisions(a,['records:orders','records:rules','channels']);const before=read();
b.prepare('INSERT INTO records VALUES(?,?,?)').run('orders','o',Buffer.from('PRIVATE_ORDER_BODY'));
assert.notDeepEqual(read(),before);assert.equal(read()['records:rules'],before['records:rules']);assert.equal(read().channels,before.channels);
const committed=read();b.exec('BEGIN');b.prepare('UPDATE records SET payload=?').run(Buffer.from('PRIVATE_NEW_BODY'));b.exec('ROLLBACK');assert.deepEqual(read(),committed);
b.exec("UPDATE records SET kind='rules'");assert.ok(read()['records:orders']>committed['records:orders']);assert.ok(read()['records:rules']>committed['records:rules']);
});
function fixture(t){
assert.equal(typeof createRegionRevisions,'function');
const {Store}=require('../../src/modules/dashboard/store.cjs'),{WorkspaceStore}=require('../../src/modules/workspace/store.cjs'),{RuleStore}=require('../../src/modules/order-rules/store.cjs'),{MailStore}=require('../../src/modules/mail/store.cjs'),{StorageStore}=require('../../src/modules/storage/store.cjs'),{BpmScanStore}=require('../../src/modules/bpm/scan-store.cjs'),{AssistantStore}=require('../../src/modules/assistant/store.cjs');
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'region-contract-')),store=new Store(path.join(dir,'dashboard')),workspace=new WorkspaceStore(path.join(dir,'workspace')),orderRules=new RuleStore(path.join(dir,'rules'));
const mail={store:new MailStore(path.join(dir,'mail'))},storage={store:new StorageStore(path.join(dir,'storage'))},scanner={store:new BpmScanStore(path.join(dir,'scan'))},assistant={store:new AssistantStore(path.join(dir,'assistant'))};
const user={id:'alice-id',username:'alice',role:'operator',version:1},admin={id:'admin-id',username:'admin',role:'admin',version:1},members=[user,admin,{id:'bob-id',username:'bob',role:'operator'}];
const connection=workspace.createConnection({name:'connection',owner:'alice'},admin,members);let now=new Date('2026-10-28T00:00:00Z');orderRules.clock=()=>new Date(now);
const context={store,workspace,orderRules,mail,storage,scanner,assistant,clock:()=>new Date(now),health:{startedAt:now.toISOString(),instanceId:'fixture'}};
const revisions=createRegionRevisions(context);t.after(()=>{workspace.close();orderRules.close();mail.store.close();storage.store.close();scanner.store.close();assistant.store.close();fs.rmSync(dir,{recursive:true,force:true});});
return {context,revisions,user,admin,members,connection,setNow(value){now=new Date(value);},get(userOverride=user){return revisions.snapshot(userOverride);}};
}
test('opaque tokens are stable, independently invalidated, and never assemble or decrypt business payloads',t=>{
const f=fixture(t),first=f.get();assert.equal(first.version,1);assert.deepEqual(Object.keys(first.regions),['home','orderRules','records','health','bpm','assistant','storage','mail']);assert.equal(first.errors,undefined);assert.deepEqual(f.get(),first);
for(const key of Object.keys(first.regions))assert.match(first.regions[key],/^[a-f0-9]{64}$/);
for(const object of [f.context.orderRules,f.context.mail.store,f.context.storage.store,f.context.scanner.store,f.context.assistant.store]){object.snapshot=()=>assert.fail('must not build snapshots');object.all=()=>assert.fail('must not enumerate business records');if(object.vault)object.vault.decode=(function(decode){return function(id,...args){assert.match(id,/^(settings|stability-test):main$/,'must not decrypt business payloads');return decode.call(this,id,...args);};})(object.vault.decode);}
f.context.orderRules.db.prepare('INSERT INTO records VALUES(?,?,?)').run('orders','private-order',Buffer.from('PRIVATE_ORDER_BODY'));
const changed=f.get();assert.notEqual(changed.regions.home,first.regions.home);assert.notEqual(changed.regions.records,first.regions.records);assert.equal(changed.regions.orderRules,first.regions.orderRules);assert.equal(changed.regions.mail,first.regions.mail);assert.equal(changed.regions.storage,first.regions.storage);assert.equal(changed.errors,undefined);assert.doesNotMatch(JSON.stringify(changed),/PRIVATE|alice|connection/);
});
test('roles and connection ownership invalidate business and record tokens without a rule write',t=>{
const f=fixture(t),before=f.get();f.context.workspace.transferConnection(f.connection.id,{version:0,owner:'bob'},f.admin,f.members);const after=f.get();
for(const key of ['home','orderRules','records','health','bpm'])assert.notEqual(after.regions[key],before.regions[key],key);
const role=f.get({...f.user,role:'viewer',version:2});for(const key of Object.keys(role.regions))assert.notEqual(role.regions[key],after.regions[key]);
const bob=f.get({id:'bob-id',username:'bob',role:'operator'});for(const key of Object.keys(bob.regions))assert.notEqual(bob.regions[key],after.regions[key]);
assert.throws(()=>f.get(null),error=>error.status===401);assert.throws(()=>f.get({...f.user,enabled:false}),error=>error.status===401);
});
test('assistant turn revisions stay private to their owner and include same-status payload changes',t=>{
const f=fixture(t),a=f.context.assistant.store,own=a.create(f.user.id),other=a.create('bob-id'),before=f.get();
a.db.prepare('UPDATE conversations SET payload=? WHERE id=?').run(Buffer.from('PRIVATE_BOB_BODY'),other.id);assert.equal(f.get().regions.assistant,before.regions.assistant);
a.db.prepare('INSERT INTO turns VALUES(?,?,?,?,?,?)').run('own-turn',own.id,'success',Buffer.from('PRIVATE_ALICE_BODY'),'2026-10-28','2026-10-28T00:00:00Z');const turned=f.get();assert.notEqual(turned.regions.assistant,before.regions.assistant);
a.db.prepare('UPDATE turns SET payload=? WHERE id=?').run(Buffer.from('PRIVATE_ALICE_UPDATED_BODY'),'own-turn');assert.notEqual(f.get().regions.assistant,turned.regions.assistant);
});
test('effective stability expiry and collection/send boundaries invalidate at the exact instant',t=>{
const f=fixture(t);f.context.orderRules.put('stability-test',{id:'main',enabled:true,startedAt:'2026-10-27T00:00:00Z',endsAt:'2026-10-28T00:00:00.500Z'});
f.setNow('2026-10-28T00:00:00.499Z');let before=f.get();f.setNow('2026-10-28T00:00:00.500Z');let after=f.get();assert.notEqual(after.regions.home,before.regions.home);assert.notEqual(after.regions['orderRules'],before.regions['orderRules']);
for(const boundary of ['2026-10-28T00:55:00.000Z','2026-10-28T01:00:00.000Z','2026-10-28T01:01:00.001Z']){f.setNow(new Date(Date.parse(boundary)-1));before=f.get();f.setNow(boundary);after=f.get();assert.notEqual(after.regions.home,before.regions.home,boundary);}
});
test('the authenticated GET API preserves no-store and source failures force a new token with a safe error',t=>{
const f=fixture(t);let result;const headers={},response={setHeader(key,value){headers[key]=value;}},reply=(status,value)=>result={status,value};
assert.equal(f.revisions.api({route:'/api/refresh/revisions',method:'GET',user:f.user,response,reply}),true);assert.equal(result.status,200);assert.equal(headers['Cache-Control'],'no-store');assert.deepEqual(result.value,f.get());
assert.equal(f.revisions.api({route:'/other',method:'GET',user:f.user,response,reply}),false);
const db=f.context.orderRules.db;f.context.orderRules.db={prepare(){throw Error('PRIVATE_DATABASE_FAILURE');}};try{const one=f.get(),two=f.get();assert.ok(one.errors.home);assert.notEqual(one.regions.home,two.regions.home);assert.doesNotMatch(JSON.stringify(one),/PRIVATE_DATABASE_FAILURE/);}finally{f.context.orderRules.db=db;}
});
test('intentionally absent services expose stable disabled markers without hiding broken initialized sources',()=>{
assert.equal(typeof createRegionRevisions,'function');const revisions=createRegionRevisions({store:{database:()=>({pdf_jobs:0}),settings:()=>({schedule:{times:['09:00','17:00'],weekends:false}})},clock:()=>new Date('2026-10-28T00:00:00Z')}),user={id:'u',username:'worker',role:'operator'};
const first=revisions.snapshot(user);assert.equal(first.errors,undefined);assert.deepEqual(revisions.snapshot(user),first);
});
test('mail template changes invalidate configuration and rendered business records without touching storage',t=>{
const f=fixture(t),before=f.get();f.context.mail.store.db.prepare('INSERT INTO templates(id,channel_id,source_key,scope,status,version,payload,created_at) VALUES(?,?,?,?,?,?,?,?)').run('template','channel','source','scope','pending',1,Buffer.from('PRIVATE_MAIL_BODY'),'2026-10-28T00:00:00Z');
const after=f.get();for(const key of ['home','orderRules','records','mail'])assert.notEqual(after.regions[key],before.regions[key],key);assert.equal(after.regions.storage,before.regions.storage);
});
test('assistant usage and operation metadata follow exactly the aggregates visible to the actor',t=>{
const f=fixture(t),a=f.context.assistant.store,other=a.create('bob-id'),journal=new DatabaseSync(':memory:');t.after(()=>journal.close());journal.exec('CREATE TABLE operation_events(id INTEGER PRIMARY KEY,actor TEXT,payload TEXT)');f.context.assistant.journal={db:journal};
let before=f.get();a.db.prepare('INSERT INTO turns VALUES(?,?,?,?,?,?)').run('bob-turn',other.id,'success',Buffer.from('PRIVATE_BOB_TURN'),'2026-10-28','2026-10-28T00:00:00Z');let after=f.get();assert.notEqual(after.regions.assistant,before.regions.assistant,'global public usage changed');
before=after;journal.prepare('INSERT INTO operation_events VALUES(?,?,?)').run(1,'bob-id','PRIVATE_BOB_EVENT');after=f.get();assert.equal(after.regions.assistant,before.regions.assistant,'operator cannot see other actor operations');
journal.prepare('INSERT INTO operation_events VALUES(?,?,?)').run(2,f.user.id,'PRIVATE_ALICE_EVENT');assert.notEqual(f.get().regions.assistant,after.regions.assistant);
const admin=f.get(f.admin);journal.prepare('INSERT INTO operation_events VALUES(?,?,?)').run(3,'bob-id','PRIVATE_BOB_LATER_EVENT');assert.notEqual(f.get(f.admin).regions.assistant,admin.regions.assistant,'admin operation aggregate includes all actors');
});
test('source catalogue edits invalidate records, and validators need no immediate write transaction',t=>{
const f=fixture(t),before=f.get(),db=f.context.workspace.db;db.prepare("UPDATE connections SET value=json_set(value,'$.name',?) WHERE id=?").run('renamed source',f.connection.id);assert.notEqual(f.get().regions.records,before.regions.records);
});
+47
View File
@@ -0,0 +1,47 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict');
const {DatabaseSync}=require('node:sqlite');
const {createRegionRevisions,REGION_NAMES}=require('../../src/app/region-revisions.cjs');
const {installRevisionTracking}=require('../../src/shared/refresh-revisions.cjs');
const user={id:'operator-id',username:'operator',role:'operator',version:1};
function assistantFixture(t){
const db=new DatabaseSync(':memory:');t.after(()=>db.close());
db.exec('CREATE TABLE config(id INTEGER); CREATE TABLE conversations(owner TEXT);');
installRevisionTracking(db,['config',['conversations',"'owner:' || $row.owner"]]);
const reads=[];
const context={assistant:{store:{db}},clock:()=>new Date('2026-10-28T00:00:00Z')};
for(const name of ['store','workspace','orderRules','mail','storage','scanner','health','bpmSessions','bpmMonitor'])Object.defineProperty(context,name,{get(){reads.push(name);throw Error('Unrelated module must not be read');}});
return {revisions:createRegionRevisions(context),db,reads};
}
test('assistant-only validation never opens or reads unrelated modules and follows committed metadata',t=>{
const f=assistantFixture(t),before=f.revisions.snapshot(user,['assistant']);
assert.deepEqual(Object.keys(before.regions),['assistant']);assert.equal(before.errors,undefined);assert.deepEqual(f.reads,[]);
assert.deepEqual(f.revisions.snapshot(user,['assistant']),before);
f.db.exec("BEGIN; INSERT INTO conversations VALUES('operator-id'); ROLLBACK;");assert.deepEqual(f.revisions.snapshot(user,['assistant']),before);
f.db.exec("INSERT INTO conversations VALUES('operator-id')");assert.notEqual(f.revisions.snapshot(user,['assistant']).regions.assistant,before.regions.assistant);
const other=f.revisions.snapshot({...user,id:'other-id'},['assistant']);assert.notEqual(other.regions.assistant,before.regions.assistant);
});
test('selected tokens match the legacy full response and only the selected failure is returned',()=>{
const context={clock:()=>new Date('2026-10-28T00:00:00Z')},revisions=createRegionRevisions(context);
const full=revisions.snapshot(user);assert.deepEqual(Object.keys(full.regions),REGION_NAMES);
const selected=revisions.snapshot(user,['mail','storage']);
assert.deepEqual(selected,{version:1,regions:{mail:full.regions.mail,storage:full.regions.storage}});
const failed=revisions.snapshot(user,['records']);assert.deepEqual(Object.keys(failed.regions),['records']);assert.deepEqual(Object.keys(failed.errors),['records']);
});
test('invalid selections are rejected before any source access and authentication still applies',t=>{
const f=assistantFixture(t);
for(const selection of [[],['unknown'],['toString'],['__proto__'],['assistant','assistant'],'assistant',null,Array(9).fill('home')])assert.throws(()=>f.revisions.snapshot(user,selection),error=>error.status===400);
assert.deepEqual(f.reads,[]);assert.throws(()=>f.revisions.snapshot(null,['assistant']),error=>error.status===401);
});
test('HTTP region selection is explicit, bounded and backwards compatible',t=>{
const f=assistantFixture(t);let result;const headers={},response={setHeader:(name,value)=>headers[name]=value},reply=(status,value)=>result={status,value};
const call=query=>f.revisions.api({route:'/api/refresh/revisions',url:new URL('http://localhost/api/refresh/revisions'+query),method:'GET',user,response,reply});
assert.equal(call('?regions=assistant'),true);assert.equal(result.status,200);assert.deepEqual(Object.keys(result.value.regions),['assistant']);assert.deepEqual(f.reads,[]);assert.equal(headers['Cache-Control'],'no-store');
for(const query of ['?regions=','?regions=unknown','?regions=assistant&regions=mail','?regions=assistant,assistant'])assert.throws(()=>call(query),error=>error.status===400);
call('');assert.deepEqual(Object.keys(result.value.regions),REGION_NAMES);
});
+4 -4
View File
@@ -3,7 +3,7 @@ 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,mailHistory:true}),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 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);});
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.locator('[data-business-home]').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:'<p>正文</p>'}));return drafts;}
test('switching a template immediately retires its old editable form while the next detail loads',{timeout:45000},async t=>{
@@ -24,17 +24,17 @@ test('rerendering rule saves lock editable fields until the saved response has r
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 openRuleRoute(page,'order-rules');let failRead=false;const versions=[];await page.route('**/api/order-rules?view=summary',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('rule durable save retains returned version and permits Save and Continue without a refresh',{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?view=summary',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('规则草稿已保存。',{exact:true}).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 mapping 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',sample:{title:'订单号:A1'},fields:[{path:'order',label:'订单号',value:'A1'},{path:'brief',label:'摘要',value:'摘要'}]}],adapters:[]}}));
await page.route('**/api/order-rules/field-mappings/draft',route=>{const input=route.request().postDataJSON();versions.push(input.version);saved=true;return route.fulfill({json:{...input,id:'a1',version:versions.length,sources:{...input.sources,receivedAt:{type:'metadata',key:'receivedAt'}}}});});
await openRuleRoute(page,'rule-fields');await page.locator('#fm-manual').evaluate(e=>e.open=true);await page.locator('#fm-orderNo').selectOption('order');await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText(/已保存.*刷新失败/).waitFor();assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),false);
await page.getByText(/可选业务信息 ·/).evaluate(e=>e.parentElement.open=true);await page.locator('#fm-customer').selectOption('brief');await page.locator('a[href="#overview"]').first().click();await page.getByRole('button',{name:'保存并继续',exact:true}).click();await page.getByRole('heading',{name:'连续业务窗口',exact:true}).waitFor();assert.deepEqual(versions,[0,1]);
await page.getByText(/可选业务信息 ·/).evaluate(e=>e.parentElement.open=true);await page.locator('#fm-customer').selectOption('brief');await page.locator('a[href="#overview"]').first().click();await page.getByRole('button',{name:'保存并继续',exact:true}).click();await page.locator('[data-business-home]').waitFor();assert.deepEqual(versions,[0,1]);
});
test('template usage read failure never enables an alternate binding writer',{timeout:45000},async t=>{const {page}=await fixture(t);await mailFixture(page);await page.route('**/api/order-rules?view=summary',route=>route.fulfill({status:503,json:{error:'使用情况读取失败'}}));await page.getByRole('link',{name:'邮件模板',exact:true}).click();await page.locator('#content').getByText('使用情况读取失败',{exact:true}).waitFor();assert.equal(await page.getByRole('button',{name:'保存关联'}).count(),0);assert.equal(await page.getByRole('button',{name:'预览并确认',exact:true}).count(),2);await page.locator('[data-template=t1]').click();await page.getByLabel('发信标题',{exact:true}).waitFor();assert.equal(await page.getByLabel('发信标题',{exact:true}).inputValue(),'模板1');});
test('template usage read failure never enables an alternate binding writer',{timeout:45000},async t=>{const {page}=await fixture(t);await mailFixture(page);await page.route('**/api/order-rules/catalog',route=>route.fulfill({status:503,json:{error:'使用情况读取失败'}}));await page.getByRole('link',{name:'邮件模板',exact:true}).click();await page.locator('#content').getByText('使用情况读取失败',{exact:true}).waitFor();assert.equal(await page.getByRole('button',{name:'保存关联'}).count(),0);assert.equal(await page.getByRole('button',{name:'预览并确认',exact:true}).count(),2);await page.locator('[data-template=t1]').click();await page.getByLabel('发信标题',{exact:true}).waitFor();assert.equal(await page.getByLabel('发信标题',{exact:true}).inputValue(),'模板1');});
test('unknown and conflicted task details cannot offer ordinary retry',{timeout:45000},async t=>{const {page,runtime}=await fixture(t,'order-rules');runtime.orderRules.put('execution-tasks',{id:'unknown',connectionId:'c1',status:'unknown',version:1,row:{orderNo:'UNKNOWN'}});await openRuleRoute(page,'notification-execution');await page.getByRole('button',{name:'查看详情'}).click();await page.getByRole('heading',{name:'处理进度'}).waitFor();assert.equal(await page.getByRole('button',{name:'重试失败任务',exact:true}).count(),0);});
@@ -48,6 +48,7 @@ test(
await input.fill(' ');
assert.equal(await send.isDisabled(), true);
await input.fill('调整发送计划');
await page.waitForFunction(() => !document.querySelector('#assistant-send').disabled);
assert.equal(await send.isEnabled(), true);
assert.ok(await send.locator('svg').count());
await send.click();
@@ -48,6 +48,7 @@ async function fixture(t) {
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.locator('.assistant-workspace').waitFor();
return { page, store, assistant, calls: () => calls };
}
test(
+135
View File
@@ -0,0 +1,135 @@
'use strict';
const { test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const os = require('node:os');
const crypto = require('node:crypto');
const { managementFixture } = require('./management-fixture.cjs');
const { readRevisions } = require('../../src/shared/refresh-revisions.cjs');
const { NativeSchedules } = require('../../src/modules/assistant/native-schedules.cjs');
const { OperationJournal } = require('../../src/modules/assistant/operation-journal.cjs');
test('main refresh revisions follow DSH providers, extra quota calls and private native tasks', async (t) => {
require('../fixtures/isolated-vault-key.cjs')(t);
const f = await managementFixture(t);
const user = f.users.users().find((u) => u.username === 'admin');
const viewer = f.users.users().find((u) => u.username === 'viewer');
const ownerScope = 'owner:' + user.id;
const day = f.store.usage().today;
const scopes = [ownerScope, 'config', 'usage:' + day];
const read = () => readRevisions(f.store.db, scopes);
let before = read();
f.store.create(viewer.id);
assert.equal(read()[ownerScope], before[ownerScope]);
const conversation = f.store.create(user.id);
assert.ok(read()[ownerScope] > before[ownerScope]);
before = read();
const provider = f.store.providers.read('deepseek');
f.store.providers.save({ ...provider, name: 'Changed provider' });
assert.ok(read().config > before.config);
const turn = f.store.beginTurn(conversation.id, user.id, 'Quota fixture');
before = read();
f.store.reserveModelCall(turn.id, 1);
assert.ok(read()['usage:' + day] > before['usage:' + day]);
f.store.updateTurn(turn.id, 'success', { reply: 'Done' });
const journalFile = path.join(os.tmpdir(), 'dsh-refresh-' + crypto.randomUUID() + '.sqlite');
f.assistant.journal = new OperationJournal({ file: journalFile });
t.after(() => {
f.assistant.journal.close();
fs.rmSync(journalFile, { force: true });
});
await NativeSchedules.create({ assistant: f.assistant });
before = read();
const task = await f.assistant.schedules.createTask(
conversation.id,
{ user, sessionId: 'integration-session' },
{ confirm: true, request: { title: 'Native task', prompt: 'Read only', after_seconds: 3600 } },
);
assert.ok(read()[ownerScope] > before[ownerScope]);
assert.equal(
(await f.assistant.schedules.catalog({ user: viewer, sessionId: 'viewer' })).tasks.length,
0,
);
await f.assistant.schedules.deleteTask(
conversation.id,
task.id,
{ user, sessionId: 'integration-session' },
{ confirm: true },
);
});
test('main lazy assistant bundle includes schedules, attachments and approval dependencies', () => {
const manifest = JSON.parse(
fs.readFileSync(
path.resolve(__dirname, '../../web/modules/navigation/module-manifest.json'),
'utf8',
),
);
assert.deepEqual(manifest.assistant, ['$assistant']);
assert.deepEqual(manifest['assistant-settings'], ['$assistant']);
const files = manifest.$assistant;
for (const dependency of [
'assistant-schedules.js',
'assistant-schedule-manager.js',
'assistant-attachments.js',
'assistant-settings-review.js',
]) {
assert.ok(files.includes(dependency), dependency);
assert.ok(files.indexOf(dependency) < files.indexOf('assistant.js'));
}
assert.ok(files.indexOf('assistant-schedules.js') < files.indexOf('assistant-context-panel.js'));
});
test('main manual refresh updates DSH permissions, quota and model catalogue without losing drafts', async (t) => {
require('../fixtures/isolated-vault-key.cjs')(t);
const f = await managementFixture(t, { browser: true });
f.store.saveSettings({
...f.store.settings(),
runtimePath: process.execPath,
apiKey: 'TEST_REFRESH_KEY',
allowActions: false,
});
const user = f.users.users().find((u) => u.username === 'admin');
const c = f.store.create(user.id);
const turn = f.store.beginTurn(c.id, user.id, 'Refresh fixture');
f.store.updateTurn(turn.id, 'success', {
reply: 'Existing answer',
actions: [
{
id: 'refresh-action',
kind: 'check_storage',
targetId: 'server',
label: '检查存储连接',
status: 'proposed',
},
],
});
await f.open();
await f.page.getByRole('button', { name: '查看操作(1)', exact: true }).click();
const action = f.page.getByRole('button', { name: '执行:检查存储连接', exact: true });
assert.equal(await action.isDisabled(), true);
await f.page.getByLabel('发送给 DSH', { exact: true }).fill('Keep my draft');
f.store.saveSettings({ version: f.store.settings().version, allowActions: true, dailyLimit: 50 });
f.store.providers.save({
...f.store.providers.read('deepseek'),
models: [
{ id: 'deepseek-flash', name: 'Original model' },
{ id: 'new-model', name: 'Fresh model' },
],
});
await f.page.evaluate(() => PageLifecycle.refreshRegions('assistant'));
assert.equal(await action.isEnabled(), true);
assert.match(await f.page.locator('.aw-usage').innerText(), /50/);
assert.equal(
await f.page.getByLabel('发送给 DSH', { exact: true }).inputValue(),
'Keep my draft',
);
await f.page.locator('#assistant-model-picker').click();
await f.page.getByRole('option', { name: 'Fresh model', exact: true }).waitFor();
});
+1
View File
@@ -68,6 +68,7 @@ async function managementFixture(t, { browser = false } = {}) {
await page.getByLabel('密码', { exact: true }).fill('Test-password-123');
await page.getByRole('button', { name: '登录', exact: true }).click();
}
if (route === '#assistant') await page.locator('.assistant-workspace').waitFor();
}
return {
base,
+1 -1
View File
@@ -31,7 +31,7 @@ function fixture(t, code = 'process.exit(0)') {
repoRoot: repo,
repairRoot: repairs,
journal,
validator: { command: process.execPath, args: ['-e', code], timeoutMs: 1000 },
validator: { command: process.execPath, args: ['-e', code], timeoutMs: 5000 },
});
t.after(() => {
journal.close();
+8 -4
View File
@@ -48,10 +48,11 @@ async function fixture(t,{user={username:'alice',role:'operator'},connections,ac
});
await page.goto(base);
await page.addStyleTag({path:path.join(__dirname,'../../web/app.css')});
await page.addScriptTag({path:path.join(__dirname,'../../web/modules/navigation/lifecycle.js')});
if(fs.existsSync(source))await page.addScriptTag({path:source});
assert.equal(await page.evaluate(()=>typeof window.BpmLogin?.mount),'function','BPM page exposes a working mount function');
await page.evaluate(async user=>{
const api=async(route,body)=>{const r=await fetch('/api'+route,{method:body===undefined?'GET':'POST',headers:{'Content-Type':'application/json'},body:body===undefined?undefined:JSON.stringify(body)});return r.json();};
const api=async(route,body,{signal}={})=>{const r=await fetch('/api'+route,{signal,method:body===undefined?'GET':'POST',headers:{'Content-Type':'application/json'},body:body===undefined?undefined:JSON.stringify(body)});return r.json();};
await window.BpmLogin.mount(document.querySelector('#root'),{api,esc:v=>String(v??'').replaceAll('<','&lt;'),formatDate:v=>v||'—',notify:()=>{},user,isActive:()=>true});
},user);
return {page,calls,releaseOpen,releaseInput,releaseFrame,releaseSave,releaseAccount,releaseFill,releaseAccountSave,maxFrames:()=>maxFrames};
@@ -264,12 +265,12 @@ 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(){},isConfiguration:()=>false},BpmLogin:{dispose:async()=>events.push('release')},OrderNotificationViews:{render: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(){}},AppModules:{load:async()=>{currentUser={username:'alice',role:'admin'};events.push('load')}},AppNavigation:{primary:[],resolve:id=>id,sectionFor:()=>null,renderTabs(){},isConfiguration:()=>false},BpmLogin:{dispose:async()=>events.push('release')},OrderNotificationViews:{render:async()=>events.push('render')}}});
const source=fs.readFileSync(path.join(__dirname,'../../web/app.js'),'utf8').replace(/boot\(\)\.catch[\s\S]*$/,'');
vm.runInContext(fs.readFileSync(path.join(__dirname,'../../web/modules/records/state.js'),'utf8'),context);
vm.runInContext(source,context);
await vm.runInContext("currentUser={username:'alice',role:'admin'};renderView()",context);
assert.deepEqual(events,['release','render']);events.length=0;
assert.deepEqual(events.slice(0,2),['release','load']);events.length=0;
vm.runInContext("shell();api=async route=>events.push(route);boot=async()=>{}",Object.assign(context,{events}));
await element('#logout').onclick();assert.deepEqual(events,['release','/logout']);
});
@@ -286,8 +287,9 @@ for(const pendingAction of ['open','save'])test(`document unload sends authentic
const appSource=fs.readFileSync(path.join(__dirname,'../../web/app.js'),'utf8').replace(/boot\(\)\.catch[\s\S]*$/,'');
const fixtureServer=http.createServer(async(req,res)=>{
const requestPath=new URL(req.url,'http://localhost').pathname;
if(requestPath==='/lifecycle.js'){res.setHeader('Content-Type','application/javascript; charset=utf-8');return res.end(fs.readFileSync(path.join(__dirname,'../../web/modules/navigation/lifecycle.js')));}
if(requestPath==='/bpm.js'||requestPath==='/app.js'){res.setHeader('Content-Type','application/javascript; charset=utf-8');return res.end(requestPath==='/bpm.js'?fs.readFileSync(source):appSource);}
if(!requestPath.startsWith('/api/')){res.setHeader('Content-Type','text/html; charset=utf-8');return res.end('<div id="app"></div><div id="root"></div><script src="/bpm.js"></script><script src="/app.js"></script>');}
if(!requestPath.startsWith('/api/')){res.setHeader('Content-Type','text/html; charset=utf-8');return res.end('<div id="app"></div><div id="root"></div><script src="/lifecycle.js"></script><script src="/bpm.js"></script><script src="/app.js"></script>');}
let body='';for await(const chunk of req)body+=chunk;
calls.push({path:requestPath,body,cookie:req.headers.cookie,origin:req.headers.origin});
res.setHeader('Content-Type','application/json');
@@ -364,3 +366,5 @@ test('UI renders backend conclusions without reinterpreting raw connection flags
assert.equal(await f.page.locator('[data-sync-status] .bpm-status-yellow').count(),1);
await f.page.getByText('后端已核实会话',{exact:true}).waitFor();
});
test('remote login frames pause hidden and resume a single frame without replacing the session',async t=>{const f=await fixture(t);await f.page.getByRole('button',{name:'远程登录',exact:true}).click();await f.page.locator('[data-bpm-frame]').waitFor();await f.page.clock.install();const frames=()=>f.calls.filter(c=>c.path.endsWith('/frame')).length,before=frames();await f.page.evaluate(()=>{Object.defineProperty(document,'hidden',{value:true,configurable:true});document.dispatchEvent(new Event('visibilitychange'));});await f.page.clock.fastForward(10001);await delay(100);assert.equal(frames(),before);const response=f.page.waitForResponse(r=>r.url().endsWith('/login/frame'));await f.page.evaluate(()=>{Object.defineProperty(document,'hidden',{value:false,configurable:true});document.dispatchEvent(new Event('visibilitychange'));});await response;assert.equal(frames(),before+1);assert.equal(f.calls.filter(c=>c.path.endsWith('/open')).length,1);assert.equal(f.calls.filter(c=>c.path.endsWith('/close')).length,0);});
+49
View File
@@ -0,0 +1,49 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),cp=require('node:child_process');
const fs=require('node:fs'),os=require('node:os'),path=require('node:path');
test('native ACL policy accepts only the current owner and one protected inheritable full-control allow rule',{skip:process.platform!=='win32'},()=>{
const {privateDirectoryAcl}=require('../../src/platform/security/windows-directory.cjs');
const cases=`
$sid=[System.Security.Principal.WindowsIdentity]::GetCurrent().User
function Make-Acl($protected,$owner,$rights,$inherit,$propagation,$type,$identity) {
$acl=New-Object System.Security.AccessControl.DirectorySecurity
$acl.SetOwner($owner);$acl.SetAccessRuleProtection($protected,$false)
$rule=New-Object System.Security.AccessControl.FileSystemAccessRule($identity,$rights,$inherit,$propagation,$type)
$acl.AddAccessRule($rule);return $acl
}
$other=New-Object System.Security.Principal.SecurityIdentifier('S-1-1-0')
$rows=@(
(Test-PrivateDirectoryAcl (Make-Acl $true $sid 'FullControl' 'ContainerInherit,ObjectInherit' 'None' 'Allow' $sid) $sid),
(Test-PrivateDirectoryAcl (Make-Acl $false $sid 'FullControl' 'ContainerInherit,ObjectInherit' 'None' 'Allow' $sid) $sid),
(Test-PrivateDirectoryAcl (Make-Acl $true $other 'FullControl' 'ContainerInherit,ObjectInherit' 'None' 'Allow' $sid) $sid),
(Test-PrivateDirectoryAcl (Make-Acl $true $sid 'Read' 'ContainerInherit,ObjectInherit' 'None' 'Allow' $sid) $sid),
(Test-PrivateDirectoryAcl (Make-Acl $true $sid 'FullControl' 'None' 'None' 'Allow' $sid) $sid),
(Test-PrivateDirectoryAcl (Make-Acl $true $sid 'FullControl' 'ContainerInherit,ObjectInherit' 'InheritOnly' 'Allow' $sid) $sid),
(Test-PrivateDirectoryAcl (Make-Acl $true $sid 'FullControl' 'ContainerInherit,ObjectInherit' 'None' 'Deny' $sid) $sid),
(Test-PrivateDirectoryAcl (Make-Acl $true $sid 'FullControl' 'ContainerInherit,ObjectInherit' 'None' 'Allow' $other) $sid)
)
$extra=Make-Acl $true $sid 'FullControl' 'ContainerInherit,ObjectInherit' 'None' 'Allow' $sid
$extra.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule($other,'Read','ContainerInherit,ObjectInherit','None','Allow')))
$rows+=(Test-PrivateDirectoryAcl $extra $sid)
$hidden=New-Object System.Security.AccessControl.DirectorySecurity
$hidden.SetSecurityDescriptorSddlForm('O:'+$sid.Value+'D:P(A;OICI;FA;;;'+$sid.Value+')(OA;OICI;FA;00000000-0000-0000-0000-000000000001;;WD)')
$rows+=(Test-PrivateDirectoryAcl $hidden $sid)
ConvertTo-Json -Compress -InputObject $rows
`;
const output=cp.execFileSync('powershell.exe',['-NoLogo','-NoProfile','-NonInteractive','-Command','$ErrorActionPreference="Stop";'+privateDirectoryAcl+cases],{encoding:'utf8',windowsHide:true,timeout:15000});
assert.deepEqual(JSON.parse(output),[true,false,false,false,false,false,false,false,false,false]);
});
test('a compliant real directory is not rewritten and an unprotected directory is repaired',{skip:process.platform!=='win32'},t=>{
const {privateDirectoryAcl,secureDirectoryScript}=require('../../src/platform/security/windows-directory.cjs'),parent=path.resolve(os.tmpdir()),dir=fs.mkdtempSync(path.join(parent,'acl-policy-'));
assert.equal(path.dirname(dir),parent);t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
const run=script=>cp.execFileSync('powershell.exe',['-NoLogo','-NoProfile','-NonInteractive','-Command','$ErrorActionPreference="Stop";'+script],{input:dir,encoding:'utf8',windowsHide:true,timeout:15000}).trim();
run(secureDirectoryScript);const protectedAt=fs.statSync(dir,{bigint:true}).ctimeNs;run(secureDirectoryScript);assert.equal(fs.statSync(dir,{bigint:true}).ctimeNs,protectedAt,'read verification must not rewrite the DACL');
run('$p=[Console]::In.ReadToEnd();$acl=[IO.Directory]::GetAccessControl($p);$acl.SetAccessRuleProtection($false,$true);[IO.Directory]::SetAccessControl($p,$acl)');
run(secureDirectoryScript);
const verified=run(privateDirectoryAcl+';$p=[Console]::In.ReadToEnd();Test-PrivateDirectoryAcl ([IO.Directory]::GetAccessControl($p)) ([System.Security.Principal.WindowsIdentity]::GetCurrent().User)');assert.equal(verified,'True');
run('$p=[Console]::In.ReadToEnd();$sid=[System.Security.Principal.WindowsIdentity]::GetCurrent().User;$acl=New-Object System.Security.AccessControl.DirectorySecurity;$acl.SetSecurityDescriptorSddlForm("O:"+$sid.Value+"D:P(A;OICI;FA;;;"+$sid.Value+")(OA;OICI;FA;00000000-0000-0000-0000-000000000001;;WD)",[System.Security.AccessControl.AccessControlSections]"Access,Owner");[IO.Directory]::SetAccessControl($p,$acl)');
assert.equal(run(privateDirectoryAcl+';$p=[Console]::In.ReadToEnd();Test-PrivateDirectoryAcl ([IO.Directory]::GetAccessControl($p)) ([System.Security.Principal.WindowsIdentity]::GetCurrent().User)'),'False');
run(secureDirectoryScript);assert.equal(run(privateDirectoryAcl+';$p=[Console]::In.ReadToEnd();Test-PrivateDirectoryAcl ([IO.Directory]::GetAccessControl($p)) ([System.Security.Principal.WindowsIdentity]::GetCurrent().User)'),'True');
});
+1 -1
View File
@@ -18,5 +18,5 @@ async function startTestDashboard({stateDir,mailHistory=false,executionFactory})
await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(0,'127.0.0.1',resolve);});
return {server,store,workspace,orderRules,mail,orderExecution,async close(){await orderExecution?.stop();await mail?.stop();server.closeAllConnections();await new Promise(r=>server.close(r));workspace.close();orderRules.close();mailStore?.close();}};
}
async function login(page){await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();}
async function login(page){await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await Promise.all([page.waitForResponse(response=>response.url().endsWith('/api/login')&&response.request().method()==='POST'),page.getByRole('button',{name:'登录',exact:true}).click()]);await page.locator('#logout').waitFor();}
module.exports={startTestDashboard,login};
+24
View File
@@ -0,0 +1,24 @@
'use strict';
const crypto=require('node:crypto');
const {DatabaseSync}=require('node:sqlite');
const {RuleStore}=require('../../src/modules/order-rules/store.cjs');
const {BpmVault}=require('../../src/platform/security/vault.cjs');
function fixture(n,{status='pending',huizhou=false}={}){
const db=new DatabaseSync(':memory:');db.exec('CREATE TABLE records(kind TEXT,id TEXT,payload BLOB,PRIMARY KEY(kind,id))');
const vault=Object.assign(Object.create(BpmVault.prototype),{key:crypto.randomBytes(32)}),counts={all:{},get:{},decode:0};let now=new Date('2026-10-26T01:00:00Z');
const store=Object.assign(Object.create(RuleStore.prototype),{db,vault,clock:()=>new Date(now),schedule:()=>({times:['11:00','17:00'],weekends:false}),calendar:()=>[],capabilities:{}});
store.put('settings',{id:'main',version:1,enabled:false,processingEnabled:false,channelId:'',maxMessageBytes:20971520});
for(const draft of require('../../src/modules/order-rules/catalog.cjs').seedRules())store.put('rules',{id:draft.id,draft,published:null});
const rule={id:'bs-change',categoryId:'bs-change',name:'Synthetic',version:1,processNames:['Synthetic'],nodeNames:['Node'],scopes:[{processName:'Synthetic',nodeName:'Node'}],huizhouEnabled:huizhou,to:['fixture@example.invalid']};
for(let i=0;i<n;i++){
const row={connectionId:'a',source:'todo',portalSource:'v4',instanceId:String(i),taskId:String(i),revision:'1',processName:'Synthetic',processVersion:'1',nodeName:'Node',receivedAt:'2026-10-26T00:30:00Z',orderNo:String(i),title:'Synthetic '+i};
store.put('orders',{id:'o'+i,categoryId:rule.categoryId,status,sample:row,event:row,ruleSnapshot:rule,createdAt:row.receivedAt,notifications:huizhou?{huizhou:{status:'pending',orderNos:['H'+i],issues:[]}}:undefined});
store.put('execution-tasks',{id:'t'+i,orderId:'o'+i,connectionId:'a',status,step:'complete',categoryIds:[rule.categoryId],row,createdAt:row.receivedAt});
}
const all=store.all,get=store.get,decode=vault.decode;
store.all=function(kind){counts.all[kind]=(counts.all[kind]||0)+1;return all.call(this,kind);};
store.get=function(kind,id){counts.get[kind]=(counts.get[kind]||0)+1;return get.call(this,kind,id);};
vault.decode=function(...args){counts.decode++;return decode.apply(this,args);};
return {store,counts,context:{orderRules:store,workspace:{recordSources:()=>[{id:'a',owner:'alice'}],businessIssue:()=>null}},actor:{username:'alice',role:'operator'},reset(){counts.all={};counts.get={};counts.decode=0;},setNow(value){now=new Date(value);},close(){db.close();vault.key.fill(0);}};
}
module.exports={fixture};
+1 -1
View File
@@ -2,5 +2,5 @@
const fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {Store}=require('../../src/modules/dashboard/store.cjs'),{WorkspaceStore}=require('../../src/modules/workspace/store.cjs'),{BpmScanStore}=require('../../src/modules/bpm/scan-store.cjs'),{BpmScanner}=require('../../src/modules/bpm/scanner.cjs'),{createDashboard}=require('../../src/app/dashboard.cjs'),{loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
async function setup(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'record-nav-')),store=new Store(path.join(dir,'dashboard')),workspace=new WorkspaceStore(path.join(dir,'workspace')),scan=new BpmScanStore(path.join(dir,'scan')),password='Record-nav-test-123',actor={username:'admin',role:'admin'};store.bootstrap('admin',password);for(const role of ['viewer','operator'])store.addUser({username:role,password,role},'admin');const connection=workspace.createConnection({name:'隔离测试来源',owner:'admin'},actor,store.users());scan.saveConfig({enabled:false,intervalMinutes:9});scan.complete(scan.begin(connection.id,'admin'),connection.id,Array.from({length:105},(_,i)=>({taskId:String(i).padStart(3,'0'),serialNum:'TEST-'+String(i).padStart(3,'0'),source:'portal-v4',processName:'海外运营订单评审',activityName:'通知节点',subject:'订单样例 '+String(i).padStart(3,'0'),arrivalDay:'2026-10-20',arrivedAt:'2026-10-20T01:00:00Z'})),connection);for(let i=0;i<105;i++)store.recordJob({jobId:'job-'+String(i).padStart(3,'0'),status:'error',metadata:{order:'PDF-'+String(i).padStart(3,'0')},error:'隔离导出失败'});const scanner=new BpmScanner({store:scan,workspace,manager:{scanArrivals:async()=>[]},settings:()=>store.settings()}),server=createDashboard({store,workspace,scanner,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));const browser=await loadPlaywright().chromium.launch(browserOptions()),base='http://127.0.0.1:'+server.address().port;
t.after(async()=>{await browser.close();await scanner.stop();server.closeAllConnections();await new Promise(r=>server.close(r));scan.close();workspace.close();fs.rmSync(dir,{recursive:true,force:true});});return {store,workspace,scan,connection,browser,base,password,async page(route='#records',username='admin',clock=false){const page=await browser.newPage({viewport:{width:1280,height:900}});if(clock)await page.clock.install();await page.goto(base+'/'+route);await page.locator('#username').fill(username);await page.locator('#password').fill(password);await page.locator('#login-form button').click();return page;}};}
t.after(async()=>{await browser.close();await scanner.stop();server.closeAllConnections();await new Promise(r=>server.close(r));scan.close();workspace.close();fs.rmSync(dir,{recursive:true,force:true});});return {store,workspace,scan,connection,browser,base,password,async page(route='#records',username='admin',clock=false){const page=await browser.newPage({viewport:{width:1280,height:900}});if(clock)await page.clock.install();await page.goto(base+'/'+route);await page.locator('#username').fill(username);await page.locator('#password').fill(password);await Promise.all([page.waitForResponse(response=>response.url().endsWith('/api/login')&&response.request().method()==='POST'),page.locator('#login-form button').click()]);await page.locator('#logout').waitFor();return page;}};}
module.exports={setup};
+13
View File
@@ -0,0 +1,13 @@
'use strict';
const fs=require('node:fs'),http=require('node:http');
const {respondToPing}=require('../../src/platform/service/ping.cjs');
const file=process.env.ORDER_FIXTURE_COUNT;
fs.writeFileSync(file,String((fs.existsSync(file)?Number(fs.readFileSync(file,'utf8')):0)+1));
if(!fs.existsSync(file+'.ready')){
process.send({type:'order:startup-failed',diagnostic:{type:'Error',stage:'key_directory',code:'STORAGE_UNAVAILABLE',causeCode:'ETIMEDOUT',durationMs:30000,message:'SECRET_FIXTURE_NOT_FOR_STATE'}});
process.exitCode=1;
}else{
const server=http.createServer((request,response)=>respondToPing(request,response,{token:process.env.ORDER_SUPERVISOR_TOKEN,instanceId:process.env.ORDER_SUPERVISOR_INSTANCE,startedAt:new Date().toISOString()}));
server.listen(Number(process.env.ORDER_FIXTURE_PORT),'127.0.0.1');
process.on('message',message=>{if(message==='order:shutdown'){server.closeAllConnections();server.close(()=>process.exit(0));}});
}
+1 -1
View File
@@ -6,7 +6,7 @@ test('history UI saves IMAP-only credentials locally, explicitly queries sent ma
t.after(async()=>{await browser?.close();await runtime.close();fs.rmSync(dir,{recursive:true,force:true});});
let connects=0;
const raw=Buffer.from('From: sender@example.test\r\nTo: orders@example.test\r\nSubject: Test notice\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n<img src="https://tracker.example.test/pixel"> Huizhou evidence');
runtime.mail.imapFactory=()=>({mailbox:{uidValidity:1n},on(){},async connect(){connects++;},async list(){return [{path:'Sent',specialUse:'\\Sent'}];},async getMailboxLock(_path,opts){assert.equal(opts.readOnly,true);return {release(){}};},async search(){return [1];},async fetchOne(uid,q){return q.source?{source:raw}:{uid,size:raw.length,envelope:{subject:'Test notice'}};},async logout(){},close(){}});
runtime.mail.imapFactory=()=>({mailbox:{uidValidity:1n},on(){},async connect(){connects++;},async list(){return [{path:'Sent',specialUse:'\\Sent'}];},async getMailboxLock(_path,opts){assert.equal(opts.readOnly,true);return {release(){}};},async search(){return [1];},async *fetch(){yield {uid:1,size:raw.length,envelope:{subject:'Test notice'}};},async fetchOne(uid,q){return q.source?{source:raw}:{uid,size:raw.length,envelope:{subject:'Test notice'}};},async logout(){},close(){}});
browser=await loadPlaywright().chromium.launch(browserOptions());const page=await browser.newPage();const requests=[];page.on('request',r=>requests.push(r.url()));
await page.goto('http://127.0.0.1:'+runtime.server.address().port+'/#mail');await login(page);await page.getByRole('button',{name:'只读查阅已发送邮件',exact:true}).click();
await page.getByRole('button',{name:'添加只读邮箱',exact:true}).click({timeout:5000});
+29
View File
@@ -3,13 +3,42 @@ const {test}=require('node:test');const assert=require('node:assert/strict');
const {MailService}=require('../../src/modules/mail/service.cjs');
const fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {MailStore}=require('../../src/modules/mail/store.cjs');
const {readHistory}=require('../../src/modules/mail/history.cjs');
const raw=Buffer.from('From: sender@example.test\r\nTo: orders@example.test\r\nCc: factory@example.test\r\nSubject: Order notice\r\nDate: Sun, 18 Oct 2026 10:00:00 +0800\r\nMessage-ID: <notice@example.test>\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nOrder body');
function fixture(){
const calls=[],store={channelSecret:()=>({version:1,imap:{}}),guard(){}};
const client={mailbox:{uidValidity:9n},on(){},async connect(){},async logout(){},close(){},async list(){return [{path:'Sent',specialUse:'\\Sent',flags:new Set()},{path:'INBOX',flags:new Set()}];},async getMailboxLock(folder,options){calls.push({folder,...options});return {release(){}};},async search(query,options){calls.push({query,...options});return [1,2,3];},async fetchOne(uid,query,options){calls.push({uid,query,...options});return query.source?{source:raw}:{uid,size:raw.length,envelope:{subject:'Order notice',date:new Date('2026-10-18T02:00:00Z'),to:[{address:'orders@example.test'}]}};}};
client.fetch=async function*(range,query,options){for(const uid of range.split(',').map(Number))yield await client.fetchOne(uid,query,options);};
const service=new MailService({store,imapFactory:()=>client,smtpFactory:()=>{throw Error('SMTP must not be used');}});
return {service,calls,client};
}
test('history batches bounded UID envelopes, keeps descending order and releases its read lock',async()=>{
let locked=false,released=0,batches=0;
const client={mailbox:{uidValidity:42n},list:async()=>[{path:'Sent',specialUse:'\\Sent'}],
async getMailboxLock(folder,options){assert.equal(folder,'Sent');assert.equal(options.readOnly,true);locked=true;return {release(){locked=false;released++;}};},
async search(query,options){assert.equal(locked,true);assert.equal(options.uid,true);return [3,8,5,10,2];},
fetchOne(){assert.fail('search must not fetch each message separately');},
async *fetch(range,query,options){batches++;assert.equal(locked,true);assert.equal(range,'10,8,5');assert.deepEqual(query,{uid:true,envelope:true,size:true});assert.deepEqual(options,{uid:true});
// An expunged UID is absent; sequence order need not equal the requested order.
yield {uid:5,size:100,envelope:{subject:'Five'}};yield {uid:10,envelope:{subject:'Ten'}};
yield {uid:10,size:200};yield {uid:99,size:1,envelope:{subject:'Unrequested'}};yield {seq:1,flags:new Set()};
}
};
const result=await readHistory(client,{action:'search',folder:'Sent',since:'2026-10-01',before:'2026-10-02',limit:3});
assert.deepEqual(result.messages.map(item=>[item.uid,item.subject,item.size]),[[10,'Ten',200],[5,'Five',100]]);assert.equal(result.uidValidity,'42');assert.equal(result.truncated,true);assert.equal(batches,1);assert.equal(released,1);assert.equal(locked,false);
});
test('empty history search never FETCHes and an interrupted batch always releases its lock',async()=>{
let released=0;
const client={mailbox:{uidValidity:9n},list:async()=>[{path:'Sent',specialUse:'\\Sent'}],getMailboxLock:async()=>({release(){released++;}}),search:async()=>[],
fetchOne:()=>assert.fail('no per-message fetch'),async *fetch(){assert.fail('empty results must not become a wildcard fetch');}
};
const input={action:'search',folder:'Sent',since:'2026-10-01',before:'2026-10-02'};
assert.deepEqual((await readHistory(client,input)).messages,[]);assert.equal(released,1);
client.search=async()=>[4];client.fetch=async function*(){throw Error('batch interrupted');};
await assert.rejects(readHistory(client,input),/batch interrupted/);assert.equal(released,2);
});
test('an IMAP-only history account stores no SMTP credential and rejects all sending or template polling',async t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'history-account-')),store=new MailStore(dir);
const service=new MailService({store,smtpFactory:()=>{throw Error('SMTP should be unreachable');}});
+1 -1
View File
@@ -102,7 +102,7 @@ function dispatchFixture(t,{ready=true,capabilities=true,enabled=true,verify,sen
const record={prepared:0,begun:0,smtp:0,locked:0,status:'prepared',messages:[],sent:[]};
const config={version:1,enabled,channelId:'channel1'};
const caps={liveTodo:capabilities,pdfExport:capabilities,automaticArchive:capabilities};
const store={discoveryBlockers:()=>[],batchIncomplete:()=>false,settings:()=>({...config}),snapshot:()=>({capabilities:{...caps},batches:[structuredClone({...batch,status:record.status})]}),prepare:(date,actor,window)=>{record.prepared++;assert.equal(date,dispatchCutoff);assert.equal(actor,'系统调度');assert.equal(window.start,'2026-10-19T09:00:00.000Z');assert.equal(window.end,dispatchCutoff);assert.equal(window.startInclusive,true);assert.equal(window.endInclusive,false);return [batch];},beginSending:id=>{assert.equal(id,'batch1');record.begun++;record.status='sending';},finishSending:(id,status,message)=>{assert.equal(id,'batch1');record.status=status;record.messages.push(message);}};
const store={discoveryBlockers:()=>[],batchIncomplete:()=>false,settings:()=>({...config}),capabilities:caps,all:kind=>kind==='batches'?[structuredClone({...batch,status:record.status})]:[],prepare:(date,actor,window)=>{record.prepared++;assert.equal(date,dispatchCutoff);assert.equal(actor,'系统调度');assert.equal(window.start,'2026-10-19T09:00:00.000Z');assert.equal(window.end,dispatchCutoff);assert.equal(window.startInclusive,true);assert.equal(window.endInclusive,false);return [batch];},beginSending:id=>{assert.equal(id,'batch1');record.begun++;record.status='sending';},finishSending:(id,status,message)=>{assert.equal(id,'batch1');record.status=status;record.messages.push(message);}};
const mail={exclusive:async(id,fn)=>{assert.equal(id,'channel1');record.locked++;return fn();},store:{channelSecret:id=>({id,version:2,email:'sender@example.com',name:'通知',smtp:{host:'unused.invalid'}}),guard:(id,version)=>{assert.equal(id,'channel1');assert.equal(version,2);}},smtpFactory:()=>{record.smtp++;return {verify:async()=>{if(verify)await verify({batch,config,caps,file});},sendMail:async message=>{record.sent.push(message);if(send)return send(message);return result||{accepted:['2639266652@qq.com'],rejected:[]};},close:()=>{}};}};
const schedule={times:['09:00','17:00'],timezone:'Asia/Shanghai',weekends:false,mode:'product_line',missed:'next_window'};
let now=new Date('2026-10-20T00:59:00.000Z');
@@ -0,0 +1,74 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),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(),'rule-configuration-ui-')),runtime=await startTestDashboard({stateDir:dir});let browser;
t.after(async()=>{await browser?.close();await runtime.close();await fs.rm(dir,{recursive:true,force:true});});
const rule=runtime.orderRules.get('rules','bs-change').draft,actor=runtime.store.users()[0],connection=runtime.workspace.createConnection({name:'Isolated configuration sample',owner:'admin'},actor,[actor]);
runtime.orderRules.put('capture-samples',{id:'configuration-sample',provenance:'server-provider',processName:rule.processNames[0],capturedAt:'2026-10-27T01:00:00Z',sample:{connectionId:connection.id,source:'todo',processVersion:'1.4',nodeName:rule.nodeNames[0],serialNum:'CONFIG-SAMPLE',receivedAt:'2026-10-27T01:00:00Z',fields:{private:'DO-NOT-RETURN'}},snapshot:{html:'PRIVATE-HTML',fields:[{path:'private',value:'DO-NOT-RETURN'}]}});
browser=await loadPlaywright().chromium.launch(browserOptions());const page=await browser.newPage({viewport:{width:1440,height:1000}});page.setDefaultTimeout(5000);
const base='http://127.0.0.1:'+runtime.server.address().port,requests=[];page.on('request',r=>{if(r.url().startsWith(base+'/api/'))requests.push({path:new URL(r.url()).pathname+new URL(r.url()).search,method:r.method(),body:r.postDataJSON()});});
return {page,runtime,requests,base,enter:async()=>{await page.goto(base+'/#order-rules');await login(page);await page.getByLabel('规则名称',{exact:true}).waitFor();await page.locator('[data-rule-id="bs-change"]').click();}};
}
test('rules render without business-history reads and samples load only when requested',{timeout:60000},async t=>{
const f=await fixture(t),all=f.runtime.orderRules.all.bind(f.runtime.orderRules);let allowSamples=false;
f.runtime.orderRules.all=kind=>{assert.ok(!['orders','batches','execution-tasks','audit'].includes(kind),'configuration must not read '+kind);if(kind==='capture-samples')assert.equal(allowSamples,true,'samples must load on demand');return all(kind);};
await f.enter();
assert.equal(f.requests.filter(r=>r.path==='/api/order-rules/configuration').length,1);
assert.equal(f.requests.some(r=>r.path.includes('view=summary')||r.path.includes('view=directory')),false);
assert.equal(f.requests.some(r=>r.path.startsWith('/api/order-rules/configuration/samples')),false);
allowSamples=true;await f.page.getByRole('button',{name:'读取已采集订单',exact:true}).click();
await f.page.locator('#order-rule-sample-source option[value="capture:configuration-sample"]').waitFor({state:'attached'});
assert.equal(await f.page.getByRole('button',{name:'检查识别结果',exact:true}).isDisabled(),false);
assert.equal(f.requests.filter(r=>r.path.startsWith('/api/order-rules/configuration/samples')).length,1);
allowSamples=false;await f.page.getByRole('button',{name:'刷新规则与字段',exact:true}).click();await f.page.waitForFunction(()=>!document.querySelector('#order-rule-samples-load').disabled);
assert.equal(f.requests.filter(r=>r.path.startsWith('/api/order-rules/configuration/samples')).length,1);
assert.equal(await f.page.locator('#order-rule-preview').isDisabled(),true);
});
test('save keeps the editor and uses returned versions without reloading resource catalogs',{timeout:60000},async t=>{
const f=await fixture(t);await f.enter();const initialVersion=f.runtime.orderRules.get('rules','bs-change').draft.version;
const reads=f.requests.filter(r=>r.method==='GET'&&r.path==='/api/order-rules/configuration').length;
await f.page.getByLabel('收件人',{exact:true}).fill('OWNER@EXAMPLE.TEST\nSECOND@EXAMPLE.TEST');await f.page.getByLabel('抄送人',{exact:true}).fill('COPY@EXAMPLE.TEST\nOTHER@EXAMPLE.TEST');
await f.page.locator('#order-rule-editor').evaluate(form=>form.dataset.probe='keep-editor');
for(const name of ['First configuration save','Second configuration save']){
await f.page.getByLabel('规则名称',{exact:true}).fill(name);await f.page.getByRole('button',{name:'保存草稿',exact:true}).click();
await f.page.getByText('规则草稿已保存。',{exact:true}).waitFor();await f.page.waitForFunction(()=>!document.querySelector('#order-rule-editor button[type=submit]').disabled);
assert.equal(await f.page.locator('#order-rule-editor').getAttribute('data-probe'),'keep-editor');
assert.equal(await f.page.evaluate(()=>PageLifecycle.dirty()),false);
assert.equal(await f.page.getByLabel('收件人',{exact:true}).inputValue(),'owner@example.test\nsecond@example.test');assert.equal(await f.page.getByLabel('抄送人',{exact:true}).inputValue(),'copy@example.test\nother@example.test');assert.doesNotMatch(await f.page.locator('#rule-validation-issues').textContent(),/请配置收件人/);
}
assert.equal(f.requests.filter(r=>r.method==='GET'&&r.path==='/api/order-rules/configuration').length,reads);
const versions=f.requests.filter(r=>r.method==='POST'&&r.path==='/api/order-rules/rules').map(r=>r.body.version);
assert.deepEqual(versions,[initialVersion,initialVersion+1]);assert.match(await f.page.locator('#rule-version-state').textContent(),new RegExp('草稿 v'+(initialVersion+2)));
});
test('a delayed sample read cannot replace a different category or clear unsaved inputs',{timeout:60000},async t=>{
const f=await fixture(t);await f.enter();let release,arrive;const gate=new Promise(r=>release=r),arrived=new Promise(r=>arrive=r);
await f.page.route('**/api/order-rules/configuration/samples?*',async route=>{const response=await route.fetch();arrive();await gate;await route.fulfill({response}).catch(()=>{});});
await f.page.getByRole('button',{name:'读取已采集订单',exact:true}).click();await arrived;
const other=await f.page.locator('[data-rule-id]').evaluateAll(nodes=>nodes.find(n=>n.dataset.ruleId!=='bs-change').dataset.ruleId);
await f.page.locator('[data-rule-id="'+other+'"]').click();await f.page.getByLabel('规则名称',{exact:true}).fill('Keep this unsaved category');release();
await f.page.waitForTimeout(150);assert.equal(await f.page.getByLabel('规则名称',{exact:true}).inputValue(),'Keep this unsaved category');assert.equal(await f.page.evaluate(()=>PageLifecycle.dirty()),true);
assert.equal(await f.page.locator('#order-rule-sample-source option[value="capture:configuration-sample"]').count(),0);
});
test('discard before pausing restores saved fields and keeps a truthful dirty baseline',{timeout:60000},async t=>{
const f=await fixture(t),rules=f.runtime.orderRules,{captured}=require('../fixtures/activate-field-mapping.cjs').activateReferenceMapping(rules);
const draft=rules.saveRule({...rules.get('rules','bs-change').draft,to:['owner@example.test'],archiveDirectory:'\\\\fixture\\orders',filenameDate:'appDate'},'admin');rules.capturedPreview(captured.id);rules.publish(draft.id,{version:draft.version},'admin');
await f.enter();const savedName=await f.page.getByLabel('规则名称',{exact:true}).inputValue();await f.page.getByLabel('规则名称',{exact:true}).fill('DISCARD THIS EDIT');
await f.page.locator('[data-rule-toggle="bs-change"]').click();await f.page.getByRole('button',{name:'放弃并继续',exact:true}).click();await f.page.getByText('此规则已暂停。',{exact:true}).waitFor();
assert.equal(await f.page.getByLabel('规则名称',{exact:true}).inputValue(),savedName);assert.equal(await f.page.evaluate(()=>PageLifecycle.dirty()),false);
await f.page.getByLabel('规则名称',{exact:true}).fill(savedName+' edit');assert.equal(await f.page.evaluate(()=>PageLifecycle.dirty()),true);await f.page.getByLabel('规则名称',{exact:true}).fill(savedName);assert.equal(await f.page.evaluate(()=>PageLifecycle.dirty()),false);
});
async function mockTestConfiguration(page){
await page.route('**/api/order-rules/configuration',async route=>{const response=await route.fetch(),data=await response.json();data.restrictedTest={id:'isolated-run',version:1,enabled:true,ruleCount:data.rules.length,readyCount:data.rules.length,uncovered:[]};data.rules=data.rules.map(rule=>({...rule,testStatus:'enabled',testVersion:rule.version}));await route.fulfill({json:data});});
}
test('a paused test receipt updates the shared notice and all category test statuses',{timeout:60000},async t=>{
const f=await fixture(t);await mockTestConfiguration(f.page);await f.page.route('**/api/order-rules/rules',async route=>{const response=await route.fetch(),result=await response.json();result.restrictedTest={id:'isolated-run',version:2,enabled:false,ruleCount:15,readyCount:0,uncovered:[]};result.testStatus='paused';await route.fulfill({json:result});});
await f.enter();await f.page.getByLabel('规则名称',{exact:true}).fill('Save after test paused');await f.page.getByRole('button',{name:'保存草稿',exact:true}).click();await f.page.getByText('规则草稿已保存。',{exact:true}).waitFor();
assert.doesNotMatch(await f.page.locator('#rule-category-list').textContent(),/受限测试中/);assert.match(await f.page.locator('#rule-restricted-state').textContent(),/已暂停/);assert.equal(await f.page.getByRole('button',{name:'应用到测试',exact:true}).count(),0);
});
test('uncertain test application verifies through lightweight configuration without historical reads',{timeout:60000},async t=>{
const f=await fixture(t);await mockTestConfiguration(f.page);const all=f.runtime.orderRules.all.bind(f.runtime.orderRules);f.runtime.orderRules.all=kind=>{assert.ok(!['orders','batches','execution-tasks','audit','capture-samples'].includes(kind),'uncertain application must not read '+kind);return all(kind);};
await f.enter();await f.page.route('**/api/order-rules/restricted-test/apply',route=>route.abort('connectionreset'));await f.page.getByRole('button',{name:'应用到测试',exact:true}).click();await f.page.locator('#operation-uncertain').waitFor();await f.page.waitForFunction(()=>document.querySelector('#operation-uncertain')?.textContent.includes('已查询最新状态'));
assert.equal(f.requests.some(r=>r.method==='GET'&&r.path==='/api/order-rules'),false);assert.equal(f.requests.filter(r=>r.method==='GET'&&r.path==='/api/order-rules/configuration').length,2);
});
+139
View File
@@ -0,0 +1,139 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),crypto=require('node:crypto'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {DatabaseSync}=require('node:sqlite');
const {RuleStore}=require('../../src/modules/order-rules/store.cjs');
const {BpmVault}=require('../../src/platform/security/vault.cjs');
const {seedRules}=require('../../src/modules/order-rules/catalog.cjs');
const {Store}=require('../../src/modules/dashboard/store.cjs');
const {createDashboard}=require('../../src/app/dashboard.cjs');
const {activateReferenceMapping}=require('../fixtures/activate-field-mapping.cjs');
function memoryRules(t){
const rules=Object.create(RuleStore.prototype);rules.db=new DatabaseSync(':memory:');
rules.db.exec('CREATE TABLE records(kind TEXT NOT NULL,id TEXT NOT NULL,payload BLOB NOT NULL,PRIMARY KEY(kind,id))');
rules.vault=Object.create(BpmVault.prototype);rules.vault.key=crypto.randomBytes(32);
rules.clock=()=>new Date('2026-10-27T02:00:00Z');rules.schedule=()=>({times:['11:00','17:00'],weekends:false});rules.calendar=()=>[];rules.capabilities={liveTodo:true,pdfExport:false,automaticArchive:false};
rules.put('settings',{id:'main',version:1,enabled:false,processingEnabled:true,channelId:'channel',maxMessageBytes:20971520});
for(const draft of seedRules())rules.put('rules',{id:draft.id,draft,published:null,trialVersion:null,trialDemo:null});
t.after(()=>rules.close());return rules;
}
function poisonHistory(rules){
// Any accidental historic read must fail real AES decryption, rather than pass a mock call check.
for(const kind of ['orders','batches','execution-tasks','capture-samples','audit'])rules.db.prepare('INSERT OR REPLACE INTO records VALUES(?,?,?)').run(kind,'unreadable-history',Buffer.from('not encrypted'));
}
async function dashboard(t,{rules=memoryRules(t),mail,storage}={}){
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'rules-configuration-')),store=new Store(dir);store.bootstrap('admin','Test-password-123');
for(const role of ['operator','viewer'])store.addUser({username:role,password:'Test-password-123',role},'admin');
const workspace={recordSources:()=>[{id:'own',owner:'operator'},{id:'other',owner:'someone'}],record:()=>{}};
const execution={snapshot(){throw Error('execution history must not be read');}};
const server=createDashboard({store,workspace,orderRules:rules,orderExecution:execution,mail,storage,outputDir:dir});
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
t.after(async()=>{server.closeAllConnections();await new Promise(resolve=>server.close(resolve));fs.rmSync(dir,{recursive:true,force:true});});
const base='http://127.0.0.1:'+server.address().port,cookies={};
const request=(route,{role='admin',body}={})=>fetch(base+route,{method:body===undefined?'GET':'POST',headers:{...(cookies[role]?{Cookie:cookies[role]}:{}),...(body===undefined?{}:{Origin:base,'Content-Type':'application/json'})},body:body===undefined?undefined:JSON.stringify(body)});
for(const role of ['admin','operator','viewer']){const response=await request('/api/login',{role:'anonymous',body:{username:role,password:'Test-password-123'}});cookies[role]=response.headers.get('set-cookie').split(';')[0];}
return {rules,request};
}
const getConfiguration=async f=>{const response=await f.request('/api/order-rules/configuration');assert.equal(response.status,200);return response.json();};
test('configuration reads editable metadata without decrypting history or returning field values and message bodies',async t=>{
const rules=memoryRules(t);rules.put('scope-catalog',{id:'scope',processName:'流程A',nodeName:'审批'});rules.put('scope-process-catalog',{id:'process',processName:'流程B'});
const configured=rules.get('rules','bs-change');configured.draft.bodyTemplateId='directly-bound';rules.put('rules',configured);
rules.put('field-adapters',{id:'actual',processName:'流程A',processVersion:'2',verified:true,status:'active',label:'真实字段',sampleId:'capture',sample:{fields:{secret:'PRIVATE_FIELD'}},sources:{customer:{value:'PRIVATE_MAPPING'}}});
poisonHistory(rules);
const mail={store:{templates:()=>[{id:'active',status:'active',subject:'普通模板',notificationMode:'normal',scope:'电视',version:2,channelId:'channel',text:'PRIVATE_BODY'},{id:'bound',status:'archived',subject:'已绑定旧模板',notificationMode:'normal'},{id:'directly-bound',status:'archived',subject:'规则选中的旧模板',notificationMode:'normal'},{id:'irrelevant',status:'pending',subject:'无关模板'}],categoryBindings:()=>[{categoryId:'bs-change',templateId:'bound',version:1}]}},storage={store:{servers:()=>[{id:'server',name:'共享服务器',host:'localhost',share:'orders',directory:'archive',enabled:true,hasPassword:true,password:'PRIVATE_PASSWORD'}]}};
const f=await dashboard(t,{rules,mail,storage}),result=await getConfiguration(f);
assert.equal(result.rules.length,15);assert.equal(result.settings.processingEnabled,true);assert.equal(result.restrictedTest,null);
assert.deepEqual(result.scopeProcesses,['流程A','流程B']);assert.deepEqual(result.scopeCatalog,[{processName:'流程A',nodeName:'审批'}]);assert.equal(result.scopeError,null);
assert.deepEqual(result.resources.templates.map(x=>x.id),['active','bound','directly-bound']);assert.equal(result.resources.bindings[0].templateId,'bound');assert.equal(result.resources.servers[0].host,'localhost');assert.deepEqual(result.resources.errors,{});
assert.deepEqual(result.adapters.find(x=>x.id==='actual'),{id:'actual',processName:'流程A',processVersion:'2',verified:true,reference:false,status:'active',label:'真实字段',sampleId:'capture'});
assert.doesNotMatch(JSON.stringify(result),/PRIVATE_|"orders":|"batches":|"audit":|"samples":/);
assert.deepEqual(await(await f.request('/api/order-rules/configuration/samples')).json(),{samples:[]});
});
test('configuration reports independent resource and scope failures while preserving available editing data',async t=>{
const rules=memoryRules(t);rules.db.prepare('INSERT INTO records VALUES(?,?,?)').run('scope-catalog','corrupt',Buffer.from('unreadable'));
const f=await dashboard(t,{rules,mail:{store:{templates(){throw Error('PRIVATE_PROVIDER_ERROR');},categoryBindings:()=>[{categoryId:'bs-change',templateId:'old',version:2}]}}}),result=await getConfiguration(f);
assert.equal(result.rules.length,15);assert.equal(result.resources.templates,null);assert.equal(result.resources.servers,null);assert.equal(result.resources.bindings[0].templateId,'old');
assert.ok(result.resources.errors.templates);assert.ok(result.resources.errors.servers);assert.ok(result.scopeError);assert.doesNotMatch(JSON.stringify(result),/PRIVATE_PROVIDER_ERROR/);
});
test('sample loading honors ownership, process filters and server provenance without returning captured fields',async t=>{
const rules=memoryRules(t),sample={connectionId:'own',source:'todo',processVersion:'2',nodeName:'审批',serialNum:'SN-1',title:'订单标题',receivedAt:'2026-10-20T01:00:00Z',fields:{password:'PRIVATE_FIELD'},raw:'PRIVATE_RAW',html:'PRIVATE_HTML'};
for(const row of [{id:'old-own',processName:'流程A',sample},{id:'other-owner',processName:'流程A',sample:{...sample,connectionId:'other'}},{id:'other-process',processName:'流程B',sample},{id:'history',processName:'流程A',sample:{...sample,source:'history'}},{id:'demo',processName:'流程A',sample:{...sample,demo:true}},{id:'untrusted',processName:'流程A',provenance:'client',sample}])rules.put('capture-samples',{provenance:'server-provider',capturedAt:'2026-10-20T01:01:00Z',snapshot:{fields:[{value:'PRIVATE_FIELD'}]},...row});
const f=await dashboard(t,{rules}),route='/api/order-rules/configuration/samples?process='+encodeURIComponent('流程A')+'&process='+encodeURIComponent('流程A');
const owned=await f.request(route,{role:'operator'});assert.equal(owned.status,200);const result=await owned.json();
assert.deepEqual(result,{samples:[{id:'old-own',processName:'流程A',provenance:'server-provider',capturedAt:'2026-10-20T01:01:00Z',sample:{connectionId:'own',source:'todo',processVersion:'2',nodeName:'审批',serialNum:'SN-1',title:'订单标题',receivedAt:'2026-10-20T01:00:00Z'}}]});
assert.deepEqual((await(await f.request(route)).json()).samples.map(x=>x.id),['old-own','other-owner']);
assert.deepEqual(await(await f.request(route,{role:'viewer'})).json(),{samples:[]});
assert.deepEqual(await(await f.request('/api/order-rules/configuration/samples')).json(),{samples:[]});
assert.deepEqual((await(await f.request(route+'&process='+encodeURIComponent('流程B'),{role:'operator'})).json()).samples.map(x=>x.id),['old-own','other-process']);
});
test('configuration endpoints keep authentication, service-unavailable and malformed-query boundaries',async t=>{
const f=await dashboard(t);
for(const route of ['/api/order-rules/configuration','/api/order-rules/status','/api/order-rules/configuration/samples?process=A'])assert.equal((await f.request(route,{role:'anonymous'})).status,401);
for(const query of ['?unknown=A','?process=','?process=%20%20','?process=A%00B','?process=A%7fB','?process='+('A'.repeat(251)),'?'+Array.from({length:101},(_,i)=>'process=P'+i).join('&')])assert.equal((await f.request('/api/order-rules/configuration/samples'+query)).status,400,query);
assert.equal((await f.request('/api/order-rules/configuration/samples?'+Array.from({length:101},()=> 'process=A').join('&'))).status,200);
assert.equal((await f.request('/api/order-rules/configuration/unknown')).status,404);
const unavailable=await dashboard(t,{rules:null});for(const route of ['/api/order-rules/configuration','/api/order-rules/status','/api/order-rules/configuration/samples?process=A'])assert.equal((await unavailable.request(route)).status,503);
});
test('status reads only effective settings and in-memory capabilities',async t=>{
const rules=memoryRules(t);poisonHistory(rules);rules.db.prepare('INSERT INTO records VALUES(?,?,?)').run('rules','corrupt-rule',Buffer.from('not encrypted'));
rules.put('settings',{...rules.get('settings','main'),enabled:true});
const f=await dashboard(t,{rules}),enabled=await f.request('/api/order-rules/status',{role:'viewer'});assert.equal(enabled.status,200);assert.equal((await enabled.json()).settings.enabled,true);
rules.put('stability-test',{id:'main',enabled:true,startedAt:'2026-10-26T02:00:00Z',endsAt:'2026-10-27T02:00:00Z'});
const response=await f.request('/api/order-rules/status',{role:'viewer'});assert.equal(response.status,200);
assert.deepEqual(await response.json(),{settings:{enabled:false},capabilities:{liveTodo:true,pdfExport:false,automaticArchive:false}});
});
test('catalog and notification settings avoid history and unrelated configuration resources',async t=>{
const rules=memoryRules(t);poisonHistory(rules);
for(const kind of ['field-adapters','scope-catalog','scope-process-catalog'])rules.db.prepare('INSERT OR REPLACE INTO records VALUES(?,?,?)').run(kind,'corrupt',Buffer.from('not encrypted'));
const f=await dashboard(t,{rules});
const catalogResponse=await f.request('/api/order-rules/catalog');assert.equal(catalogResponse.status,200);
const catalog=await catalogResponse.json();assert.equal(catalog.rules.length,15);assert.equal(catalog.templateUsage.length,15);
assert.deepEqual(Object.keys(catalog.rules[0]).sort(),['categoryId','name']);assert.equal(catalog.templateUsage[0].status,'draft');
assert.doesNotMatch(JSON.stringify(catalog),/"orders":|"fields":|"adapters":|"draft":/);
const settingsResponse=await f.request('/api/order-rules/notification-settings');assert.equal(settingsResponse.status,200);
assert.deepEqual(await settingsResponse.json(),{settings:rules.settings(),restrictedTest:null});
for(const route of ['/api/order-rules/catalog','/api/order-rules/notification-settings'])assert.equal((await f.request(route,{role:'anonymous'})).status,401);
});
test('rule write receipts retain complete editor versions without historic reads or relaxing stale-version validation',async t=>{
const rules=memoryRules(t),{captured}=activateReferenceMapping(rules,'bs-change',{connectionId:'own',instanceId:'i',taskId:'t',revision:'1'});
const draft=rules.saveRule({...rules.get('rules','bs-change').draft,to:['admin@example.test'],attachPdf:false,archiveDirectory:'\\\\server\\orders',filenameDate:'appDate'},'admin');rules.capturedPreview(captured.id);
// Preserve the legitimate sample required by publish/resume while poisoning unrelated history.
for(const kind of ['orders','batches','execution-tasks','audit'])rules.db.prepare('INSERT INTO records VALUES(?,?,?)').run(kind,'unreadable-history',Buffer.from('not encrypted'));
const f=await dashboard(t,{rules}),publishedResponse=await f.request('/api/order-rules/rules/bs-change/publish',{body:{version:draft.version}});assert.equal(publishedResponse.status,200);const published=await publishedResponse.json();
assert.equal(published.id,'bs-change');assert.equal(published.activationVersion,1);assert.equal(published.publishedVersion,draft.version);assert.equal(published.hasDraft,false);assert.equal(published.restrictedTest,null);
const savedResponse=await f.request('/api/order-rules/rules',{body:{...published,intro:'新说明'}});assert.equal(savedResponse.status,200);const saved=await savedResponse.json();
assert.equal(saved.version,draft.version+1);assert.equal(saved.hasDraft,true);assert.equal(saved.activationVersion,1);assert.equal(saved.publishedVersion,draft.version);assert.equal(saved.restrictedTest,null);
assert.equal((await f.request('/api/order-rules/rules',{body:published})).status,409);
const pausedResponse=await f.request('/api/order-rules/rules/bs-change/pause',{body:{version:saved.version,activationVersion:1}});assert.equal(pausedResponse.status,200);const paused=await pausedResponse.json();assert.equal(paused.activationVersion,2);assert.equal(paused.status,'paused');assert.equal(paused.restrictedTest,null);
assert.equal((await f.request('/api/order-rules/rules/bs-change/resume',{body:{version:saved.version,publishedVersion:draft.version,activationVersion:1}})).status,409);
const resumedResponse=await f.request('/api/order-rules/rules/bs-change/resume',{body:{version:saved.version,publishedVersion:draft.version,activationVersion:2}});assert.equal(resumedResponse.status,200);const resumed=await resumedResponse.json();assert.equal(resumed.activationVersion,3);assert.equal(resumed.status,'enabled');assert.equal(resumed.hasDraft,true);assert.equal(resumed.restrictedTest,null);
assert.equal((await f.request('/api/order-rules/rules',{role:'operator',body:saved})).status,403);assert.equal((await f.request('/api/order-rules/rules/bs-change/pause',{role:'viewer',body:{version:saved.version}})).status,403);
assert.doesNotMatch(JSON.stringify(resumed),/"orders"|"batches"|"audit"|"fields"|"snapshot"/);
});
test('restricted-test apply preserves the run receipt and returns current lightweight rule editing state',async t=>{
const rules=memoryRules(t),directory=fs.mkdtempSync(path.join(os.tmpdir(),'rules-restricted-configuration-')),archive=path.join(directory,'archive');fs.mkdirSync(archive);rules.desktopRoot=directory;
t.after(()=>fs.rmSync(directory,{recursive:true,force:true}));
const unc='\\\\localhost\\'+archive[0].toLowerCase()+'$\\'+archive.slice(3);
activateReferenceMapping(rules,'bs-change',{connectionId:'own',instanceId:'i',taskId:'t',revision:'1'});
const draft=rules.saveRule({...rules.get('rules','bs-change').draft,to:['2639266652@qq.com'],attachPdf:false,archiveDirectory:unc,filenameDate:'appDate'},'admin');
const run=rules.saveRestrictedTest({version:0,enabled:true,recipient:'2639266652@qq.com',archiveRoot:unc,channelId:'channel',ruleIds:['bs-change']},{username:'admin',role:'admin'});
// An unchanged approved version need not inspect historic orders or execution tasks.
for(const kind of ['orders','batches','execution-tasks','audit'])rules.db.prepare('INSERT INTO records VALUES(?,?,?)').run(kind,'unreadable-history',Buffer.from('not encrypted'));
const f=await dashboard(t,{rules}),response=await f.request('/api/order-rules/restricted-test/apply',{body:{version:run.version,rules:[{id:'bs-change',version:draft.version}]}});assert.equal(response.status,200);const receipt=await response.json();
assert.equal(receipt.applied,true);assert.equal(receipt.count,1);assert.equal(receipt.test.version,run.version+1);assert.ok(receipt.restrictedTest);assert.equal(receipt.restrictedTest.version,run.version+1);
const updated=receipt.rules.find(rule=>rule.id==='bs-change');assert.equal(updated.testVersion,draft.version);assert.equal(updated.testStatus,'enabled');assert.equal(updated.testHasDraft,false);assert.equal(updated.hasDraft,true);
assert.equal((await f.request('/api/order-rules/restricted-test/apply',{body:{version:run.version,rules:[{id:'bs-change',version:draft.version}]}})).status,409);
assert.doesNotMatch(JSON.stringify(receipt),/"orders":|"batches":|"audit":|"fields":|"snapshot":/);
rules.db.prepare('INSERT INTO records VALUES(?,?,?)').run('capture-samples','unreadable-history',Buffer.from('not encrypted'));
const config=await getConfiguration(f);assert.equal(config.restrictedTest.readyCount,1);assert.equal(config.rules.find(rule=>rule.id==='bs-change').testVersion,draft.version);
const savedResponse=await f.request('/api/order-rules/rules',{body:{...draft,intro:'测试中的新草稿'}});assert.equal(savedResponse.status,200);const saved=await savedResponse.json();
assert.equal(saved.testVersion,draft.version);assert.equal(saved.version,draft.version+1);assert.equal(saved.testHasDraft,true);assert.equal(saved.testStatus,'enabled');assert.equal(saved.restrictedTest.readyCount,1);
});
@@ -6,7 +6,7 @@ const at='2026-10-27T03:30:00.000Z';
function fixture({verifyError,sendError,result,channelId='mail',expired=false}={}){
const batch={id:'batch',status:'prepared',cutoff:expired?'2026-10-27T02:00:00.000Z':at,channelId,to:['2639266652@qq.com'],cc:[],attachments:[],orderIds:['order'],ruleSnapshot:{}};
const completions=[];let submissions=0,begun=0;
const store={get:()=>null,now:()=>at,settings:()=>({enabled:true,channelId:'mail'}),snapshot:()=>({batches:[batch],capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true}}),discoveryBlockers:()=>[],batchIncomplete:()=>false,beginSending:()=>{begun++;},finishSending:(...args)=>completions.push(args)};
const store={get:()=>null,now:()=>at,settings:()=>({enabled:true,channelId:'mail'}),all:kind=>kind==='batches'?[structuredClone(batch)]:[],capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true},discoveryBlockers:()=>[],batchIncomplete:()=>false,beginSending:()=>{begun++;},finishSending:(...args)=>completions.push(args)};
const mail={store:{channelSecret:()=>({id:'mail',version:1,email:'sender@example.com',smtp:{}}),guard:()=>{}},smtpFactory:()=>({verify:async()=>{if(verifyError)throw verifyError;},sendMail:async()=>{submissions++;if(sendError)throw sendError;return result||{accepted:['2639266652@qq.com'],rejected:[]};},close:()=>{}})};
const dispatcher=new OrderRuleDispatcher({store,mail,settings:()=>({}),clock:()=>new Date(at),providersReady:()=>true});
return {dispatcher,batch,store,completions,counts:()=>({submissions,begun})};
@@ -19,7 +19,7 @@ test('authorized users can explicitly revalidate only the original departed task
});
test('test settings and rule editor name uncovered flows even when all categories are ready',{timeout:90000},async t=>{
const {page}=await orderDrivenUI(t,'#notification-orders'),name='零售国内返工订单更改评审<待适配>';
await page.route('**/api/order-rules?view=summary',async route=>{const response=await route.fetch(),data=await response.json();data.restrictedTest={id:'coverage-test',version:1,enabled:true,ruleCount:15,readyCount:15,recipient:'2639266652@qq.com',archiveRoot:'C:\\isolated',since:'2026-10-26T00:00:00Z',uncovered:[{categoryId:'domestic-change',processName:name}]};await route.fulfill({json:data});});
await page.route(/\/api\/order-rules\/(notification-settings|configuration)$/,async route=>{const response=await route.fetch(),data=await response.json();data.restrictedTest={id:'coverage-test',version:1,enabled:true,ruleCount:15,readyCount:15,recipient:'2639266652@qq.com',archiveRoot:'C:\\isolated',since:'2026-10-26T00:00:00Z',uncovered:[{categoryId:'domestic-change',processName:name}]};await route.fulfill({json:data});});
for(const hash of ['notification-settings','order-rules']){await page.goto(new URL('/#'+hash,page.url()).href);await page.getByText(name,{exact:true}).waitFor();assert.equal(await page.locator('待适配').count(),0);assert.match(await page.locator('#content').innerText(),/domestic-change/);}
});
test('failure modal shows field sources and actionable diagnosis without offering an unsafe immediate retry',{timeout:90000},async t=>{
+2 -2
View File
@@ -57,7 +57,7 @@ test('template confirmation sends selected Hui mode and lists mode-specific publ
});
test('real trial separates mixed Hui mail and exposes no-match and uncertain selections',{timeout:90000},async t=>{
const f=await fixture(t),{runtime,page}=f,reference=require('../../src/modules/order-rules/catalog.cjs').adapters.find(a=>a.id==='bs-change');activateReferenceMapping(runtime.orderRules,'bs-change',{title:mixed,fields:{[reference.fields.orderNo]:'O-100'}});f.configure();await f.open();await page.locator('[data-rule-id="bs-change"]').click();await page.getByRole('button',{name:'检查识别结果',exact:true}).click();
const f=await fixture(t),{runtime,page}=f,reference=require('../../src/modules/order-rules/catalog.cjs').adapters.find(a=>a.id==='bs-change');activateReferenceMapping(runtime.orderRules,'bs-change',{title:mixed,fields:{[reference.fields.orderNo]:'O-100'}});f.configure();await f.open();await page.locator('[data-rule-id="bs-change"]').click();await page.getByRole('button',{name:'读取已采集订单',exact:true}).click();await page.getByRole('button',{name:'检查识别结果',exact:true}).click();
const normal=page.locator('[data-notification-preview="normal"]'),hui=page.locator('[data-notification-preview="huizhou"]');await hui.waitFor();
assert.match(await normal.locator('pre').textContent(),/O-100/);assert.match(await normal.locator('pre').textContent(),/H-200/);assert.match(await hui.locator('pre').textContent(),/H-200/);assert.doesNotMatch((await hui.locator('dd').first().textContent())+(await hui.locator('pre').textContent()),/O-100|CORE-O/);assert.match(await hui.textContent(),/owner@example.test/);assert.match(await hui.textContent(),/copy@example.test/);assert.equal(await hui.locator('dd').last().textContent(),await normal.locator('dd').last().textContent());assert.match(await hui.locator('dd').last().textContent(),/不附带 PDF/);assert.doesNotMatch(await page.locator('#order-rule-preview-result').textContent(),/额外通知规则尚未确认/);
await fs.mkdir('output/verification',{recursive:true});await page.screenshot({path:'output/verification/huizhou-task3-preview-desktop.png',fullPage:true});
@@ -65,7 +65,7 @@ test('real trial separates mixed Hui mail and exposes no-match and uncertain sel
// Use the real capture/mapping pipeline for each selection; storage is isolated per test.
const sample={...structuredClone(reference.sample),demo:false,title,taskId:'ui-'+status,fields:{...reference.sample.fields,[reference.fields.orderNo]:status==='empty'?'O-100':'HA200'}};
const captured=runtime.orderRules.recordCapture({sample,taskId:'ui-'+status,snapshot:{processVersion:sample.processVersion,fields:Object.entries(sample.fields).map(([path,value])=>({path,value}))}});
await page.getByRole('button',{name:'刷新规则与字段',exact:true}).click();await page.locator('[data-rule-id="bs-change"]').click();await page.locator('#order-rule-sample-source').selectOption('capture:'+captured.id);await page.getByRole('button',{name:'检查识别结果',exact:true}).click();await page.locator('[data-notification-preview="huizhou"][data-notification-status="'+status+'"]').waitFor();
await page.getByRole('button',{name:'刷新规则与字段',exact:true}).click();await page.locator('[data-rule-id="bs-change"]').click();await page.getByRole('button',{name:'读取已采集订单',exact:true}).click();await page.locator('#order-rule-sample-source').selectOption('capture:'+captured.id);await page.getByRole('button',{name:'检查识别结果',exact:true}).click();await page.locator('[data-notification-preview="huizhou"][data-notification-status="'+status+'"]').waitFor();
assert.match(await page.locator('[data-notification-preview="huizhou"]').textContent(),status==='empty'?/未匹配惠州明细/:/需核实|不能|无法|不足|确认/);
}
await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);await page.screenshot({path:'output/verification/huizhou-task3-preview-mobile.png',fullPage:true});
@@ -0,0 +1,68 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict');
const {fixture}=require('../fixtures/query-performance.cjs');
const query=require('../../src/modules/order-rules/query.cjs');
for(const operation of ['queryOrders','queryBatches','summary'])test(operation+' decrypts each task set once per read, including window checks',t=>{
const f=fixture(40);t.after(()=>f.close());
const result=operation==='summary'?query.summary(f.context,f.actor):query[operation](f.context,{},f.actor);
if(operation==='queryOrders'){assert.equal(result.total,40);assert.equal(result.items.length,25);}
if(operation==='queryBatches'){assert.equal(result.total,1);assert.equal(result.items[0].orderCount,40);}
if(operation==='summary'){assert.equal(result.counts.orders,40);assert.equal(result.home.pendingOrders,40);}
assert.ok((f.counts.all['execution-tasks']||0)<=1,JSON.stringify(f.counts));
assert.ok((f.counts.all.orders||0)<=1,JSON.stringify(f.counts));
assert.ok(f.counts.decode<200,JSON.stringify(f.counts));
});
test('completed modes perform no intake eligibility reads',t=>{
const f=fixture(40,{status:'sent'});t.after(()=>f.close());
const groups=require('../../src/modules/order-rules/collecting-batches.cjs').list(f.store);assert.deepEqual(groups,[]);
assert.equal(f.counts.all['execution-tasks']||0,0);
});
test('a frozen normal category excludes eligibility while a pending Hui mode remains independent',t=>{
const f=fixture(1,{status:'sent',huizhou:true});t.after(()=>f.close());
f.store.put('batches',{id:'frozen',categoryId:'bs-change',status:'unknown',cutoff:'2026-10-26T03:00:00.000Z',orderIds:['o0']});
const collecting=require('../../src/modules/order-rules/collecting-batches.cjs');
assert.deepEqual(collecting.list(f.store).map(b=>[b.notificationMode,b.orderIds]),[['huizhou',['o0']]]);
const order=f.store.get('orders','o0');order.status='pending';order.notifications.huizhou.status='unknown';f.store.put('orders',order);f.reset();
assert.deepEqual(collecting.list(f.store),[]);assert.equal(f.counts.all['execution-tasks']||0,0);
});
test('queries see writes even when the connection-local change counter is unchanged',t=>{
const f=fixture(1);t.after(()=>f.close());f.store.queryRevision=()=>1;
assert.equal(query.queryOrders(f.context,{},f.actor).items[0].status,'pending');
const order=f.store.get('orders','o0');order.status='sent';f.store.put('orders',order);
assert.equal(query.queryOrders(f.context,{},f.actor).items[0].status,'sent');
});
test('a later read rechecks window time and returned objects cannot change durable notices',t=>{
const f=fixture(1,{huizhou:true});t.after(()=>f.close());
const first=query.queryOrders(f.context,{},f.actor);assert.equal(first.items[0].collectingBatches.length,2);
first.items[0].notifications.huizhou.status='sent';
assert.equal(f.store.get('orders','o0').notifications.huizhou.status,'pending');
f.setNow('2026-10-26T04:00:00Z');assert.deepEqual(query.queryOrders(f.context,{},f.actor).items[0].collectingBatches,[]);
});
test('identity candidates scale with matching tasks while legacy portal overlap remains ambiguous',()=>{
const identity=require('../../src/modules/order-rules/task-identity.cjs'),{readStore}=require('../../src/modules/order-rules/read-context.cjs');let visits=0;
const tasks=Array.from({length:100},(_,i)=>({id:'t'+i,row:{get source(){visits++;return 'todo';},taskId:String(i),portalSource:'v4'}}));
const store=readStore({all:()=>tasks,get:()=>null});
for(let i=0;i<100;i++)assert.equal(identity.lookup(store,'execution-tasks',{source:'todo',taskId:String(i),portalSource:'v4'}).id,'t'+i);
assert.ok(visits<=400,'identity lookup revisited '+visits+' task sources');
const legacy=readStore({all:()=>[{id:'native',row:{source:'todo',taskId:'1',portalSource:'v4'}},{id:'legacy',row:{source:'todo',taskId:'1'}}],get:()=>null});
assert.throws(()=>identity.lookup(legacy,'execution-tasks',{source:'todo',taskId:'1',portalSource:'v4'}),e=>e.status===409);
assert.deepEqual(identity.records(legacy,'execution-tasks',{source:'todo',taskId:'1',portalSource:'v8'}).map(row=>row.id),['legacy']);
});
for(const status of ['sent','unknown','ignored','failed'])test('intake expiry skips inactive '+status+' history without scanning task eligibility',t=>{
const f=fixture(40,{status});t.after(()=>f.close());const before=f.store.queryRevision();
f.store.expireIntakes();
assert.equal(f.store.queryRevision(),before,'history must remain untouched');
assert.equal(f.counts.all['execution-tasks']||0,0,JSON.stringify(f.counts));
assert.equal(f.counts.get.batches||0,0,JSON.stringify(f.counts));
});
for(const huizhou of [false,true])test('active carry advancement skips eligibility for 300 archived sent orders '+(huizhou?'with disabled Hui records':'without a Hui notice'),t=>{
const f=fixture(300,{status:'sent',huizhou});t.after(()=>f.close());
const settings=f.store.get('settings','main');f.store.put('settings',{...settings,enabled:true,processingEnabled:true});
for(const order of f.store.all('orders'))f.store.put('orders',{...order,ruleSnapshot:{...order.ruleSnapshot,huizhouEnabled:false},archive:{archivedAt:'2026-10-26T00:45:00Z',files:[{name:'notice.pdf',path:'C:\\fixture\\notice.pdf',sha256:'a'.repeat(64),size:128,kind:'pdf'}]}});
const revision=f.store.queryRevision();f.reset();
assert.deepEqual(require('../../src/modules/order-rules/carry-forward.cjs').advance(f.store),{moved:[]});
assert.equal(f.counts.all['execution-tasks']||0,0,JSON.stringify(f.counts));
assert.equal(f.counts.get['capture-samples']||0,0,JSON.stringify(f.counts));
assert.equal(f.store.queryRevision(),revision,'completed and disabled modes must stay untouched');
});
@@ -4,9 +4,9 @@ const {orderDrivenUI}=require('../fixtures/order-driven-ui.cjs');
test('healthy todo without matched orders shows pending verification without loosening capability gates',{timeout:60000},async t=>{
const {page,runtime}=await orderDrivenUI(t,'#notification-settings'),s=runtime.orderRules;
s.put('settings',{...s.get('settings','main'),enabled:true,processingEnabled:true});s.capabilities={liveTodo:true,pdfExport:false,automaticArchive:false};
await page.getByRole('button',{name:'刷新数据',exact:true}).click();await page.getByRole('link',{name:'自动通知待验证',exact:true}).waitFor();
await page.getByRole('button',{name:'刷新数据',exact:true}).click();await page.getByRole('link',{name:'自动通知待核验',exact:true}).waitFor();
assert.equal(s.providersReady(),false);assert.equal(s.settings().enabled,true);
s.put('execution-scans',{id:'failed-source',status:'failed',error:'fixture failure'});
await page.getByRole('button',{name:'刷新数据',exact:true}).click();await page.getByRole('link',{name:'自动通知受阻',exact:true}).waitFor();
await page.getByRole('button',{name:'刷新数据',exact:true}).click();await page.getByRole('link',{name:'自动通知待核验',exact:true}).waitFor();
assert.equal(s.providersReady(),false);
});
+5 -5
View File
@@ -3,11 +3,11 @@ const test=require('node:test'),assert=require('node:assert/strict'),fs=require(
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();page.setDefaultTimeout(5000);await page.setContent('<main id="root"></main>');
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.BusinessRecordViews={render:async(host,options,kind)=>{host.textContent='授权分页 '+kind;}};window.OrderExecutionViews={fields:async panel=>{panel.textContent='字段映射';}};const snapshot={rules:[],adapters:[],settings:{enabled:false,processingEnabled:false,version:1},counts:{orders:3,blocked:1,unknown:1,activeBatches:2},capabilities:{},window:{available:true,start:'2026-10-19T00:00:00Z',end:'2026-10-19T11:00:00Z'}};window[owner].configure(window.viewHelpers={api:async(url,body)=>{window.calls.push(url);if(body)return new Promise(r=>window.releaseAction=()=>r({version:2}));if(url==='/mail'&&mailFailure)throw Error('SMTP目录暂不可读');return url==='/mail'?{channels:[]}:snapshot;},esc:value=>String(value??'').replaceAll('&','&amp;').replaceAll('<','&lt;'),formatDate:v=>v||'—',user:{role:'admin'}});await window[owner].render(document.querySelector('#root'),()=>window.active,section);},{section,owner,mailFailure});return page;
for(const file of ['navigation/lifecycle.js','order-notifications/home.js','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.BusinessRecordViews={render:async(host,options,kind)=>{host.textContent='授权分页 '+kind;}};window.OrderExecutionViews={fields:async panel=>{panel.textContent='字段映射';}};const snapshot={rules:[],adapters:[],settings:{enabled:false,processingEnabled:false,version:1},counts:{orders:3,blocked:1,unknown:1,activeBatches:2},capabilities:{},window:{available:true,start:'2026-10-19T00:00:00Z',end:'2026-10-19T11:00:00Z'}};window[owner].configure(window.viewHelpers={api:async(url,body)=>{window.calls.push(url);if(body)return new Promise(r=>window.releaseAction=()=>r({version:2}));if(url==='/mail'&&mailFailure)throw Error('SMTP目录暂不可读');return url==='/mail'?{channels:[]}:snapshot;},esc:value=>String(value??'').replaceAll('&','&amp;').replaceAll('<','&lt;'),formatDate:v=>v||'—',user:{role:'admin'}});await window[owner].render(document.querySelector('#root'),()=>window.active,section);},{section,owner,mailFailure});return page;
}
test('order and batch sections delegate to bounded query views without loading full snapshots',async t=>{const page=await setup(t,'orders');assert.equal(await page.locator('main').innerText(),'授权分页 orders');assert.deepEqual(await page.evaluate(()=>calls),[]);await page.evaluate(()=>OrderNotificationViews.render(document.querySelector('#root'),()=>active,'pending'));assert.equal(await page.locator('main').innerText(),'授权分页 batches');assert.deepEqual(await page.evaluate(()=>calls),[]);});
test('fields delegate their lifecycle without notification runtime reads',async t=>{const page=await setup(t,'fields','OrderRuleViews');await page.getByText('字段映射',{exact:true}).waitFor();assert.deepEqual(await page.evaluate(()=>calls),[]);});
test('business homepage uses bounded summary and concrete remediation links',async t=>{const page=await setup(t,'workbench');assert.match(await page.locator('main').innerText(),/2026-10-19T11: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?view=summary']);});
test('mailbox failure is explicit and cannot save an empty catalog',async t=>{const page=await setup(t,'settings','OrderNotificationViews',true);assert.match(await page.locator('main').innerText(),/邮箱目录读取失败/);await page.getByRole('button',{name:'保存设置'}).click();assert.deepEqual(await page.evaluate(()=>calls),['/order-rules?view=summary','/mail']);});
test('late settings action after departure starts no readback or saved feedback',async t=>{const page=await setup(t,'settings');await page.getByRole('button',{name:'保存设置'}).click();await page.waitForFunction(()=>typeof releaseAction==='function');await page.evaluate(()=>{active=false;releaseAction();});await page.waitForFunction(()=>!document.querySelector('#order-rule-settings button').disabled);assert.deepEqual(await page.evaluate(()=>calls),['/order-rules?view=summary','/mail','/order-rules/settings']);assert.equal(await page.locator('form [role=alert]').innerText(),'');});
test('business homepage uses bounded summary and concrete remediation links',async t=>{const page=await setup(t,'workbench');assert.equal(await page.locator('[data-home-next-send]').innerText(),'19:00');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?view=summary']);});
test('mailbox failure is explicit and cannot save an empty catalog',async t=>{const page=await setup(t,'settings','OrderNotificationViews',true);assert.match(await page.locator('main').innerText(),/邮箱目录读取失败/);await page.getByRole('button',{name:'保存设置'}).click();assert.deepEqual(await page.evaluate(()=>calls),['/order-rules/notification-settings','/mail']);});
test('late settings action after departure starts no readback or saved feedback',async t=>{const page=await setup(t,'settings');await page.getByRole('button',{name:'保存设置'}).click();await page.waitForFunction(()=>typeof releaseAction==='function');await page.evaluate(()=>{active=false;releaseAction();});await page.waitForFunction(()=>!document.querySelector('#order-rule-settings button').disabled);assert.deepEqual(await page.evaluate(()=>calls),['/order-rules/notification-settings','/mail','/order-rules/settings']);assert.equal(await page.locator('form [role=alert]').innerText(),'');});
+11 -4
View File
@@ -4,6 +4,7 @@ const assert=require('node:assert/strict');
const fs=require('node:fs/promises');
const os=require('node:os');
const path=require('node:path');
const crypto=require('node:crypto');
const {Store}=require('../../src/modules/dashboard/store.cjs');
const {createDashboard}=require('../../src/app/dashboard.cjs');
const {RuleStore}=require('../../src/modules/order-rules/store.cjs');
@@ -20,21 +21,27 @@ test('category editor saves/reloads drafts, previews readable evidence without i
data.window={start:'2026-10-20T00:00:00+08:00',end:'2026-10-20T11:00:00+08:00',label:'工作日第一时段',available:true};
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/mail',route=>route.fulfill({json:{channels:[],templates:[],receipts:[],sends:[]}}));
await page.route('**/api/refresh/revisions*',route=>{const token=crypto.createHash('sha256').update(JSON.stringify([data.orders,data.batches,data.settings,data.window])).digest('hex');return route.fulfill({json:{version:1,regions:{home:token,orderRules:token,records:token,health:token,bpm:token,assistant:token,storage:token,mail:token}}});});
await page.route('**/api/order-rules**',async route=>{
const req=route.request(),url=new URL(req.url());let result;
if(req.method()==='GET'){
if(url.pathname.endsWith('/fields'))result={samples:[{id:'real-1',provenance:'server-provider',processName:'订单流程',sample:{...sample,receivedAt:'2026-10-19T09:00:00+08:00'}}]};
if(url.pathname==='/api/order-rules/configuration')result={...data,adapters:data.adapters.map(({sample,fields,...adapter})=>({...adapter,reference:false})),scopeProcesses:['订单流程'],scopeCatalog:[{processName:'订单流程',nodeName:'通知'}],resources:{templates:[],bindings:[],servers:[],errors:{}},restrictedTest:null};
else if(url.pathname==='/api/order-rules/status')result={settings:{enabled:data.settings.enabled},capabilities:data.capabilities};
else if(url.pathname==='/api/order-rules/notification-settings')result={settings:data.settings,restrictedTest:null};
else if(url.pathname==='/api/order-rules/catalog')result={processes:[{processName:'订单流程',nodes:['通知']}],bindings:[],templates:[],groups:[],servers:[],errors:{},window:{...data.window}};
else if(url.pathname==='/api/order-rules/configuration/samples'){const {fields,...metadata}=sample;result={samples:[{id:'real-1',provenance:'server-provider',processName:'订单流程',sample:{...metadata,receivedAt:'2026-10-19T09:00:00+08:00'}}]};}
else if(url.pathname.endsWith('/fields'))result={samples:[{id:'real-1',provenance:'server-provider',processName:'订单流程',sample:{...sample,receivedAt:'2026-10-19T09:00:00+08:00'}}]};
else if(['/api/order-rules/orders','/api/order-rules/batches'].includes(url.pathname)){
const items=url.pathname.endsWith('/orders')?data.orders:data.batches;
result={items,total:items.length,page:1,pageSize:25,totalPages:1,from:items.length?1:0,to:items.length,revision:String(items.length)};
}else if(url.pathname==='/api/order-rules'){
assert.equal(url.searchParams.get('view'),'summary','business views must request the bounded summary');
const {orders,batches,audit,...summary}=data;
result={...summary,issues:[],templateUsage:[],counts:{orders:orders.length,blocked:0,unknown:0,activeBatches:batches.length}};
result={...summary,window:{...data.window,available:true},issues:[],templateUsage:[],counts:{orders:orders.length,blocked:0,unknown:0,activeBatches:batches.length}};
}else throw Error('Unexpected fixture GET '+url.pathname);
}else{
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];}
if(url.pathname.endsWith('/rules')){data.rules[0]={...data.rules[0],...body,version:data.rules[0].version+1};result={...data.rules[0],restrictedTest:null};}
else if(url.pathname.endsWith('/trial'))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'))return route.fulfill({status:409,json:{error:'实时待办接入待联调,暂不可发布'}});
else if(url.pathname.endsWith('/settings')){
@@ -49,7 +56,7 @@ test('category editor saves/reloads drafts, previews readable evidence without i
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.find(w=>w.path.endsWith('/rules')).body.processNames,['订单流程']);
await page.reload();await openRuleRoute(page,'order-rules');assert.equal(await page.getByLabel('规则名称',{exact:true}).inputValue(),'订单类别更新');
await page.getByRole('button',{name:'检查识别结果',exact:true}).click();await page.locator('#order-rule-preview-result').getByText('识别通过',{exact:true}).waitFor();assert.doesNotMatch(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('/trial')).body.sampleId,'real-1');assert.equal(await page.locator('#order-rule-sample').count(),0);
await page.getByRole('button',{name:'读取已采集订单',exact:true}).click();await page.getByRole('button',{name:'检查识别结果',exact:true}).click();await page.locator('#order-rule-preview-result').getByText('识别通过',{exact:true}).waitFor();assert.doesNotMatch(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('/trial')).body.sampleId,'real-1');assert.equal(await page.locator('#order-rule-sample').count(),0);
await page.getByRole('button',{name:'发布此版本',exact:true}).click();await page.getByText('实时待办接入待联调,暂不可发布',{exact:true}).waitFor();
await openRuleRoute(page,'notification-settings');
const processing=page.getByLabel('自动处理订单(采集、生成 PDF、归档)',{exact:true}),mail=page.getByLabel('自动发送分类邮件',{exact:true});
+4 -4
View File
@@ -10,7 +10,7 @@ async function setup(t){
require('../../src/modules/order-rules/scope-catalog.cjs').observe(runtime.orderRules,[{source:'todo',processName:'试产订单更改评审',nodeName:'订单专员(订单通知书)'}]);
const initial=runtime.orderRules.get('rules','bs-change').draft;runtime.orderRules.saveRule({...initial,archiveDirectory:'\\\\fixture-server\\orders'},'admin');
const page=await browser.newPage({viewport:{width:1440,height:1000}});page.setDefaultTimeout(7000);await page.route('**/api/order-rules/fields',route=>route.fulfill({json:runtime.orderRules.fields()}));
await page.goto('http://127.0.0.1:'+runtime.server.address().port+'/#order-rules');await login(page);await page.locator('[data-rule-id="bs-change"]').click();return{page,runtime,captured,browser};
await page.goto('http://127.0.0.1:'+runtime.server.address().port+'/#order-rules');await login(page);await page.locator('[data-rule-id="bs-change"]').click();await page.getByRole('button',{name:'读取已采集订单',exact:true}).click();await page.locator('#order-rule-sample-source option[value="capture:'+captured.id+'"]').waitFor({state:'attached'});return{page,runtime,captured,browser};
}
test('workbench searches categories, pairs rows and trials unsaved input before saved real evidence',{timeout:90000},async t=>{
const {page,runtime,captured}=await setup(t);
@@ -39,10 +39,10 @@ test('editing while a trial is pending invalidates its output and failed saves p
await page.route('**/api/order-rules/rules',route=>route.fulfill({status:409,json:{error:'规则版本冲突,请刷新核对'}}));await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText('规则版本冲突,请刷新核对',{exact:true}).waitFor();assert.equal(await page.getByLabel('规则名称',{exact:true}).inputValue(),'新输入不能被旧结果覆盖');
});
test('saved state remains the clean baseline when the following list refresh fails',{timeout:60000},async t=>{
test('saved state remains clean without requesting a resource refresh',{timeout:60000},async t=>{
const {page,runtime}=await setup(t);await page.getByLabel('规则名称',{exact:true}).fill('已保存但刷新失败');
await page.route('**/api/order-rules?view=summary',route=>route.fulfill({status:503,json:{error:'列表暂不可用'}}));
await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText(/规则草稿已保存。 刷新失败/).waitFor();
await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText('规则草稿已保存。',{exact:true}).waitFor();
assert.equal(runtime.orderRules.get('rules','bs-change').draft.name,'已保存但刷新失败');assert.equal(await page.getByLabel('规则名称',{exact:true}).inputValue(),'已保存但刷新失败');
await page.getByLabel('规则名称',{exact:true}).dispatchEvent('input');
assert.equal(await page.locator('#order-rule-dirty').innerText(),'');await page.getByRole('link',{name:'字段映射',exact:true}).first().click();assert.equal(await page.getByRole('dialog',{name:'未保存的修改'}).count(),0);
@@ -65,6 +65,6 @@ test('rule search is not a dirty edit and operators/viewers keep their role boun
test('captured field evidence follows the adapter selected in the current draft rather than registry order',{timeout:60000},async t=>{
const {page,runtime}=await setup(t),original=require('../../src/modules/order-rules/catalog.cjs').adapters.find(a=>a.id==='bs-change').sample,real={...original,demo:false,title:'订单号:ALT-2',fields:{...original.fields,'Alternate.Order':'ALT-2','Alternate.Brief':'新字段摘要'}};
const capture=runtime.orderRules.recordCapture({taskId:'alternate-fields',sample:real,snapshot:{processVersion:real.processVersion,fields:Object.entries(real.fields).map(([path,value])=>({path,value}))}}),adapter=activateFieldMapping(runtime.orderRules,{sampleId:capture.id,processName:real.processName,processVersion:real.processVersion,version:1,fields:{orderNo:'Alternate.Order',brief:'Alternate.Brief'}},{username:'admin',role:'admin'});
const old=runtime.orderRules.get('rules','bs-change').draft;runtime.orderRules.saveRule({...old,adapterIds:[adapter.id]},'admin');await page.getByRole('button',{name:'刷新规则与字段',exact:true}).click();await page.waitForFunction(()=>!document.querySelector('#order-rule-refresh').disabled);await page.getByLabel('已采集的 BPM 订单',{exact:true}).selectOption('capture:'+capture.id);
const old=runtime.orderRules.get('rules','bs-change').draft;runtime.orderRules.saveRule({...old,adapterIds:[adapter.id]},'admin');await page.getByRole('button',{name:'刷新规则与字段',exact:true}).click();await page.waitForFunction(()=>!document.querySelector('#order-rule-refresh').disabled);await page.getByRole('button',{name:'读取已采集订单',exact:true}).click();await page.getByLabel('已采集的 BPM 订单',{exact:true}).selectOption('capture:'+capture.id);
await page.getByRole('button',{name:'检查识别结果',exact:true}).click();await page.locator('#order-rule-preview-result').getByText('ALT-2',{exact:true}).waitFor();assert.doesNotMatch(await page.locator('#order-rule-preview-result').innerText(),/Alternate\.Order/);assert.equal(await page.locator('[data-adapter-choice]').count(),0);
});
+12 -1
View File
@@ -53,5 +53,16 @@ test('unknown port owners remain running, and repeated real exits enter cooldown
guard=new ServiceSupervisor({stateDir,entry:path.resolve('tests/fixtures/managed-service.cjs'),ports:[listenPort],env:{ORDER_FIXTURE_PORT:String(listenPort),ORDER_FIXTURE_COUNT:path.join(stateDir,'count'),ORDER_FIXTURE_ALWAYS_CRASH:'1'},timing:{intervalMs:40,pingTimeoutMs:50,startupGraceMs:1000,backoffMs:[30],maxRestarts:1,cooldownMs:1000,windowMs:30000,stopGraceMs:500}});await guard.start();await until(()=>guard.snapshot().status==='cooldown');assert.ok(guard.snapshot().nextRestartAt);await guard.stop();
});
test('restart backoff is bounded and repeated failures enter a cooldown',()=>{
const {restartPlan}=require('../../src/platform/service/supervisor.cjs');assert.deepEqual([0,1,2,20].map(failures=>restartPlan({failures,recent:0}).delayMs),[2000,5000,10000,60000]);assert.equal(restartPlan({failures:9,recent:8}).cooldown,true);assert.equal(restartPlan({failures:9,recent:8}).delayMs,300000);
const {restartPlan}=require('../../src/platform/service/supervisor.cjs');assert.deepEqual([0,1,2,20].map(failures=>restartPlan({failures,recent:0}).delayMs),[2000,5000,10000,60000]);assert.equal(restartPlan({failures:9,recent:8}).cooldown,true);assert.equal(restartPlan({failures:9,recent:8}).delayMs,300000);assert.equal(restartPlan({failures:0,recent:0,startupFailures:3}).cooldown,true);
});
test('three failed startups retain safe diagnostics and enter cooldown, then explicit retry can recover',{timeout:30000},async t=>{
const {ServiceSupervisor}=require('../../src/platform/service/supervisor.cjs'),stateDir=await fs.mkdtemp(path.join(os.tmpdir(),'startup-cooldown-')),listenPort=await port(),count=path.join(stateDir,'count');let guard;
t.after(async()=>{await guard?.stop();await fs.rm(stateDir,{recursive:true,force:true});});
guard=new ServiceSupervisor({stateDir,entry:path.resolve('tests/fixtures/startup-failure-service.cjs'),ports:[listenPort],env:{ORDER_FIXTURE_PORT:String(listenPort),ORDER_FIXTURE_COUNT:count},timing:{intervalMs:30,pingTimeoutMs:60,startupGraceMs:500,stopGraceMs:1000,backoffMs:[20],cooldownMs:5000,maxRestarts:99}});
await guard.start();await until(()=>guard.snapshot().status==='cooldown');
assert.equal(await fs.readFile(count,'utf8'),'3');assert.equal(guard.snapshot().consecutiveStartupFailures,3);
assert.equal(guard.snapshot().reason,'startup_failed');assert.equal(guard.snapshot().startupError.stage,'key_directory');assert.equal(guard.snapshot().startupError.causeCode,'ETIMEDOUT');assert.doesNotMatch(JSON.stringify(guard.snapshot()),/SECRET/);
await fs.writeFile(count+'.ready','ready');await guard.restart();await until(()=>guard.snapshot().status==='running');
assert.equal(guard.snapshot().consecutiveStartupFailures,0);assert.equal(guard.snapshot().startupError,null);
});
+79
View File
@@ -0,0 +1,79 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path');
const {FileArea,SmbClient,MAX_FILE}=require('../../src/modules/storage/files.cjs');
const {StorageService}=require('../../src/modules/storage/service.cjs');
const {storageApi}=require('../../src/modules/storage/api.cjs');
const {validate}=require('../../src/modules/storage/smb-operation.cjs');
const {makePreviewFiles}=require('../fixtures/storage-preview-files.cjs');
async function fixture(t){const root=await fs.mkdtemp(path.join(os.tmpdir(),'storage-range-'));t.after(()=>fs.rm(root,{recursive:true,force:true}));return {root,area:new FileArea(root)};}
async function request(storage,range,{action='file',relative='large.bin',role='operator'}={}){
const headers={},url=new URL('http://localhost/api/storage/servers/local/'+action+'?path='+encodeURIComponent(relative));let status,bytes;
await storageApi({storage,user:{username:'tester',role},url,route:url.pathname,method:'GET',request:{headers:range===undefined?{}:{range}},response:{setHeader(name,value){headers[name]=value;},writeHead(value){status=value;},end(value){bytes=value||Buffer.alloc(0);}}});return {headers,status,bytes};
}
function countReads(t){let bytes=0,opens=0;const original=fs.open;t.mock.method(fs,'open',async(...args)=>{const handle=await original(...args),read=handle.read.bind(handle);opens++;handle.read=async(...args)=>{const value=await read(...args);bytes+=value.bytesRead;return value;};return handle;});return {get bytes(){return bytes;},get opens(){return opens;}};}
for(const preview of [false,true])test(`64 KiB ${preview?'PDF preview':'download'} range reads bounded bytes through the real route, service and FileArea`,async t=>{
const {root,area}=await fixture(t),relative=preview?'large.pdf':'large.bin',source=Buffer.alloc(16*1024*1024,7);if(preview)source.write('%PDF-1.7');await fs.writeFile(path.join(root,relative),source);
const storage=new StorageService({store:{secret:()=>({enabled:true})},client:{area:async()=>area}});t.after(()=>storage.stop());const reads=countReads(t);
const result=await request(storage,'bytes=1048576-1114111',{action:preview?'content':'file',relative});
assert.equal(result.status,206);assert.equal(result.headers['Content-Range'],'bytes 1048576-1114111/16777216');assert.equal(result.bytes.length,65536);assert.deepEqual(result.bytes,source.subarray(1048576,1114112));
assert.ok(reads.bytes<100*1024,`range must not read the full file: ${reads.bytes}`);assert.equal(reads.opens,1,'header and requested content must use the same handle');
});
test('suffixes, open ends, invalid ranges and empty downloads preserve complete-size HTTP metadata',async t=>{
const {root,area}=await fixture(t);await fs.writeFile(path.join(root,'large.bin'),'0123456789');const storage=new StorageService({store:{secret:()=>({enabled:true})},client:{area:async()=>area}});t.after(()=>storage.stop());
for(const [range,want,contentRange] of [['bytes=-3','789','bytes 7-9/10'],['bytes=7-','789','bytes 7-9/10'],['bytes=7-99','789','bytes 7-9/10'],['bytes=-99','0123456789','bytes 0-9/10']]){const result=await request(storage,range);assert.equal(result.status,206);assert.equal(result.bytes.toString(),want);assert.equal(result.headers['Content-Range'],contentRange);}
for(const range of ['bytes=-0','bytes=10-','bytes=9-8','bytes=-','bytes=0-1,3-4','items=0-1','bytes=9007199254740992-','bytes=-9007199254740992']){const result=await request(storage,range);assert.equal(result.status,416,range);assert.equal(result.headers['Content-Range'],'bytes */10');assert.equal(result.bytes.length,0);}
await fs.writeFile(path.join(root,'empty.bin'),'');const empty=await request(storage,undefined,{relative:'empty.bin'});assert.equal(empty.status,200);assert.equal(empty.bytes.length,0);assert.equal((await request(storage,'bytes=0-',{relative:'empty.bin'})).status,416);
});
test('PDF ranges still validate the header and whole-file limits before reading content',async t=>{
const {root,area}=await fixture(t);await fs.writeFile(path.join(root,'fake.pdf'),'Not a PDF body');await assert.rejects(area.readPreview('fake.pdf',{range:'bytes=5-7'}),error=>error.status===415);
await fs.writeFile(path.join(root,'huge.bin'),'');await fs.truncate(path.join(root,'huge.bin'),MAX_FILE+1);await assert.rejects(area.readFile('huge.bin',MAX_FILE,{range:'bytes=0-1'}),error=>error.status===413);
await fs.writeFile(path.join(root,'huge.pdf'),'%PDF-');await fs.truncate(path.join(root,'huge.pdf'),MAX_FILE+1);await assert.rejects(area.readPreview('huge.pdf',{range:'bytes=0-1'}),error=>error.status===413);
});
test('a source that shrinks during range reading is rejected instead of returning partial success',async t=>{
const {root,area}=await fixture(t),file=path.join(root,'large.bin');await fs.writeFile(file,Buffer.alloc(1024,1));const original=fs.open;let changed=false;
t.mock.method(fs,'open',async(...args)=>{const handle=await original(...args),read=handle.read.bind(handle);handle.read=async(...args)=>{if(!changed){changed=true;await fs.truncate(file,100);}return read(...args);};return handle;});
await assert.rejects(area.readFile('large.bin',MAX_FILE,{range:'bytes=512-767'}),error=>error.status===409);
});
for(const change of ['grow','replace'])test(`a source that ${change==='grow'?'grows':'is replaced'} between PDF header and content is rejected`,async t=>{
const {root,area}=await fixture(t),file=path.join(root,'sample.pdf');await fs.writeFile(file,Buffer.from('%PDF-'+'.'.repeat(1019)));const original=fs.open;let changed=false;
t.mock.method(fs,'open',async(...args)=>{const handle=await original(...args),read=handle.read.bind(handle);handle.read=async(...args)=>{const result=await read(...args);if(!changed){changed=true;if(change==='grow')await fs.appendFile(file,'x');else{await fs.rename(file,file+'.old');await fs.writeFile(file,Buffer.alloc(1024,1));}}return result;};return handle;});
await assert.rejects(area.readPreview('sample.pdf',{range:'bytes=100-199'}),error=>error.status===409);
});
test('Office and image ranges retain whole-file validation and text ranges address decoded UTF-8 bytes',async t=>{
const {root,area}=await fixture(t);await makePreviewFiles(root);
for(const relative of ['sample.docx','sample.xlsx','sample.png']){
const full=await area.readPreview(relative),part=await area.readPreview(relative,{range:'bytes=0-7'});
assert.equal(part.total,full.bytes.length);assert.equal(part.status,206);assert.deepEqual(part.bytes,full.bytes.subarray(0,8));
}
const full=await area.readPreview('gbk.txt'),part=await area.readPreview('gbk.txt',{range:'bytes=-3'});assert.equal(part.total,6);assert.deepEqual(part.bytes,full.bytes.subarray(3));assert.equal(part.bytes.toString(),'文');
await assert.rejects(area.readPreview('bad.png',{range:'bytes=0-1'}),error=>error.status===415);
const office=await fs.readFile(path.join(root,'sample.docx')),central=office.indexOf(Buffer.from([0x50,0x4b,0x01,0x02]));office.writeUInt32LE(70*1024*1024,central+24);await fs.writeFile(path.join(root,'bomb.docx'),office);
await assert.rejects(area.readPreview('bomb.docx',{range:'bytes=0-1'}),error=>error.status===413);
});
test('range access keeps relative-path, link, and role restrictions',async t=>{
const {root,area}=await fixture(t),outside=await fs.mkdtemp(path.join(os.tmpdir(),'storage-range-outside-'));t.after(()=>fs.rm(outside,{recursive:true,force:true}));await fs.writeFile(path.join(outside,'secret.bin'),'private');await fs.symlink(outside,path.join(root,'link'),'junction');
for(const relative of ['../secret.bin','link/secret.bin','x:stream'])await assert.rejects(area.readFile(relative,MAX_FILE,{range:'bytes=0-1'}),error=>error.status===400);
const storage={readFile:()=>assert.fail('viewers must not reach storage')};await assert.rejects(request(storage,'bytes=0-1',{role:'viewer'}),error=>error.status===403);
});
test('range metadata and bounded buffers survive real worker IPC while malformed offsets are rejected',async t=>{
const {root}=await fixture(t);await fs.writeFile(path.join(root,'large.bin'),Buffer.alloc(16*1024*1024,8));const server={root,pidFile:path.join(root,'worker.pid'),enabled:true,version:1},client=new SmbClient({workerPath:path.join(__dirname,'worker-fixture.cjs')}),storage=new StorageService({store:{secret:()=>server},client,operationTimeoutMs:5000});t.after(()=>storage.stop());
const result=await storage.readFile('local','large.bin',{range:'bytes=-65536'});assert.equal(result.total,16777216);assert.equal(result.start,16711680);assert.equal(result.end,16777215);assert.equal(result.status,206);assert.equal(result.bytes.length,65536);assert.ok(result.bytes.every(byte=>byte===8));
assert.throws(()=>validate('readFile',{filename:'x',total:10,start:5,end:7,status:206,bytes:Buffer.alloc(1)}),error=>error.status===502);
const invalid=await storage.readFile('local','large.bin',{range:'bytes=16777216-'});assert.equal(invalid.status,416);assert.equal(invalid.total,16777216);assert.equal(invalid.bytes.length,0);
});
test('production worker dispatch preserves range options and returns unsatisfied totals as metadata',async t=>{
const {root,area}=await fixture(t);await fs.writeFile(path.join(root,'sample.pdf'),'%PDF-1.7 data');
let handle,message,exitCode;const vm=require('node:vm'),source=await fs.readFile(path.join(__dirname,'../../src/modules/storage/smb-operation-worker.cjs'),'utf8');
vm.runInNewContext(source,{require:specifier=>specifier==='./files.cjs'?{SmbClient:class{async area(){return area;}}}:{validate},process:{once(event,handler){assert.equal(event,'message');handle=handler;},send(value,callback){message=value;callback();},exit(code){exitCode=code;}}});
await handle({server:{},operation:'readPreview',args:['sample.pdf',{range:'bytes=5-7'}]});assert.equal(message.ok,true);assert.equal(message.value.status,206);assert.equal(message.value.total,13);assert.equal(message.value.bytes.toString(),'1.7');assert.equal(exitCode,0);
await handle({server:{},operation:'readFile',args:['sample.pdf',MAX_FILE,{range:'bytes=99-'}]});assert.equal(message.ok,true);assert.equal(message.value.status,416);assert.equal(message.value.total,13);assert.equal(message.value.bytes.length,0);
});
+89
View File
@@ -0,0 +1,89 @@
'use strict';
const {test}=require('node:test');
const assert=require('node:assert/strict');
const {compareVersions,parseRelease,createUpdateChecker}=require('../../src/modules/system-update/checker.cjs');
test('compares semantic versions with an optional v prefix and prerelease ordering',()=>{
assert.equal(compareVersions('v0.2.0','0.1.9'),1);
assert.equal(compareVersions('0.1.0','v0.1.0'),0);
assert.equal(compareVersions('0.1.0-beta.1','0.1.0'),-1);
});
test('parses a Gitea release into a safe update descriptor',()=>{
assert.deepEqual(parseRelease({tag_name:'v0.2.0',name:'第二版',body:'修复问题',html_url:'https://git.simgreek.com/Skyworth_Digital_Hardware/order-notification-automation/releases/tag/v0.2.0',published_at:'2026-10-27T00:00:00Z'},'0.1.0'),{
status:'update-available',currentVersion:'0.1.0',latest:{version:'0.2.0',name:'第二版',notes:'修复问题',url:'https://git.simgreek.com/Skyworth_Digital_Hardware/order-notification-automation/releases/tag/v0.2.0',publishedAt:'2026-10-27T00:00:00.000Z'}
});
});
test('returns no-release and unavailable states without throwing',async()=>{
const none=await createUpdateChecker({currentVersion:'0.1.0',fetchImpl:async()=>new Response('',{status:404})})();
assert.deepEqual(none,{status:'none',currentVersion:'0.1.0',latest:null});
const unavailable=await createUpdateChecker({currentVersion:'0.1.0',fetchImpl:async()=>{throw new Error('offline');}})();
assert.deepEqual(unavailable,{status:'unavailable',currentVersion:'0.1.0',latest:null});
});
test('reports only a newer valid release',async()=>{
const checker=createUpdateChecker({currentVersion:'0.1.0',fetchImpl:async()=>new Response(JSON.stringify({tag_name:'v0.2.0',name:'Release',body:'Notes',html_url:'https://git.simgreek.com/Skyworth_Digital_Hardware/order-notification-automation/releases/tag/v0.2.0',published_at:null}),{status:200,headers:{'content-type':'application/json'}})});
const result=await checker();
assert.equal(result.status,'update-available');
assert.equal(result.latest.version,'0.2.0');
});
test('marks an equal release as current',()=>{
assert.deepEqual(parseRelease({tag_name:'v0.1.0',name:'首版'},'0.1.0'),{status:'current',currentVersion:'0.1.0',latest:null});
});
test('supports build metadata and follows ASCII semver prerelease ordering',()=>{
assert.equal(compareVersions('v1.2.3+build.7','1.2.3'),0);
assert.equal(compareVersions('1.0.0-Z','1.0.0-a'),-1);
assert.equal(compareVersions('1.0.0-99999999999999999999','1.0.0-99999999999999999998'),1);
assert.throws(()=>compareVersions('1.0.0-01','1.0.0'));
});
test('malformed and unstable release responses never claim a valid stable update',()=>{
for(const data of [null,{},[],{tag_name:'banana'}])assert.equal(parseRelease(data,'0.1.0').status,'unavailable');
for(const data of [{tag_name:'v0.2.0',draft:true},{tag_name:'v0.2.0',prerelease:true},{tag_name:'v0.2.0-beta.1'}])assert.equal(parseRelease(data,'0.1.0').status,'none');
});
test('release links never include credentials or leave the selected repository',()=>{
for(const url of ['https://user:password@git.simgreek.com/Skyworth_Digital_Hardware/order-notification-automation/releases/tag/v0.2.0','javascript:alert(1)','https://example.org/releases/tag/v0.2.0','https://git.simgreek.com/other/repo/releases/tag/v0.2.0']){
assert.equal(parseRelease({tag_name:'v0.2.0',html_url:url},'0.1.0').latest.url,'');
}
});
test('checker bounds a streamed response before reading all chunks and disables redirects',async()=>{
let cancelled=false;
const checker=createUpdateChecker({currentVersion:'0.1.0',fetchImpl:async(url,options)=>{
if(options.redirect!=='error')throw Error('redirects are allowed');
return new Response(new ReadableStream({pull(controller){controller.enqueue(new Uint8Array(200000));},cancel(){cancelled=true;}}),{status:200});
}});
assert.equal((await checker()).status,'unavailable');
assert.equal(cancelled,true);
});
test('network timeout returns unavailable and preserves the current version',async()=>{
const checker=createUpdateChecker({currentVersion:'0.1.0',timeoutMs:25,fetchImpl:async(url,{signal})=>new Promise((resolve,reject)=>signal.addEventListener('abort',()=>reject(signal.reason),{once:true}))});
assert.deepEqual(await checker(),{status:'unavailable',currentVersion:'0.1.0',latest:null});
});
test('concurrent update checks share one upstream read and the next manual check is fresh',async()=>{
let requests=0,release;
const gate=new Promise(resolve=>{release=resolve;});
const checker=createUpdateChecker({currentVersion:'0.1.0',fetchImpl:async()=>{requests++;await gate;return new Response(JSON.stringify({tag_name:'v0.2.0'}));}});
const pending=Array.from({length:8},()=>checker());
assert.equal(requests,1,'simultaneous readers must share the in-flight request');
release();const results=await Promise.all(pending);
assert.ok(results.every(result=>result.status==='update-available'));
results[0].latest.version='caller-mutation';assert.equal(results[1].latest.version,'0.2.0');
assert.equal((await checker()).latest.version,'0.2.0');assert.equal(requests,2,'a completed check must not mask a later manual refresh');
});
test('a coalesced failed check clears in-flight state and a new check can recover',async()=>{
let requests=0,reject;
const failed=new Promise((resolve,rejectPromise)=>{reject=rejectPromise;});
const checker=createUpdateChecker({currentVersion:'0.1.0',fetchImpl:async()=>{requests++;if(requests===1)return failed;return new Response('',{status:404});}});
const first=checker(),second=checker();assert.equal(requests,1);
reject(Error('offline'));
assert.deepEqual(await first,{status:'unavailable',currentVersion:'0.1.0',latest:null});assert.equal((await second).status,'unavailable');
assert.equal((await checker()).status,'none');assert.equal(requests,2);
});
@@ -0,0 +1,57 @@
'use strict';
const {test}=require('node:test');
const assert=require('node:assert/strict');
const fs=require('node:fs');
const os=require('node:os');
const path=require('node:path');
const {Store}=require('../../src/modules/dashboard/store.cjs');
const {createDashboard}=require('../../src/app/dashboard.cjs');
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
function fixture(updateChecker){
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'system-update-'));
const store=new Store(dir);store.bootstrap('admin','Update-test-123');
const server=createDashboard({store,outputDir:dir,updateChecker});
return {dir,store,server};
}
test('authenticated update endpoint returns the checker result',async t=>{
const fixtureData=fixture(async()=>({status:'none',currentVersion:'0.1.0',latest:null}));
const {server,dir}=fixtureData;await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
t.after(async()=>{server.closeAllConnections();await new Promise(resolve=>server.close(resolve));fs.rmSync(dir,{recursive:true,force:true});});
const base='http://127.0.0.1:'+server.address().port;
const call=(route,body,cookie)=>fetch(base+route,{method:body===undefined?'GET':'POST',headers:{...(body?{'Content-Type':'application/json','Origin':base}:{}),...(cookie?{Cookie:cookie}:{})},body:body===undefined?undefined:JSON.stringify(body)});
assert.equal((await call('/api/update')).status,401);
const login=await call('/api/login',{username:'admin',password:'Update-test-123'});const cookie=login.headers.get('set-cookie').split(';')[0];
const response=await call('/api/update',undefined,cookie);assert.equal(response.status,200);assert.deepEqual(await response.json(),{status:'none',currentVersion:'0.1.0',latest:null});
});
test('sidebar displays the current version and a newer release after checking',async t=>{
let state={status:'none',currentVersion:'0.1.0',latest:null};
const fixtureData=fixture(async()=>state);
const {server,dir}=fixtureData;await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
t.after(async()=>{server.closeAllConnections();await new Promise(resolve=>server.close(resolve));fs.rmSync(dir,{recursive:true,force:true});});
const browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());
const page=await browser.newPage({viewport:{width:1440,height:1000}});page.setDefaultTimeout(10000);const errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto('http://127.0.0.1:'+server.address().port+'/#overview');
await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Update-test-123');await page.getByRole('button',{name:'登录',exact:true}).click();
await page.locator('#app-version').waitFor();assert.match(await page.locator('#app-version').textContent(),/v0\.1\.0/);assert.equal(await page.locator('#update-status').count(),1);
await page.locator('#update-status').getByText('暂无可用发行版本',{exact:true}).waitFor();
state={status:'update-available',currentVersion:'0.1.0',latest:{version:'0.2.0',name:'第二版',notes:'修复问题\n<img src=x onerror="alert(1)">',url:'https://git.simgreek.com/Skyworth_Digital_Hardware/order-notification-automation/releases/tag/v0.2.0',publishedAt:'2026-10-27T00:00:00Z'}};
await page.getByRole('button',{name:'检查更新',exact:true}).click();
const dialog=page.getByRole('dialog',{name:'系统更新',exact:true});await dialog.waitFor();
await dialog.getByText('发现新版本 v0.2.0',{exact:true}).waitFor();
assert.equal(await dialog.locator('img').count(),0);assert.match(await dialog.locator('pre').textContent(),/<img src=x/);
const contrast=await dialog.locator('pre').evaluate(node=>{
const canvas=document.createElement('canvas');canvas.width=canvas.height=1;const context=canvas.getContext('2d');
const luminance=value=>{context.fillStyle=value;context.fillRect(0,0,1,1);const parts=Array.from(context.getImageData(0,0,1,1).data).slice(0,3).map(v=>{v/=255;return v<=.04045?v/12.92:((v+.055)/1.055)**2.4;});return parts[0]*.2126+parts[1]*.7152+parts[2]*.0722;};
const style=getComputedStyle(node),a=luminance(style.color),b=luminance(style.backgroundColor);return (Math.max(a,b)+.05)/(Math.min(a,b)+.05);
});assert.ok(contrast>=4.5,'release notes must remain readable on their background');
assert.match(await dialog.textContent(),/2026/);assert.equal(await dialog.getByRole('link',{name:'前往发行页面'}).getAttribute('href'),state.latest.url);
await dialog.getByRole('button',{name:'关闭',exact:true}).click();await dialog.waitFor({state:'hidden'});
state={status:'unavailable',currentVersion:'0.1.0',latest:null};await page.getByRole('button',{name:'检查更新',exact:true}).click();await dialog.getByText('暂时无法检查更新',{exact:true}).waitFor();
assert.match(await page.locator('#app-version').textContent(),/v0\.1\.0/);
await page.keyboard.press('Escape');await dialog.waitFor({state:'hidden'});await page.setViewportSize({width:390,height:844});await page.getByRole('button',{name:'展开菜单',exact:true}).click();
await page.locator('#sidebar-menu.show').waitFor();await page.waitForFunction(()=>!document.querySelector('#sidebar-menu').classList.contains('collapsing'));
await page.getByRole('button',{name:'检查更新',exact:true}).click();await dialog.waitFor();assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
assert.deepEqual(errors,[]);
});
+2
View File
@@ -60,3 +60,5 @@
.rule-scope-row .ts-wrapper{--bs-body-bg:var(--tblr-bg-surface,#fff);--bs-body-color:var(--tblr-body-color,#182433);--bs-border-radius:var(--tblr-border-radius,6px)}
.bpm-account-status{display:inline-flex;align-items:center;gap:7px;font-size:.8rem;font-weight:600;white-space:nowrap}.bpm-status-light{width:9px;height:9px;border-radius:50%;background:currentColor;flex-shrink:0}.bpm-status-green{color:#23834b}.bpm-status-yellow{color:#996600}.bpm-status-red{color:#c53030}.bpm-status-details>summary{cursor:pointer;font-size:.8rem;color:#657b81}.bpm-status-details>div{display:flex;gap:.75rem;flex-wrap:wrap;align-items:center;margin-top:.65rem}
.bpm-sync-summary{display:flex;align-items:center;gap:.75rem;flex-wrap:wrap}
.sidebar-system-update{line-height:1.6}.sidebar-version{margin-top:9px;color:#52655d;font-variant-numeric:tabular-nums}.sidebar-update-button{margin-top:8px;padding:.25rem .55rem;font-size:.68rem}.sidebar-update-status{margin-top:6px;font-size:.68rem;color:#87958e;overflow-wrap:anywhere}.sidebar-update-status.is-update{color:#a35d1b;font-weight:600}.sidebar-update-status a{color:inherit;text-decoration:underline;font-weight:500}@media(max-width:991px){.sidebar-system-update{margin-top:1rem;padding:1rem!important}.sidebar-update-status{max-width:320px}}
.sidebar-release-details{border:0;background:none;padding:4px 0;color:inherit;text-decoration:underline;font-size:inherit;display:block}.system-update-dialog{width:min(580px,calc(100vw - 32px));max-height:85vh;overflow:auto;border:1px solid var(--tblr-border-color);border-radius:12px;padding:24px;color:var(--tblr-body-color);background:#fff}.system-update-dialog::backdrop{background:#18243366}.system-update-notes{color:inherit;white-space:pre-wrap;overflow-wrap:anywhere;font:inherit;font-size:.85rem;max-height:40vh;overflow:auto;background:#f5f7f8;padding:12px;border-radius:8px}
+85 -21
View File
@@ -4,20 +4,51 @@ const esc=value=>String(value??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;
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,automationRevision=0,overviewRevision=0;
let currentUser=null,settings=null,currentView='overview',overview=null,refreshTimer=null,viewGeneration=0,historyIndex=0,historyTransition=null,automationRevision=0,overviewRevision=0,updateRevision=0;
let updateState={status:'unavailable',currentVersion:'—',latest:null};
const views={tools:['工具','手工导出、文件查看与助手'],'records-pdf':['订单与导出记录','查询PDF导出结果、文件可用性与存储归档记录'],'order-notifications':['通知总览','查看当前发送时段、待发订单及接入阻塞'],'notification-execution':['订单执行','扫描真实待办,查看归档进度与受控恢复'],'notification-orders':['订单中心','查看订单分类、归档证据及所属邮件批次'],'notification-batches':['邮件批次','按发送时段检查分类汇总和冻结内容'],'notification-history':['发送记录','核对发送结果、冻结内容和人工恢复记录'],'notification-settings':['发送设置','维护发件邮箱、邮件限制与自动通知开关'],'rule-fields':['字段映射','采集BPM流程和节点,供分类规则选择匹配项'],'assistant-settings':['助手设置','配置 DSH 运行包、模型与受控操作权限'],'business-settings':['业务设置','维护Excel分类规则、收件人和BPM流程节点目录'],'system-settings':['系统设置','集中管理服务连接、运行维护和团队权限'],account:['个人账号','维护自己的登录密码与访问安全'],'order-rules':['分类通知规则','按 Excel 类别维护匹配、归档、收件人与通知正文'],health:['系统健康','查看服务守护、登录自启和各模块最近检查结果'],assistant:['DSH 助手','对话查询运行状态、分析异常与执行受控恢复'],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();
const pendingWrites=new Map(),pendingReads=new Map();
function mutationRegions(route){
if(route.startsWith('/assistant'))return ['assistant','health'];
if(route.startsWith('/storage'))return ['storage','records','home','orderRules','health'];
if(route.startsWith('/mail'))return ['mail','orderRules','home','health'];
if(route.startsWith('/connections')||route.startsWith('/bpm'))return ['bpm','records','orderRules','home','health'];
if(route.startsWith('/order-')||route==='/settings'||route==='/calendar'||route.startsWith('/exceptions'))return ['orderRules','home','records','bpm','health'];
if(route.startsWith('/jobs'))return ['records','storage','home','health'];
if(route.startsWith('/users'))return ['home','orderRules','records','health','bpm','assistant','storage','mail'];
return [];
}
// Share transport only while a read is pending; each caller owns cancellation and its result.
function readRequest(route,signal,user,scope){
if(signal?.aborted)return Promise.reject(signal.reason||new DOMException('Aborted','AbortError'));
let entry=pendingReads.get(route);
if(!entry||entry.user!==user||entry.scope!==scope){
const controller=new AbortController(),timeout=setTimeout(()=>controller.abort(),30000);
entry={user,scope,controller,subscribers:0,work:null};
entry.work=fetch('/api'+route,{signal:controller.signal,credentials:'same-origin',method:'GET',headers:{}}).then(async response=>({ok:response.ok,status:response.status,result:await response.json()})).finally(()=>{clearTimeout(timeout);if(pendingReads.get(route)===entry)pendingReads.delete(route);});
pendingReads.set(route,entry);
}
entry.subscribers++;
return new Promise((resolve,reject)=>{
let settled=false;
const finish=(work,value)=>{if(settled)return;settled=true;signal?.removeEventListener('abort',abort);entry.subscribers--;if(!entry.subscribers){if(pendingReads.get(route)===entry)pendingReads.delete(route);entry.controller.abort();}work(value);};
const abort=()=>finish(reject,signal.reason||new DOMException('Aborted','AbortError'));
signal?.addEventListener('abort',abort,{once:true});
entry.work.then(value=>finish(resolve,structuredClone(value)),error=>finish(reject,error));
});
}
async function api(route,body,{signal,ownerCheck,managedOutcome=false}={}) {
const originGeneration=viewGeneration,originUser=currentUser,originRevision=window.PageLifecycle?.revision;const originActive=()=>viewGeneration===originGeneration&&currentUser===originUser&&window.PageLifecycle?.revision===originRevision;const submission=window.PageLifecycle?.submission,hasBody=body!==undefined,write=hasBody&&route!=='/order-rules/field-mappings/propose'&&!/^\/assistant\/providers\/[^/]+\/models$/.test(route),key=originGeneration+':'+originRevision+':'+route+':'+JSON.stringify(body);const pending=pendingWrites.get(key);if(write&&pending?.user===originUser)return pending.work;
const originGeneration=viewGeneration,originUser=currentUser,originRevision=window.PageLifecycle?.revision;const originActive=()=>viewGeneration===originGeneration&&currentUser===originUser&&window.PageLifecycle?.revision===originRevision;const submission=window.PageLifecycle?.submission,hasBody=body!==undefined,write=hasBody&&route!=='/order-rules/field-mappings/propose'&&route!=='/assistant/management/query'&&!/^\/assistant\/providers\/[^/]+\/models$/.test(route),key=originGeneration+':'+originRevision+':'+route+':'+JSON.stringify(body);const pending=pendingWrites.get(key);if(write&&pending?.user===originUser)return pending.work;
if(write){pendingReads.clear();if(originUser)window.PageLifecycle?.invalidateRegion?.(mutationRegions(route));}
const work=(async()=>{const controller=new AbortController(),timeout=setTimeout(()=>controller.abort(),30000);const combined=signal?AbortSignal.any([signal,controller.signal]):controller.signal;
try {const response=await fetch('/api'+route,{signal:combined,credentials:'same-origin',keepalive:route.endsWith('/login/close'),method:hasBody?'POST':'GET',headers:hasBody?{'Content-Type':'application/json'}:{},body:hasBody?JSON.stringify(body):undefined});const result=await response.json();
try {const response=hasBody?await fetch('/api'+route,{signal:combined,credentials:'same-origin',keepalive:route.endsWith('/login/close'),method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}):await readRequest(route,combined,originUser,originGeneration+':'+originRevision);const result=hasBody?await response.json():response.result;
if(!response.ok){if(response.status===401&&currentUser&&originActive()&&(!ownerCheck||ownerCheck())){window.RecordState?.clear();currentUser=null;++viewGeneration;await window.PageLifecycle?.dispose();window.BpmLogin?.dispose();await boot();}throw Object.assign(Error(result.error||'操作失败,请核对输入。'),{status:response.status,outcome:'rejected'});}if(write&&originActive())window.PageLifecycle?.succeeded(submission);return result;
}catch(error){if(write&&originActive())window.PageLifecycle?.failed(submission);if(write&&(error.name==='AbortError'||error instanceof TypeError)){if(originActive()&&!managedOutcome)void verifyUncertainWrite(route,originActive);throw Object.assign(Error('结果待核实:请求超时或连接中断,正在查询状态;不会自动重试。'),{outcome:'uncertain'});}throw error;
}finally{clearTimeout(timeout);}})();if(write)pendingWrites.set(key,{user:originUser,work});try{return await work;}finally{if(write&&pendingWrites.get(key)?.work===work)pendingWrites.delete(key);}
}finally{clearTimeout(timeout);if(write){pendingReads.clear();if(currentUser===originUser&&originUser)window.PageLifecycle?.invalidateRegion?.(mutationRegions(route));}}})();if(write)pendingWrites.set(key,{user:originUser,work});try{return await work;}finally{if(write&&pendingWrites.get(key)?.work===work)pendingWrites.delete(key);}
}
async function verifyUncertainWrite(route,isActive){
const resource=route.startsWith('/order-rules/field-mappings/')||route==='/order-rules/field-samples/capture'?['/order-rules/fields','processes']:route.startsWith('/order-execution')?['/order-execution','tasks']:route.startsWith('/order-rules')?['/order-rules','rules']:route.startsWith('/assistant')?['/assistant','settings']:route.startsWith('/mail')?['/mail','channels']:route.startsWith('/storage')?['/storage','servers']:route==='/settings'?['/settings','schedule']:route==='/calendar'?['/workspace','calendar']:route.startsWith('/connections')?['/workspace','connections']:route.startsWith('/exceptions')?['/workspace','exceptions']:route.startsWith('/users')?['/users','users']:route==='/account/password'?['/me','user']:['/overview','stats'];
const resource=route.startsWith('/order-rules/field-mappings/')||route==='/order-rules/field-samples/capture'?['/order-rules/fields','processes']:route.startsWith('/order-execution')?['/order-execution','tasks']:(route.startsWith('/order-rules/rules')||route==='/order-rules/restricted-test/apply')?['/order-rules/configuration','rules']:route.startsWith('/order-rules')?['/order-rules','rules']:route.startsWith('/assistant')?['/assistant','settings']:route.startsWith('/mail')?['/mail','channels']:route.startsWith('/storage')?['/storage','servers']:route==='/settings'?['/settings','schedule']:route==='/calendar'?['/workspace','calendar']:route.startsWith('/connections')?['/workspace','connections']:route.startsWith('/exceptions')?['/workspace','exceptions']:route.startsWith('/users')?['/users','users']:route==='/account/password'?['/me','user']:['/overview','stats'];
const panel=document.querySelector('#content');if(!isActive()||!panel)return;let alert=panel.querySelector('#operation-uncertain');if(!alert){alert=document.createElement('div');alert.id='operation-uncertain';alert.className='alert alert-warning';alert.setAttribute('role','alert');panel.prepend(alert);}const prefix='结果待核实:请求超时或连接中断;不会自动重试。';alert.textContent=prefix+' 正在查询状态。';
if(route==='/order-rules/field-samples/list'){alert.textContent='待办列表读取结果待确认,请使用读取按钮核实同次请求;系统不会归档、发信或办理节点。';return;}
const controller=new AbortController(),timeout=setTimeout(()=>controller.abort(),8000),unregister=window.PageLifecycle?.onDispose(()=>controller.abort());
@@ -32,10 +63,41 @@ function notify(message,type='success') {
}
function badge(status){const [label,color]=statusMap[status] || ['待处理','secondary'];return `<span class="badge bg-${color}-lt">${label}</span>`;}
function navItem(id,symbol){return `<li class="nav-item"><a class="nav-link ${currentView===id?'active':''}" href="${window.RecordState?.href(id)||'#'+id}" data-view="${id}"><span class="nav-link-icon" aria-hidden="true">${window.AppNavigation.icon(symbol)}</span><span class="nav-link-title">${id==='order-notifications'?'订单通知管理':views[id][0]}</span></a></li>`;}
function renderUpdateStatus(data){
updateState=data||updateState;
const version=document.querySelector('#app-version');if(version)version.textContent='版本 v'+(updateState.currentVersion||'—');
const status=document.querySelector('#update-status');if(!status)return;
status.className='sidebar-update-status';
if(updateState.status==='update-available'&&updateState.latest){
status.classList.add('is-update');status.innerHTML=`<span class="badge bg-yellow-lt">发现新版本 v${esc(updateState.latest.version)}</span><button type="button" class="sidebar-release-details">查看更新</button>`;
status.querySelector('button').onclick=()=>showUpdateDetails();
}else if(updateState.status==='current'){status.textContent='已是最新版本';}
else if(updateState.status==='none'){status.textContent='暂无可用发行版本';}
else if(updateState.status==='unavailable'){status.textContent='暂时无法检查更新';}
else status.textContent='更新状态未知';
}
function showUpdateDetails(loading=false){
let dialog=document.querySelector('#system-update-dialog');
if(!dialog){dialog=document.createElement('dialog');dialog.id='system-update-dialog';dialog.className='system-update-dialog';dialog.setAttribute('aria-labelledby','system-update-title');root.append(dialog);}
const release=updateState.latest;
const message=loading?'正在检查更新…':updateState.status==='update-available'&&release?'发现新版本 v'+release.version:({none:'暂无可用发行版本',current:'已是最新版本',unavailable:'暂时无法检查更新'}[updateState.status]||'更新状态未知');
dialog.innerHTML=`<h2 id="system-update-title" class="h3">系统更新</h2><p class="text-secondary">当前版本 v${esc(updateState.currentVersion)}</p><p role="status">${esc(message)}</p>${!loading&&release?`<h3 class="h4">${esc(release.name)}</h3>${release.publishedAt?`<p class="small text-secondary">发布时间(北京时间):${esc(formatDate(release.publishedAt))}</p>`:''}<pre class="system-update-notes">${esc(release.notes||'此版本未填写更新说明。')}</pre>${release.url?`<a class="btn btn-primary" href="${esc(release.url)}" target="_blank" rel="noopener noreferrer">前往发行页面</a>`:''}<p class="small text-secondary mt-3">由部署管理员根据发行说明安排更新。</p>`:''}<form method="dialog" class="text-end mt-3"><button class="btn" type="submit">关闭</button></form>`;
if(!dialog.open)dialog.showModal();
}
async function checkSystemUpdate(isActive=()=>!!currentUser,{manual=false}={}){
const user=currentUser,request=++updateRevision,button=document.querySelector('#check-updates'),ownsResponse=()=>currentUser===user&&!!user&&button?.isConnected&&isActive();if(button)button.disabled=true;
const status=document.querySelector('#update-status');if(status&&manual)status.textContent='正在检查更新…';
if(manual)showUpdateDetails(true);
try{const result=await api('/update',undefined,{ownerCheck:ownsResponse});if(!ownsResponse()||request!==updateRevision)return;renderUpdateStatus(result);if(manual&&document.querySelector('#system-update-dialog')?.open)showUpdateDetails();}
catch(error){if(ownsResponse()&&request===updateRevision){updateState={...updateState,status:'unavailable',latest:null};renderUpdateStatus(updateState);if(manual&&document.querySelector('#system-update-dialog')?.open)showUpdateDetails();}}
finally{if(button&&request===updateRevision)button.disabled=false;}
}
function shell() {
root.innerHTML=`<div class="page"><aside class="navbar navbar-vertical navbar-expand-lg"><div class="container-fluid"><button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#sidebar-menu" aria-controls="sidebar-menu" aria-label="展开菜单"><span class="navbar-toggler-icon"></span></button><a class="navbar-brand" href="#overview"><span class="brand-mark">单</span>订单通知中心</a><div class="collapse navbar-collapse" id="sidebar-menu"><ul class="navbar-nav pt-lg-3">${window.AppNavigation.primary.map(([id,symbol])=>navItem(id,symbol)).join('')}</ul></div></div></aside><header class="navbar d-print-none"><div class="container-xl"><div class="d-flex gap-2 flex-wrap"><a class="badge bg-secondary-lt text-decoration-none" id="automation-status" href="#notification-settings" title="正在读取服务端通知状态" aria-live="polite">通知状态待确认</a></div><div class="navbar-nav flex-row order-md-last ms-auto align-items-center gap-3"><div><div class="account-name">${esc(currentUser.username)}</div><div class="small text-secondary">${roles[currentUser.role]}</div></div><a class="btn btn-sm" href="#account">修改密码</a><button class="btn btn-sm" id="logout">退出</button></div></div></header><div class="page-wrapper"><div class="page-header d-print-none"><div class="container-xl"><div class="row g-2 align-items-center"><div class="col"><nav id="view-breadcrumb" class="mb-2" aria-label="设置导航" hidden></nav><h1 class="page-title" id="view-title"></h1><div class="text-secondary mt-2" id="view-description"></div></div><div class="col-auto ms-auto"><button class="btn" id="refresh">刷新数据</button></div></div></div></div><div class="page-body"><div class="container-xl"><nav class="nav nav-segmented settings-tabs" id="settings-tabs" aria-label="页面导航" hidden></nav><div id="content"></div></div></div></div></div>`;
document.querySelector('#logout').onclick=()=>window.PageLifecycle.guard(async()=>{++viewGeneration;await window.BpmLogin?.dispose();await api('/logout',{});window.RecordState.clear();currentUser=null;clearInterval(refreshTimer);await window.PageLifecycle.dispose();await boot();});
document.querySelector('#refresh').onclick=()=>window.PageLifecycle.guard(()=>{const generation=viewGeneration;void updateAutomationStatus(()=>generation===viewGeneration&&!!currentUser);return window.RecordTable?.active?window.RecordTable.active.refresh():renderView();}).catch(error=>notify(error.message,'danger'));
root.innerHTML=`<div class="page"><aside class="navbar navbar-vertical navbar-expand-lg"><div class="container-fluid"><button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#sidebar-menu" aria-controls="sidebar-menu" aria-label="展开菜单"><span class="navbar-toggler-icon"></span></button><a class="navbar-brand" href="#overview"><span class="brand-mark">单</span>订单通知中心</a><div class="collapse navbar-collapse" id="sidebar-menu"><ul class="navbar-nav pt-lg-3">${window.AppNavigation.primary.map(([id,symbol])=>navItem(id,symbol)).join('')}</ul><div class="mt-auto p-3 text-secondary small sidebar-system-update"><div class="sidebar-version" id="app-version">版本 v${esc(updateState.currentVersion)}</div><button class="btn btn-sm btn-outline-secondary sidebar-update-button" id="check-updates" type="button">检查更新</button><div class="sidebar-update-status" id="update-status" aria-live="polite">正在读取更新状态…</div></div></div></div></aside><header class="navbar d-print-none"><div class="container-xl"><div class="d-flex gap-2 flex-wrap"><a class="badge bg-secondary-lt text-decoration-none" id="automation-status" href="#notification-settings" title="正在读取服务端通知状态" aria-live="polite">通知状态待确认</a></div><div class="navbar-nav flex-row order-md-last ms-auto align-items-center gap-3"><div><div class="account-name">${esc(currentUser.username)}</div><div class="small text-secondary">${roles[currentUser.role]}</div></div><a class="btn btn-sm" href="#account">修改密码</a><button class="btn btn-sm" id="logout">退出</button></div></div></header><div class="page-wrapper"><div class="page-header d-print-none"><div class="container-xl"><div class="row g-2 align-items-center"><div class="col"><nav id="view-breadcrumb" class="mb-2" aria-label="设置导航" hidden></nav><h1 class="page-title" id="view-title"></h1><div class="text-secondary mt-2" id="view-description"></div></div><div class="col-auto ms-auto"><button class="btn" id="refresh">刷新数据</button></div></div></div></div><div class="page-body"><div class="container-xl"><nav class="nav nav-segmented settings-tabs" id="settings-tabs" aria-label="页面导航" hidden></nav><div id="content"></div></div></div></div></div>`;
renderUpdateStatus(updateState);
document.querySelector('#logout').onclick=()=>window.PageLifecycle.guard(async()=>{++viewGeneration;await window.BpmLogin?.dispose();await api('/logout',{});window.RecordState.clear();currentUser=null;refreshTimer?.dispose();await window.PageLifecycle.dispose();await boot();});
document.querySelector('#check-updates').onclick=()=>checkSystemUpdate(()=>!!currentUser,{manual:true});
document.querySelector('#refresh').onclick=()=>window.PageLifecycle.guard(async()=>{void refreshTimer?.refresh().catch(()=>{});const region=({overview:'home','order-notifications':'home',health:'health',bpm:'bpm',assistant:'assistant',records:'records','records-pdf':'records','notification-orders':'records','notification-batches':'records','notification-execution':'records','notification-history':'records'})[currentView];if(region&&await window.PageLifecycle.refreshRegions(region))return;return window.RecordTable?.active?window.RecordTable.active.refresh():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');});
}
function empty(title,text){return `<div class="empty-state"><div class="avatar avatar-lg bg-blue-lt mb-3">▤</div><h3>${title}</h3><p class="text-secondary">${text}</p></div>`;}
@@ -58,8 +120,9 @@ async function viewSchedule(container,isActive=()=>true) {
}
async function viewTemplates(container,isActive=()=>true){
container.innerHTML='<div class="alert alert-info">模板仅维护内容。有效模板选择统一在 <a href="#order-rules">分类规则</a> 保存并发布。</div><div id="mail-templates"></div><div id="category-templates"></div>';
const usageRead=api('/order-rules/catalog').then(data=>({data}),error=>({error}));
const mail=await window.MailViews.templates(container.querySelector('#mail-templates'),isActive);if(!isActive())return;
let data;try{data=await api('/order-rules?view=summary');}catch(error){if(isActive())container.querySelector('#category-templates').innerHTML='<div class="alert alert-warning"><strong>模板使用情况读取失败</strong><div>'+esc(error.message)+'</div></div>';return;}if(!isActive())return;
let data;try{const result=await usageRead;if(result.error)throw result.error;data=result.data;}catch(error){if(isActive())container.querySelector('#category-templates').innerHTML='<div class="alert alert-warning"><strong>模板使用情况读取失败</strong><div>'+esc(error.message)+'</div></div>';return;}if(!isActive())return;
const usage=data.templateUsage||[];
if(usage.some(r=>r.legacyBinding)){
try{const legacy=await api('/mail/templates/categories');if(!isActive())return;for(const row of usage)if(row.legacyBinding)row.templateId=legacy.bindings.find(b=>b.categoryId===row.categoryId)?.templateId||'';}
@@ -70,18 +133,17 @@ async function viewTemplates(container,isActive=()=>true){
}
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=`<div class="card"><div class="card-header"><h2 class="card-title">最近操作记录</h2><span class="text-secondary ms-auto">按时间展示最近 200 条</span></div>${audit.length?`<div class="table-responsive"><table class="table card-table"><thead><tr><th>时间(北京时间)</th><th>操作人</th><th>操作</th><th>详情</th></tr></thead><tbody>${audit.slice(0,200).map(item=>`<tr><td class="small text-secondary">${formatDate(item.at)}</td><td>${esc(item.actor)}</td><td>${esc(window.WorkspaceViews.activityText(item.action))}</td><td class="audit-detail text-secondary">${esc(item.detail)}</td></tr>`).join('')}</tbody></table></div>`:empty('暂无操作记录','保存设置或导出订单后,可在这里查看。')}</div>`;}
function viewRules(container,isActive){return window.OrderRuleViews.render(container,isActive,'rules');}
async function updateAutomationStatus(isActive){
async function updateAutomationStatus(isActive,{signal}={}){
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?view=summary',undefined,{ownerCheck:isActive});if(!isActive())return;
const data=await api('/order-rules/status',undefined,{signal,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&&data.capabilities?.liveTodo===true&&data.counts?.orders===0&&!(data.scans||[]).some(scan=>scan.status==='failed'))apply('自动通知待验证','yellow','当前没有匹配订单;'+missing.join('、')+'尚待实际业务验证。匹配订单到达后按流程核验。');
else if(missing.length)apply('自动通知受阻','yellow','未通过实际检查:'+missing.join('、')+'。点击查看发送设置。');
else if(missing.length)apply('自动通知待核验','yellow','部分接入能力尚待核验,请到通知总览查看实际订单和阻塞详情。');
else apply('自动通知已启用','green','通知开关已启用;实际任务、类别及批次仍按各自检查结果执行。');
}catch(error){apply('通知状态待确认','yellow',error.message+';请刷新重试。');}
}catch(error){if(signal?.aborted)throw error;apply('通知状态待确认','yellow',error.message+';请刷新重试。');throw error;}
}
function configurationHost(container){
container.innerHTML='<section class="card notification-configuration"><div class="card-header"><nav id="notification-config-tabs" class="nav nav-segmented settings-tabs configuration-tabs" aria-label="通知配置导航"></nav></div><div class="card-body" id="notification-config-content"></div></section>';
@@ -96,7 +158,7 @@ async function renderView() {
history.replaceState(history.state,'',window.RecordState.serialize(resolved,Object.fromEntries(params)));
}
if(window.RecordState.isRecord(location.hash)&&currentView===resolved&&window.RecordTable?.active?.view===resolved){historyIndex=Number.isInteger(history.state?.appIndex)?history.state.appIndex:historyIndex;void updateAutomationStatus(()=>!!currentUser&&currentView===resolved);return window.RecordTable.active.navigate();}
if(window.RecordState.isRecord(location.hash)&&currentView===resolved&&window.RecordTable?.active?.view===resolved){historyIndex=Number.isInteger(history.state?.appIndex)?history.state.appIndex:historyIndex;void refreshTimer?.run().catch(()=>{});return window.RecordTable.active.navigate();}
const wasRecord=['records','records-pdf'].includes(currentView);
const generation=++viewGeneration;const isActive=()=>generation===viewGeneration && !!currentUser;
await window.PageLifecycle?.dispose();
@@ -108,13 +170,14 @@ async function renderView() {
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 sectionTitle=views[section]?.[0];
const breadcrumb=document.querySelector('#view-breadcrumb');breadcrumb.hidden=!section||section===currentView||section==='records';breadcrumb.innerHTML=breadcrumb.hidden?'':`<a href="#${section}" class="${section==='tools'?'btn btn-outline-primary tools-return':''}" aria-label="返回${sectionTitle}">← 返回${sectionTitle}</a> <span class="text-secondary"> / ${esc(views[currentView][0])}</span>`;
const breadcrumb=document.querySelector('#view-breadcrumb');breadcrumb.hidden=!section||section===currentView||section==='records';breadcrumb.innerHTML=breadcrumb.hidden?'':`<a href="#${section}" aria-label="返回${sectionTitle}">← ${sectionTitle}</a> <span class="text-secondary"> / ${esc(views[currentView][0])}</span>`;
document.querySelector('#view-title').textContent=views[currentView][0];document.querySelector('#view-description').textContent=views[currentView][1];
const container=document.querySelector('#content');if(!(wasRecord&&['records','records-pdf'].includes(currentView)))container.innerHTML='<div class="card"><div class="card-body text-secondary">正在加载…</div></div>';
try{await window.AppModules.load(currentView);if(generation!==viewGeneration)return;configureLoadedViews();}catch(error){if(isActive()){container.innerHTML=`<div class="alert alert-danger" role="alert">${esc(error.message)} <button class="btn btn-sm" type="button" data-module-retry>重试加载页面</button> <button class="btn btn-sm" type="button" data-module-reload>重新加载工作台</button></div>`;container.querySelector('[data-module-retry]').onclick=()=>renderView();container.querySelector('[data-module-reload]').onclick=()=>location.reload();}return;}
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,'records-pdf':viewPdfRecords,schedule:viewSchedule,templates:viewTemplates,mail:window.MailViews?.accounts,users:window.AccountViews?.users,audit:viewAudit,rules:viewRules}[currentView];
void updateAutomationStatus(isActive);
void refreshTimer?.run().catch(()=>{});
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=`<div class="alert alert-danger">${esc(error.message)}</div>`;}
}
async function authScreen() {
@@ -123,9 +186,10 @@ async function authScreen() {
document.querySelector('#login-form').onsubmit=async event=>{event.preventDefault();const button=event.target.querySelector('button[type="submit"]');button.disabled=true;try{const result=await api(initialize?'/bootstrap':'/login',{username:document.querySelector('#username').value,password:document.querySelector('#password').value});currentUser=result.user;enter();}catch(error){document.querySelector('#auth-error').textContent=error.message;}finally{button.disabled=false;}};
}
async function passwordChanged(actorId){if(currentUser&&currentUser.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.RecordState.configure(currentUser,({hash,push})=>{if(push&&location.hash!==hash)history.pushState({appIndex:++historyIndex},'',hash);else history.replaceState({...history.state,appIndex:historyIndex},'',hash);});window.PdfRecordViews?.configure({api,esc,formatDate,notify,user:currentUser});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,user:currentUser});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);}},15000);}
async function boot(){try{const setup=await api('/bootstrap/status');currentUser=(await api('/me')).user;enter();}catch{await authScreen();}}
async function passwordChanged(actorId){if(currentUser&&currentUser.id!==actorId)return false;currentUser=null;++viewGeneration;refreshTimer?.dispose();await window.PageLifecycle?.dispose();await window.BpmLogin?.dispose().catch(()=>{});await boot();return true;}
function configureLoadedViews(){window.PdfRecordViews?.configure({api,esc,formatDate,notify,user:currentUser});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,user:currentUser});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});}
function enter(){window.PageLifecycle.configureRegions({read:(signal,region)=>api('/refresh/revisions?regions='+encodeURIComponent(region),undefined,{signal}),user:()=>currentUser});window.RecordState.configure(currentUser,({hash,push})=>{if(push&&location.hash!==hash)history.pushState({appIndex:++historyIndex},'',hash);else history.replaceState({...history.state,appIndex:historyIndex},'',hash);});configureLoadedViews();shell();refreshTimer?.dispose();const statusUser=currentUser;refreshTimer=window.PageLifecycle.regionPoll('orderRules',{refresh:signal=>updateAutomationStatus(()=>currentUser===statusUser,{signal}),onError:error=>{const node=document.querySelector('#automation-status');if(node&&currentUser===statusUser){node.textContent='通知状态待确认';node.className='badge bg-yellow-lt text-decoration-none';node.title=error.message+';请刷新重试。';}}},15000,{isActive:()=>!!currentUser&&currentUser===statusUser,owned:false});renderView();void checkSystemUpdate(()=>!!currentUser);}
async function boot(){try{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});});
document.addEventListener('click',event=>{const link=event.target.closest('a[href^="#"]');if(!currentUser||!link||event.ctrlKey||event.metaKey)return;event.preventDefault();if(location.hash===link.hash&&window.RecordState.isRecord(link.hash))return;window.PageLifecycle.guard(()=>{if(location.hash!==link.hash){history.pushState({appIndex:++historyIndex},'',link.hash);}return renderView();});});
+2 -2
View File
@@ -1,3 +1,3 @@
<!doctype html>
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>订单通知中心</title><link href="/vendor/tabler.css" rel="stylesheet"><link href="/vendor/tom-select.css" rel="stylesheet"><link href="/app.css" rel="stylesheet"><link href="/assistant-workspace.css" rel="stylesheet"><link href="/field-mappings.css" rel="stylesheet"><link href="/business-home.css" rel="stylesheet"></head>
<body><div id="app"><div class="page page-center"><div class="container-tight py-4"><div class="card"><div class="card-body text-center">正在连接订单通知中心…</div></div></div></div></div><script src="/vendor/tabler.js" defer></script><script src="/vendor/tom-select.js" defer></script><script src="/bpm-sync-settings.js" defer></script><script src="/bpm.js" defer></script><script src="/workspace.js" defer></script><script src="/mail-history.js" defer></script><script src="/mail-template-editor.js" defer></script><script src="/mail.js" defer></script><script src="/record-state.js" defer></script><script src="/record-table.js" defer></script><script src="/record-ui.js" defer></script><script src="/orders.js" defer></script><script src="/pdf-records.js" defer></script><script src="/storage-preview-host.js" defer></script><script src="/storage.js" defer></script><script src="/notifications.js" defer></script><script src="/field-sample-picker.js" defer></script><script src="/field-recognition-panel.js" defer></script><script src="/order-rules-scopes.js" defer></script><script src="/order-rules-resources.js" defer></script><script src="/order-rules-import.js" defer></script><script src="/order-rules-editor.js" defer></script><script src="/order-rules-preview.js" defer></script><script src="/field-mappings.js" defer></script><script src="/order-execution.js" defer></script><script src="/order-notifications-shared.js" defer></script><script src="/modules/order-notifications/batch-editor.js" defer></script><script src="/modules/order-notifications/detail.js" defer></script><script src="/modules/order-notifications/records.js" defer></script><script src="/business-home.js" defer></script><script src="/order-notifications.js" defer></script><script src="/order-rules.js" defer></script><script src="/health.js" defer></script><script src="/vendor/marked.js" defer></script><script src="/assistant-dsh-native.js" defer></script><script src="/assistant-layout.js" defer></script><script src="/assistant-conversation.js" defer></script><script src="/assistant-commands.js" defer></script><script src="/assistant-schedules.js" defer></script><script src="/assistant-schedule-manager.js" defer></script><script src="/assistant-context-panel.js" defer></script><script src="/assistant-events-client.js" defer></script><script src="/assistant-operations.js" defer></script><script src="/assistant-providers.js" defer></script><script src="/assistant-model-picker.js" defer></script><script src="/assistant-settings-review.js" defer></script><script src="/assistant-attachments.js" defer></script><script src="/assistant.js" defer></script><script src="/account.js" defer></script><script src="/navigation.js" defer></script><script src="/page-lifecycle.js" defer></script><script src="/app.js" defer></script></body></html>
<html lang="zh-CN"><head><meta name="app-modules" content=""><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>订单通知中心</title><link href="/vendor/tabler.css" rel="stylesheet"><link href="/vendor/tom-select.css" rel="stylesheet"><link href="/app.css" rel="stylesheet"><link href="/field-mappings.css" rel="stylesheet"><link href="/business-home.css" rel="stylesheet"><link href="/assistant-workspace.css" rel="stylesheet"></head>
<body><div id="app"><div class="page page-center"><div class="container-tight py-4"><div class="card"><div class="card-body text-center">正在连接订单通知中心…</div></div></div></div></div><script src="/vendor/tabler.js" defer></script><script src="/navigation.js" defer></script><script src="/page-lifecycle.js" defer></script><script src="/record-state.js" defer></script><script src="/modules/navigation/module-loader.js" defer></script><script src="/app.js" defer></script></body></html>
+5
View File
@@ -232,6 +232,11 @@ window.AssistantContextPanel = {
drawActions();
drawEvents();
},
updateSettings(next) {
Object.assign(settings, next);
actionSignature = '';
drawActions();
},
showActions() {
select('actions');
},
+30 -1
View File
@@ -374,7 +374,7 @@
root.querySelector('.aw-usage').textContent = '调用额度暂不可用';
}
}
function loadCurrent() {
function loadCurrent(signal) {
if (!currentId || !live()) return Promise.resolve();
const id = currentId,
at = revision,
@@ -385,6 +385,8 @@
if (!live() || currentId !== id || revision !== at) return;
const next = await api(
'/assistant/conversations/' + id + (deletedScope ? '?scope=deleted' : ''),
undefined,
{ signal, ownerCheck: () => live() && currentId === id && revision === at },
);
if (!live() || currentId !== id || revision !== at) return;
conversation = next;
@@ -778,6 +780,7 @@
d.remove();
});
transcript.dispose();
regionWatcher?.dispose();
taskManager.dispose();
panel.dispose();
layout.dispose();
@@ -785,6 +788,32 @@
pendingActions.clear();
input.value = '';
}
const regionWatcher = window.PageLifecycle?.regionPoll?.(
'assistant',
{ refresh: async () => false, onError: showError },
1200,
{ isActive: live, enabled: () => false },
);
if (regionWatcher)
regionWatcher.refreshRegion = async () => {
const next = await api('/assistant');
if (!live()) return;
panel.updateSettings(next.settings);
data.usage = next.usage;
root.querySelector('.aw-usage').textContent =
'今日 ' + next.usage.calls + ' / ' + next.usage.limit;
root.querySelector('.aw-connection').textContent =
(next.settings.runtimeConfigured ?? !!next.settings.runtimePath)
? '诊断已配置'
: '待配置';
await picker.refresh({ force: true });
if (!live()) return;
await window.PageLifecycle.validateRegion('assistant').catch(showError);
await refreshList();
await loadCurrent();
await panel.refresh().catch(showError);
if (live()) draw();
};
window.PageLifecycle?.onDispose(dispose);
await Promise.all([
refreshList(1),
+6 -5
View File
@@ -4,8 +4,8 @@ window.OrderViews=(()=>{
const defaults=()=>({scope:'current',business:'orders',kind:'all',q:'',connectionId:'',from:'',to:'',page:1});
function configure(options){if(user?.username!==options.user.username)filters=defaults();({api,esc,formatDate,notify,user}=options);}
async function records(container,isActive){
filters=window.RecordState.read('records');let disposed=false,status=null,timer,statusController;const live=()=>!disposed&&isActive(),get=id=>container.querySelector('#'+id);
window.PageLifecycle?.onDispose(()=>{disposed=true;clearTimeout(timer);statusController?.abort();});
filters=window.RecordState.read('records');let disposed=false,status=null,statusController;const live=()=>!disposed&&isActive(),get=id=>container.querySelector('#'+id);
window.PageLifecycle?.onDispose(()=>{disposed=true;statusController?.abort();});
const option=(value,label,current)=>'<option value="'+esc(value)+'" '+(value===current?'selected':'')+'>'+esc(label)+'</option>';
container.innerHTML='<div class="record-monitor small text-secondary" data-monitor aria-live="polite">正在读取监听状态…</div><div class="alert alert-warning" data-record-error hidden role="alert"></div><section class="card"><div class="card-header flex-wrap gap-2"><h2 class="card-title">流程到达台账</h2><div class="btn-list ms-auto"><a href="#bpm" class="btn btn-sm">管理连接</a>'+(user.role!=='viewer'?'<button type="button" class="btn btn-primary btn-sm" id="scan-now">立即同步</button>':'')+'</div></div><div class="card-body record-filters"><div class="row g-3"><div class="col-12 col-sm-6 col-lg-4"><label class="form-label" for="arrival-query">搜索流程记录</label><input class="form-control" id="arrival-query" maxlength="200" placeholder="流水号、流程、订单标题" value="'+esc(filters.q)+'"></div><div class="col-6 col-sm-3 col-lg-2"><label class="form-label" for="arrival-scope">记录范围</label><select class="form-select" id="arrival-scope">'+option('current','现有连接',filters.scope)+option('archived','历史归档',filters.scope)+option('all','全部来源',filters.scope)+'</select></div><div class="col-6 col-sm-3 col-lg-2"><label class="form-label" for="arrival-business">业务范围</label><select class="form-select" id="arrival-business">'+option('orders','订单相关流程',filters.business)+option('all','全部 BPM 流程',filters.business)+'</select></div><div class="col-6 col-sm-8 col-lg-2"><label class="form-label" for="arrival-kind">到达类型</label><select class="form-select" id="arrival-kind">'+option('all','全部到达类型',filters.kind)+option('todo','待办到达记录',filters.kind)+option('inform','待阅到达记录',filters.kind)+'</select></div><div class="col-6 col-sm-4 col-lg-2 d-flex align-items-end"><button type="button" class="btn w-100" id="arrival-submit" data-record-query>查询</button></div></div><details class="mt-3"><summary class="small text-secondary">更多筛选:来源与日期</summary><div class="row g-3 mt-0"><div class="col-12 col-md-4"><label class="form-label" for="arrival-connection">来源连接</label><select class="form-select" id="arrival-connection"><option value="">全部来源连接</option></select></div><div class="col-6 col-md-4"><label class="form-label" for="arrival-from">起始日期</label><input class="form-control" id="arrival-from" type="date" value="'+esc(filters.from)+'"></div><div class="col-6 col-md-4"><label class="form-label" for="arrival-to">结束日期</label><input class="form-control" id="arrival-to" type="date" value="'+esc(filters.to)+'"></div></div></details></div><div data-arrival-list></div>'+window.RecordUi.footer+'</section><div class="small text-secondary mt-2">按北京时间记录到达历史 · 分类与邮件批次见 <a href="#notification-orders">通知订单</a></div>';
const detail=window.RecordUi.details(container,'流程到达详情');
@@ -16,9 +16,10 @@ window.OrderViews=(()=>{
function open(row,trigger){const f=(label,value)=>window.RecordUi.field(esc,label,value);detail.show('<dl class="record-detail-grid">'+f('流水号',row.serialNum)+f('流程',row.processName)+f('流程版本',row.processVersion)+f('节点',row.activityName)+f('到达类型',row.kind==='todo'?'待办到达记录':'待阅到达记录')+f('到达时间',formatDate(row.arrivedAt))+f('来源连接',row.origin.name)+f('来源账号',row.origin.identity||'账号未记录')+f('负责人',row.origin.owner)+f('来源状态',row.origin.status==='archived'?'历史归档':row.origin.enabled?'现有连接':'现有连接 · 已停用')+f('来源归档时间',row.origin.archivedAt?formatDate(row.origin.archivedAt):row.origin.status==='archived'?'未记录':'—')+(row.origin.missing?f('来源说明','来源信息缺失,保留原连接标识:'+row.connectionId):'')+f('首次采集',formatDate(row.firstSeenAt))+f('最近观察',formatDate(row.lastSeenAt))+f('任务标识',row.taskId)+f('完整标题',row.subject)+'</dl>',trigger);}
function draw(data){const host=container.querySelector('[data-arrival-list]');host.innerHTML=data.items.length?'<div class="table-responsive"><table class="table table-vcenter table-hover card-table record-ledger"><thead><tr><th scope="col">流水号/流程</th><th scope="col" class="record-node">节点/类型</th><th scope="col">标题摘要</th><th scope="col" class="record-source">来源</th><th scope="col" class="record-time">到达时间</th><th scope="col">详情</th></tr></thead><tbody>'+data.items.map((row,index)=>'<tr data-arrival-row><td class="record-identity"><strong>'+esc(row.serialNum||'—')+'</strong><div class="small text-secondary">'+esc(row.processName)+'</div><div class="record-inline-source small text-secondary">'+esc(row.origin.name)+(row.origin.status==='archived'?' · 历史归档':row.origin.enabled?'':' · 已停用')+'</div><div class="record-inline-time small text-secondary">'+esc(formatDate(row.arrivedAt))+'</div><div class="record-inline-summary record-summary small">'+esc(row.subject||'—')+'</div></td><td class="record-node">'+esc(row.activityName==='sysInform'?'知会':row.activityName||'—')+'<div class="small text-secondary">'+(row.kind==='todo'?'待办到达':'待阅到达')+'</div></td><td class="record-summary-cell"><div class="record-summary">'+esc(row.subject||'—')+'</div></td><td class="record-source"><div>'+esc(row.origin.name)+'</div><span class="badge bg-'+(row.origin.status==='archived'?'secondary':row.origin.enabled?'green':'yellow')+'-lt">'+(row.origin.status==='archived'?'历史归档':row.origin.enabled?'现有连接':'已停用')+'</span></td><td class="record-time small text-secondary text-nowrap">'+esc(formatDate(row.arrivedAt))+'</td><td class="record-action"><button type="button" class="btn btn-sm" data-arrival-detail="'+index+'">查看详情</button></td></tr>').join('')+'</tbody></table></div>':'<div class="empty py-5"><p class="empty-title">暂无匹配的到达记录</p><p class="empty-subtitle text-secondary">可调整日期、业务范围或查看历史归档。</p></div>';host.querySelectorAll('[data-arrival-detail]').forEach(button=>button.onclick=()=>open(data.items[Number(button.dataset.arrivalDetail)],button));sourceOptions(data.sources);monitor();}
const table=window.RecordTable.mount({view:'records',container,isActive:live,api,onCommit:next=>{filters=next;},render:draw,readDraft(){const scope=get('arrival-scope').value;return {q:get('arrival-query').value.trim(),scope,business:get('arrival-business').value,kind:get('arrival-kind').value,connectionId:filters.scope!==scope?'':get('arrival-connection').value,from:get('arrival-from').value,to:get('arrival-to').value};},writeDraft(next){for(const [field,id]of Object.entries({q:'arrival-query',scope:'arrival-scope',business:'arrival-business',kind:'arrival-kind',connectionId:'arrival-connection',from:'arrival-from',to:'arrival-to'}))get(id).value=next[field];}});
async function refresh(){clearTimeout(timer);try{statusController?.abort();statusController=new AbortController();const next=await api('/bpm-scan',undefined,{signal:statusController.signal});if(!live())return;status=next;monitor();const runs=status.runs.filter(r=>(filters.kind==='all'||(r.kind||'inform')===filters.kind)&&(!filters.connectionId||r.connectionId===filters.connectionId));if(runs[0]?.status==='error')container.querySelector('[data-monitor]').textContent+=' · 最近同步失败:'+runs[0].message;else if(runs[0]?.status==='success')container.querySelector('[data-monitor]').textContent+=' · 同步完成 '+formatDate(runs[0].finishedAt);}catch(e){if(live())error('监听状态读取失败:'+e.message);}finally{if(live())timer=setTimeout(refresh,10000);}}
if(get('scan-now'))get('scan-now').onclick=async()=>{const button=get('scan-now');button.disabled=true;try{for(const c of candidates())for(const kind of filters.kind==='all'?['todo','inform']:[filters.kind])await api('/bpm-scan/run',{connectionId:c.id,kind});if(live()){notify('只读同步已启动。');clearTimeout(timer);await refresh();}}catch(e){if(live())error(e.message+';已接受的同步请查看最新结果。');}finally{if(live())monitor();}};
await table.ready;if(!live())return;await refresh();
async function refresh(signal){try{statusController?.abort();statusController=new AbortController();const next=await api('/bpm-scan',undefined,{signal:AbortSignal.any([signal,statusController.signal]),ownerCheck:live});if(!live())return;status=next;monitor();const runs=status.runs.filter(r=>(filters.kind==='all'||(r.kind||'inform')===filters.kind)&&(!filters.connectionId||r.connectionId===filters.connectionId));if(runs[0]?.status==='error')container.querySelector('[data-monitor]').textContent+=' · 最近同步失败:'+runs[0].message;else if(runs[0]?.status==='success')container.querySelector('[data-monitor]').textContent+=' · 同步完成 '+formatDate(runs[0].finishedAt);}catch(e){throw e;}}
const polling=window.PageLifecycle.regionPoll('bpm',{refresh,onError:e=>{if(live())error('监听状态读取失败:'+e.message);}},10000,{isActive:live});
if(get('scan-now'))get('scan-now').onclick=async()=>{const button=get('scan-now');button.disabled=true;try{for(const c of candidates())for(const kind of filters.kind==='all'?['todo','inform']:[filters.kind])await api('/bpm-scan/run',{connectionId:c.id,kind});if(live()){notify('只读同步已启动。');await polling.refresh();}}catch(e){if(live())error(e.message+';已接受的同步请查看最新结果。');}finally{if(live())monitor();}};
await Promise.all([table.ready,polling.run().catch(async()=>{await refresh(new AbortController().signal).catch(e=>{if(live())error('监听状态读取失败:'+e.message);});})]);
}
return {configure,records};
})();
+12 -12
View File
@@ -15,12 +15,12 @@ window.BpmLogin=(()=>{
const status=(c,kind='account')=>{const state=observation(c,kind),[color,label]=({healthy:['green','健康'],error:['red','异常'],pending:['yellow','警告'],paused:['yellow','已暂停']})[state.status]||['yellow','待确认'];return `<span class="bpm-account-status bpm-status-${color}"><span class="bpm-status-light" aria-hidden="true"></span>${kind==='account'?'账号':'同步'} · ${label}</span>`;};
function feedback(message,type='danger'){if(!live())return;const el=$('[data-bpm-feedback]');if(el){el.hidden=false;el.className=`alert alert-${type}`;el.textContent=message;}notify(message,type);}
function release(r,{unload=false}={}){
r.closed=true;clearTimeout(r.timer);r.controller?.abort();if(r.url){URL.revokeObjectURL(r.url);r.url=null;}
r.closed=true;r.polling?.dispose();r.controller?.abort();if(r.url){URL.revokeObjectURL(r.url);r.url=null;}
if(unload){if(!r.closeRequest)r.closeRequest=fetch('/api'+route(r.id,'login/close'),{method:'POST',credentials:'same-origin',keepalive:true,headers:{'Content-Type':'application/json'},body:'{}'}).then(()=>{}).catch(()=>{});return r.closeRequest;}
if(r.release)return r.release;
r.release=(async()=>{await r.opening.catch(()=>{});await r.queue.catch(()=>{});await r.operation?.catch(()=>{});if(!r.closeRequest)r.closeRequest=api(route(r.id,'login/close'),{}).catch(()=>{});await r.closeRequest;})();return r.release;
}
const handle={dispose(options){disposed=true;++statusRevision;clearTimeout(statusTimer);container.querySelectorAll('[data-account-form]').forEach(form=>form.reset());return remote?release(remote,options):Promise.resolve();}};
const handle={dispose(options){disposed=true;++statusRevision;statusTimer?.dispose();container.querySelectorAll('[data-account-form]').forEach(form=>form.reset());return remote?release(remote,options):Promise.resolve();}};
active=handle;
const valid=r=>live()&&remote===r&&!r.closed;
function controls(r){if(!valid(r))return;container.querySelectorAll('[data-bpm-control]').forEach(el=>el.disabled=!!r.busy);const input=$('[data-bpm-input]');if(input)input.disabled=!!r.busy;}
@@ -94,14 +94,14 @@ window.BpmLogin=(()=>{
+row('投递重试',delivery.retryAt?formatDate(delivery.retryAt):'无')
+(delivery.message?row('投递说明',delivery.message):'')+'</details>';
}
async function refreshStatus(){
async function refreshStatus(signal){
if(!live())return;
try{
if(accountBusy||mutationBusy)return;const request=statusRevision,next=await api('/workspace');if(!live()||request!==statusRevision)return;
if(accountBusy||mutationBusy)return false;const request=statusRevision,next=await api('/workspace',undefined,{signal,ownerCheck:live});if(!live()||request!==statusRevision)return false;
const rows=next.connections||[],changed=JSON.stringify(connections.map(c=>[c.id,c.status,c.version,c.owner]))!==JSON.stringify(rows.map(c=>[c.id,c.status,c.version,c.owner]));connections=rows;
if(changed&&!remote&&!container.querySelector('[data-account-form]')&&!window.PageLifecycle?.dirty())drawCards();
else for(const c of connections){const badge=container.querySelector('[data-connection-status="'+c.id+'"]'),health=container.querySelector('[data-connection-health="'+c.id+'"]');if(badge)badge.innerHTML=status(c);if(health){const expanded=health.querySelector('details')?.open;health.innerHTML=observations(c);if(expanded)health.querySelector('details').open=true;}}
}catch{}finally{if(live())statusTimer=setTimeout(refreshStatus,5000);}
}catch(error){throw error;}
}
function ownerForm(c){
if(user.role!=='admin')return '';
@@ -138,21 +138,21 @@ window.BpmLogin=(()=>{
catch(error){feedback(error.message);}finally{accountControls(false);}
}
async function mutate(button,action,message){++statusRevision;mutationBusy=true;button.disabled=true;try{const id=button.dataset[action],connection=connections.find(c=>c.id===id);const result=await api(route(id,action),['enable','disable'].includes(action)?{version:connection.version||0}:{});if(!live())return;update(result,button.dataset[action]);feedback(message,'success');}catch(error){feedback(error.message);}finally{mutationBusy=false;if(live())button.disabled=false;}}
async function frame(r){
async function frame(r,signal){
if(!valid(r))return;
try{
r.controller=new AbortController();
const response=await fetch('/api'+route(r.id,'login/frame'),{credentials:'same-origin',cache:'no-store',signal:r.controller.signal});
const response=await fetch('/api'+route(r.id,'login/frame'),{credentials:'same-origin',cache:'no-store',signal:AbortSignal.any([signal,r.controller.signal])});
if(!response.ok){let message='登录画面加载失败,请重新打开窗口。';try{message=(await response.json()).error||message;}catch{}throw new Error(message);}
const blob=await response.blob();if(!valid(r))return;
const url=URL.createObjectURL(blob),old=r.url;r.url=url;const image=$('[data-bpm-frame]');image.src=url;image.hidden=false;const loading=$('[data-bpm-loading]');if(loading)loading.hidden=true;if(old)URL.revokeObjectURL(old);
}catch(error){if(valid(r)&&error.name!=='AbortError'){feedback(error.message);await close(r);return;}}
if(valid(r))r.timer=setTimeout(()=>frame(r),650);
}
async function close(r){if(remote===r)remote=null;await release(r);if(live()){$('#bpm-remote').innerHTML='';drawCards();}}
async function open(id){
if(remote||accountBusy||!live())return;
const r={id,closed:false,queue:Promise.resolve(),busy:false,failed:false,url:null,timer:null};remote=r;drawCards();
const r={id,closed:false,queue:Promise.resolve(),busy:false,failed:false,url:null};remote=r;drawCards();
r.opening=api(route(id,'login/open'),{});
try{
const session=await r.opening;if(!valid(r)){await release(r);return;}
@@ -171,7 +171,7 @@ window.BpmLogin=(()=>{
try{await r.queue;if(!valid(r))return;if(r.failed)throw Error('输入未送达,请关闭后重新打开登录窗口。');r.operation=api(route(id,'login/save'),{});const result=await r.operation;if(!valid(r))return;update(result,id);const saved=result.connection||result;feedback(saved.status==='connected'?'连接已检查并保存。':'请完成登录后再次检查。',saved.status==='connected'?'success':'warning');}
catch(error){feedback(error.message);}finally{r.busy=false;if(valid(r)){controls(r);$('[data-bpm-close]').disabled=false;$('[data-bpm-save-state]').textContent='完成登录后保存连接';}}
};
frame(r);
r.polling=window.PageLifecycle.poll(signal=>frame(r,signal),650,{isActive:()=>valid(r)});void r.polling.run();
}catch(error){if(valid(r)){remote=null;drawCards();feedback(error.message);}}
}
function bindInput(r){
@@ -194,12 +194,12 @@ window.BpmLogin=(()=>{
input.onkeydown=keydown;surface.onkeydown=event=>{if(event.target!==input)keydown(event);};surface.onpaste=event=>{if(event.target!==input)input.onpaste(event);};
}
try{
data=await api('/workspace');if(!live())return;connections=data.connections||[];
let initial,initialError;try{initial=await window.PageLifecycle.validateRegion('bpm');}catch(error){initialError=error;}data=await api('/workspace');if(!live())return;connections=data.connections||[];
container.innerHTML=`<div data-bpm-feedback hidden role="alert"></div><div class="connection-layout bpm-layout"><div><div id="bpm-list"></div></div>${user.role==='admin'?`<form class="card" id="connection-create"><div class="card-header"><h2 class="card-title">添加 BPM 连接</h2></div><div class="card-body"><div class="mb-3"><label class="form-label required" for="connection-name">连接名称</label><input class="form-control" id="connection-name" required maxlength="100" placeholder="例如:业务团队 BPM"></div><div><label class="form-label required" for="connection-owner">负责人</label><select class="form-select" id="connection-owner" required><option value="">请选择负责人</option>${(data.members||[]).filter(m=>m.role!=='viewer').map(m=>`<option value="${esc(m.username)}">${esc(m.username)}</option>`).join('')}</select></div></div><div class="card-footer text-end"><button class="btn btn-primary" type="submit">创建连接</button></div></form>`:''}</div><div id="bpm-remote" aria-live="polite"></div><div id="bpm-sync-settings"></div>`;
if(user.role==='admin')$('#connection-create').onsubmit=async event=>{event.preventDefault();const button=event.target.querySelector('button[type=submit]');button.disabled=true;try{const result=await api('/connections',{name:$('#connection-name').value.trim(),owner:$('#connection-owner').value});if(!live())return;++statusRevision;connections.unshift(result.connection||result);event.target.reset();drawCards();feedback('连接已创建。','success');}catch(error){feedback(error.message);}finally{if(live())button.disabled=false;}};
drawCards();
connections.filter(c=>c.status!=='disabled'&&authorized(c)).forEach(c=>loadAccount(c.id).then(refreshAccountSummary).catch(error=>feedback(error.message)));
statusTimer=setTimeout(refreshStatus,5000);
statusTimer=window.PageLifecycle.regionPoll('bpm',{refresh:refreshStatus,onError:error=>feedback('状态读取失败:'+error.message+';保留上次状态,请刷新重试。')},5000,{isActive:live,initial});if(initialError)feedback('状态读取失败:'+initialError.message+';正在显示已读取的连接,请刷新重试。');
await window.BpmSyncSettings?.mount($('#bpm-sync-settings'),{api,user,notify,isActive:live});
}catch(error){if(live())throw error;}
}
+1 -1
View File
@@ -24,7 +24,7 @@
lock(busy);
}
window.PageLifecycle.onDispose(()=>{disposed=true;revision++;});
try{if(admin){const workspace=await api('/workspace');if(!live())return;connections=(workspace.connections||[]).filter(c=>c.status!=='disabled'&&c.enabled!==false);}await load();}catch(e){if(live())host.innerHTML='<div class="alert alert-danger">字段映射加载失败:'+esc(e.message)+'。请重新进入此页重试。</div>';}
try{const [workspace,fresh]=await Promise.all([admin?api('/workspace'):null,api('/order-rules/fields?view=scopes')]);if(!live())return;if(admin)connections=(workspace.connections||[]).filter(c=>c.status!=='disabled'&&c.enabled!==false);data=fresh;draw();}catch(e){if(live())host.innerHTML='<div class="alert alert-danger">字段映射加载失败:'+esc(e.message)+'。请重新进入此页重试。</div>';}
return {dispose(){disposed=true;revision++;}};
}
window.FieldMappingViews={render};
Loaded 100 of 113 files, more files were not shown because too many files have changed in this diff. Show more